fix: 🐛 fixing issues with creating markdown files

This commit is contained in:
chezsmithy 2025-05-11 21:46:25 -07:00
parent 8b418165d9
commit 5c1c2d626f
4 changed files with 250 additions and 47 deletions

View file

@ -2,6 +2,7 @@ import { jest } from "@jest/globals";
import * as lineStream from "./lineStream";
// eslint-disable-next-line max-lines-per-function
describe("lineStream", () => {
let mockFullStop: jest.Mock;
@ -204,6 +205,33 @@ describe("lineStream", () => {
});
describe("filterCodeBlockLines", () => {
it("should handle unfenced code", async () => {
const linesGenerator = await getLineGenerator(["const x = 5;"]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;"]);
});
it("should handle unfenced code with a code block", async () => {
const linesGenerator = await getLineGenerator(["const x = 5;","```bash","ls -al","```"]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
});
it("should handle unfenced code with two code blocks", async () => {
const linesGenerator = await getLineGenerator(["const x = 5;","```bash","ls -al","```","```bash","ls -al","```"]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```","```bash","ls -al","```"]);
});
it("should remove lines before the first valid line", async () => {
const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]);
@ -213,7 +241,59 @@ describe("lineStream", () => {
expect(filteredLines).toEqual(["const x = 5;"]);
});
it.todo("Need some sample inputs to properly test this");
it("should remove outer blocks", async () => {
const linesGenerator = await getLineGenerator(["```ts", "const x = 5;","```"]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;"]);
});
it("should leave inner blocks intact", async () => {
const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","```"]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
});
it("should handle included inner ticks", async () => {
const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","echo ```test```","```","```"]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;","```bash","echo ```test```","```"]);
});
it("should leave single inner blocks intact but not return trailing text", async () => {
const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","```","trailing text"]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
});
it("should leave double inner blocks intact but not return trailing text", async () => {
const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","const y = 10;","```sh","echo `hello world`","```","```","trailing text"]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```","const y = 10;","```sh","echo `hello world`","```"]);
});
it("should leave inner blocks intact but not return trailing or leading text", async () => {
const linesGenerator = await getLineGenerator(["[CODE]", "const x = 5;", "```bash","ls -al","```","[/CODE]","trailing text"]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
});
});
describe("filterEnglishLinesAtStart", () => {

View file

@ -55,8 +55,8 @@ function shouldChangeLineAndStop(line: string): string | undefined {
return line;
}
if (line.includes(CODE_START_BLOCK)) {
return line.split(CODE_START_BLOCK)[0].trimEnd();
if (line.includes(CODE_STOP_BLOCK)) {
return line.split(CODE_STOP_BLOCK)[0].trimEnd();
}
return undefined;
@ -71,9 +71,9 @@ function isUselessLine(line: string): boolean {
return hasUselessLine || trimmed.startsWith("// end");
}
export const USELESS_LINES = ["", "```"];
export const USELESS_LINES = [""];
export const CODE_KEYWORDS_ENDING_IN_SEMICOLON = ["def"];
export const CODE_START_BLOCK = "[/CODE]";
export const CODE_STOP_BLOCK = "[/CODE]";
export const BRACKET_ENDING_CHARS = [")", "]", "}", ";"];
export const PREFIXES_TO_SKIP = ["<COMPLETION>"];
export const LINES_TO_STOP_AT = ["# End of file.", "<STOP EDITING HERE"];
@ -343,34 +343,38 @@ export async function* removeTrailingWhitespace(
* 4. Yields processed lines that are part of the actual code block content.
*/
export async function* filterCodeBlockLines(rawLines: LineStream): LineStream {
let seenValidLine = false;
let waitingToSeeIfLineIsLast = undefined;
let seenFirstFence = false;
let nestCount = 0;
for await (const line of rawLines) {
// Filter out starting ```
if (!seenValidLine) {
// Filter out starting ``` or START
if (!seenFirstFence) {
if (shouldRemoveLineBeforeStart(line)) {
continue;
continue
}
seenValidLine = true;
seenFirstFence = true;
nestCount = 1;
}
// Filter out ending ```
if (typeof waitingToSeeIfLineIsLast !== "undefined") {
yield waitingToSeeIfLineIsLast;
waitingToSeeIfLineIsLast = undefined;
}
const changedEndLine = shouldChangeLineAndStop(line);
if (typeof changedEndLine === "string") {
yield changedEndLine;
return;
}
if (line.startsWith("```")) {
waitingToSeeIfLineIsLast = line;
} else {
yield line;
if (nestCount > 0) {
// Inside a block
const changedEndLine = shouldChangeLineAndStop(line);
if (typeof changedEndLine === "string") {
// Ending a block with just backticks (```) or STOP
nestCount--;
if (nestCount === 0) {
return;
} else {
yield line;
}
} else if (line.startsWith("```")) {
// Going into a nested codeblock
nestCount++;
yield line;
} else {
yield line;
}
}
}
}

View file

@ -0,0 +1,105 @@
import { patchNestedMarkdown } from './patchNestedMarkdown';
describe('patchNestedMarkdown', () => {
it('should return unchanged content when no markdown codeblocks are present', () => {
const source = 'Regular text\n```javascript\nconsole.log("hello");\n```';
expect(patchNestedMarkdown(source)).toBe(source);
});
it('should replace backticks with tildes for markdown codeblocks', () => {
const source = '```markdown\n# Header\nSome text\n```';
const expected = '~~~markdown\n# Header\nSome text\n~~~';
expect(patchNestedMarkdown(source)).toBe(expected);
});
it('should handle nested codeblocks within markdown blocks', () => {
const source = '```markdown\n# Example\n```js\nconsole.log("nested");\n```\n```';
const expected = '~~~markdown\n# Example\n```js\nconsole.log("nested");\n```\n~~~';
expect(patchNestedMarkdown(source)).toBe(expected);
});
it('should handle .md file extension', () => {
const source = '```test.md\nContent\n```';
const expected = '~~~test.md\nContent\n~~~';
expect(patchNestedMarkdown(source)).toBe(expected);
});
it('should handle multiple levels of nesting', () => {
const source = '```markdown\n# Doc\n```js\nlet x = "```nested```";\n```\n```';
const expected = '~~~markdown\n# Doc\n```js\nlet x = "```nested```";\n```\n~~~';
expect(patchNestedMarkdown(source)).toBe(expected);
});
it('should handle blocks that start with md', () => {
const source = '```md\n# Header\nSome text\n```';
const expected = '~~~md\n# Header\nSome text\n~~~';
expect(patchNestedMarkdown(source)).toBe(expected);
});
it('should handle blocks with language specifier followed by md', () => {
const source = '```lang md\n# Header\nSome text\n```';
const expected = '~~~lang md\n# Header\nSome text\n~~~';
expect(patchNestedMarkdown(source)).toBe(expected);
});
it('should handle blocks with language specifier followed by markdown', () => {
const source = '```lang markdown\n# Header\nSome text\n```';
const expected = '~~~lang markdown\n# Header\nSome text\n~~~';
expect(patchNestedMarkdown(source)).toBe(expected);
});
it('should not replace backticks for non-markdown file extensions', () => {
const source = '```test.js\nContent\n```';
expect(patchNestedMarkdown(source)).toBe(source);
});
it('should check the file extension branch when extension is not md/markdown/gfm', () => {
// This tests the extension check branch with an unrecognized extension
const source = '```test.txt\nContent with md keyword\n```';
expect(patchNestedMarkdown(source)).toBe(source);
});
it('should handle empty file name in code block header', () => {
// This covers the branch where file is empty or undefined
const source = '``` \nSome content\n```';
expect(patchNestedMarkdown(source)).toBe(source);
});
it('should handle file names with no extension', () => {
// This covers the branch where ext might be undefined
const source = '```filename\nContent\n```';
expect(patchNestedMarkdown(source)).toBe(source);
});
it('should correctly identify .markdown extension', () => {
// This specifically tests the ext === "markdown" condition in the extension check
const source = '```example.markdown\n# Some markdown content\n```';
const expected = '~~~example.markdown\n# Some markdown content\n~~~';
expect(patchNestedMarkdown(source)).toBe(expected);
});
// GitHub-specific tests
it('should handle gfm language identifier', () => {
const source = '```gfm\n# Header\nSome text\n```';
const expected = '~~~gfm\n# Header\nSome text\n~~~';
expect(patchNestedMarkdown(source)).toBe(expected);
});
it('should handle github-markdown language identifier', () => {
const source = '```github-markdown\n# Header\nSome text\n```';
const expected = '~~~github-markdown\n# Header\nSome text\n~~~';
expect(patchNestedMarkdown(source)).toBe(expected);
});
it('should handle language specifier followed by gfm', () => {
const source = '```lang gfm\n# Header\nSome text\n```';
const expected = '~~~lang gfm\n# Header\nSome text\n~~~';
expect(patchNestedMarkdown(source)).toBe(expected);
});
it('should handle .gfm file extension', () => {
const source = '```example.gfm\n# Some GitHub markdown content\n```';
const expected = '~~~example.gfm\n# Some GitHub markdown content\n~~~';
expect(patchNestedMarkdown(source)).toBe(expected);
});
});

View file

@ -1,47 +1,61 @@
/*
This is a patch for outputing markdown code that contains codeblocks
It notices markdown blocks, keeps track of when that specific block is closed,
It notices markdown blocks (including GitHub-specific variants),
keeps track of when that specific block is closed,
and uses ~~~ instead of ``` for that block
Note, this was benchmarked at sub-millisecond
// TODO support github-specific markdown as well, edge case
*/
export const patchNestedMarkdown = (source: string): string => {
if (!source.match(/```(\w+\.(md|markdown))/)) return source; // For performance
// const start = Date.now();
// Early return if no markdown codeblock pattern is found (including GitHub variants)
if (!source.match(/```(\w*|.*)(md|markdown|gfm|github-markdown)/)) return source;
let nestCount = 0;
const lines = source.split("\n");
const trimmedLines = lines.map((l) => l.trim());
for (let i = 0; i < trimmedLines.length; i++) {
const line = trimmedLines[i];
if (nestCount) {
if (nestCount > 0) {
// Inside a markdown block
if (line.match(/^`+$/)) {
// Ending a block
if (nestCount === 1) lines[i] = "~~~"; // End of markdown block
// Ending a block with just backticks (```)
nestCount--;
if (nestCount === 0) {
lines[i] = "~~~"; // End of markdown block
}
} else if (line.startsWith("```")) {
// Going into a nested codeblock
nestCount++;
}
} else {
// Enter the markdown block, start tracking nesting
// Not inside a markdown block yet
if (line.startsWith("```")) {
const header = line.replaceAll("`", "");
const file = header.split(" ")[0];
if (file) {
const ext = file.split(".").at(-1);
if (ext === "md" || ext === "markdown") {
nestCount = 1;
lines[i] = lines[i].replaceAll("`", "~"); // Replace backticks with tildes
}
// Check if this is a markdown codeblock using a consolidated approach (including GitHub-specific variants)
const isMarkdown =
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");
if (isMarkdown) {
nestCount = 1;
lines[i] = lines[i].replaceAll("`", "~");
}
}
}
}
const out = lines.join("\n");
// console.log(`patched in ${Date.now() - start}ms`);
return out;
return lines.join("\n");
};