diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 75b1ad2..96591b5 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -7,7 +7,7 @@ design is in the "Proposal: Cross-File Reference System" doc (2026-10-19). | Folder | Package | Contents | | ------------------ | ---------------------------- | ------------------------------------------------------------------------ | -| `packages/core/` | `@interref/core` | Comment lexer, scanner, path resolution, Markdown headings, checks. Used by both tools. | +| `packages/core/` | `@interref/core` | Comment lexer, scanner, path resolution, Markdown headings, stamps, checks. Used by both tools. | | `packages/cli/` | `@normal-computing/interref` | The command-line tool. Its commands are `interref` and `iref`. | | `packages/vscode/` | `vscode-interref` | The VS Code extension. Attached to each GitHub release as a `.vsix`. | diff --git a/README.md b/README.md index 8059a62..eadc478 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ iref:./relative/to/this/file iref:../also/relative iref:/some/doc.md#heading-slug iref:#heading-in-this-file +sync:/some/doc.md#heading-slug@3f9a1c2e ``` - A path starts with `/` (from the repo root), `./` or `../` (from the directory of the file that @@ -67,6 +68,7 @@ iref:#heading-in-this-file - Percent-encode spaces, `#` and `%` in paths (`%20`, `%23`, `%25`). - The ref ends at whitespace, a quote, a backtick or a bracket. A trailing `-->`, `*/` or `. , ; : ! ?` is not part of it. +- A ref can end in a [stamp](#stamps): `@` and 8 hex digits. - Write `iref\:` to show the syntax in a comment without making a ref. ### Where a ref counts @@ -143,6 +145,78 @@ Note: some site generators, for example MkDocs, make heading ids differently fro merges repeated hyphens. Use the GitHub form. When a slug is wrong, `interref check` and the editor suggest the nearest correct slug. +### Stamps + +A stamp ends a ref: `@` and the first 8 hex digits of the SHA-256 of the target file's text. It +records the text that someone checked the ref against. When that text changes, `interref check` +fails on the ref (`stale-stamp`), so that someone reads the change and updates the file that holds +the ref. + +```typescript +// TTL must match the docs: sync:/docs/auth.md#token-lifetime@f24671a0 +``` + +- The stamp always covers the whole file. A heading fragment does not change this: a change + anywhere in the file makes the stamp stale. A directory, or a file that is binary or cannot be + read, has no stamp (`invalid-stamp`). +- A byte order mark, line ends, trailing spaces and blank lines do not count. Neither do stamps, + refs in comments, comments that hold only refs, and the spaces next to them. Thus adding a ref to + a file, or stamping one, does not make the stamps of other refs to it stale. +- The other text of comments counts, doc comments and docstrings too: a changed docstring makes the + stamps of the refs to its file stale, also when the docstring holds a ref. +- A ref without a stamp works as before: a change to its target does not fail the check. +- A path that the repo has as written, such as `/lib/v@1a2b3c4d`, is a path, not a stamp. + +Do not write a stamp by hand. `interref stamp ...` writes the current stamp into each +stamped ref in the files, once you have checked that they agree with their targets. +`--add sync` also stamps the `sync:` refs that have no stamp yet: + +```console +$ interref stamp --add sync src config +config/auth.yaml:3:9 sync:/docs/auth.md#token-lifetime stamped @f24671a0 +src/auth/session.ts:1:29 sync:/docs/auth.md#token-lifetime stamped @f24671a0 +2 refs stamped (3 refs in 3 files) +``` + +After a change to the file, `interref check` shows each stale stamp. Under the first one of a file, +it lists every ref in the repo to that file or to one of its headings, also those without a stamp: + +```console +$ interref check +config/auth.yaml:3:9 error sync:/docs/auth.md#token-lifetime@f24671a0 docs/auth.md changed since this ref was stamped [stale-stamp] + refs to docs/auth.md: + config/auth.yaml:3:9 sync:/docs/auth.md#token-lifetime@f24671a0 + src/auth/notes.py:1:7 iref:/docs/auth.md#token-lifetime + src/auth/session.ts:1:29 sync:/docs/auth.md#token-lifetime@f24671a0 +src/auth/session.ts:1:29 error sync:/docs/auth.md#token-lifetime@f24671a0 docs/auth.md changed since this ref was stamped [stale-stamp] +2 broken refs (3 refs in 5 files) +``` + +With `--format json`, each record has its `stamp`, and a stale one also has the list of `refs` to +the file. + +To see what changed, find the commit that wrote the stamp, then compare the target with it: + +```sh +git log -1 --format=%H -S'@f24671a0' -- src/auth/session.ts +git diff -- docs/auth.md +``` + +Update each file in the list to agree with the new text. Then stamp only the refs that you +checked: `--to` keeps the refs to one file and its headings. `--to` with a `#heading` is an error, +because the stamp covers the whole file. + +```console +$ interref stamp src/auth/session.ts config/auth.yaml --to docs/auth.md +config/auth.yaml:3:9 sync:/docs/auth.md#token-lifetime@f24671a0 @f24671a0 -> @9c41e7b2 +src/auth/session.ts:1:29 sync:/docs/auth.md#token-lifetime@f24671a0 @f24671a0 -> @9c41e7b2 +2 refs stamped (2 refs in 2 files) +``` + +A fix that `check` suggests for a moved file or heading keeps the stamp, so `check` still compares +it with the new target. `stamp` does not write through a symlink (the file that it points to is +stamped when it is in the paths too), and does not rewrite a file that is not valid UTF-8. + ## CLI Run it from anywhere in the repo that you want to check: @@ -156,6 +230,7 @@ src/auth/session.ts:3:5 error iref:/docs/auth.md#tokn no heading #tokn in doc | Command | Output | | ------------------------------------- | ------------------------------------------------------------------------ | | `interref check [...]` | Broken refs in the repo, or under the paths. Exit 1 if any. | +| `interref stamp ... [--to ]` | Write the current [stamp](#stamps) into the stamped refs in the paths, or only into those to `` and its headings. `--add P` also stamps the `P:` refs that have none. | | `interref links ... [--to ]` | Refs that the files hold and where each one goes. | | `interref backlinks ...` | Refs in the repo that point at the files or directories. | | `interref graph []` | The link graph: `--format dot` (default), `mermaid`, `json` or `drawio`. | @@ -172,7 +247,9 @@ src/auth/session.ts:3:5 error iref:/docs/auth.md#tokn no heading #tokn in doc | `-v`, `--version` | Show the version. | Exit codes: 0 clean, 1 broken refs, 2 usage, git, config file, network or editor error. `links` and -`backlinks` also exit 1 when a ref that they list is broken. +`backlinks` also exit 1 when a ref that they list is broken, and `stamp` when a ref that it would +stamp is broken, or when it does not write a file: a symlink to a file outside the paths, or a file +that is not valid UTF-8. ### Paths from stdin @@ -265,6 +342,8 @@ source of the guide is [skills/iref/SKILL.md](skills/iref/SKILL.md). | `reserved-authority` | error | The ref uses `iref://` (or `sync://`, …), kept for cross-repo refs. | | `case-mismatch` | error | The path differs from a repo path only by case. | | `invalid-encoding` | error | The percent-encoding is bad. | +| `stale-stamp` | error | The target's text changed since the ref was stamped. | +| `invalid-stamp` | error | The stamp is on a directory, or on a file that is binary or cannot be read. | | `target-ignored` | warn | The target is untracked or ignored by git. | ### Config file diff --git a/packages/cli/src/format.ts b/packages/cli/src/format.ts index ba03f83..db1a6a7 100644 --- a/packages/cli/src/format.ts +++ b/packages/cli/src/format.ts @@ -8,6 +8,12 @@ export function location(record: RefRecord): string { return `${record.source.path}:${record.source.line}:${record.source.col}`; } +/** The line of `check` for a ref that has a problem, with its fixes. */ +export function problemLine(record: RefRecord): string { + const hint = record.suggestions.length > 0 ? ` (fix: ${record.suggestions.join(" or ")})` : ""; + return `${location(record)} ${record.status} ${record.raw} ${record.message ?? ""} [${record.rule ?? ""}]${hint}`; +} + export function describeTarget(record: RefRecord): string { const target = record.target; if (target === undefined) return "?"; @@ -19,8 +25,8 @@ export function describeTarget(record: RefRecord): string { /** The record as the proposal's JSON shape, without editor-only offsets. */ export function recordJson(record: RefRecord): { [key: string]: JsonValue } { const json: { [key: string]: JsonValue } = { - source: { path: record.source.path, line: record.source.line, col: record.source.col }, - raw: record.raw, + ...refJson(record), + ...(record.stamp === undefined ? {} : { stamp: record.stamp }), target: null, status: record.status, }; @@ -37,6 +43,11 @@ export function recordJson(record: RefRecord): { [key: string]: JsonValue } { return json; } +/** Where a ref is written, and the ref. */ +export function refJson(record: RefRecord): { [key: string]: JsonValue } { + return { source: { path: record.source.path, line: record.source.line, col: record.source.col }, raw: record.raw }; +} + /** Prints `values` as one JSON array, or one value per line for ndjson. */ export function printJson(values: readonly JsonValue[], format: "json" | "ndjson"): void { if (format === "json") console.log(JSON.stringify(values, null, 2)); @@ -93,6 +104,8 @@ const RULE_TEXT: Readonly> = { "case-mismatch": "Path differs from a repo path only by case", "unsupported-fragment": "Only heading fragments are supported", "invalid-encoding": "Bad percent-encoding", + "stale-stamp": "Target text changed since the ref was stamped", + "invalid-stamp": "A directory, or a file that is binary or cannot be read, has no stamp", "target-ignored": "Target is untracked or ignored by git", }; diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts index 7965d33..d326e0e 100644 --- a/packages/cli/src/main.ts +++ b/packages/cli/src/main.ts @@ -1,7 +1,7 @@ #!/usr/bin/env node /** interref: outgoing refs, backlinks, broken refs and the link graph of a git repo. */ -import { readFileSync } from "node:fs"; +import { lstatSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs"; import { basename, resolve } from "node:path"; import { parseArgs } from "node:util"; import { @@ -21,7 +21,9 @@ import { describeTarget, location, printJson, + problemLine, recordJson, + refJson, sarif, type ContextOptions, type JsonValue, @@ -48,6 +50,7 @@ Commands: links ... [--to ] Refs written in the files, optionally only those that reach backlinks ... Refs in the repo that point at the files or directories check [...] Report broken refs in the repo or under the paths + stamp ... [--to ] Write the current stamp of the target into each stamped ref in the paths graph [] Export the link graph, whole repo or around one file (> x.drawio) install-extension Install or update the VS Code extension from the newest GitHub release @@ -57,6 +60,8 @@ Options: -C N, -A N, -B N Show N lines of context around each ref where it is written -T N, --show-target N Show N lines of the target, from the heading or the top --format F text | json | ndjson, plus sarif for check; dot | mermaid | json | drawio for graph + --add P stamp: also stamp the P: refs that have no stamp (repeat for more protocols) + --to stamp: only the refs to that file and its headings --editor CMD install-extension: the editor's command (default code; also cursor, windsurf, codium) --prerelease install-extension: also use prereleases --check install-extension: only tell if an update is available @@ -71,6 +76,10 @@ links and backlinks also exit 1 when a ref that they list is broken. Once a day, the CLI asks npm for a newer stable version. INTERREF_NO_UPDATE_CHECK=1 turns this off. A ref starts with a protocol name from the config file: iref: or sync: by default. Only heading fragments (#some-heading) are supported for now. iref is a short name for interref. +A ref can end in a stamp, @ and 8 hex digits of the SHA-256 of its target file's text (iref:/a.md#b@3f9a1c2e). +The stamp covers the whole file, also when the ref has a heading. check fails when the file changes; +stamp writes the new stamp once you have checked the ref. Stamp only the refs that you checked: +--to keeps the refs to one file. The guide is an Agent Skill file. Read it for best practices, or save it as a skill, for example ${NAME} --guide > .claude/skills/iref/SKILL.md or ${NAME} --guide > .agents/skills/iref/SKILL.md @@ -87,6 +96,7 @@ const OPTIONS = { "show-target": { type: "string", short: "T" }, format: { type: "string" }, to: { type: "string" }, + add: { type: "string", multiple: true }, editor: { type: "string" }, prerelease: { type: "boolean" }, check: { type: "boolean" }, @@ -266,34 +276,154 @@ function commandBacklinks(repo: Repo, values: Values, positionals: readonly stri return printRecords(repo, shown, values, outputFormat); } +/** Whether `path` is one of the roots or under one. Without roots (no arguments), every path is. */ +function under(roots: readonly string[] | undefined): (path: string) => boolean { + return (path) => roots === undefined || roots.some((root) => root === "" || path === root || path.startsWith(`${root}/`)); +} + +const plural = (n: number, noun: string): string => `${n} ${noun}${n === 1 ? "" : "s"}`; + function commandCheck(repo: Repo, values: Values, positionals: readonly string[]): number { const outputFormat = format(values.format, ["text", "json", "ndjson", "sarif"] as const); // With -, an empty list checks nothing; with no arguments, the whole repo. const roots = positionals.length === 0 ? undefined : repoPaths(repo, positionals); - const include = (path: string): boolean => - roots === undefined || roots.some((root) => root === "" || path === root || path.startsWith(`${root}/`)); - const scan = scanRepo(repo, include); + const scan = scanRepo(repo, under(roots)); const problems = scan.records.filter((record) => record.status !== "ok"); const errors = problems.filter((record) => record.status === "error").length; + // A file that changed since a stamp, and every ref in the repo to it or to one of its headings: + // each one may need the change. + const changed = (record: RefRecord): string | undefined => (record.rule === "stale-stamp" ? record.targetPath : undefined); + const all = roots !== undefined && problems.some((record) => changed(record) !== undefined) ? scanRepo(repo).records : scan.records; + const refsTo = (path: string): RefRecord[] => all.filter((ref) => ref.target?.path === path && ref.target.kind === "file"); if (outputFormat === "sarif") console.log(JSON.stringify(sarif(problems), null, 2)); - else if (outputFormat !== "text") printJson(problems.map(recordJson), outputFormat); - else { + else if (outputFormat !== "text") { + const json = problems.map((record) => { + const path = changed(record); + return path === undefined ? recordJson(record) : { ...recordJson(record), refs: refsTo(path).map(refJson) }; + }); + printJson(json, outputFormat); + } else { const context = contextOptions(values); + // The refs to a changed file show once, under its first stale stamp. + const listed = new Set(); for (const record of problems) { - const hint = record.suggestions.length > 0 ? ` (fix: ${record.suggestions.join(" or ")})` : ""; - console.log(`${location(record)} ${record.status} ${record.raw} ${record.message ?? ""} [${record.rule ?? ""}]${hint}`); + console.log(problemLine(record)); for (const extra of contextBlock(repo, record, context)) console.log(extra); + const path = changed(record); + if (path === undefined || listed.has(path)) continue; + listed.add(path); + console.log(` refs to ${path}:`); + for (const ref of refsTo(path)) console.log(` ${location(ref)} ${ref.raw}`); } const warnings = problems.length - errors; - const files = `${scan.filesScanned} file${scan.filesScanned === 1 ? "" : "s"}`; - const parts = [`${errors} broken ref${errors === 1 ? "" : "s"}`]; - if (warnings > 0) parts.push(`${warnings} warning${warnings === 1 ? "" : "s"}`); - console.log(`${parts.join(", ")} (${scan.records.length} refs in ${files})`); + const parts = [plural(errors, "broken ref")]; + if (warnings > 0) parts.push(plural(warnings, "warning")); + console.log(`${parts.join(", ")} (${scan.records.length} refs in ${plural(scan.filesScanned, "file")})`); } return errors > 0 ? 1 : 0; } +/** The file of `stamp --to`. A heading is an error: a stamp covers the whole file. */ +function stampTarget(repo: Repo, argument: string): string { + const hash = argument.indexOf("#"); + const path = repo.relative(resolve(hash < 0 ? argument : argument.slice(0, hash))); + if (hash >= 0 && path !== undefined && repo.kind(path) === "file") { + throw new UsageError(`--to ${argument}: give the file without #heading, since a stamp covers the whole file`); + } + return repoPath(repo, argument); +} + +/** + * Writes the current stamp of the target into each stamped ref in the paths, and into the refs of + * the `--add` protocols that have none. `--to` keeps only the refs to one file. A broken + * ref is not stamped: it shows as in `check`. + */ +function commandStamp(repo: Repo, values: Values, positionals: readonly string[]): number { + format(values.format, ["text"] as const); + if (positionals.length === 0) throw new UsageError("stamp needs a path"); + const add = new Set(values.add); + for (const protocol of add) { + if (!repo.config.protocols.includes(protocol)) { + throw new UsageError(`--add ${protocol}: the protocols are ${repo.config.protocols.join(", ")}`); + } + } + const to = values.to === undefined ? undefined : stampTarget(repo, values.to); + const wanted = (record: RefRecord): boolean => + (record.stamp !== undefined || add.has(record.raw.slice(0, record.raw.indexOf(":")))) && + (to === undefined || record.targetPath === to); + const scan = scanRepo(repo, under(repoPaths(repo, positionals))); + // The new stamps, by the file that holds the refs. + const edits = new Map(); + let broken = 0; + for (const record of scan.records) { + if (!wanted(record)) continue; + const target = record.target; + const usable = record.status !== "error" || record.rule === "stale-stamp"; + const stamp = usable && target?.kind === "file" ? repo.stamp(target.path) : undefined; + if (stamp === undefined) { + // A ref to a directory has no stamp; only a ref that already has one is an error. + if (record.status === "error") { + console.log(problemLine(record)); + broken++; + } + continue; + } + if (stamp === record.stamp) continue; + const list = edits.get(record.source.path) ?? []; + list.push({ record, stamp }); + edits.set(record.source.path, list); + } + + // The files written so far, by their device and inode (a hard link has its own real path), or by + // their real path where the file system gives no inode. A symlink is not written through: the file + // that it points to is written when it is in the paths too. A file that two paths reach is written + // once: a second write would put its stamps at the offsets of the text before the first. + const written = new Map(); + let stamped = 0; + let refused = 0; + for (const [path, list] of edits) { + const file = repo.absolute(path); + if (lstatSync(file).isSymbolicLink()) { + const target = repo.relative(file); + if (target === undefined || !edits.has(target)) { + console.log(`${path} not stamped: a symlink; stamp the file that it points to`); + refused++; + } + continue; + } + const { dev, ino } = statSync(file, { bigint: true }); + const real = ino === 0n ? realpathSync.native(file) : `${dev}:${ino}`; + const same = written.get(real); + if (same !== undefined) { + console.log(`${path} not stamped: the same file as ${same}`); + continue; + } + // Reading replaces the bytes that are not UTF-8, so writing the text back would change them. + let text = repo.text(path) ?? ""; + if (!Buffer.from(text, "utf8").equals(readFileSync(file))) { + console.log(`${path} not stamped: it is not valid UTF-8, and stamp would change its bytes`); + refused++; + continue; + } + for (const { record, stamp } of list.toReversed()) { + const unstamped = record.stamp === undefined ? record.raw : record.raw.slice(0, -record.stamp.length - 1); + text = `${text.slice(0, record.start)}${unstamped}@${stamp}${text.slice(record.end)}`; + } + writeFileSync(file, text); + written.set(real, path); + for (const { record, stamp } of list) { + console.log(`${location(record)} ${record.raw} ${record.stamp === undefined ? "stamped" : `@${record.stamp} ->`} @${stamp}`); + } + stamped += list.length; + } + const parts = [`${plural(stamped, "ref")} stamped`]; + if (broken > 0) parts.push(plural(broken, "broken ref")); + if (refused > 0) parts.push(`${plural(refused, "file")} not stamped`); + console.log(`${parts.join(", ")} (${plural(scan.records.length, "ref")} in ${plural(scan.filesScanned, "file")})`); + return broken > 0 || refused > 0 ? 1 : 0; +} + function commandGraph(repo: Repo, values: Values, positionals: readonly string[]): number { const outputFormat = format(values.format, ["dot", "mermaid", "json", "drawio"] as const); if (positionals.length > 1) throw new UsageError("graph takes at most one file"); @@ -338,6 +468,7 @@ const COMMANDS: Readonly { }); }); +describe("stamps", () => { + let repo = ""; + const run = (...args: string[]): { code: number | null; stdout: string; stderr: string } => { + const result = spawnSync(process.execPath, [CLI, ...args], { cwd: repo, encoding: "utf8" }); + return { code: result.status, stdout: result.stdout, stderr: result.stderr }; + }; + const read = (path: string): string => readFileSync(join(repo, path), "utf8"); + // The stamp of docs/spec.md: its lines without the blank ones. It covers the whole file, also in a ref to a heading. + const spec = createHash("sha256") + .update("# Spec\n## Tokens\nA token lasts 15 minutes.\n## Sessions\nA session ends after 8 hours.") + .digest("hex") + .slice(0, 8); + + before(() => { + repo = realpathSync(mkdtempSync(join(tmpdir(), "refs-stamps-"))); + const files: Record = { + ".interref.toml": 'yaml-values = ["model/**"]\n', + "docs/spec.md": "# Spec\n\n## Tokens\n\nA token lasts 15 minutes.\n\n## Sessions\n\nA session ends after 8 hours.\n", + "src/model.py": "# sync:/docs/spec.md#tokens@00000000\nTOKEN_MINUTES = 15\n", + "src/notes.ts": "// iref:/docs/spec.md#tokens\n", + "model/limits.yaml": "tokens:\n spec: sync:/docs/spec.md#tokens\n", + "docs/index.md": "\n\n\n", + }; + for (const [path, content] of Object.entries(files)) { + mkdirSync(dirname(join(repo, path)), { recursive: true }); + writeFileSync(join(repo, path), content); + } + execFileSync("git", ["init", "-q"], { cwd: repo }); + execFileSync("git", ["add", "-A"], { cwd: repo }); + }); + + after(() => rmSync(repo, { recursive: true, force: true })); + + it("check fails on a stale stamp and lists every ref to the changed file and to its headings", () => { + const { code, stdout } = run("check"); + assert.equal(code, 1); + assert.equal( + stdout, + [ + "src/model.py:1:3 error sync:/docs/spec.md#tokens@00000000 docs/spec.md changed since this ref was stamped [stale-stamp]", + " refs to docs/spec.md:", + " docs/index.md:1:6 iref:/docs/spec.md", + " docs/index.md:2:6 iref:/docs/spec.md#spec", + " docs/index.md:3:6 iref:/docs/spec.md#sessions", + " model/limits.yaml:2:9 sync:/docs/spec.md#tokens", + " src/model.py:1:3 sync:/docs/spec.md#tokens@00000000", + " src/notes.ts:1:4 iref:/docs/spec.md#tokens", + "1 broken ref (6 refs in 6 files)", + "", + ].join("\n"), + ); + }); + + it("check --format json gives the stamp and the refs to the changed file", () => { + const json = JSON.parse(run("check", "src", "--format", "json").stdout) as { + stamp?: string; + rule?: string; + refs?: { source: { path: string; line: number; col: number }; raw: string }[]; + }[]; + assert.equal(json.length, 1); + assert.equal(json[0]?.stamp, "00000000"); + assert.equal(json[0]?.rule, "stale-stamp"); + assert.deepEqual( + json[0]?.refs?.map((ref) => `${ref.source.path}:${ref.source.line}:${ref.source.col} ${ref.raw}`), + [ + "docs/index.md:1:6 iref:/docs/spec.md", + "docs/index.md:2:6 iref:/docs/spec.md#spec", + "docs/index.md:3:6 iref:/docs/spec.md#sessions", + "model/limits.yaml:2:9 sync:/docs/spec.md#tokens", + "src/model.py:1:3 sync:/docs/spec.md#tokens@00000000", + "src/notes.ts:1:4 iref:/docs/spec.md#tokens", + ], + ); + }); + + it("stamp writes the current stamps, and --add stamps the refs of a protocol that have none", () => { + const { code, stdout } = run("stamp", "src", "model", "--add", "sync"); + assert.equal(code, 0); + assert.equal( + stdout, + [ + `model/limits.yaml:2:9 sync:/docs/spec.md#tokens stamped @${spec}`, + `src/model.py:1:3 sync:/docs/spec.md#tokens@00000000 @00000000 -> @${spec}`, + "2 refs stamped (3 refs in 3 files)", + "", + ].join("\n"), + ); + assert.equal(read("src/model.py"), `# sync:/docs/spec.md#tokens@${spec}\nTOKEN_MINUTES = 15\n`); + assert.equal(read("model/limits.yaml"), `tokens:\n spec: sync:/docs/spec.md#tokens@${spec}\n`); + assert.equal(read("src/notes.ts"), "// iref:/docs/spec.md#tokens\n"); + assert.equal(run("check").code, 0); + assert.match(run("stamp", "src").stdout, /^0 refs stamped \(2 refs in 2 files\)$/mu); + }); + + it("stamp --to stamps only the refs to that file, to any of its headings", () => { + writeFileSync( + join(repo, "src/sessions.py"), + "# sync:/docs/spec.md#sessions@00000000\n# sync:/docs/spec.md@00000000\n# sync:/src/notes.ts@00000000\n", + ); + const { code, stdout } = run("stamp", "src", "--to", "docs/spec.md"); + assert.equal(code, 0); + assert.equal( + stdout, + [ + `src/sessions.py:1:3 sync:/docs/spec.md#sessions@00000000 @00000000 -> @${spec}`, + `src/sessions.py:2:3 sync:/docs/spec.md@00000000 @00000000 -> @${spec}`, + "2 refs stamped (5 refs in 3 files)", + "", + ].join("\n"), + ); + assert.equal( + read("src/sessions.py"), + `# sync:/docs/spec.md#sessions@${spec}\n# sync:/docs/spec.md@${spec}\n# sync:/src/notes.ts@00000000\n`, + ); + }); + + it("stamp rejects an --add protocol that the config does not have, and --to with a heading", () => { + const { code, stderr } = run("stamp", "src", "--add", "nope"); + assert.equal(code, 2); + assert.match(stderr, /^interref: --add nope: the protocols are iref, sync$/mu); + const heading = run("stamp", "src", "--to", "docs/spec.md#tokens"); + assert.equal(heading.code, 2); + assert.match( + heading.stderr, + /^interref: --to docs\/spec\.md#tokens: give the file without #heading, since a stamp covers the whole file$/mu, + ); + }); +}); + +describe("stamp writes each file once, and only valid UTF-8", () => { + let repo = ""; + const spec = createHash("sha256") + .update("# Spec\n## Tokens\nA token lasts 15 minutes.\n## Sessions\nA session ends after 8 hours.") + .digest("hex") + .slice(0, 8); + const latin1 = Buffer.from("# caf\u00e9 sync:/docs/spec.md#tokens\n", "latin1"); + + before(() => { + repo = realpathSync(mkdtempSync(join(tmpdir(), "refs-stamp-files-"))); + mkdirSync(join(repo, "docs")); + mkdirSync(join(repo, "src")); + writeFileSync(join(repo, "docs/spec.md"), "# Spec\n\n## Tokens\n\nA token lasts 15 minutes.\n\n## Sessions\n\nA session ends after 8 hours.\n"); + writeFileSync(join(repo, "src/model.py"), "# sync:/docs/spec.md#tokens\nTOKEN_MINUTES = 15 # sync:/docs/spec.md#sessions\n"); + symlinkSync("model.py", join(repo, "src/link.py")); + mkdirSync(join(repo, "lib")); + writeFileSync(join(repo, "lib/other.py"), "# sync:/docs/spec.md#tokens\n"); + symlinkSync("../lib/other.py", join(repo, "src/other.py")); + writeFileSync(join(repo, "src/latin1.py"), latin1); + execFileSync("git", ["init", "-q"], { cwd: repo }); + execFileSync("git", ["add", "-A"], { cwd: repo }); + }); + + after(() => rmSync(repo, { recursive: true, force: true })); + + it("skips a symlink and a file that is not valid UTF-8, and exits 1 unless the symlink's file is in the paths", () => { + const result = spawnSync(process.execPath, [CLI, "stamp", "src", "--add", "sync"], { cwd: repo, encoding: "utf8" }); + assert.equal(result.status, 1); + assert.equal( + result.stdout, + [ + "src/latin1.py not stamped: it is not valid UTF-8, and stamp would change its bytes", + `src/model.py:1:3 sync:/docs/spec.md#tokens stamped @${spec}`, + `src/model.py:2:23 sync:/docs/spec.md#sessions stamped @${spec}`, + "src/other.py not stamped: a symlink; stamp the file that it points to", + "2 refs stamped, 2 files not stamped (6 refs in 4 files)", + "", + ].join("\n"), + ); + assert.equal(readFileSync(join(repo, "lib/other.py"), "utf8"), "# sync:/docs/spec.md#tokens\n"); + assert.equal( + readFileSync(join(repo, "src/model.py"), "utf8"), + `# sync:/docs/spec.md#tokens@${spec}\nTOKEN_MINUTES = 15 # sync:/docs/spec.md#sessions@${spec}\n`, + ); + assert.deepEqual(readFileSync(join(repo, "src/latin1.py")), latin1); + }); +}); + +describe("stamp writes a file that two hard links reach once", () => { + let repo = ""; + const spec = createHash("sha256").update("# Spec").digest("hex").slice(0, 8); + + before(() => { + repo = realpathSync(mkdtempSync(join(tmpdir(), "refs-stamp-links-"))); + mkdirSync(join(repo, "docs")); + mkdirSync(join(repo, "src")); + writeFileSync(join(repo, "docs/spec.md"), "# Spec\n"); + writeFileSync(join(repo, "src/a.py"), "# sync:/docs/spec.md\n"); + linkSync(join(repo, "src/a.py"), join(repo, "src/b.py")); + execFileSync("git", ["init", "-q"], { cwd: repo }); + execFileSync("git", ["add", "-A"], { cwd: repo }); + }); + + after(() => rmSync(repo, { recursive: true, force: true })); + + it("stamps the refs of the first path, and skips the second", () => { + const result = spawnSync(process.execPath, [CLI, "stamp", "src", "--add", "sync"], { cwd: repo, encoding: "utf8" }); + assert.equal(result.status, 0); + assert.equal( + result.stdout, + [ + `src/a.py:1:3 sync:/docs/spec.md stamped @${spec}`, + "src/b.py not stamped: the same file as src/a.py", + "1 ref stamped (2 refs in 2 files)", + "", + ].join("\n"), + ); + assert.equal(readFileSync(join(repo, "src/b.py"), "utf8"), `# sync:/docs/spec.md@${spec}\n`); + }); +}); + describe("usage errors", () => { it("exit 2", () => { assert.equal(refs().code, 2); diff --git a/packages/core/src/check.ts b/packages/core/src/check.ts index 6d953d5..c7791ba 100644 --- a/packages/core/src/check.ts +++ b/packages/core/src/check.ts @@ -12,6 +12,7 @@ import { type HeadingFragment, type RuleId, } from "./resolve.js"; +import { literalPath } from "./stamp.js"; import { LineIndex, type RefMatch } from "./syntax.js"; export type Status = "ok" | "warn" | "error"; @@ -30,6 +31,8 @@ export interface RefRecord { /** Offsets of `raw` in the source text. */ readonly start: number; readonly end: number; + /** The stamp at the end of `raw`, without `@`. */ + readonly stamp?: string; /** Set when the path resolved to something that exists, even if the ref has a problem. */ readonly target?: ResolvedTarget; /** The repo path that the ref names, set when the path is valid, also when nothing is there. */ @@ -83,13 +86,15 @@ export function similarPaths(repo: Repo, path: string): string[] { } /** Checks one ref written in `source` (a repo-relative path), with the rule settings of the config. */ -export function checkRef(repo: Repo, source: string, match: RefMatch, lines: LineIndex): RefRecord { +export function checkRef(repo: Repo, source: string, written: RefMatch, lines: LineIndex): RefRecord { + const match = literalPath(repo, source, written); const position = lines.position(match.start); let base: Omit = { source: { path: source, ...position }, raw: match.raw, start: match.start, end: match.end, + ...(match.stamp === undefined ? {} : { stamp: match.stamp }), }; const problem = (rule: RuleId, message: string, suggestions: readonly string[] = [], target?: ResolvedTarget): RefRecord => { const setting = repo.config.rules[rule] ?? RULE_SEVERITY[rule]; @@ -99,15 +104,19 @@ export function checkRef(repo: Repo, source: string, match: RefMatch, lines: Lin }; const fragmentSuffix = match.fragment === undefined ? "" : `#${match.fragment}`; + // A fix keeps the stamp, so that check still compares it with the new target. + const stampSuffix = match.stamp === undefined ? "" : `@${match.stamp}`; const resolved = resolveTarget(source, match.path, match.protocol); if (!resolved.ok) { - const suggestions = resolved.problem.rule === "bare-path" ? [`${match.protocol}:./${match.path}${fragmentSuffix}`] : []; + const suggestions = + resolved.problem.rule === "bare-path" ? [`${match.protocol}:./${match.path}${fragmentSuffix}${stampSuffix}`] : []; return problem(resolved.problem.rule, resolved.problem.message, suggestions); } const { path, style, trailingSlash } = resolved.value; base = { ...base, targetPath: path }; - const rewrite = (to: string, kind: EntryKind, slug = match.fragment): string => + const format = (to: string, kind: EntryKind, slug = match.fragment): string => formatRef(source, to, { style, directory: kind === "directory" && trailingSlash, slug, protocol: match.protocol }); + const rewrite = (to: string, kind: EntryKind, slug = match.fragment): string => format(to, kind, slug) + stampSuffix; let kind = repo.kind(path); let warning: { rule: RuleId; message: string } | undefined; @@ -173,6 +182,16 @@ export function checkRef(repo: Repo, source: string, match: RefMatch, lines: Lin target = { ...target, line: heading.line }; } + // A stamp covers the whole file, also in a ref to one of its headings. + if (match.stamp !== undefined) { + const stamp = kind === "file" ? repo.stamp(path) : undefined; + if (stamp === undefined) { + const what = kind === "directory" ? "a directory" : "a file that is binary or cannot be read"; + return problem("invalid-stamp", `${what} has no stamp`, [format(path, kind)], target); + } + if (stamp !== match.stamp) return problem("stale-stamp", `${path} changed since this ref was stamped`, [], target); + } + if (warning !== undefined) return problem(warning.rule, warning.message, [], target); return { ...base, target, status: "ok", suggestions: [] }; } diff --git a/packages/core/src/repo.ts b/packages/core/src/repo.ts index 6bbdcd5..7cfd79e 100644 --- a/packages/core/src/repo.ts +++ b/packages/core/src/repo.ts @@ -1,4 +1,4 @@ -/** A snapshot of one git repo: which paths exist, which are tracked, and their headings. */ +/** A snapshot of one git repo: which paths exist, which are tracked, their headings and stamps. */ import { execFile } from "node:child_process"; import { readdirSync, readFileSync, realpathSync, statSync } from "node:fs"; @@ -6,6 +6,8 @@ import { dirname, isAbsolute, join, relative, sep } from "node:path"; import { promisify } from "node:util"; import { DEFAULT_CONFIG, excluder, globToRegExp, loadConfig, type Config } from "./config.js"; import { extractHeadings, isMarkdownPath, type Heading } from "./markdown.js"; +import { literalPath, stampLines, stampOf } from "./stamp.js"; +import type { RefMatch } from "./syntax.js"; const run = promisify(execFile); @@ -63,6 +65,10 @@ export class Repo { private readonly byLowerCase = new Map(); private readonly children = new Map>(); private readonly headingCache = new Map(); + /** By path: the stamp of the file, undefined when the file is not text. */ + private readonly stampCache = new Map(); + /** By the real path of a file, the cached paths that are symlinks to it, so that `invalidate` forgets them too. */ + private readonly linksTo = new Map>(); private readonly excluded: (path: string) => boolean; private readonly yamlValues: readonly RegExp[]; @@ -216,6 +222,15 @@ export class Repo { return this.readText(this.absolute(path)); } + /** Notes the real path of a path that is about to be cached, when it is a symlink. */ + private noteLink(path: string): void { + const real = this.relative(this.absolute(path)); + if (real === undefined || real === path) return; + const links = this.linksTo.get(real) ?? new Set(); + links.add(path); + this.linksTo.set(real, links); + } + /** The headings of a Markdown file, cached until `invalidate`. Other files have none. */ headings(path: string): readonly Heading[] { if (!isMarkdownPath(path)) return []; @@ -223,14 +238,47 @@ export class Repo { if (headings === undefined) { const text = this.text(path); headings = text === undefined ? [] : extractHeadings(text); + this.noteLink(path); this.headingCache.set(path, headings); } return headings; } - /** Forgets cached headings for one path, or for all paths. */ - invalidate(path?: string): void { - if (path === undefined) this.headingCache.clear(); - else this.headingCache.delete(path); + /** + * The stamp of a file, cached until `invalidate`. Stamps, refs in comments and the comments that + * hold only refs do not count (see `stampLines`). Undefined for a file that is binary or cannot be + * read. + */ + stamp(path: string): string | undefined { + if (this.stampCache.has(path)) return this.stampCache.get(path); + const text = this.text(path); + let stamp: string | undefined; + if (text !== undefined) { + const read = (ref: RefMatch): RefMatch => literalPath(this, path, ref); + stamp = stampOf(stampLines(path, text, this.config.protocols, this.readsYamlValues(path), read)); + } + this.noteLink(path); + this.stampCache.set(path, stamp); + return stamp; + } + + /** + * Forgets cached headings and stamps for one path, and for the symlinks to it, or for all paths. + * Returns whether it forgot any, that is whether a ref that was checked may now resolve differently. + */ + invalidate(path?: string): boolean { + if (path === undefined) { + const cached = this.headingCache.size > 0 || this.stampCache.size > 0; + this.headingCache.clear(); + this.stampCache.clear(); + this.linksTo.clear(); + return cached; + } + let forgot = false; + for (const each of [path, ...(this.linksTo.get(path) ?? [])]) { + if (this.headingCache.delete(each)) forgot = true; + if (this.stampCache.delete(each)) forgot = true; + } + return forgot; } } diff --git a/packages/core/src/resolve.ts b/packages/core/src/resolve.ts index e5e0dd6..7f19861 100644 --- a/packages/core/src/resolve.ts +++ b/packages/core/src/resolve.ts @@ -12,6 +12,8 @@ export type RuleId = | "case-mismatch" | "unsupported-fragment" | "invalid-encoding" + | "stale-stamp" + | "invalid-stamp" | "target-ignored"; export type Severity = "error" | "warn"; @@ -25,6 +27,8 @@ export const RULE_SEVERITY: Readonly> = { "case-mismatch": "error", "unsupported-fragment": "error", "invalid-encoding": "error", + "stale-stamp": "error", + "invalid-stamp": "error", "target-ignored": "warn", }; diff --git a/packages/core/src/stamp.ts b/packages/core/src/stamp.ts new file mode 100644 index 0000000..b04955e --- /dev/null +++ b/packages/core/src/stamp.ts @@ -0,0 +1,143 @@ +/** + * Stamps. A ref can end in `@` and 8 hex digits, for example `#tokens@3f9a1c2e`: the start of the + * SHA-256 of the text of its target file when someone last checked the ref. A heading fragment does + * not change what the stamp covers: it is always the whole file. When the file changes, the stamp no + * longer matches, and `check` reports the ref. + */ + +import { createHash } from "node:crypto"; +import { commentSpans, findRefs, type Span } from "./comments.js"; +import type { Repo } from "./repo.js"; +import { resolveTarget } from "./resolve.js"; +import { DEFAULT_PROTOCOLS, scanRefs, type RefMatch } from "./syntax.js"; + +/** The spaces after a removed comment or ref. */ +const SPACES = /[ \t]*/uy; + +/** A letter or a digit. A comment that has none besides its refs and its markers holds only refs. */ +const WORD = /[\p{L}\p{N}]/u; + +/** + * The comment markers that have letters, at the start of a comment: `REM` in Batch and VB, `=begin` + * in Ruby, `=pod` and `=begin comment` or `=for comment` in Perl, `\begin{comment}` in LaTeX, + * `{% comment %}` in Jinja, `#+begin_comment` in Org, and the prefix of a Python docstring such as + * `r"""`. They are not words of the comment. + */ +const OPEN_MARKER = + /^[ \t@]*(?:rem(?=[ \t]|$)|=(?:begin|for)[ \t]+comment\b|=[a-z]\w*|\\begin\{comment\}|\{%-?[ \t]*comment[ \t]*-?%\}|#\+begin_comment|[rubft]{1,2}(?=["']))/iu; + +/** + * The comment markers that have letters, at the end of a comment, as `OPEN_MARKER`. In Perl, the + * `=end comment` before `=cut` is one too. + */ +const CLOSE_MARKER = + /(?:(? b` reads `a b` and `text ref"""` reads `text"""`. A line in the middle of a comment + * that has no letters or digits besides its refs does not count either, with a ref or without one, + * such as ` *` in a doc comment: so adding the line ` * ref`, or writing the ref on a line ` *`, does + * not change the stamp. The other text of comments counts, doc comments and docstrings too. With `values` + * (a YAML file that the config names in `yaml-values`), a ref in a value counts, but its stamp does + * not; `read` tells a stamp from the end of a path such as `/lib/v@1a2b3c4d` (see `literalPath`). A + * removed span keeps its line breaks, so the text before it and after it stays on separate lines. A + * byte order mark, line ends (also a lone `\r`) and trailing spaces do not count. The byte order mark + * is removed before the comments are found, so that it does not hide a docstring on the first line. + */ +export function stampLines( + path: string, + source: string, + protocols: readonly string[] = DEFAULT_PROTOCOLS, + values = false, + read: (ref: RefMatch) => RefMatch = (ref) => ref, +): string[] { + const text = source.replace(/^\uFEFF/u, ""); + const removed: Span[] = []; + // Removes a span and the spaces after it, or the spaces before it when none follow. + const remove = (start: number, end: number): void => { + SPACES.lastIndex = end; + const after = SPACES.exec(text)?.[0].length ?? 0; + let first = start; + if (after === 0) while (first > 0 && (text[first - 1] === " " || text[first - 1] === "\t")) first--; + removed.push({ start: first, end: end + after }); + }; + for (const comment of commentSpans(path, text) ?? []) { + const body = text.slice(comment.start, comment.end); + const refs = scanRefs(body, protocols); + const rest = withoutRefs(body, refs, 0); + if (refs.length > 0 && !WORD.test(rest.replace(OPEN_MARKER, "").replace(CLOSE_MARKER, ""))) { + remove(comment.start, comment.end); + continue; + } + for (const line of middleLines(text, comment)) { + const onLine = refs.filter((ref) => comment.start + ref.start >= line.start && comment.start + ref.end <= line.end); + if (!WORD.test(withoutRefs(text.slice(line.start, line.end), onLine, line.start - comment.start))) removed.push(line); + } + for (const ref of refs) remove(comment.start + ref.start, comment.start + ref.end); + } + if (values) { + for (const ref of findRefs(path, text, protocols, true)) { + const stamp = ref.stamp === undefined ? undefined : read(ref).stamp; + if (stamp !== undefined) removed.push({ start: ref.end - stamp.length - 1, end: ref.end }); + } + } + let kept = ""; + let at = 0; + for (const span of removed.sort((a, b) => a.start - b.start)) { + if (span.end <= at) continue; + const start = Math.max(span.start, at); + kept += text.slice(at, start) + text.slice(start, span.end).replace(/[^\r\n]+/gu, ""); + at = span.end; + } + kept += text.slice(at); + // Each line of the file, with the lines that a lone `\r` makes joined by `\n` and blank ones dropped. + return kept.split("\n").map((line) => + line + .split("\r") + .map((part) => part.trimEnd()) + .filter((part) => part !== "") + .join("\n"), + ); +} + +/** The lines of a comment after its first line break and before its last one. */ +function middleLines(text: string, comment: Span): Span[] { + const lines: Span[] = []; + const breaks = /\r\n?|\n/gu; + breaks.lastIndex = comment.start; + let start: number | undefined; + for (let found = breaks.exec(text); found !== null && found.index < comment.end; found = breaks.exec(text)) { + if (start !== undefined) lines.push({ start, end: found.index }); + start = found.index + found[0].length; + } + return lines; +} + +/** `text` without `refs`, whose offsets are from `offset` before the start of `text`. */ +function withoutRefs(text: string, refs: readonly RefMatch[], offset: number): string { + return refs.reduceRight((kept, ref) => kept.slice(0, ref.start - offset) + kept.slice(ref.end - offset), text); +} + +/** + * The stamp of a file from its `stampLines`. Blank lines do not count, so with `stampLines`, adding a + * ref to the text does not change its stamp. + */ +export function stampOf(lines: readonly string[]): string { + const kept = lines.filter((line) => line !== ""); + return createHash("sha256").update(kept.join("\n")).digest("hex").slice(0, 8); +} diff --git a/packages/core/src/syntax.ts b/packages/core/src/syntax.ts index e5b37f2..b893d80 100644 --- a/packages/core/src/syntax.ts +++ b/packages/core/src/syntax.ts @@ -27,8 +27,16 @@ export interface RefMatch { readonly path: string; /** The fragment without `#`, or undefined when the ref has no fragment. */ readonly fragment: string | undefined; + /** The stamp without `@`, or undefined when the ref has no stamp. */ + readonly stamp: string | undefined; } +/** + * A stamp ends a ref: `@` and 8 hex digits of the SHA-256 of the target's text (see `stamp.ts`). + * A path or a fragment comes before it, so `iref:@3f9a1c2e` is a bare path, as it was before stamps. + */ +const STAMP = /(?<=[^:#])@([0-9a-f]{8})$/u; + const TRAILING_PUNCTUATION = /[.,;:!?]$/u; /** @@ -63,14 +71,17 @@ export function scanRefs(text: string, protocols: readonly string[] = DEFAULT_PR const raw = trimRef(text, start, match[0], prefixLength); // A prefix with no path and no fragment, such as `# iref: ` in Python, is not a ref. if (raw.length === prefixLength) continue; - const hash = raw.indexOf("#"); + const stamp = STAMP.exec(raw)?.[1]; + const target = stamp === undefined ? raw : raw.slice(0, -stamp.length - 1); + const hash = target.indexOf("#"); refs.push({ raw, protocol, start, end: start + raw.length, - path: hash < 0 ? raw.slice(prefixLength) : raw.slice(prefixLength, hash), - fragment: hash < 0 ? undefined : raw.slice(hash + 1), + path: hash < 0 ? target.slice(prefixLength) : target.slice(prefixLength, hash), + fragment: hash < 0 ? undefined : target.slice(hash + 1), + stamp, }); } return refs; diff --git a/packages/core/test/check.test.ts b/packages/core/test/check.test.ts index 5974d85..0657ac5 100644 --- a/packages/core/test/check.test.ts +++ b/packages/core/test/check.test.ts @@ -1,4 +1,5 @@ import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; import { mkdirSync, renameSync } from "node:fs"; import { join } from "node:path"; import { after, before, describe, it } from "node:test"; @@ -21,8 +22,10 @@ describe("checkText", () => { "src/db/config.go": "package db\n", "src/db/pool.go": "// iref:./config.go\n", "src/Readme.md": "# Readme\n", + "assets/logo.png": "\u0089PNG\r\n\u001a\n\u0000\u0000", + "lib/a@3f9a1c2e": "text\n", }, - { "notes/draft.md": "# Draft\n", "build/out.txt": "x\n" }, + { "notes/draft.md": "# Draft\n", "build/out.txt": "x\n", "build/v@1a2b3c4d": "x\n" }, ); repo = await Repo.open(fixture.root); }); @@ -111,6 +114,46 @@ describe("checkText", () => { assert.equal(only("docs/a.md", "iref:/docs/auth.md/").rule, "missing-file"); }); + it("checks stamps, and keeps the stamp in a fix", () => { + // A stamp covers the whole file, also in a ref to one of its headings. + const auth = createHash("sha256").update("# Auth\n## Token lifetime\nText.").digest("hex").slice(0, 8); + assert.equal(only("src/auth/session.ts", `iref:/docs/auth.md#token-lifetime@${auth}`).status, "ok"); + assert.equal(only("src/auth/session.ts", `iref:/docs/auth.md@${auth}`).status, "ok"); + const stale = only("src/auth/session.ts", "iref:/docs/auth.md#token-lifetime@00000000"); + assert.equal(stale.rule, "stale-stamp"); + assert.equal(stale.message, "docs/auth.md changed since this ref was stamped"); + assert.equal(stale.stamp, "00000000"); + // A fix keeps the stamp, so that the next check compares it with the new target. + assert.deepEqual(only("docs/tokens.md", "iref:./auth.md#token-lifetimes@00000000").suggestions, [ + "iref:./auth.md#token-lifetime@00000000", + ]); + assert.deepEqual(only("src/db/pool.go", "iref:./confg.go@00000000").suggestions, ["iref:./config.go@00000000"]); + assert.deepEqual(only("src/db/pool.go", "sync:config.go@00000000").suggestions, ["sync:./config.go@00000000"]); + assert.deepEqual(only("docs/a.md", "iref:/src/readme.md@00000000").suggestions, ["iref:/src/Readme.md@00000000"]); + }); + + it("reports a stamp on a directory or a binary file, with the ref without it as the fix", () => { + const directory = only("docs/a.md", "iref:/src/db/@00000000"); + assert.equal(directory.rule, "invalid-stamp"); + assert.deepEqual(directory.suggestions, ["iref:/src/db/"]); + const binary = only("docs/a.md", "iref:/assets/logo.png@00000000"); + assert.equal(binary.rule, "invalid-stamp"); + assert.equal(binary.message, "a file that is binary or cannot be read has no stamp"); + assert.deepEqual(binary.suggestions, ["iref:/assets/logo.png"]); + }); + + it("reads a path that ends in @ and 8 hex digits as a path when the repo has it, and a ref with nothing before @ as before", () => { + const literal = only("docs/a.md", "iref:/lib/a@3f9a1c2e"); + assert.equal(literal.status, "ok"); + assert.equal(literal.stamp, undefined); + assert.equal(literal.target?.path, "lib/a@3f9a1c2e"); + assert.equal(only("docs/a.md", "iref:/lib/b@3f9a1c2e").rule, "missing-file"); + const ignored = only("docs/a.md", "iref:/build/v@1a2b3c4d"); + assert.equal(ignored.rule, "target-ignored"); + assert.equal(ignored.stamp, undefined); + assert.equal(only("docs/a.md", "iref:@3f9a1c2e").rule, "bare-path"); + }); + it("finds refs only in comments", () => { const text = [ "// see iref:/docs/auth.md", diff --git a/packages/core/test/stamp.test.ts b/packages/core/test/stamp.test.ts new file mode 100644 index 0000000..8c278b0 --- /dev/null +++ b/packages/core/test/stamp.test.ts @@ -0,0 +1,144 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { symlinkSync } from "node:fs"; +import { join } from "node:path"; +import { after, before, describe, it } from "node:test"; +import { Repo } from "../src/repo.js"; +import { stampLines, stampOf } from "../src/stamp.js"; +import { DEFAULT_PROTOCOLS } from "../src/syntax.js"; +import { makeRepo } from "./fixture.js"; + +const sha = (text: string): string => createHash("sha256").update(text).digest("hex").slice(0, 8); + +describe("stamps", () => { + const stamp = (text: string, path = "docs/spec.md"): string => stampOf(stampLines(path, text)); + const spec = "# Spec\n\n## Tokens\n\nA token lasts 15 minutes.\n\n## Sessions\n\nA session ends after 8 hours.\n"; + + it("hashes the whole file, without line ends, trailing spaces, blank lines and comments with a ref", () => { + const expected = sha("# Spec\n## Tokens\nA token lasts 15 minutes.\n## Sessions\nA session ends after 8 hours."); + assert.equal(stamp(spec), expected); + const edited = spec + .replace("A token lasts 15 minutes.", "A token lasts 15 minutes. \n\n") + .replace("A session ends", "A session ends") + .replaceAll("\n", "\r\n"); + assert.equal(stamp(`\uFEFF${edited}`), expected); + assert.equal(stamp(spec.replaceAll("\n", "\r")), expected); + // A change in any section changes the stamp. + assert.notEqual(stamp(spec.replace("8 hours", "9 hours")), expected); + assert.notEqual(stamp(spec.replace("15 minutes", "30 minutes")), expected); + }); + + it("counts the comments that hold no ref, doc comments and docstrings too", () => { + assert.notEqual(stamp(spec.replace("A token lasts 15 minutes.", "A token lasts 15 minutes. ")), stamp(spec)); + const model = '"""A token lasts 15 minutes."""\nTOKEN_MINUTES = 15 # sync:/docs/spec.md#tokens@3f9a1c2e\n'; + assert.equal(stamp(model, "src/model.py"), sha('"""A token lasts 15 minutes."""\nTOKEN_MINUTES = 15')); + assert.notEqual(stamp(model.replace("15 minutes", "30 minutes"), "src/model.py"), stamp(model, "src/model.py")); + }); + + it("counts the other text of a comment that holds a ref, but not the ref and the spaces next to it", () => { + const model = (docstring: string): string => stamp(`${docstring}\nTOKEN_MINUTES = 15\n`, "src/model.py"); + const plain = model('"""Tokens last 15 minutes."""'); + assert.equal(model('"""Tokens last 15 minutes. sync:/docs/spec.md#tokens@3f9a1c2e"""'), plain); + assert.notEqual(model('"""Tokens last 30 minutes. sync:/docs/spec.md#tokens@3f9a1c2e"""'), plain); + const note = spec.replace("A token lasts 15 minutes.", "A token lasts 15 minutes. "); + assert.equal(stamp(note.replace("configurable -->", "configurable sync:/src/x.py -->")), stamp(note)); + assert.equal(stamp(note.replace("TTL is", "TTL iref:/src/x.py is")), stamp(note)); + assert.notEqual(stamp(note.replace("configurable", "fixed")), stamp(note)); + }); + + it("does not count a line of a doc comment that holds only a ref and the comment's leader", () => { + const code = (comment: string): string => stamp(`${comment}\nexport const TTL = 15;\n`, "src/model.ts"); + const plain = code("/**\n * Token lifetime.\n */"); + assert.equal(code("/**\n * Token lifetime.\n * sync:/docs/spec.md@3f9a1c2e\n */"), plain); + assert.equal(code("/**\n * Token lifetime.\n * - sync:/docs/spec.md iref:/docs/a.md\n */"), plain); + assert.equal(stamp("/* Token lifetime.\n * iref:/a.md\n */\nx;\n", "src/a.c"), stamp("/* Token lifetime.\n */\nx;\n", "src/a.c")); + // A ref on a line that holds only the leader, and a line with the leader alone, do not count. + const separated = "/**\n * Token lifetime.\n *\n * Details.\n */"; + assert.equal(code(separated.replace(" *\n", " * sync:/docs/spec.md\n")), code(separated)); + assert.equal(code(separated), code("/**\n * Token lifetime.\n * Details.\n */")); + assert.equal(code(separated.replaceAll("\n", "\r")), code(separated)); + // The words on the line of a ref still count. + assert.notEqual(code("/**\n * Token lifetime.\n * See sync:/docs/spec.md\n */"), plain); + }); + + it("does not count a comment that holds only refs and markers that have letters", () => { + const same = (path: string, code: string, comment: string): void => { + assert.equal(stamp(`${code}${comment}\n`, path), stamp(code, path), `${path}: ${comment}`); + }; + same("run.bat", "@echo off\nset TTL=15\n", "REM iref:/a.py"); + same("run.bat", "@echo off\nset TTL=15\n", "@rem iref:/a.py"); + same("model.vb", "Dim ttl = 15\n", "Rem iref:/a.py"); + same("model.rb", "TTL = 15\n", "=begin\niref:/a.py\n=end"); + same("model.pl", "my $ttl = 15;\n", "=pod\n\niref:/a.py\n\n=cut"); + same("model.pl", "my $ttl = 15;\n", "=begin comment\n\niref:/a.py\n\n=end comment\n\n=cut"); + same("model.pl", "my $ttl = 15;\n", "=for comment iref:/a.py\n\n=cut"); + same("model.py", "TTL = 15\n", 'r"""iref:/a.py"""'); + // A marker word that is not at the start or the end of the comment still counts. + assert.notEqual(stamp("x = 1\n# rem iref:/a.py\n", "model.py"), stamp("x = 1\n", "model.py")); + assert.notEqual(stamp("TTL = 15\n=head1 NAME\niref:/a.py\n=cut\n", "model.pl"), stamp("TTL = 15\n", "model.pl")); + }); + + it("finds the comments after it removes a byte order mark", () => { + const model = '"""sync:/docs/spec.md"""\nx = 1\n'; + assert.equal(stamp(`\uFEFF${model}`, "src/model.py"), stamp(model, "src/model.py")); + assert.equal(stamp(model, "src/model.py"), sha("x = 1")); + }); + + it("finds the same comments as check when a string holds a lone line end", () => { + // check finds this ref, so stamp writes a stamp into it: the stamp of the file must not change. + const code = 'char *s = "a\r"; // sync:/docs/spec.md\nint y;\n'; + assert.equal(stamp(code.replace("spec.md", "spec.md@3f9a1c2e"), "src/a.c"), stamp(code, "src/a.c")); + }); + + it("leaves out the stamps of the refs in the values of a YAML file, but not the refs", () => { + const yaml = (ref: string): string[] => stampLines("model/limits.yaml", `tokens:\n spec: ${ref}\n`, DEFAULT_PROTOCOLS, true); + assert.deepEqual(yaml("sync:/docs/spec.md#tokens@3f9a1c2e"), yaml("sync:/docs/spec.md#tokens")); + assert.notDeepEqual(yaml("sync:/docs/spec.md#sessions"), yaml("sync:/docs/spec.md#tokens")); + }); +}); + +describe("Repo.stamp", () => { + let fixture: ReturnType; + + before(() => { + fixture = makeRepo({ + ".interref.toml": 'yaml-values = ["model/**"]\n', + "docs/spec.md": "# Spec\n\n## Tokens\n\nA token lasts 15 minutes.\n", + "src/model.py": "TOKEN_MINUTES = 15\n", + "lib/a@3f9a1c2e": "text\n", + "model/a1.yaml": "path: iref:/lib/a@3f9a1c2e\n", + "model/a2.yaml": "path: iref:/lib/a@00000000\n", + "model/b1.yaml": "path: iref:/lib/b@3f9a1c2e\n", + "model/b2.yaml": "path: iref:/lib/b@00000000\n", + }); + symlinkSync("spec.md", join(fixture.root, "docs/current.md")); + }); + after(() => fixture.dispose()); + + it("counts the end of a path such as /lib/a@3f9a1c2e in a YAML value, but not a stamp", async () => { + const repo = await Repo.open(fixture.root); + assert.notEqual(repo.stamp("model/a1.yaml"), repo.stamp("model/a2.yaml")); + assert.equal(repo.stamp("model/b1.yaml"), repo.stamp("model/b2.yaml")); + }); + + it("forgets the stamps and headings of a symlink when the file that it points to changes", async () => { + const repo = await Repo.open(fixture.root); + assert.equal(repo.stamp("docs/current.md"), repo.stamp("docs/spec.md")); + assert.equal(repo.invalidate("docs/spec.md"), true); + assert.equal(repo.invalidate("docs/spec.md"), false); + assert.equal(repo.headings("docs/current.md").length, 2); + assert.equal(repo.invalidate("docs/spec.md"), true); + }); + + it("caches the stamps of a file, and invalidate tells whether it forgot any", async () => { + const repo = await Repo.open(fixture.root); + assert.equal(repo.invalidate("docs/spec.md"), false); + assert.equal(repo.stamp("docs/spec.md"), sha("# Spec\n## Tokens\nA token lasts 15 minutes.")); + assert.equal(repo.invalidate("src/model.py"), false); + assert.equal(repo.invalidate("docs/spec.md"), true); + assert.equal(repo.invalidate("docs/spec.md"), false); + assert.equal(repo.stamp("src/model.py"), sha("TOKEN_MINUTES = 15")); + assert.equal(repo.invalidate(), true); + assert.equal(repo.invalidate(), false); + }); +}); diff --git a/packages/core/test/syntax.test.ts b/packages/core/test/syntax.test.ts index 7465e0e..0c6e1a9 100644 --- a/packages/core/test/syntax.test.ts +++ b/packages/core/test/syntax.test.ts @@ -11,6 +11,25 @@ describe("scanRefs", () => { assert.deepEqual(raws("-- mirrored in iref:/src/models/user.py"), ["iref:/src/models/user.py"]); }); + it("splits a stamp off the end of a ref, and reads a ref without one as before", () => { + const parts = (text: string): unknown[] => + scanRefs(text).map((ref) => [ref.raw, ref.path, ref.fragment, ref.stamp]); + assert.deepEqual(parts("sync:/a.md#b@3f9a1c2e iref:/a.md@3f9a1c2e."), [ + ["sync:/a.md#b@3f9a1c2e", "/a.md", "b", "3f9a1c2e"], + ["iref:/a.md@3f9a1c2e", "/a.md", undefined, "3f9a1c2e"], + ]); + assert.deepEqual(parts("iref:/a.md#b iref:/lib/@scope/x.ts iref:/a@3F9A1C2E"), [ + ["iref:/a.md#b", "/a.md", "b", undefined], + ["iref:/lib/@scope/x.ts", "/lib/@scope/x.ts", undefined, undefined], + ["iref:/a@3F9A1C2E", "/a@3F9A1C2E", undefined, undefined], + ]); + // With nothing before `@`, there is no stamp, so the ref is wrong as it was before stamps. + assert.deepEqual(parts("iref:@3f9a1c2e iref:/a.md#@3f9a1c2e"), [ + ["iref:@3f9a1c2e", "@3f9a1c2e", undefined, undefined], + ["iref:/a.md#@3f9a1c2e", "/a.md", "@3f9a1c2e", undefined], + ]); + }); + it("splits path and fragment", () => { const [ref] = scanRefs("x iref:../api.md#auth y"); assert.equal(ref?.path, "../api.md"); diff --git a/packages/vscode/README.md b/packages/vscode/README.md index 76867e6..2800d25 100644 --- a/packages/vscode/README.md +++ b/packages/vscode/README.md @@ -4,7 +4,8 @@ This extension makes `iref:` links in comments clickable, and it shows broken li - Cmd/Ctrl+click a ref to open its target. A heading fragment opens the file at that heading. - Hover over a ref to see the start of its target. -- Broken refs show in Problems. Cmd/Ctrl+. offers fixes. +- Broken refs and stale stamps show in Problems. Cmd/Ctrl+. offers fixes. After you check a ref with a + stale stamp, run `interref stamp --to ` to write the new stamp. - "Copy ref" in the editor or explorer context menu copies `iref:/path#heading`. - In a comment, or in a YAML value that can be a ref, type `iref:/`, `iref:./` or `#` to get completions for paths and headings. `iref:`, `sync:` and the other protocols in the config file diff --git a/packages/vscode/src/extension.ts b/packages/vscode/src/extension.ts index 5f61e59..9ba37c4 100644 --- a/packages/vscode/src/extension.ts +++ b/packages/vscode/src/extension.ts @@ -37,15 +37,19 @@ export function activate(context: vscode.ExtensionContext): void { }), ); - // Headings live in file text, so edits to one file can fix or break refs in another. + // Headings and stamps live in file text, so edits to one file can fix or break refs in another. repos.onDidChange(() => diagnostics.scheduleAll(), undefined, context.subscriptions); context.subscriptions.push( vscode.workspace.onDidOpenTextDocument((document) => diagnostics.schedule(document, 0)), - vscode.workspace.onDidCloseTextDocument((document) => diagnostics.forget(document)), + vscode.workspace.onDidCloseTextDocument((document) => { + diagnostics.forget(document); + // Closed without saving: the cache may hold headings and stamps of the unsaved text. + repos.invalidate(document.uri); + }), vscode.workspace.onDidChangeTextDocument((event) => { if (event.contentChanges.length === 0) return; diagnostics.schedule(event.document); - if (isMarkdownPath(event.document.uri.fsPath)) repos.invalidate(event.document.uri); + repos.invalidate(event.document.uri); }), vscode.workspace.onDidChangeConfiguration((event) => { if (!event.affectsConfiguration("interref")) return; @@ -67,7 +71,7 @@ export function activate(context: vscode.ExtensionContext): void { watcher.onDidDelete(refreshSoon), watcher.onDidChange((uri) => { if (INDEX_FILES.has(basename(uri.fsPath))) refreshSoon(); - else if (isMarkdownPath(uri.fsPath)) repos.invalidate(uri); + else repos.invalidate(uri); }), { dispose: () => clearTimeout(refreshTimer) }, ); diff --git a/packages/vscode/src/repos.ts b/packages/vscode/src/repos.ts index b2cbe40..fba1ba8 100644 --- a/packages/vscode/src/repos.ts +++ b/packages/vscode/src/repos.ts @@ -82,14 +82,18 @@ export class Repos implements vscode.Disposable { this.changed.fire(); } - /** Forgets cached headings of a file that changed. */ + /** + * Forgets cached headings and stamps of a file that changed. Fires `onDidChange` only when there + * were some, since a file that no checked ref has read cannot change how refs resolve. + */ invalidate(uri: vscode.Uri): void { if (uri.scheme !== "file") return; + let forgot = false; for (const repo of this.loaded) { const path = repo.relative(uri.fsPath); - if (path !== undefined) repo.invalidate(path); + if (path !== undefined && repo.invalidate(path)) forgot = true; } - this.changed.fire(); + if (forgot) this.changed.fire(); } dispose(): void { diff --git a/skills/iref/SKILL.md b/skills/iref/SKILL.md index 1fd0f21..23e5ee6 100644 --- a/skills/iref/SKILL.md +++ b/skills/iref/SKILL.md @@ -1,6 +1,6 @@ --- name: iref -description: Add, edit and check interref links (iref:, sync:) between files of a git repo. Use when you write a comment that points to another file, spec section or doc heading; when two files must stay in sync (for example a spec and its model); when you move, rename or delete a file or heading in a repo that has refs; when you review a change or a pull request for inconsistency between linked files; or when you run `iref check`, `iref links`, `iref backlinks` or `iref graph`. +description: Add, edit, stamp and check interref links (iref:, sync:) between files of a git repo. Use when you write a comment that points to another file, spec section or doc heading; when two files must stay in sync (for example a spec and its model); when you move, rename or delete a file or heading in a repo that has refs; when `iref check` reports a stale stamp; when you review a change or a pull request for inconsistency between linked files; or when you run `iref check`, `iref stamp`, `iref links`, `iref backlinks` or `iref graph`. --- # Use iref @@ -28,6 +28,7 @@ iref:../also/relative iref:/some/doc.md#heading-slug iref:#heading-in-this-file iref:/some/directory/ +sync:/some/doc.md#heading-slug@3f9a1c2e ``` - Use `iref:#heading` only in a Markdown file. Other files have no headings. @@ -53,6 +54,25 @@ headings. For example, `## Faults, overflow and reset` becomes are errors. Point to the most specific heading that the code depends on, not only to the page. +### Stamps + +A ref can end in a stamp: `@` and 8 hex digits of the SHA-256 of the target +file's text, as in `sync:/docs/auth.md#token-lifetime@f24671a0`. The stamp says +that someone checked the ref against that text. When the text changes, +`iref check` fails on the ref (`stale-stamp`). + +- The stamp always covers the whole file, also when the ref has a heading. A + change anywhere in the file makes the stamp stale. A directory, or a file + that is binary or cannot be read, has no stamp (`invalid-stamp`). +- Line ends, trailing spaces, blank lines, stamps, refs in comments and the + comments that hold only refs do not count. Adding a ref to a file does not + make other stamps stale. The other text of comments counts, docstrings too. +- A ref without a stamp works as before. +- Never write or change a stamp by hand. Stamp only the refs that you + reviewed: after you checked the refs in a file to a target, run + `iref stamp --to `. `--add sync` also stamps the `sync:` + refs that have none. + ## Put the ref in a comment A ref counts only in a comment, with one exception: in the YAML files that @@ -122,7 +142,8 @@ repo root. | Command | Use | |---|---| -| `iref check [...]` | Find broken refs. Exit 1 if there is one. Each error tells the rule and, if possible, a fix. | +| `iref check [...]` | Find broken refs. Exit 1 if there is one. Each error tells the rule and, if possible, a fix. Under a stale stamp, it lists every ref to the changed file and to its headings. | +| `iref stamp ... --to ` | Write the current stamp into each stamped ref in the paths to that file and its headings (no `--to`: all). Add `--add sync` to also stamp the `sync:` refs that have none. Exit 1 if one of them is broken or a file is not written. | | `iref links ...` | Show the refs in the files and their targets. Exit 1 if one is broken. | | `iref links --to ` | Show only the refs that reach the second file. Add `-r` to see each chain. | | `iref backlinks ...` | Show the refs in the repo that point to the files or directories. Exit 1 if one is broken. Give a path without `#fragment`. | @@ -147,7 +168,9 @@ lines around each ref), `-T N` (show the first N lines of the target), of the file. 4. Run `iref check`. Fix all errors. A new target file gives a `target-ignored` warning until you `git add` it. -5. Run the project's tests and docs build. A changed docstring or an HTML +5. If the other refs of the same protocol in the repo have stamps, stamp the + new ones: `iref stamp --add sync --to `. +6. Run the project's tests and docs build. A changed docstring or an HTML comment can change output that a check reads. ### Move or rename a file or a heading @@ -167,12 +190,43 @@ lines around each ref), `-T N` (show the first N lines of the target), If there is no fix, use the refs that you recorded in step 1 and the new path or heading. +5. A fix keeps the stamp of the ref. If the text of the target changed, for + example a renamed heading, the stamp is now stale: follow "Fix a stale + stamp". ### Change a file that has sync refs 1. Run `iref links ` and `iref backlinks `. 2. For each `sync:` link, read the other file and update it to agree with your change. +3. Run `iref check`. A stamp on a ref to the file that you changed is now + stale. Follow "Fix a stale stamp". + +### Fix a stale stamp + +1. Run `iref check`. Under the first stale stamp of a file, it lists every ref + in the repo to that file or to one of its headings, also the refs without a + stamp. +2. Find what changed in the file since the ref was stamped. Find the commit + that wrote the stamp, then compare the target with it: + + ```sh + git log -1 --format=%H -S'@' -- + git diff -- + ``` + +3. For each ref in the list, read the file that holds it and update the file + to agree with the target. A change in one section of the target can be + unrelated to a ref to another heading: then the file needs no update, but + still stamp the ref. If you are not sure that it agrees, tell the user and + do not stamp it. +4. Run `iref check`. Fix the errors other than the stale stamps that you + checked. +5. Run `iref stamp ... --to ` with the files that + you checked. Stamp only the refs that you reviewed: the stamp says that + its file agrees with the target. Without `--to`, `iref stamp` also stamps + the other stamped refs in the files. +6. Run `iref check` again. ### Check a set of changes for inconsistency @@ -196,9 +250,9 @@ changed | iref backlinks - # refs to the changed files: the target changed ``` 1. Run the two commands. Each one exits 1 if a ref that it lists is broken. - Fix the broken refs. `iref check` with no paths shows all problems, also the - ones that were there before the change. Do not fix those unless the user - asks. + Fix the broken refs. For a stale stamp, follow "Fix a stale stamp". + `iref check` with no paths shows all problems, also the ones that were + there before the change. Do not fix those unless the user asks. 2. Keep only the `sync:` links: add `| grep ' sync:'` to each command. A line that is in the output of both commands is a link where both sides changed: `{ changed | iref links -; changed | iref backlinks -; } | sort | uniq -d`. @@ -241,6 +295,8 @@ heading fragment, so you can filter by `#heading-slug`. | `escapes-root` | `..` goes above the repo root. | | `case-mismatch` | The path differs from a repo path only in case. | | `invalid-encoding` | The percent-encoding is bad. | +| `stale-stamp` | The target's text changed since the ref was stamped. | +| `invalid-stamp` | The stamp is on a directory, or on a file that is binary or cannot be read. | | `reserved-authority` | The ref uses `iref://`, which is kept for cross-repo refs. | | `target-ignored` (warning) | The target is untracked or ignored by git. |