Skip to content
Open
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
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,25 @@ The output is:

`--numbered` works with generating, `--check`, `--print` and `--insert`; use the same flag when generating and checking, because a bulleted block counts as stale under `--check --numbered`.

### Bullet marker

Use `--bullet` to choose the marker of the bullets: `-` (the default), `*` or `+`. It takes the next argument as its value, or `--bullet=MARKER`, and any other value is an error. Nested entries keep their two-space indentation.

For a file with `# Guide`, `## Installation` and `### Sub`, `bun run src/cli.ts --print --bullet "*" README.md` prints:

```markdown
* [Guide](#guide)
* [Installation](#installation)
* [Sub](#sub)
```

`--bullet` works with generating, `--check`, `--print` and `--insert`; use the same marker when generating and checking, because a block with another marker counts as stale. It cannot be combined with `--numbered`, which writes numbers instead of bullets, and an invalid value or the combination exits 1:

```text
mdtoc: --bullet must be -, * or +.
mdtoc: --bullet and --numbered cannot be used together.
```

### Version

Use `--version` (or `-v`) to print the version of mdtoc, read from `package.json`, and exit. It needs no file and writes nothing:
Expand Down Expand Up @@ -216,6 +235,7 @@ mdtoc 0.2.0
| `--exclude <text>` | Leave out headings whose text is exactly this (repeatable). |
| `--insert` | Add the marker pair first when the file has neither marker. |
| `--numbered` | Write the entries as a numbered list (`1.`, `2.`) instead of bullets. |
| `--bullet <marker>` | Use `-`, `*` or `+` for the bullets (default `-`; not with `--numbered`). |
| `--version`, `-v` | Print the version from package.json and exit. |

### Add the markers
Expand Down
15 changes: 14 additions & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,23 @@ export interface CliOptions {
print: boolean;
insert?: boolean;
numbered?: boolean;
bullet?: string;
version?: boolean;
maxDepth: number;
minDepth: number;
exclude: string[];
help: boolean;
}

export const USAGE = `Usage: bun run src/cli.ts [--check] [--print] [--insert] [--numbered] [--max-depth <1-6>] [--min-depth <1-6>] [--exclude <text>]... <file>...
export const USAGE = `Usage: bun run src/cli.ts [--check] [--print] [--insert] [--numbered] [--bullet <-|*|+>] [--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.
--print Print the generated entries to stdout; never write; no markers needed.
--insert Add the marker pair first when the file has neither marker.
--numbered Write the entries as a numbered list (1. 2. 3.) instead of bullets.
--bullet <-|*|+> Use this marker for the bullets instead of - (not with --numbered).
--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).
Expand Down Expand Up @@ -58,6 +60,12 @@ export function parseArgs(args: string[]): CliOptions {
options.insert = true;
} else if (!positionalOnly && argument === "--numbered") {
options.numbered = true;
} else if (!positionalOnly && (argument === "--bullet" || argument.startsWith("--bullet="))) {
const value = argument === "--bullet" ? args[++index] : argument.slice("--bullet=".length);
if (value !== "-" && value !== "*" && value !== "+") {
throw new Error("--bullet must be -, * or +.");
}
options.bullet = value;
} else if (
!positionalOnly &&
(argument === "--max-depth" || argument.startsWith("--max-depth="))
Expand Down Expand Up @@ -111,6 +119,9 @@ export function parseArgs(args: string[]): CliOptions {
if (!options.help && !options.version && options.insert && options.print) {
throw new Error("--insert and --print cannot be used together.");
}
if (!options.help && !options.version && options.bullet && options.numbered) {
throw new Error("--bullet and --numbered cannot be used together.");
}
return options;
}

Expand Down Expand Up @@ -138,6 +149,7 @@ export async function main(args: string[] = Bun.argv.slice(2)): Promise<number>
options.minDepth,
options.exclude,
options.numbered,
options.bullet,
);
if (entries) {
console.log(entries);
Expand All @@ -156,6 +168,7 @@ export async function main(args: string[] = Bun.argv.slice(2)): Promise<number>
options.minDepth,
options.exclude,
options.numbered,
options.bullet,
);
if (options.check) {
if (updated !== markdown) {
Expand Down
6 changes: 4 additions & 2 deletions src/toc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ export function generateToc(
minDepth = 1,
exclude: readonly string[] = [],
numbered = false,
bullet = "-",
): string {
validateMaxDepth(maxDepth);
validateMinDepth(minDepth);
Expand All @@ -165,7 +166,7 @@ export function generateToc(
const label = heading.text.replace(/\\/g, "\\\\").replace(/[[\]]/g, "\\$&");
const depth = heading.level - minDepth;
if (!numbered) {
return `${" ".repeat(depth)}- [${label}](#${heading.anchor})`;
return `${" ".repeat(depth)}${bullet} [${label}](#${heading.anchor})`;
}
numberedCounts[depth] = (numberedCounts[depth] ?? 0) + 1;
numberedCounts.length = depth + 1;
Expand All @@ -181,6 +182,7 @@ export function updateToc(
minDepth = 1,
exclude: readonly string[] = [],
numbered = false,
bullet = "-",
): string {
validateMaxDepth(maxDepth);
validateMinDepth(minDepth);
Expand All @@ -202,6 +204,6 @@ export function updateToc(
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, exclude, numbered);
const toc = generateToc(source, maxDepth, newline, minDepth, exclude, numbered, bullet);
return `${before}${newline}${toc ? toc + newline : ""}${after}`;
}
220 changes: 220 additions & 0 deletions tests/bullet.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { parseArgs } from "../src/cli";
import { generateToc, updateToc } from "../src/toc";

const root = fileURLToPath(new URL("../", import.meta.url));
const cli = join(root, "src", "cli.ts");
const sample = ["# Guide", "## Installation", "### Sub", "## Usage"].join("\n");

describe("bullet marker", () => {
let directory: string;

beforeEach(() => {
directory = realpathSync(mkdtempSync(join(tmpdir(), "mdtoc bullet tests ")));
});

afterEach(() => {
rmSync(directory, { recursive: true, force: true });
});

function writeMarkdown(name: string, markdown: string): string {
const file = join(directory, name);
writeFileSync(file, markdown);
return file;
}

async function run(args: string[]) {
const child = Bun.spawn([process.execPath, "run", cli, "--", ...args], {
cwd: directory,
stdout: "pipe",
stderr: "pipe",
});
const timeout = setTimeout(() => child.kill(), 30_000);
try {
const [exitCode, stdout, stderr] = await Promise.all([
child.exited,
new Response(child.stdout).text(),
new Response(child.stderr).text(),
]);
return {
exitCode,
stdout: stdout.replace(/\r\n/g, "\n"),
stderr: stderr.replace(/\r\n/g, "\n"),
};
} finally {
clearTimeout(timeout);
}
}

test("keeps the default key absent and accepts the three markers in both spellings", () => {
const defaults = parseArgs(["NOTES.md"]);
expect(defaults.bullet).toBeUndefined();
expect(Object.hasOwn(defaults, "bullet")).toBe(false);

for (const marker of ["-", "*", "+"]) {
expect(parseArgs(["--bullet", marker, "NOTES.md"])).toMatchObject({ bullet: marker });
expect(parseArgs([`--bullet=${marker}`, "NOTES.md"])).toMatchObject({ bullet: marker });
expect(parseArgs(["NOTES.md", "--bullet", marker])).toMatchObject({
files: ["NOTES.md"],
bullet: marker,
});
}
});

test("the last occurrence wins and the value is the next argument whatever it is", () => {
expect(parseArgs(["--bullet", "*", "--bullet=+", "NOTES.md"]).bullet).toBe("+");
expect(() => parseArgs(["--bullet", "--check", "NOTES.md"])).toThrow(
"--bullet must be -, * or +.",
);
expect(parseArgs(["--bullet", "-", "NOTES.md"]).files).toEqual(["NOTES.md"]);
});

test("rejects every other value and a missing value", () => {
for (const args of [
["--bullet", "x", "NOTES.md"],
["--bullet", "", "NOTES.md"],
["--bullet=", "NOTES.md"],
["--bullet=**", "NOTES.md"],
["--bullet", "1.", "NOTES.md"],
["--bullet", " -", "NOTES.md"],
["NOTES.md", "--bullet"],
]) {
expect(() => parseArgs(args)).toThrow("--bullet must be -, * or +.");
}
});

test("treats the flag after the delimiter as a path", () => {
const parsed = parseArgs(["--", "--bullet"]);
expect(parsed.files).toEqual(["--bullet"]);
expect(Object.hasOwn(parsed, "bullet")).toBe(false);
});

test("writes the chosen marker and keeps the two-space nesting", () => {
expect(generateToc(sample, 6, "\n", 1, [], false, "*")).toBe(
[
"* [Guide](#guide)",
" * [Installation](#installation)",
" * [Sub](#sub)",
" * [Usage](#usage)",
].join("\n"),
);
expect(generateToc(sample, 6, "\n", 2, [], false, "+")).toBe(
["+ [Installation](#installation)", " + [Sub](#sub)", "+ [Usage](#usage)"].join("\n"),
);
expect(generateToc(sample, 6, "\n", 1, [], false, "-")).toBe(generateToc(sample));
});

test("leaves labels, anchors and the numbered list alone", () => {
const markdown = ["# A [b] \\ c", "## Hello, World!", "## Hello, World!"].join("\n");
expect(generateToc(markdown, 6, "\n", 1, [], false, "*")).toBe(
[
"* [A \\[b\\] \\\\ c](#a-b-c)",
" * [Hello, World!](#hello-world)",
" * [Hello, World!](#hello-world-1)",
].join("\n"),
);
expect(generateToc(sample, 6, "\n", 1, [], true, "*")).toBe(
generateToc(sample, 6, "\n", 1, [], true),
);
});

test("updates the block between the markers with the chosen marker", () => {
const source = ["<!-- toc -->", "<!-- tocstop -->", "# Guide", "## Usage"].join("\n");
expect(updateToc(source, 6, 1, [], false, "+")).toBe(
[
"<!-- toc -->",
"+ [Guide](#guide)",
" + [Usage](#usage)",
"<!-- tocstop -->",
"# Guide",
"## Usage",
].join("\n"),
);
});

test("rejects the combination with --numbered but lets help and version win", () => {
expect(() => parseArgs(["--bullet", "*", "--numbered", "NOTES.md"])).toThrow(
"--bullet and --numbered cannot be used together.",
);
expect(() => parseArgs(["--numbered", "--bullet=+", "NOTES.md"])).toThrow(
"--bullet and --numbered cannot be used together.",
);
expect(parseArgs(["--bullet", "*", "--numbered", "--help"])).toMatchObject({ help: true });
expect(parseArgs(["--bullet", "*", "--numbered", "-v"])).toMatchObject({ version: true });
expect(() => parseArgs(["--bullet", "?", "--numbered", "--help"])).toThrow(
"--bullet must be -, * or +.",
);
});

test("generates, checks and prints with the marker through the command line", async () => {
const file = writeMarkdown("NOTES.md", "<!-- toc -->\n<!-- tocstop -->\n# Guide\n## Usage\n");

expect(await run(["--bullet", "*", "NOTES.md"])).toEqual({
exitCode: 0,
stdout: "",
stderr: "",
});
expect(readFileSync(file, "utf8")).toBe(
"<!-- toc -->\n* [Guide](#guide)\n * [Usage](#usage)\n<!-- tocstop -->\n# Guide\n## Usage\n",
);
expect(await run(["--check", "--bullet=*", "NOTES.md"])).toEqual({
exitCode: 0,
stdout: "",
stderr: "",
});

const stale = await run(["--check", "NOTES.md"]);
expect(stale.exitCode).toBe(1);
expect(stale.stderr).toBe('TOC is stale in "NOTES.md". Run without --check to update it.\n');

const printed = await run(["--print", "--bullet", "+", "--min-depth", "2", "NOTES.md"]);
expect(printed).toEqual({ exitCode: 0, stdout: "+ [Usage](#usage)\n", stderr: "" });
});

test("works with --insert and reports an invalid marker with exit code 1", async () => {
const file = writeMarkdown("NOTES.md", "# Guide\n\n## Usage\n");

expect((await run(["--insert", "--bullet", "*", "NOTES.md"])).exitCode).toBe(0);
expect(readFileSync(file, "utf8")).toBe(
"# Guide\n<!-- toc -->\n* [Guide](#guide)\n * [Usage](#usage)\n<!-- tocstop -->\n\n## Usage\n",
);

const invalid = await run(["--bullet", "x", "NOTES.md"]);
expect(invalid).toEqual({
exitCode: 1,
stdout: "",
stderr: "mdtoc: --bullet must be -, * or +.\n",
});
const both = await run(["--bullet", "*", "--numbered", "NOTES.md"]);
expect(both).toEqual({
exitCode: 1,
stdout: "",
stderr: "mdtoc: --bullet and --numbered cannot be used together.\n",
});
});

test("documents the option in the help text and in the README", async () => {
const help = await run(["--help"]);
const lines = help.stdout.split("\n");
expect(lines[0]).toContain("[--numbered] [--bullet <-|*|+>] [--max-depth <1-6>]");
const numberedLine = lines.indexOf(
" --numbered Write the entries as a numbered list (1. 2. 3.) instead of bullets.",
);
expect(lines[numberedLine + 1]).toBe(
" --bullet <-|*|+> Use this marker for the bullets instead of - (not with --numbered).",
);

const readme = readFileSync(join(root, "README.md"), "utf8").replace(/\r\n/g, "\n");
expect(readme.indexOf("### Bullet marker")).toBeGreaterThan(
readme.indexOf("### Numbered list"),
);
expect(readme.indexOf("### Bullet marker")).toBeLessThan(readme.indexOf("### Version"));
expect(readme).toContain(
"| `--bullet <marker>` | Use `-`, `*` or `+` for the bullets (default `-`; not with `--numbered`). |",
);
});
});
2 changes: 1 addition & 1 deletion tests/insert.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ describe("insert option CLI", () => {
expect(result.exitCode).toBe(0);
expect(result.stderr).toBe("");
expect(output).toContain(
"Usage: bun run src/cli.ts [--check] [--print] [--insert] [--numbered] [--max-depth <1-6>] [--min-depth <1-6>] [--exclude <text>]... <file>...",
"Usage: bun run src/cli.ts [--check] [--print] [--insert] [--numbered] [--bullet <-|*|+>] [--max-depth <1-6>] [--min-depth <1-6>] [--exclude <text>]... <file>...",
);
expect(insertLine).toBeGreaterThan(printLine);
});
Expand Down
2 changes: 1 addition & 1 deletion tests/numbered.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ describe("numbered table of contents", () => {
expect(help.exitCode).toBe(0);
expect(help.stderr).toBe("");
expect(output.split("\n")[0]).toBe(
"Usage: bun run src/cli.ts [--check] [--print] [--insert] [--numbered] [--max-depth <1-6>] [--min-depth <1-6>] [--exclude <text>]... <file>...",
"Usage: bun run src/cli.ts [--check] [--print] [--insert] [--numbered] [--bullet <-|*|+>] [--max-depth <1-6>] [--min-depth <1-6>] [--exclude <text>]... <file>...",
);
const helpLines = output.split("\n");
const insertLine = helpLines.indexOf(
Expand Down
2 changes: 1 addition & 1 deletion tests/print.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ describe("print mode CLI", () => {
expect(result.exitCode).toBe(0);
expect(result.stderr).toBe("");
expect(output).toContain(
"Usage: bun run src/cli.ts [--check] [--print] [--insert] [--numbered] [--max-depth <1-6>] [--min-depth <1-6>] [--exclude <text>]... <file>...",
"Usage: bun run src/cli.ts [--check] [--print] [--insert] [--numbered] [--bullet <-|*|+>] [--max-depth <1-6>] [--min-depth <1-6>] [--exclude <text>]... <file>...",
);
const checkLine = output.indexOf(
" --check Exit 1 if the TOC is stale; never write the files.",
Expand Down
Loading