diff --git a/README.md b/README.md index 52ae13e..17cdb68 100644 --- a/README.md +++ b/README.md @@ -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: @@ -216,6 +235,7 @@ mdtoc 0.2.0 | `--exclude ` | 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 ` | Use `-`, `*` or `+` for the bullets (default `-`; not with `--numbered`). | | `--version`, `-v` | Print the version from package.json and exit. | ### Add the markers diff --git a/src/cli.ts b/src/cli.ts index d761cbc..6b8d736 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -9,6 +9,7 @@ export interface CliOptions { print: boolean; insert?: boolean; numbered?: boolean; + bullet?: string; version?: boolean; maxDepth: number; minDepth: number; @@ -16,7 +17,7 @@ export interface CliOptions { help: boolean; } -export const USAGE = `Usage: bun run src/cli.ts [--check] [--print] [--insert] [--numbered] [--max-depth <1-6>] [--min-depth <1-6>] [--exclude ]... ... +export const USAGE = `Usage: bun run src/cli.ts [--check] [--print] [--insert] [--numbered] [--bullet <-|*|+>] [--max-depth <1-6>] [--min-depth <1-6>] [--exclude ]... ... Generate a Markdown table of contents between and . ... Markdown files to update (or check). @@ -24,6 +25,7 @@ Generate a Markdown table of contents between and . --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 Leave out headings with this exact text (repeatable). @@ -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=")) @@ -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; } @@ -138,6 +149,7 @@ export async function main(args: string[] = Bun.argv.slice(2)): Promise options.minDepth, options.exclude, options.numbered, + options.bullet, ); if (entries) { console.log(entries); @@ -156,6 +168,7 @@ export async function main(args: string[] = Bun.argv.slice(2)): Promise options.minDepth, options.exclude, options.numbered, + options.bullet, ); if (options.check) { if (updated !== markdown) { diff --git a/src/toc.ts b/src/toc.ts index 38ce887..e254b7f 100644 --- a/src/toc.ts +++ b/src/toc.ts @@ -152,6 +152,7 @@ export function generateToc( minDepth = 1, exclude: readonly string[] = [], numbered = false, + bullet = "-", ): string { validateMaxDepth(maxDepth); validateMinDepth(minDepth); @@ -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; @@ -181,6 +182,7 @@ export function updateToc( minDepth = 1, exclude: readonly string[] = [], numbered = false, + bullet = "-", ): string { validateMaxDepth(maxDepth); validateMinDepth(minDepth); @@ -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}`; } diff --git a/tests/bullet.test.ts b/tests/bullet.test.ts new file mode 100644 index 0000000..5254feb --- /dev/null +++ b/tests/bullet.test.ts @@ -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 = ["", "", "# Guide", "## Usage"].join("\n"); + expect(updateToc(source, 6, 1, [], false, "+")).toBe( + [ + "", + "+ [Guide](#guide)", + " + [Usage](#usage)", + "", + "# 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", "\n\n# Guide\n## Usage\n"); + + expect(await run(["--bullet", "*", "NOTES.md"])).toEqual({ + exitCode: 0, + stdout: "", + stderr: "", + }); + expect(readFileSync(file, "utf8")).toBe( + "\n* [Guide](#guide)\n * [Usage](#usage)\n\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\n* [Guide](#guide)\n * [Usage](#usage)\n\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 ` | Use `-`, `*` or `+` for the bullets (default `-`; not with `--numbered`). |", + ); + }); +}); diff --git a/tests/insert.test.ts b/tests/insert.test.ts index 8678a2a..648999c 100644 --- a/tests/insert.test.ts +++ b/tests/insert.test.ts @@ -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 ]... ...", + "Usage: bun run src/cli.ts [--check] [--print] [--insert] [--numbered] [--bullet <-|*|+>] [--max-depth <1-6>] [--min-depth <1-6>] [--exclude ]... ...", ); expect(insertLine).toBeGreaterThan(printLine); }); diff --git a/tests/numbered.test.ts b/tests/numbered.test.ts index da6933f..e42d9ce 100644 --- a/tests/numbered.test.ts +++ b/tests/numbered.test.ts @@ -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 ]... ...", + "Usage: bun run src/cli.ts [--check] [--print] [--insert] [--numbered] [--bullet <-|*|+>] [--max-depth <1-6>] [--min-depth <1-6>] [--exclude ]... ...", ); const helpLines = output.split("\n"); const insertLine = helpLines.indexOf( diff --git a/tests/print.test.ts b/tests/print.test.ts index ae5c046..bdd5788 100644 --- a/tests/print.test.ts +++ b/tests/print.test.ts @@ -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 ]... ...", + "Usage: bun run src/cli.ts [--check] [--print] [--insert] [--numbered] [--bullet <-|*|+>] [--max-depth <1-6>] [--min-depth <1-6>] [--exclude ]... ...", ); const checkLine = output.indexOf( " --check Exit 1 if the TOC is stale; never write the files.",