diff --git a/README.md b/README.md index bb9aef4..ba1f2ed 100644 --- a/README.md +++ b/README.md @@ -121,6 +121,24 @@ For a file with `# Guide`, `## Installation`, `## Usage`, and `### Sub`, the gen `--min-depth` accepts integers from 1 through 6. Entries are indented relative to the selected minimum depth. Use the same depth when generating and checking. +### Leave out headings + +Use `--exclude` to leave out headings by their visible text. For a file with `# Guide`, the marker pair, `## Installation`, `## Usage`, `### Sub`, and `## License`, run: + +```sh +bun run src/cli.ts --min-depth 2 --exclude License README.md +``` + +The generated entries are: + +```markdown +- [Installation](#installation) +- [Usage](#usage) + - [Sub](#sub) +``` + +The match is exact and case-sensitive, and every heading with matching text is left out. Sub-headings stay, and entries keep their indentation relative to the minimum depth, so combine `--exclude` with `--min-depth 2` to omit a `#` page title without indenting the top entries. Anchors are still counted over all headings, including excluded headings. Use the same options when generating and checking. + ### Options | Option | Description | @@ -129,6 +147,7 @@ For a file with `# Guide`, `## Installation`, `## Usage`, and `### Sub`, the gen | `--check` | Do not write; exit 1 if the table of contents is stale. | | `--max-depth <1-6>` | Include headings only up to this level. | | `--min-depth <1-6>` | Skip heading levels above this depth (default 1). | +| `--exclude ` | Leave out headings whose text is exactly this (repeatable). | ### Headings and anchors diff --git a/src/cli.ts b/src/cli.ts index fec2c6c..73ea6d8 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -7,21 +7,30 @@ export interface CliOptions { check: boolean; maxDepth: number; minDepth: number; + exclude: string[]; help: boolean; } -export const USAGE = `Usage: bun run src/cli.ts [--check] [--max-depth <1-6>] [--min-depth <1-6>] ... +export const USAGE = `Usage: bun run src/cli.ts [--check] [--max-depth <1-6>] [--min-depth <1-6>] [--exclude ]... ... Generate a Markdown table of contents between and . ... Markdown files to update (or check). --check Exit 1 if the TOC is stale; never write the files. --max-depth <1-6> Include heading levels up to this depth (default: 6). --min-depth <1-6> Skip heading levels above this depth (default: 1). + --exclude Leave out headings with this exact text (repeatable). --help, -h Show this help. -- Treat remaining arguments as file paths.`; export function parseArgs(args: string[]): CliOptions { - const options: CliOptions = { files: [], check: false, maxDepth: 6, minDepth: 1, help: false }; + const options: CliOptions = { + files: [], + check: false, + maxDepth: 6, + minDepth: 1, + exclude: [], + help: false, + }; let positionalOnly = false; for (let index = 0; index < args.length; index += 1) { const argument = args[index]; @@ -51,6 +60,13 @@ export function parseArgs(args: string[]): CliOptions { throw new Error("--min-depth must be an integer from 1 through 6."); } options.minDepth = Number(value); + } else if (!positionalOnly && (argument === "--exclude" || argument.startsWith("--exclude="))) { + const value = argument === "--exclude" ? args[++index] : argument.slice("--exclude=".length); + const text = value?.trim(); + if (!text) { + throw new Error("--exclude requires a non-empty heading text."); + } + options.exclude.push(text); } else if (!positionalOnly && argument.startsWith("-")) { throw new Error(`Unknown option: ${argument}. Use --help for usage.`); } else if (!options.files.some((file) => resolve(file) === resolve(argument))) { @@ -81,7 +97,7 @@ export async function main(args: string[] = Bun.argv.slice(2)): Promise for (const file of options.files) { try { const markdown = await readFile(file, "utf8"); - const updated = updateToc(markdown, options.maxDepth, options.minDepth); + const updated = updateToc(markdown, options.maxDepth, options.minDepth, options.exclude); if (options.check) { if (updated !== markdown) { console.error(`TOC is stale in "${file}". Run without --check to update it.`); diff --git a/src/toc.ts b/src/toc.ts index 04514da..9b13896 100644 --- a/src/toc.ts +++ b/src/toc.ts @@ -101,11 +101,20 @@ export function extractHeadings(markdown: string): Heading[] { return headings; } -export function generateToc(markdown: string, maxDepth = 6, newline = "\n", minDepth = 1): string { +export function generateToc( + markdown: string, + maxDepth = 6, + newline = "\n", + minDepth = 1, + exclude: readonly string[] = [], +): string { validateMaxDepth(maxDepth); validateMinDepth(minDepth); return extractHeadings(markdown) - .filter((heading) => heading.level >= minDepth && heading.level <= maxDepth) + .filter( + (heading) => + heading.level >= minDepth && heading.level <= maxDepth && !exclude.includes(heading.text), + ) .map((heading) => { const label = heading.text.replace(/\\/g, "\\\\").replace(/[[\]]/g, "\\$&"); return `${" ".repeat(heading.level - minDepth)}- [${label}](#${heading.anchor})`; @@ -114,7 +123,12 @@ export function generateToc(markdown: string, maxDepth = 6, newline = "\n", minD } /** Require one ordered marker pair before constructing any replacement. */ -export function updateToc(markdown: string, maxDepth = 6, minDepth = 1): string { +export function updateToc( + markdown: string, + maxDepth = 6, + minDepth = 1, + exclude: readonly string[] = [], +): string { validateMaxDepth(maxDepth); validateMinDepth(minDepth); const start = markdown.indexOf(TOC_START); @@ -135,6 +149,6 @@ export function updateToc(markdown: string, maxDepth = 6, minDepth = 1): string const newline = /\r\n|\n|\r/.exec(markdown)?.[0] ?? "\n"; // A stale TOC must not contribute headings to its own replacement. const source = `${before}${newline}${after}`; - const toc = generateToc(source, maxDepth, newline, minDepth); + const toc = generateToc(source, maxDepth, newline, minDepth, exclude); return `${before}${newline}${toc ? toc + newline : ""}${after}`; } diff --git a/tests/cli.test.ts b/tests/cli.test.ts index f02b6a7..796846f 100644 --- a/tests/cli.test.ts +++ b/tests/cli.test.ts @@ -166,6 +166,44 @@ describe("TOC rendering and marker replacement", () => { expect(generateToc("# Usage\n## Usage", 6, "\n", 2)).toBe("- [Usage](#usage-1)"); }); + test("excludes exact visible text case-sensitively and keeps duplicate headings' children", () => { + const markdown = "# License\n## Installation\n### License\n## license\n## Licenses"; + expect(generateToc(markdown, 6, "\n", 1, ["License", "Licens"])).toBe( + " - [Installation](#installation)\n - [license](#license-2)\n - [Licenses](#licenses)", + ); + }); + + test("excludes Setext and inline-formatted headings by their visible text", () => { + const markdown = [ + "Visible `License`", + "===", + "## **License** and [Guide](guide.md)", + "## License policy", + ].join("\n"); + expect(generateToc(markdown, 6, "\n", 1, ["Visible License", "License and Guide"])).toBe( + " - [License policy](#license-policy)", + ); + }); + + test("exclusion keeps anchors assigned over all headings", () => { + expect(generateToc("## Usage!\n## Usage", 6, "\n", 1, ["Usage!"])).toBe( + " - [Usage](#usage-1)", + ); + }); + + test("excluding every heading produces an empty TOC block", () => { + expect(updateToc(marked("# License\n## License"), 6, 1, ["License"])).toBe( + "\n\n# License\n## License", + ); + }); + + test("exclusion composes with minimum and maximum depth", () => { + const markdown = "# Guide\n## License\n## Installation\n### Sub\n#### Details"; + expect(generateToc(markdown, 3, "\n", 2, ["License"])).toBe( + "- [Installation](#installation)\n - [Sub](#sub)", + ); + }); + test("minimum depth can produce an empty TOC block", () => { expect(updateToc(marked("# Guide\n## Installation"), 6, 3)).toBe( "\n\n# Guide\n## Installation", @@ -222,6 +260,7 @@ describe("CLI argument parsing", () => { check: false, maxDepth: 6, minDepth: 1, + exclude: [], help: false, }); }); @@ -250,6 +289,28 @@ describe("CLI argument parsing", () => { ); }); + test("accepts repeatable exclusion options and trims their values", () => { + expect(parseArgs(["--exclude", " License ", "guide.md", "--exclude=Usage"])).toEqual({ + files: ["guide.md"], + check: false, + maxDepth: 6, + minDepth: 1, + exclude: ["License", "Usage"], + help: false, + }); + }); + + test("consumes an option-looking argument as the exclusion text", () => { + expect(parseArgs(["--exclude", "--check", "README.md"])).toEqual({ + files: ["README.md"], + check: false, + maxDepth: 6, + minDepth: 1, + exclude: ["--check"], + help: false, + }); + }); + test("supports help and option-like paths after --", () => { expect(parseArgs(["--help"]).help).toBe(true); expect(parseArgs(["-h"]).help).toBe(true); @@ -403,6 +464,61 @@ describe("CLI subprocess behavior", () => { expect(readFileSync(second, "utf8")).toBe(updateToc(marked(body), 1)); }); + test("applies exclusions to every file and checks both added and removed exclusions", async () => { + const files = [join(directory, "first.md"), join(directory, "second.md")]; + const body = "# Guide\n## License\n## Usage\n### Sub"; + for (const path of files) writeFileSync(path, marked(body)); + + expect((await run(files)).exitCode).toBe(0); + const fullTocs = files.map((path) => readFileSync(path)); + const staleWithExclusion = await run([ + "--check", + files[0], + "--min-depth", + "2", + "--exclude", + "License", + files[1], + ]); + expect(staleWithExclusion.exitCode).toBe(1); + expect(staleWithExclusion.stderr).toContain("TOC is stale"); + expect(files.map((path) => readFileSync(path))).toEqual(fullTocs); + + const generated = await run(["--exclude=License", "--min-depth=2", ...files]); + expect(generated.exitCode).toBe(0); + const excludedTocs = files.map((path) => readFileSync(path, "utf8")); + expect(excludedTocs).toEqual(files.map(() => updateToc(marked(body), 6, 2, ["License"]))); + + const current = await run(["--check", "--min-depth", "2", "--exclude=License", ...files]); + expect(current.exitCode).toBe(0); + expect(current.stderr).toBe(""); + + const staleWithoutExclusion = await run(["--check", files[0], "--min-depth", "2", files[1]]); + expect(staleWithoutExclusion.exitCode).toBe(1); + expect(staleWithoutExclusion.stderr).toContain("TOC is stale"); + expect(files.map((path) => readFileSync(path, "utf8"))).toEqual(excludedTocs); + }); + + test("consumes --check as exclusion text in a real CLI invocation", async () => { + writeFileSync(file, marked("# Guide\n## --check")); + const result = await run(["--exclude", "--check", file]); + expect(result.exitCode).toBe(0); + expect(readFileSync(file, "utf8")).toBe( + "\n- [Guide](#guide)\n\n# Guide\n## --check", + ); + }); + + test.each([ + { args: ["--exclude"], message: "--exclude requires a non-empty heading text." }, + { args: ["--exclude", ""], message: "--exclude requires a non-empty heading text." }, + { args: ["--exclude", " "], message: "--exclude requires a non-empty heading text." }, + { args: ["--exclude="], message: "--exclude requires a non-empty heading text." }, + ])("rejects an empty exclusion value: $args", async ({ args, message }) => { + const result = await run([...args]); + expect(result.exitCode).toBe(1); + expect(result.stderr).toBe(`mdtoc: ${message}\n`); + }); + test("generates with minimum depth and checks matching or stale TOCs", async () => { const body = "# Guide\n## Installation\n## Usage\n### Sub"; writeFileSync(file, marked(body)); @@ -549,9 +665,10 @@ describe("CLI subprocess behavior", () => { expect(result.stderr).toBe(""); }); - test("help documents minimum depth", async () => { + test("help documents minimum depth and heading exclusion", async () => { const result = await run(["--help"]); expect(result.stdout).toContain("--min-depth"); + expect(result.stdout).toContain("--exclude"); }); test("accepts a relative, option-like filename after --", async () => { @@ -616,6 +733,43 @@ describe("documentation, license, and existing scaffold", () => { } }); + test("README heading exclusion example matches real CLI output", async () => { + expect(readme).toContain("### Leave out headings"); + expect(readme).toContain("bun run src/cli.ts --min-depth 2 --exclude License README.md"); + + const toc = ["- [Installation](#installation)", "- [Usage](#usage)", " - [Sub](#sub)"].join( + "\n", + ); + expect(readme).toContain(["```markdown", toc, "```"].join("\n")); + + const directory = mkdtempSync(join(tmpdir(), "mdtoc exclusion example ")); + const exampleFile = join(directory, "README.md"); + const headings = ["# Guide", "## Installation", "## Usage", "### Sub", "## License"]; + writeFileSync(exampleFile, ["", "", ...headings].join("\n")); + try { + const child = Bun.spawn( + [process.execPath, "run", cli, "--min-depth", "2", "--exclude", "License", exampleFile], + { + cwd: directory, + stdout: "pipe", + stderr: "pipe", + timeout: 30_000, + }, + ); + const [exitCode, stderr] = await Promise.all([ + child.exited, + new Response(child.stderr).text(), + ]); + expect(exitCode).toBe(0); + expect(stderr).toBe(""); + expect(readFileSync(exampleFile, "utf8")).toBe( + ["", toc, "", ...headings].join("\n"), + ); + } finally { + rmSync(directory, { recursive: true, force: true }); + } + }); + test("README documents check-mode exit codes and maximum depth with examples", () => { expect(readme).toContain("bun run src/cli.ts --check README.md"); expect(prose).toMatch(/--check.*never writes.*code 0.*current.*code 1.*stale/i);