Merge pull request #5624 from chezsmithy/fix-markdown-creation

fix: 🐛 fixing issues with creating markdown files
This commit is contained in:
Nate Sesti 2025-05-13 13:14:57 -07:00 • committed by GitHub
commit caa0029a8e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 341 additions and 46 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,48 @@ 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;
// nestCount is set to 1 when the entire code block is wrapped with ``` or START blocks. It's then incremented
// when an inner code block is discovered to avoid exiting the function prematurly. The function will exit early
// when all blocks are matched. When no outer fence is discovered the function will always continue to the end.
let nestCount = 0;
for await (const line of rawLines) {
// Filter out starting ```
if (!seenValidLine) {
if (!seenFirstFence) {
if (shouldRemoveLineBeforeStart(line)) {
continue;
// Filter out starting ``` or START block
continue
}
seenValidLine = true;
// Regardless of a fence or START block start tracking the nesting level
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 including the outer block
const changedEndLine = shouldChangeLineAndStop(line);
if (typeof changedEndLine === "string") {
// Ending a block with just backticks (```) or STOP
nestCount--;
if (nestCount === 0) {
// if we are closing the outer block then exit early
// only exit early if the outer block was started with a block
// it it was text, we will never exit early
return;
} else {
// otherwise just yield the line
yield line;
}
} else if (line.startsWith("```")) {
// Going into a nested codeblock
nestCount++;
yield line;
} else {
// otherwise just yield the line
yield line;
}
}
}
}

View file

@ -0,0 +1,65 @@
import { headerIsMarkdown } from './headerIsMarkdown';
describe('headerIsMarkdown', () => {
// Test exact match with common Markdown identifiers
it('should identify exact matches with common Markdown identifiers', () => {
expect(headerIsMarkdown('md')).toBe(true);
expect(headerIsMarkdown('markdown')).toBe(true);
expect(headerIsMarkdown('gfm')).toBe(true);
expect(headerIsMarkdown('github-markdown')).toBe(true);
});
// Test identifiers preceded by a space
it('should identify identifiers preceded by a space', () => {
expect(headerIsMarkdown('lang md')).toBe(true);
expect(headerIsMarkdown('something markdown')).toBe(true);
expect(headerIsMarkdown('language gfm')).toBe(true);
expect(headerIsMarkdown('spec github-markdown')).toBe(true);
});
// Test file extensions
it('should identify file names with markdown extensions', () => {
expect(headerIsMarkdown('example.md')).toBe(true);
expect(headerIsMarkdown('document.markdown')).toBe(true);
expect(headerIsMarkdown('readme.gfm')).toBe(true);
});
// Test more complex cases with extensions
it('should identify file names with markdown extensions followed by other text', () => {
expect(headerIsMarkdown('example.md additional text')).toBe(true);
expect(headerIsMarkdown('document.markdown with some description')).toBe(true);
expect(headerIsMarkdown('readme.gfm v2.0')).toBe(true);
});
// Test non-markdown cases
it('should not identify non-markdown headers', () => {
expect(headerIsMarkdown('javascript')).toBe(false);
expect(headerIsMarkdown('typescript')).toBe(false);
expect(headerIsMarkdown('plain')).toBe(false);
expect(headerIsMarkdown('python')).toBe(false);
});
// Test edge cases
it('should handle edge cases correctly', () => {
expect(headerIsMarkdown('')).toBe(false);
expect(headerIsMarkdown('mdx')).toBe(false); // Similar but not exactly "md"
expect(headerIsMarkdown('readme md')).toBe(true);
expect(headerIsMarkdown('md.js')).toBe(false); // "md" is not the extension
});
// Test case sensitivity
it('should respect case sensitivity', () => {
expect(headerIsMarkdown('MD')).toBe(false);
expect(headerIsMarkdown('MARKDOWN')).toBe(false);
expect(headerIsMarkdown('example.MD')).toBe(false);
expect(headerIsMarkdown('lang MD')).toBe(false);
});
// Test with special characters and spacing
it('should handle special characters and spacing correctly', () => {
expect(headerIsMarkdown(' md')).toBe(true); // Space before "md"
expect(headerIsMarkdown('md ')).toBe(true); // Space after "md"
expect(headerIsMarkdown('hello-md')).toBe(false); // "md" with hyphen prefix
expect(headerIsMarkdown('markdown:')).toBe(false); // "markdown" with suffix
});
});

View file

@ -0,0 +1,26 @@
/**
* Determines if a given header string represents Markdown content.
*
* The function checks various patterns to identify Markdown headers:
* - Exact match with common Markdown identifiers (md, markdown, gfm, github-markdown)
* - Contains these identifiers preceded by a space
* - First word has a file extension of md, markdown, or gfm
*
* @param header - The string to check for Markdown indicators
* @returns True if the header represents Markdown content, false otherwise
*/
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")
);
}

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,52 @@
/*
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
*/
import { headerIsMarkdown } from './headerIsMarkdown';
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 = headerIsMarkdown(header);
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");
};