deduplicate code
This commit is contained in:
parent
938b7506cf
commit
f6d6c4fb81
7 changed files with 441 additions and 370 deletions
|
|
@ -3,6 +3,17 @@ import { distance } from "fastest-levenshtein";
|
|||
import { DiffLine } from "../../..";
|
||||
import { LineStream } from "../../../diff/util";
|
||||
|
||||
import {
|
||||
headerIsMarkdown,
|
||||
isMarkdownFile,
|
||||
MarkdownBlockStateTracker,
|
||||
collectAllLines,
|
||||
} from "../../../utils/markdownUtils";
|
||||
import {
|
||||
shouldStopAtMarkdownBlock,
|
||||
processBlockNesting as processBlockNestingUtil,
|
||||
} from "../../../utils/streamMarkdownUtils";
|
||||
|
||||
export { filterCodeBlockLines } from "./filterCodeBlock";
|
||||
|
||||
export type LineFilter = (args: {
|
||||
|
|
@ -18,23 +29,6 @@ export type CharacterFilter = (args: {
|
|||
multiline: boolean;
|
||||
}) => AsyncGenerator<string>;
|
||||
|
||||
// Duplicated from gui/src/components/StyledMarkdownPreview/utils/headerIsMarkdown.ts
|
||||
function headerIsMarkdown(header: string): boolean {
|
||||
return (
|
||||
header === "md" ||
|
||||
header === "markdown" ||
|
||||
header === "gfm" ||
|
||||
header === "github-markdown" ||
|
||||
header.includes(" md") ||
|
||||
header.includes(" markdown") ||
|
||||
header.includes(" gfm") ||
|
||||
header.includes(" github-markdown") ||
|
||||
header.split(" ")[0]?.split(".").pop() === "md" ||
|
||||
header.split(" ")[0]?.split(".").pop() === "markdown" ||
|
||||
header.split(" ")[0]?.split(".").pop() === "gfm"
|
||||
);
|
||||
}
|
||||
|
||||
function isBracketEnding(line: string): boolean {
|
||||
return line
|
||||
.trim()
|
||||
|
|
@ -124,19 +118,6 @@ function isUselessLine(line: string): boolean {
|
|||
return hasUselessLine || trimmed.startsWith("// end");
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if a file is a markdown file based on its filepath.
|
||||
*/
|
||||
export function isMarkdownFile(filepath?: string): boolean {
|
||||
if (!filepath) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return ["md", "markdown", "gfm"].includes(
|
||||
filepath.split(".").pop()?.toLowerCase() || "",
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if the code block has nested markdown blocks.
|
||||
*/
|
||||
|
|
@ -147,116 +128,25 @@ export function hasNestedMarkdownBlocks(
|
|||
return (
|
||||
(firstLine.startsWith("```") &&
|
||||
headerIsMarkdown(firstLine.replace(/`/g, ""))) ||
|
||||
Boolean(filepath && headerIsMarkdown(filepath))
|
||||
Boolean(filepath && isMarkdownFile(filepath))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects all lines from a LineStream into an array for analysis.
|
||||
*/
|
||||
export async function collectAllLines(rawLines: LineStream): Promise<string[]> {
|
||||
const allLines: string[] = [];
|
||||
for await (const line of rawLines) {
|
||||
allLines.push(line);
|
||||
}
|
||||
return allLines;
|
||||
}
|
||||
// Re-export shared utilities
|
||||
export { collectAllLines, isMarkdownFile };
|
||||
export { MarkdownBlockStateTracker as MarkdownBlockState };
|
||||
export { shouldStopAtMarkdownBlock };
|
||||
|
||||
/**
|
||||
* State tracker for markdown block analysis to avoid recomputing on each call.
|
||||
*/
|
||||
export class MarkdownBlockState {
|
||||
private trimmedLines: string[];
|
||||
private bareBacktickPositions: number[];
|
||||
private markdownNestCount: number = 0;
|
||||
private lastProcessedIndex: number = -1;
|
||||
|
||||
constructor(allLines: string[]) {
|
||||
this.trimmedLines = allLines.map((l) => l.trim());
|
||||
// Pre-compute positions of all bare backtick lines for faster lookup
|
||||
this.bareBacktickPositions = [];
|
||||
for (let i = 0; i < this.trimmedLines.length; i++) {
|
||||
if (this.trimmedLines[i].match(/^`+$/)) {
|
||||
this.bareBacktickPositions.push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if we should stop at the given markdown block position.
|
||||
* Maintains state across calls to avoid redundant computation.
|
||||
*/
|
||||
shouldStopAtPosition(currentIndex: number): boolean {
|
||||
if (this.trimmedLines[currentIndex] !== "```") {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Process any lines we haven't seen yet up to currentIndex
|
||||
for (let j = this.lastProcessedIndex + 1; j <= currentIndex; j++) {
|
||||
const currentLine = this.trimmedLines[j];
|
||||
|
||||
if (this.markdownNestCount > 0) {
|
||||
// Inside a markdown block
|
||||
if (currentLine.match(/^`+$/)) {
|
||||
// Found bare backticks - check if this is the last one
|
||||
if (j === currentIndex) {
|
||||
const remainingBareBackticks = this.bareBacktickPositions.filter(
|
||||
(pos) => pos > j,
|
||||
).length;
|
||||
if (remainingBareBackticks === 0) {
|
||||
this.markdownNestCount = 0;
|
||||
this.lastProcessedIndex = j;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else if (currentLine.startsWith("```")) {
|
||||
// Going into a nested codeblock
|
||||
this.markdownNestCount++;
|
||||
}
|
||||
} else {
|
||||
// Not inside a markdown block yet
|
||||
if (currentLine.startsWith("```")) {
|
||||
const header = currentLine.replaceAll("`", "");
|
||||
if (headerIsMarkdown(header)) {
|
||||
this.markdownNestCount = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.lastProcessedIndex = currentIndex;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if we should stop at a markdown block based on nested markdown logic.
|
||||
* This handles the complex case where markdown blocks contain other markdown blocks.
|
||||
* Uses optimized state tracking to avoid redundant computation.
|
||||
*/
|
||||
export function shouldStopAtMarkdownBlock(
|
||||
stateTracker: MarkdownBlockState,
|
||||
currentIndex: number,
|
||||
): boolean {
|
||||
return stateTracker.shouldStopAtPosition(currentIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes block nesting logic and returns updated state.
|
||||
*/
|
||||
// Wrapper for processBlockNesting with local shouldRemoveLineBeforeStart function
|
||||
export function processBlockNesting(
|
||||
line: string,
|
||||
seenFirstFence: boolean,
|
||||
): { newSeenFirstFence: boolean; shouldSkip: boolean } {
|
||||
if (!seenFirstFence && shouldRemoveLineBeforeStart(line)) {
|
||||
return { newSeenFirstFence: false, shouldSkip: true };
|
||||
}
|
||||
|
||||
if (!seenFirstFence) {
|
||||
return { newSeenFirstFence: true, shouldSkip: false };
|
||||
}
|
||||
|
||||
return { newSeenFirstFence: seenFirstFence, shouldSkip: false };
|
||||
return processBlockNestingUtil(
|
||||
line,
|
||||
seenFirstFence,
|
||||
shouldRemoveLineBeforeStart,
|
||||
);
|
||||
}
|
||||
|
||||
export const USELESS_LINES = [""];
|
||||
|
|
@ -326,7 +216,7 @@ export async function* avoidPathLine(
|
|||
// Sometimes the model with copy this pattern, which is unwanted
|
||||
for await (const line of stream) {
|
||||
if (line.startsWith(`${comment} Path: `)) {
|
||||
continue;
|
||||
continue; // continue in the Continue codebase! How meta!
|
||||
}
|
||||
yield line;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -846,32 +846,6 @@ describe("lineStream", () => {
|
|||
});
|
||||
|
||||
// Tests for new helper functions
|
||||
describe("isMarkdownFile", () => {
|
||||
it("should return true for markdown file extensions", () => {
|
||||
expect(lineStream.isMarkdownFile("README.md")).toBe(true);
|
||||
expect(lineStream.isMarkdownFile("docs.markdown")).toBe(true);
|
||||
expect(lineStream.isMarkdownFile("notes.gfm")).toBe(true);
|
||||
expect(lineStream.isMarkdownFile("path/to/file.md")).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false for non-markdown file extensions", () => {
|
||||
expect(lineStream.isMarkdownFile("script.js")).toBe(false);
|
||||
expect(lineStream.isMarkdownFile("styles.css")).toBe(false);
|
||||
expect(lineStream.isMarkdownFile("document.txt")).toBe(false);
|
||||
expect(lineStream.isMarkdownFile("config.json")).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false for undefined or empty filepath", () => {
|
||||
expect(lineStream.isMarkdownFile(undefined)).toBe(false);
|
||||
expect(lineStream.isMarkdownFile("")).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle case insensitive extensions", () => {
|
||||
expect(lineStream.isMarkdownFile("README.MD")).toBe(true);
|
||||
expect(lineStream.isMarkdownFile("docs.MARKDOWN")).toBe(true);
|
||||
expect(lineStream.isMarkdownFile("notes.GFM")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hasNestedMarkdownBlocks", () => {
|
||||
it("should detect nested markdown blocks from first line", () => {
|
||||
|
|
@ -1037,59 +1011,6 @@ describe("lineStream", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("processBlockNesting", () => {
|
||||
it("should skip lines that should be removed before start", () => {
|
||||
const result = lineStream.processBlockNesting("```typescript", false);
|
||||
expect(result).toEqual({
|
||||
newSeenFirstFence: false,
|
||||
shouldSkip: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("should skip [CODE] blocks", () => {
|
||||
const result = lineStream.processBlockNesting("[CODE]", false);
|
||||
expect(result).toEqual({
|
||||
newSeenFirstFence: false,
|
||||
shouldSkip: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("should set first fence when not seen yet", () => {
|
||||
const result = lineStream.processBlockNesting("const x = 5;", false);
|
||||
expect(result).toEqual({
|
||||
newSeenFirstFence: true,
|
||||
shouldSkip: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("should not change state when first fence already seen", () => {
|
||||
const result = lineStream.processBlockNesting("const x = 5;", true);
|
||||
expect(result).toEqual({
|
||||
newSeenFirstFence: true,
|
||||
shouldSkip: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle <COMPLETION> prefix", () => {
|
||||
const result = lineStream.processBlockNesting("<COMPLETION>", false);
|
||||
expect(result).toEqual({
|
||||
newSeenFirstFence: false,
|
||||
shouldSkip: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle START EDITING HERE blocks", () => {
|
||||
const result = lineStream.processBlockNesting(
|
||||
"<START EDITING HERE>",
|
||||
false,
|
||||
);
|
||||
expect(result).toEqual({
|
||||
newSeenFirstFence: false,
|
||||
shouldSkip: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("MarkdownBlockState", () => {
|
||||
it("should initialize with correct state", () => {
|
||||
const allLines = ["```markdown", "content", "```", "more content", "```"];
|
||||
|
|
|
|||
|
|
@ -6,168 +6,11 @@ import {
|
|||
import { streamDiff } from "../../diff/streamDiff.js";
|
||||
import { LineStream, streamLines } from "../../diff/util.js";
|
||||
import { DiffLine, ILLM } from "../../index.js";
|
||||
import { stopAtLinesWithMarkdownSupport } from "../../utils/streamMarkdownUtils.js";
|
||||
|
||||
import { lazyApplyPromptForModel, UNCHANGED_CODE } from "./prompts.js";
|
||||
import { BUFFER_LINES_BELOW, getReplacementWithLlm } from "./replace.js";
|
||||
|
||||
function headerIsMarkdown(header: string): boolean {
|
||||
return (
|
||||
header === "md" ||
|
||||
header === "markdown" ||
|
||||
header === "gfm" ||
|
||||
header === "github-markdown" ||
|
||||
header.includes(" md") ||
|
||||
header.includes(" markdown") ||
|
||||
header.includes(" gfm") ||
|
||||
header.includes(" github-markdown") ||
|
||||
header.split(" ")[0]?.split(".").pop() === "md" ||
|
||||
header.split(" ")[0]?.split(".").pop() === "markdown" ||
|
||||
header.split(" ")[0]?.split(".").pop() === "gfm"
|
||||
);
|
||||
}
|
||||
|
||||
function isMarkdownFile(filename: string): boolean {
|
||||
const ext = filename.split(".").pop()?.toLowerCase();
|
||||
return ["md", "markdown", "gfm"].includes(ext || "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Optimized state tracker for markdown block analysis to avoid recomputing on each call.
|
||||
*/
|
||||
class MarkdownBlockStateTracker {
|
||||
private trimmedLines: string[];
|
||||
private bareBacktickPositions: number[];
|
||||
private markdownNestCount: number = 0;
|
||||
private lastProcessedIndex: number = -1;
|
||||
|
||||
constructor(allLines: string[]) {
|
||||
this.trimmedLines = allLines.map((l) => l.trim());
|
||||
// Pre-compute positions of all bare backtick lines for faster lookup
|
||||
this.bareBacktickPositions = [];
|
||||
for (let i = 0; i < this.trimmedLines.length; i++) {
|
||||
if (this.trimmedLines[i].match(/^`+$/)) {
|
||||
this.bareBacktickPositions.push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if we should stop at the given markdown block position.
|
||||
* Maintains state across calls to avoid redundant computation.
|
||||
*/
|
||||
shouldStopAtPosition(currentIndex: number): boolean {
|
||||
if (this.trimmedLines[currentIndex] !== "```") {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Process any lines we haven't seen yet up to currentIndex
|
||||
for (let j = this.lastProcessedIndex + 1; j <= currentIndex; j++) {
|
||||
const currentLine = this.trimmedLines[j];
|
||||
|
||||
if (this.markdownNestCount > 0) {
|
||||
// Inside a markdown block
|
||||
if (currentLine.match(/^`+$/)) {
|
||||
// Found bare backticks - check if this is the last one
|
||||
if (j === currentIndex) {
|
||||
const remainingBareBackticks = this.bareBacktickPositions.filter(
|
||||
(pos) => pos > j,
|
||||
).length;
|
||||
if (remainingBareBackticks === 0) {
|
||||
this.markdownNestCount = 0;
|
||||
this.lastProcessedIndex = j;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else if (currentLine.startsWith("```")) {
|
||||
// Going into a nested codeblock
|
||||
this.markdownNestCount++;
|
||||
}
|
||||
} else {
|
||||
// Not inside a markdown block yet
|
||||
if (currentLine.startsWith("```")) {
|
||||
const header = currentLine.replaceAll("`", "");
|
||||
if (headerIsMarkdown(header)) {
|
||||
this.markdownNestCount = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.lastProcessedIndex = currentIndex;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function* stopAtLinesWithMarkdownSupport(
|
||||
lines: LineStream,
|
||||
filename: string,
|
||||
): LineStream {
|
||||
if (!isMarkdownFile(filename)) {
|
||||
for await (const line of lines) {
|
||||
if (line.trim() === "```") {
|
||||
return;
|
||||
}
|
||||
yield line;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const allLines: string[] = [];
|
||||
for await (const line of lines) {
|
||||
allLines.push(line);
|
||||
}
|
||||
|
||||
const source = allLines.join("\n");
|
||||
if (!source.match(/```(\w*|.*)(md|markdown|gfm|github-markdown)/)) {
|
||||
for (let i = 0; i < allLines.length; i++) {
|
||||
if (allLines[i].trim() === "```") {
|
||||
for (let j = 0; j < i; j++) {
|
||||
yield allLines[j];
|
||||
}
|
||||
return;
|
||||
}
|
||||
yield allLines[i];
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Use optimized state tracker for markdown block analysis
|
||||
const stateTracker = new MarkdownBlockStateTracker(allLines);
|
||||
let nestCount = 0;
|
||||
const trimmedLines = allLines.map((l) => l.trim());
|
||||
|
||||
for (let i = 0; i < trimmedLines.length; i++) {
|
||||
const line = trimmedLines[i];
|
||||
|
||||
if (nestCount > 0) {
|
||||
if (line.match(/^`+$/)) {
|
||||
// Use optimized state tracker for markdown block logic
|
||||
if (stateTracker.shouldStopAtPosition(i)) {
|
||||
for (let j = 0; j < i; j++) {
|
||||
yield allLines[j];
|
||||
}
|
||||
return;
|
||||
}
|
||||
} else if (line.startsWith("```")) {
|
||||
nestCount++;
|
||||
}
|
||||
} else {
|
||||
if (line.startsWith("```")) {
|
||||
const header = line.replaceAll("`", "");
|
||||
const isMarkdown = headerIsMarkdown(header);
|
||||
|
||||
if (isMarkdown) {
|
||||
nestCount = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const line of allLines) {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
|
||||
export async function* streamLazyApply(
|
||||
oldCode: string,
|
||||
filename: string,
|
||||
|
|
|
|||
113
core/utils/markdownUtils.ts
Normal file
113
core/utils/markdownUtils.ts
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
/**
|
||||
* Utility functions for working with markdown files and code blocks
|
||||
*/
|
||||
|
||||
/**
|
||||
* Determines if a code block header indicates markdown content
|
||||
*/
|
||||
export function headerIsMarkdown(header: string): boolean {
|
||||
return (
|
||||
header === "md" ||
|
||||
header === "markdown" ||
|
||||
header === "gfm" ||
|
||||
header === "github-markdown" ||
|
||||
header.includes(" md") ||
|
||||
header.includes(" markdown") ||
|
||||
header.includes(" gfm") ||
|
||||
header.includes(" github-markdown") ||
|
||||
header.split(" ")[0]?.split(".").pop() === "md" ||
|
||||
header.split(" ")[0]?.split(".").pop() === "markdown" ||
|
||||
header.split(" ")[0]?.split(".").pop() === "gfm"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if a file is a markdown file based on its filepath.
|
||||
*/
|
||||
export function isMarkdownFile(filepath?: string): boolean {
|
||||
if (!filepath) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const ext = filepath.split(".").pop()?.toLowerCase() || "";
|
||||
return ["md", "markdown", "gfm"].includes(ext);
|
||||
}
|
||||
|
||||
/**
|
||||
* State tracker for markdown block analysis to avoid recomputing on each call.
|
||||
* Optimized to handle nested markdown code blocks.
|
||||
*/
|
||||
export class MarkdownBlockStateTracker {
|
||||
private trimmedLines: string[];
|
||||
private bareBacktickPositions: number[];
|
||||
private markdownNestCount: number = 0;
|
||||
private lastProcessedIndex: number = -1;
|
||||
|
||||
constructor(allLines: string[]) {
|
||||
this.trimmedLines = allLines.map((l) => l.trim());
|
||||
// Pre-compute positions of all bare backtick lines for faster lookup
|
||||
this.bareBacktickPositions = [];
|
||||
for (let i = 0; i < this.trimmedLines.length; i++) {
|
||||
if (this.trimmedLines[i].match(/^`+$/)) {
|
||||
this.bareBacktickPositions.push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if we should stop at the given markdown block position.
|
||||
* Maintains state across calls to avoid redundant computation.
|
||||
*/
|
||||
shouldStopAtPosition(currentIndex: number): boolean {
|
||||
if (this.trimmedLines[currentIndex] !== "```") {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Process any lines we haven't seen yet up to currentIndex
|
||||
for (let j = this.lastProcessedIndex + 1; j <= currentIndex; j++) {
|
||||
const currentLine = this.trimmedLines[j];
|
||||
|
||||
if (this.markdownNestCount > 0) {
|
||||
// Inside a markdown block
|
||||
if (currentLine.match(/^`+$/)) {
|
||||
// Found bare backticks - check if this is the last one
|
||||
if (j === currentIndex) {
|
||||
const remainingBareBackticks = this.bareBacktickPositions.filter(
|
||||
(pos) => pos > j,
|
||||
).length;
|
||||
if (remainingBareBackticks === 0) {
|
||||
this.markdownNestCount = 0;
|
||||
this.lastProcessedIndex = j;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else if (currentLine.startsWith("```")) {
|
||||
// Going into a nested codeblock
|
||||
this.markdownNestCount++;
|
||||
}
|
||||
} else {
|
||||
// Not inside a markdown block yet
|
||||
if (currentLine.startsWith("```")) {
|
||||
const header = currentLine.replaceAll("`", "");
|
||||
if (headerIsMarkdown(header)) {
|
||||
this.markdownNestCount = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.lastProcessedIndex = currentIndex;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects all lines from a LineStream into an array for analysis.
|
||||
*/
|
||||
export async function collectAllLines<T>(stream: AsyncGenerator<T>): Promise<T[]> {
|
||||
const allLines: T[] = [];
|
||||
for await (const line of stream) {
|
||||
allLines.push(line);
|
||||
}
|
||||
return allLines;
|
||||
}
|
||||
80
core/utils/markdownUtils.vitest.ts
Normal file
80
core/utils/markdownUtils.vitest.ts
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
import { test, expect } from 'vitest';
|
||||
import { headerIsMarkdown, isMarkdownFile, MarkdownBlockStateTracker } from './markdownUtils';
|
||||
|
||||
test('headerIsMarkdown correctly identifies markdown headers', () => {
|
||||
// Should return true for markdown headers
|
||||
expect(headerIsMarkdown('md')).toBe(true);
|
||||
expect(headerIsMarkdown('markdown')).toBe(true);
|
||||
expect(headerIsMarkdown('gfm')).toBe(true);
|
||||
expect(headerIsMarkdown('github-markdown')).toBe(true);
|
||||
expect(headerIsMarkdown('language md')).toBe(true);
|
||||
expect(headerIsMarkdown('language markdown')).toBe(true);
|
||||
expect(headerIsMarkdown('filename.md')).toBe(true);
|
||||
expect(headerIsMarkdown('path/to/file.md language')).toBe(true);
|
||||
|
||||
// Should return false for non-markdown headers
|
||||
expect(headerIsMarkdown('javascript')).toBe(false);
|
||||
expect(headerIsMarkdown('typescript')).toBe(false);
|
||||
expect(headerIsMarkdown('python')).toBe(false);
|
||||
expect(headerIsMarkdown('')).toBe(false);
|
||||
});
|
||||
|
||||
test('isMarkdownFile correctly identifies markdown files', () => {
|
||||
// Should return true for markdown files
|
||||
expect(isMarkdownFile('test.md')).toBe(true);
|
||||
expect(isMarkdownFile('path/to/file.markdown')).toBe(true);
|
||||
expect(isMarkdownFile('README.md')).toBe(true);
|
||||
|
||||
// Should return false for non-markdown files
|
||||
expect(isMarkdownFile('test.js')).toBe(false);
|
||||
expect(isMarkdownFile('script.ts')).toBe(false);
|
||||
expect(isMarkdownFile('')).toBe(false);
|
||||
expect(isMarkdownFile(undefined)).toBe(false);
|
||||
});
|
||||
|
||||
test('MarkdownBlockStateTracker correctly tracks nested markdown blocks', () => {
|
||||
const lines = [
|
||||
'# Header',
|
||||
'',
|
||||
'Some text',
|
||||
'',
|
||||
'```md',
|
||||
'Nested markdown content',
|
||||
'```javascript',
|
||||
'function test() {',
|
||||
' return true;',
|
||||
'}',
|
||||
'```',
|
||||
'More nested markdown',
|
||||
'```',
|
||||
'',
|
||||
'End of file'
|
||||
];
|
||||
|
||||
const stateTracker = new MarkdownBlockStateTracker(lines);
|
||||
|
||||
// First backtick closure is within nested block (not markdown end)
|
||||
expect(stateTracker.shouldStopAtPosition(10)).toBe(false);
|
||||
|
||||
// This is the backtick that closes the outer markdown block
|
||||
expect(stateTracker.shouldStopAtPosition(12)).toBe(true);
|
||||
});
|
||||
|
||||
test('MarkdownBlockStateTracker handles simple code blocks correctly', () => {
|
||||
const lines = [
|
||||
'Some code:',
|
||||
'',
|
||||
'```javascript',
|
||||
'function test() {',
|
||||
' return true;',
|
||||
'}',
|
||||
'```',
|
||||
'',
|
||||
'More text'
|
||||
];
|
||||
|
||||
const stateTracker = new MarkdownBlockStateTracker(lines);
|
||||
|
||||
// This is just a simple code block, not nested markdown
|
||||
expect(stateTracker.shouldStopAtPosition(6)).toBe(false);
|
||||
});
|
||||
122
core/utils/streamMarkdownUtils.ts
Normal file
122
core/utils/streamMarkdownUtils.ts
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
import { LineStream } from "../diff/util";
|
||||
import {
|
||||
isMarkdownFile,
|
||||
MarkdownBlockStateTracker,
|
||||
headerIsMarkdown,
|
||||
} from "./markdownUtils";
|
||||
|
||||
/**
|
||||
* Determines if we should stop at a markdown block based on nested markdown logic.
|
||||
* This handles the complex case where markdown blocks contain other markdown blocks.
|
||||
* Uses optimized state tracking to avoid redundant computation.
|
||||
*/
|
||||
export function shouldStopAtMarkdownBlock(
|
||||
stateTracker: MarkdownBlockStateTracker,
|
||||
currentIndex: number,
|
||||
): boolean {
|
||||
return stateTracker.shouldStopAtPosition(currentIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes block nesting logic and returns updated state.
|
||||
*/
|
||||
export function processBlockNesting(
|
||||
line: string,
|
||||
seenFirstFence: boolean,
|
||||
shouldRemoveLineBeforeStart: (line: string) => boolean,
|
||||
): { newSeenFirstFence: boolean; shouldSkip: boolean } {
|
||||
if (!seenFirstFence && shouldRemoveLineBeforeStart(line)) {
|
||||
return { newSeenFirstFence: false, shouldSkip: true };
|
||||
}
|
||||
|
||||
if (!seenFirstFence) {
|
||||
return { newSeenFirstFence: true, shouldSkip: false };
|
||||
}
|
||||
|
||||
return { newSeenFirstFence: seenFirstFence, shouldSkip: false };
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream transformation that stops when encountering a markdown code block ending.
|
||||
* Handles nested markdown blocks in markdown files.
|
||||
*/
|
||||
export async function* stopAtLinesWithMarkdownSupport(
|
||||
lines: LineStream,
|
||||
filename: string,
|
||||
): LineStream {
|
||||
if (!isMarkdownFile(filename)) {
|
||||
for await (const line of lines) {
|
||||
if (line.trim() === "```") {
|
||||
return;
|
||||
}
|
||||
yield line;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const allLines: string[] = [];
|
||||
for await (const line of lines) {
|
||||
allLines.push(line);
|
||||
}
|
||||
|
||||
const source = allLines.join("\n");
|
||||
if (!source.match(/```(\w*|.*)(md|markdown|gfm|github-markdown)/)) {
|
||||
// No nested markdown blocks detected, check for simple ``` stopping condition
|
||||
let foundStandaloneBackticks = false;
|
||||
for (let i = 0; i < allLines.length; i++) {
|
||||
if (allLines[i].trim() === "```") {
|
||||
// Found standalone backticks, yield lines up to this point
|
||||
for (let j = 0; j < i; j++) {
|
||||
yield allLines[j];
|
||||
}
|
||||
foundStandaloneBackticks = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// No standalone backticks found, yield all lines
|
||||
if (!foundStandaloneBackticks) {
|
||||
for (const line of allLines) {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Use optimized state tracker for markdown block analysis
|
||||
const stateTracker = new MarkdownBlockStateTracker(allLines);
|
||||
let nestCount = 0;
|
||||
const trimmedLines = allLines.map((l) => l.trim());
|
||||
|
||||
for (let i = 0; i < trimmedLines.length; i++) {
|
||||
const line = trimmedLines[i];
|
||||
|
||||
if (nestCount > 0) {
|
||||
if (line.match(/^`+$/)) {
|
||||
// Use optimized state tracker for markdown block logic
|
||||
if (stateTracker.shouldStopAtPosition(i)) {
|
||||
for (let j = 0; j < i; j++) {
|
||||
yield allLines[j];
|
||||
}
|
||||
return;
|
||||
}
|
||||
} else if (line.startsWith("```")) {
|
||||
nestCount++;
|
||||
}
|
||||
} else {
|
||||
if (line.startsWith("```")) {
|
||||
const header = line.replaceAll("`", "");
|
||||
const isMarkdown = headerIsMarkdown(header);
|
||||
|
||||
if (isMarkdown) {
|
||||
nestCount = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we get here, yield all lines
|
||||
for (const line of allLines) {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
102
core/utils/streamMarkdownUtils.vitest.ts
Normal file
102
core/utils/streamMarkdownUtils.vitest.ts
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
import { expect, test } from "vitest";
|
||||
import { LineStream } from "../diff/util";
|
||||
import {
|
||||
processBlockNesting,
|
||||
stopAtLinesWithMarkdownSupport,
|
||||
} from "./streamMarkdownUtils";
|
||||
|
||||
test("processBlockNesting correctly handles starting blocks", () => {
|
||||
// Mock function to determine which lines should be removed
|
||||
const shouldRemoveLineBeforeStart = (line: string) =>
|
||||
line === "[CODE]" || line === "```";
|
||||
|
||||
// Test not seeing first fence yet
|
||||
const result1 = processBlockNesting(
|
||||
"[CODE]",
|
||||
false,
|
||||
shouldRemoveLineBeforeStart,
|
||||
);
|
||||
expect(result1.newSeenFirstFence).toBe(false);
|
||||
expect(result1.shouldSkip).toBe(true);
|
||||
|
||||
// Test not seeing first fence but line shouldn't be removed
|
||||
const result2 = processBlockNesting(
|
||||
"normal code",
|
||||
false,
|
||||
shouldRemoveLineBeforeStart,
|
||||
);
|
||||
expect(result2.newSeenFirstFence).toBe(true);
|
||||
expect(result2.shouldSkip).toBe(false);
|
||||
|
||||
// Test already seen first fence
|
||||
const result3 = processBlockNesting(
|
||||
"more code",
|
||||
true,
|
||||
shouldRemoveLineBeforeStart,
|
||||
);
|
||||
expect(result3.newSeenFirstFence).toBe(true);
|
||||
expect(result3.shouldSkip).toBe(false);
|
||||
});
|
||||
|
||||
test("stopAtLinesWithMarkdownSupport handles non-markdown files", async () => {
|
||||
// Create a mock line stream
|
||||
const mockLines = ["line 1", "line 2", "```", "line 4"];
|
||||
const lineStream: LineStream = (async function* () {
|
||||
for (const line of mockLines) {
|
||||
yield line;
|
||||
}
|
||||
})();
|
||||
|
||||
// Test with a non-markdown file
|
||||
const filename = "test.js";
|
||||
const result = stopAtLinesWithMarkdownSupport(lineStream, filename);
|
||||
|
||||
// Should only yield lines up to the backticks
|
||||
const collected = [];
|
||||
for await (const line of result) {
|
||||
collected.push(line);
|
||||
}
|
||||
|
||||
expect(collected).toEqual(["line 1", "line 2"]);
|
||||
});
|
||||
|
||||
test("stopAtLinesWithMarkdownSupport handles markdown files with no nested blocks", async () => {
|
||||
// Create a mock line stream with markdown content - but NOT nested markdown blocks
|
||||
const mockLines = [
|
||||
"Some markdown text",
|
||||
"",
|
||||
"```javascript",
|
||||
"function test() {",
|
||||
" return true;",
|
||||
"}",
|
||||
"```",
|
||||
"More text",
|
||||
];
|
||||
|
||||
const lineStream: LineStream = (async function* () {
|
||||
for (const line of mockLines) {
|
||||
yield line;
|
||||
}
|
||||
})();
|
||||
|
||||
// Test with a markdown file
|
||||
const filename = "test.md";
|
||||
const result = stopAtLinesWithMarkdownSupport(lineStream, filename);
|
||||
|
||||
// Should yield everything since there's no nested markdown blocks
|
||||
const collected = [];
|
||||
for await (const line of result) {
|
||||
collected.push(line);
|
||||
}
|
||||
|
||||
// The function should stop at the standalone ``` line (not yield it or lines after)
|
||||
// This is the correct behavior - it stops when it encounters standalone backticks
|
||||
expect(collected).toEqual([
|
||||
"Some markdown text",
|
||||
"",
|
||||
"```javascript",
|
||||
"function test() {",
|
||||
" return true;",
|
||||
"}",
|
||||
]);
|
||||
});
|
||||
Loading…
Add table
Reference in a new issue