Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand All @@ -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 <text>` | Leave out headings whose text is exactly this (repeatable). |

### Headings and anchors

Expand Down
22 changes: 19 additions & 3 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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>] <file>...
export const USAGE = `Usage: bun run src/cli.ts [--check] [--max-depth <1-6>] [--min-depth <1-6>] [--exclude <text>]... <file>...

Generate a Markdown table of contents between <!-- toc --> and <!-- tocstop -->.
<file>... 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 <text> 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];
Expand Down Expand Up @@ -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))) {
Expand Down Expand Up @@ -81,7 +97,7 @@ export async function main(args: string[] = Bun.argv.slice(2)): Promise<number>
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.`);
Expand Down
22 changes: 18 additions & 4 deletions src/toc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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})`;
Expand All @@ -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);
Expand All @@ -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}`;
}
156 changes: 155 additions & 1 deletion tests/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
"<!-- toc -->\n<!-- tocstop -->\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(
"<!-- toc -->\n<!-- tocstop -->\n# Guide\n## Installation",
Expand Down Expand Up @@ -222,6 +260,7 @@ describe("CLI argument parsing", () => {
check: false,
maxDepth: 6,
minDepth: 1,
exclude: [],
help: false,
});
});
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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(
"<!-- toc -->\n- [Guide](#guide)\n<!-- tocstop -->\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));
Expand Down Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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, ["<!-- toc -->", "<!-- tocstop -->", ...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 -->", toc, "<!-- tocstop -->", ...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);
Expand Down
Loading