diff --git a/generator/konfig-dash/packages/konfig-cli/src/util/insert-table-of-contents.ts b/generator/konfig-dash/packages/konfig-cli/src/util/insert-table-of-contents.ts index 53b311b5d0..3d33ad6bb2 100644 --- a/generator/konfig-dash/packages/konfig-cli/src/util/insert-table-of-contents.ts +++ b/generator/konfig-dash/packages/konfig-cli/src/util/insert-table-of-contents.ts @@ -19,16 +19,46 @@ export function insertTableOfContents({ fs.writeFileSync(readmePath, withTocAndReferenceLinkFix) } +const { slugify } = require('markdown-toc/lib/utils') + // https://github.com/pypa/readme_renderer/issues/169#issuecomment-808577486 /** * Turns all headings into links by adding after them with no space. * Uses regex to avoid parsing the markdown AST. */ -function applyReferenceLinkFix(markdown: string): string { - const { slugify } = require('markdown-toc/lib/utils') +/** + * Applies reference link fix to markdown text, excluding code blocks. + * + * @param markdown - The markdown text. + * @returns The fixed markdown text. + */ +export function applyReferenceLinkFix(markdown: string): string { + // This regex matches code blocks. + const codeBlockRegex = /```[\s\S]*?```/g + // This regex matches headings outside code blocks. const headingRegex = /^#+\s+(.*)$/gm - return markdown.replace(headingRegex, (match, p1) => { + + // Function to replace headings with slugified anchors. + function replaceHeadings(match: string, p1: string): string { const slug = slugify(p1) return `${match}` + } + + // Split the content by code blocks and process non-code sections. + const parts = markdown.split(codeBlockRegex) + const codeBlocks = markdown.match(codeBlockRegex) || [] + + let fixedMarkdown = '' + let codeBlockIndex = 0 + + parts.forEach((part, index) => { + // Apply fix to non-code parts. + fixedMarkdown += part.replace(headingRegex, replaceHeadings) + // Re-insert code blocks where they were. + if (codeBlockIndex < codeBlocks.length) { + fixedMarkdown += codeBlocks[codeBlockIndex++] + } }) + + return fixedMarkdown } diff --git a/generator/konfig-dash/packages/konfig-cli/test/util/insert-table-of-contents.test.ts b/generator/konfig-dash/packages/konfig-cli/test/util/insert-table-of-contents.test.ts new file mode 100644 index 0000000000..aa99f87202 --- /dev/null +++ b/generator/konfig-dash/packages/konfig-cli/test/util/insert-table-of-contents.test.ts @@ -0,0 +1,13 @@ +import { applyReferenceLinkFix } from '../../src/util/insert-table-of-contents' + +it('apply reference link fix', () => { + expect(applyReferenceLinkFix(`# Heading 1`)).toMatchInlineSnapshot( + `"# Heading 1"` + ) + expect(applyReferenceLinkFix(`\`\`\`python\n#comment\n\`\`\``)) + .toMatchInlineSnapshot(` + "\`\`\`python + #comment + \`\`\`" + `) +})