diff --git a/.gitignore b/.gitignore index 90eb999..6e2240d 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ release/ # Copied from the repo root when a package is packed. packages/*/LICENSE +packages/*/THIRD-PARTY-NOTICES # Copied from the repo README when the CLI is packed. packages/vscode/README.md is its own file. packages/cli/README.md .DS_Store diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index b35b318..75b1ad2 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -45,6 +45,12 @@ comment marker does not start a comment. To add a language, add an entry to `EXT `NAMES`, and reuse a language that has the same rules or make one with `language(...)`. Add a test to `packages/core/test/comments.test.ts` with a ref in a comment and a ref in a string. +In the YAML files that the config names in `yaml-values`, a whole value can also be a ref. To find +the values, `packages/core/src/values.ts` uses the [`yaml`](https://eemeli.org/yaml/) parser, which +has no dependencies of its own. esbuild bundles it into the CLI and the extension, so both packages +ship its license in `THIRD-PARTY-NOTICES`. When a bundle takes in another package, add its license +there too. + To check the lexer on real code, compare it with Shiki, which has the TextMate grammars of VS Code. Shiki is a dev dependency only: it is not in the CLI or the extension. @@ -66,8 +72,8 @@ the lexer, on repos that use the languages you changed. That file is the whole npm package, so it has no dependencies at run time. esbuild also writes the version from `package.json` into the bundle, for `--version` and the update check, and the agent guide `skills/iref/SKILL.md`, for `--guide`. It adds the version to the guide's frontmatter as -`metadata.interref-version`, so do not write a `metadata` key in `SKILL.md`. `prepack` copies the repo README and LICENSE into -`packages/cli`, so the npm page shows the README. +`metadata.interref-version`, so do not write a `metadata` key in `SKILL.md`. `prepack` copies the repo README, LICENSE and +THIRD-PARTY-NOTICES into `packages/cli`, so the npm page shows the README. `scripts/npm-readme.mjs` changes the relative links in the copy to GitHub URLs. `packages/cli/src/update.ts` has the network code. The update check reads the `latest` dist-tag diff --git a/README.md b/README.md index ae9de56..8059a62 100644 --- a/README.md +++ b/README.md @@ -71,8 +71,9 @@ iref:#heading-in-this-file ### Where a ref counts -A ref counts only in a comment. interref ignores the same text in a string, in code, in Markdown -text and in a code block. Thus an example in a test string or in a README is not a link: +A ref counts only in a comment, with one exception: in the YAML files that the config file names, a +value can also be a ref (see below). interref ignores the same text in a string, in code, in +Markdown text and in a code block. Thus an example in a test string or in a README is not a link: ```python # iref:/docs/auth.md <- a ref @@ -87,6 +88,19 @@ url = "iref:/docs/auth.md" # not a ref: it is in a string first line of a `def` or `class` body. An f-string is not a docstring. - In GraphQL, a `"""` description is a comment. - In JSON, a ref counts in a `//` or `/* */` comment (as in `tsconfig.json`). +- In YAML, a value can also be a ref, but only in the files that the `yaml-values` key of the + [config file](#config-file) names. interref reads these files with a YAML parser. The value must + be exactly one ref, and it can be plain or in quotes. Examples are + `spec: sync:/docs/auth.md#token-lifetime` and `- "iref:/docs/auth.md"`. An item of a `[...]` list + also counts, as in `specs: [sync:/docs/auth.md, sync:/docs/api.md]`, and so does a list that goes + across lines. The value can be on the line under its key, and it can have an anchor or a tag + before it. The ref must be the whole value, and the value must be on one line. In these cases, + the text is not a ref: + - `note: see sync:/docs/auth.md`, because the value has other text before the ref. + - `note: sync:/docs/auth.md, and more`, because the value has other text after the ref. + - A `|` or `>` block. + - A plain value that continues on the next line, or that continues the line before it. + - A key, as in `sync:/docs/auth.md: text`. interref finds the language from the file extension or the file name (for example `Dockerfile`, `Makefile`, `CMakeLists.txt`). A file with no extension can name its language in a `#!` line. A file @@ -255,13 +269,16 @@ source of the guide is [skills/iref/SKILL.md](skills/iref/SKILL.md). ### Config file -The config file at the repo root sets which files are not scanned, which protocols start a ref, and -the rule levels. It can have one of these names: `interref.toml`, `.interref.toml`, `interref.json` -or `.interref.json`. Use only one of them; two or more config files is an error. +The config file at the repo root sets four things: the files that interref does not scan, the +protocols that start a ref, the YAML files in which a value can be a ref, and the rule levels. The +config file can have one of these names: +`interref.toml`, `.interref.toml`, `interref.json` or `.interref.json`. Use only one of them; two or +more config files is an error. ```toml exclude = ["vendor/**", "**/*.min.js"] protocols = ["iref", "sync"] # the default +yaml-values = ["config/**/*.yaml"] # in these YAML files, a value can be a ref [rules] target-ignored = "off" # "off", "warn" or "error" @@ -273,6 +290,7 @@ The same config as JSON: { "exclude": ["vendor/**", "**/*.min.js"], "protocols": ["iref", "sync"], + "yaml-values": ["config/**/*.yaml"], "rules": { "target-ignored": "off" } } ``` @@ -292,7 +310,7 @@ an excluded file still resolve. | Problems | Broken refs get a red or yellow underline (`interref.diagnostics.enabled`). | | Quick fix | Cmd/Ctrl+. on a broken ref offers the suggested refs. | | Copy ref | Right-click in an editor or the explorer. Copies `iref:/path`, plus `#slug` of the heading above the cursor in Markdown. | -| Completion | In a comment, type `iref:/` or `iref:./` for paths, and `#` after a Markdown path for headings. | +| Completion | In a comment or a YAML value that can be a ref, type `iref:/` or `iref:./` for paths, and `#` after a Markdown path for headings. | | Graph | "interref: Show ref graph" (command palette, editor or explorer context menu). Pick 1 or 2 hops around the file, or the whole repo. | ### Graph preview diff --git a/THIRD-PARTY-NOTICES b/THIRD-PARTY-NOTICES new file mode 100644 index 0000000..5295bca --- /dev/null +++ b/THIRD-PARTY-NOTICES @@ -0,0 +1,21 @@ +The interref CLI and the interref VS Code extension bundle the following +third-party software. Its license asks for the notice below in every copy. + +-------------------------------------------------------------------------------- + +yaml (https://github.com/eemeli/yaml) +ISC License + +Copyright Eemeli Aro + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. diff --git a/packages/cli/esbuild.mjs b/packages/cli/esbuild.mjs index 6976f2c..0cd4e41 100644 --- a/packages/cli/esbuild.mjs +++ b/packages/cli/esbuild.mjs @@ -25,5 +25,8 @@ await build({ INTERREF_VERSION: JSON.stringify(manifest.version), INTERREF_GUIDE: JSON.stringify(guide), }, + // The yaml package that core uses is CommonJS, and it requires Node modules such as `process`. + // An ES module has no `require`, so the bundle makes one. + banner: { js: 'import { createRequire } from "node:module";\nconst require = createRequire(import.meta.url);' }, logLevel: "warning", }); diff --git a/packages/cli/package.json b/packages/cli/package.json index 761acd8..91f4ac4 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -23,7 +23,8 @@ "iref": "./dist/interref.mjs" }, "files": [ - "dist/interref.mjs" + "dist/interref.mjs", + "THIRD-PARTY-NOTICES" ], "publishConfig": { "access": "public" @@ -33,7 +34,7 @@ }, "scripts": { "bundle": "node esbuild.mjs", - "prepack": "cp ../../LICENSE . && node ../../scripts/npm-readme.mjs", + "prepack": "cp ../../LICENSE ../../THIRD-PARTY-NOTICES . && node ../../scripts/npm-readme.mjs", "test": "node --test \"dist/test/**/*.test.js\"" }, "devDependencies": { diff --git a/packages/core/package.json b/packages/core/package.json index 6bf4063..b196a9b 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -15,6 +15,9 @@ "scripts": { "test": "node --test \"dist/test/**/*.test.js\"" }, + "dependencies": { + "yaml": "^2.9.1" + }, "devDependencies": { "@types/node": "catalog:" } diff --git a/packages/core/src/check.ts b/packages/core/src/check.ts index 567fc93..6d953d5 100644 --- a/packages/core/src/check.ts +++ b/packages/core/src/check.ts @@ -178,12 +178,13 @@ export function checkRef(repo: Repo, source: string, match: RefMatch, lines: Lin } /** - * Scans and checks every ref in the comments of one file. A file that the config excludes, or - * whose language is not known, has none. + * Scans and checks every ref in the comments of one file. If the file is a YAML file that the + * config names in `yaml-values`, it also scans and checks the refs in the YAML values. A file has + * no refs if the config excludes it or if its language is not known. */ export function checkText(repo: Repo, source: string, text: string): RefRecord[] { if (repo.isExcluded(source)) return []; - const matches = findRefs(source, text, repo.config.protocols); + const matches = findRefs(source, text, repo.config.protocols, repo.readsYamlValues(source)); if (matches.length === 0) return []; const lines = new LineIndex(text); return matches.map((match) => checkRef(repo, source, match, lines)); diff --git a/packages/core/src/comments.ts b/packages/core/src/comments.ts index 6077c35..2472750 100644 --- a/packages/core/src/comments.ts +++ b/packages/core/src/comments.ts @@ -6,11 +6,13 @@ * marker does not start a comment. The lexer is not a parser. It knows enough of each language to * tell a comment from a string, which is the only question that it has to answer. The language comes * from the file name, or from the `#!` line of a file that has no known extension. A file of an - * unknown language has no comments, so it has no refs. + * unknown language has no comments, so it has no refs. In the YAML files that the config names, a + * value can also be a ref, if the whole value is one ref (see `values.ts`). */ import { posix } from "node:path"; import { DEFAULT_PROTOCOLS, scanRefs, type RefMatch } from "./syntax.js"; +import { yamlValueRefs, yamlValueStartAt } from "./values.js"; /** Offsets of one comment, its markers included (UTF-16 code units). */ export interface Span { @@ -682,8 +684,26 @@ export function commentSpans(path: string, text: string): Span[] | undefined { return comments; } -/** Returns every ref in the comments of `text`, in order. `path` selects the language. */ -export function findRefs(path: string, text: string, protocols: readonly string[] = DEFAULT_PROTOCOLS): RefMatch[] { +/** + * In a YAML file, returns where the value that the cursor at `offset` is in starts, so that the VS + * Code completion can offer paths for a ref that starts a value. See `yamlValueStartAt`. Other files + * have none. + */ +export function valueStartAt(path: string, text: string, offset: number): number | undefined { + return languageOf(path, text) === YAML ? yamlValueStartAt(text, offset) : undefined; +} + +/** + * Returns every ref in the comments of `text`, in order. `path` selects the language. If `values` + * is true and the file is YAML, it also returns the refs that are the whole value of a scalar, + * plain or in quotes. + */ +export function findRefs( + path: string, + text: string, + protocols: readonly string[] = DEFAULT_PROTOCOLS, + values = false, +): RefMatch[] { if (!protocols.some((name) => text.includes(`${name}:`))) return []; const refs: RefMatch[] = []; for (const span of commentSpans(path, text) ?? []) { @@ -691,5 +711,6 @@ export function findRefs(path: string, text: string, protocols: readonly string[ refs.push({ ...ref, start: ref.start + span.start, end: ref.end + span.start }); } } - return refs; + if (!values || languageOf(path, text) !== YAML) return refs; + return [...refs, ...yamlValueRefs(text, protocols)].sort((a, b) => a.start - b.start); } diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts index 7bb9e5e..6e97a36 100644 --- a/packages/core/src/config.ts +++ b/packages/core/src/config.ts @@ -3,11 +3,12 @@ * * exclude = ["vendor/**", "**\/*.min.js"] * protocols = ["iref", "sync"] + * yaml-values = ["model/**\/*.yaml"] * * [rules] * target-ignored = "warn" * - * A `.json` file holds the same keys: `{ "exclude": [...], "protocols": [...], "rules": {...} }`. + * A `.json` file holds the same keys: `{ "exclude": [...], "protocols": [...], "yaml-values": [...], "rules": {...} }`. */ import { join } from "node:path"; @@ -24,10 +25,15 @@ export interface Config { readonly exclude: readonly string[]; /** The names before `:` that start a ref, for example `iref` in `iref:/a.md`. */ readonly protocols: readonly string[]; + /** + * Globs of the YAML files in which a value can be a ref, not only a comment. The whole value must + * be one ref. + */ + readonly yamlValues: readonly string[]; readonly rules: Readonly>>; } -export const DEFAULT_CONFIG: Config = { exclude: [], protocols: DEFAULT_PROTOCOLS, rules: {} }; +export const DEFAULT_CONFIG: Config = { exclude: [], protocols: DEFAULT_PROTOCOLS, yamlValues: [], rules: {} }; export class ConfigError extends Error {} @@ -75,6 +81,7 @@ export function parseConfig(text: string, file = "interref.toml"): Config { function parseTomlConfig(text: string, file: string): Config { const exclude: string[] = []; let protocols: string[] | undefined; + const yamlValues: string[] = []; const rules: Partial> = {}; let table = ""; const lines = text.split(/\r?\n/u); @@ -93,7 +100,7 @@ function parseTomlConfig(text: string, file: string): Config { const key = pair[1]; let value = pair[2]; - if (table === "" && (key === "exclude" || key === "protocols")) { + if (table === "" && (key === "exclude" || key === "protocols" || key === "yaml-values")) { // Arrays may span lines: keep reading until the closing bracket. while (!value.trimEnd().endsWith("]") && i + 1 < lines.length) { i++; @@ -104,6 +111,7 @@ function parseTomlConfig(text: string, file: string): Config { if (array?.[1] === undefined) throw new ConfigError(`${where}: ${key} must be an array of strings`); const items = (array[1].match(/"(?:[^"\\]|\\.)*"|'[^']*'|[^,\s]+/gu) ?? []).map((item) => parseString(item, where)); if (key === "exclude") exclude.push(...items); + else if (key === "yaml-values") yamlValues.push(...items); else { checkProtocols(items, where); protocols = items; @@ -117,7 +125,7 @@ function parseTomlConfig(text: string, file: string): Config { throw new ConfigError(`${where}: unknown key ${key}`); } } - return { exclude, protocols: protocols ?? DEFAULT_PROTOCOLS, rules }; + return { exclude, protocols: protocols ?? DEFAULT_PROTOCOLS, yamlValues, rules }; } const isStringArray = (value: unknown): value is string[] => @@ -135,11 +143,13 @@ function parseJsonConfig(text: string, file: string): Config { if (!isObject(data)) throw new ConfigError(`${file}: expected an object`); const exclude: string[] = []; let protocols: readonly string[] = DEFAULT_PROTOCOLS; + const yamlValues: string[] = []; const rules: Partial> = {}; for (const [key, value] of Object.entries(data)) { - if (key === "exclude" || key === "protocols") { + if (key === "exclude" || key === "protocols" || key === "yaml-values") { if (!isStringArray(value)) throw new ConfigError(`${file}: ${key} must be an array of strings`); if (key === "exclude") exclude.push(...value); + else if (key === "yaml-values") yamlValues.push(...value); else { checkProtocols(value, file); protocols = value; @@ -157,7 +167,7 @@ function parseJsonConfig(text: string, file: string): Config { throw new ConfigError(`${file}: unknown key ${key}`); } } - return { exclude, protocols, rules }; + return { exclude, protocols, yamlValues, rules }; } /** diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index aa8d9bc..a6ffa72 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,4 +1,4 @@ -export { commentSpans, findRefs } from "./comments.js"; +export { commentSpans, findRefs, valueStartAt } from "./comments.js"; export type { Span } from "./comments.js"; export { checkRef, checkText, editDistance, scanRepo, similarPaths } from "./check.js"; export type { RefRecord, RepoScan, ResolvedTarget, Status } from "./check.js"; diff --git a/packages/core/src/repo.ts b/packages/core/src/repo.ts index f2c12f7..6bbdcd5 100644 --- a/packages/core/src/repo.ts +++ b/packages/core/src/repo.ts @@ -4,7 +4,7 @@ import { execFile } from "node:child_process"; import { readdirSync, readFileSync, realpathSync, statSync } from "node:fs"; import { dirname, isAbsolute, join, relative, sep } from "node:path"; import { promisify } from "node:util"; -import { DEFAULT_CONFIG, excluder, loadConfig, type Config } from "./config.js"; +import { DEFAULT_CONFIG, excluder, globToRegExp, loadConfig, type Config } from "./config.js"; import { extractHeadings, isMarkdownPath, type Heading } from "./markdown.js"; const run = promisify(execFile); @@ -64,6 +64,7 @@ export class Repo { private readonly children = new Map>(); private readonly headingCache = new Map(); private readonly excluded: (path: string) => boolean; + private readonly yamlValues: readonly RegExp[]; /** * @param root absolute path of the repo top level @@ -78,6 +79,7 @@ export class Repo { readonly config: Config = DEFAULT_CONFIG, ) { this.excluded = excluder(config); + this.yamlValues = config.yamlValues.map(globToRegExp); this.trackedSet = new Set(tracked); this.fileSet = new Set([...tracked, ...untracked]); for (const file of this.fileSet) { @@ -129,6 +131,14 @@ export class Repo { return this.excluded(path); } + /** + * Returns whether the config names `path` in `yaml-values`. If it does, a YAML value in that file + * can be a ref, if the whole value is one ref. + */ + readsYamlValues(path: string): boolean { + return this.yamlValues.some((pattern) => pattern.test(path)); + } + private addLowerCase(path: string): void { const key = path.toLowerCase(); const list = this.byLowerCase.get(key); diff --git a/packages/core/src/resolve.ts b/packages/core/src/resolve.ts index e5e0dd6..dbf1078 100644 --- a/packages/core/src/resolve.ts +++ b/packages/core/src/resolve.ts @@ -116,9 +116,12 @@ export function parseFragment(encoded: string): Result { return { ok: true, value: { kind: "heading", slug: fragment } }; } -const UNSAFE_PATH_CHAR = /[\s%#"'`<>()[\]{}]/gu; +const UNSAFE_PATH_CHAR = /[\s%#"'`<>()[\]{},]/gu; -/** Percent-encodes the characters that would end a ref or change its meaning. */ +/** + * Percent-encodes the characters that would end a ref or change its meaning. A `,` ends a ref in a + * YAML `[...]` or `{...}` value, and a `,` at the end of a ref is dropped as punctuation. + */ export function encodeRefPath(path: string): string { return path.replace(UNSAFE_PATH_CHAR, (ch) => Array.from(new TextEncoder().encode(ch), (byte) => `%${byte.toString(16).toUpperCase().padStart(2, "0")}`).join(""), diff --git a/packages/core/src/values.ts b/packages/core/src/values.ts new file mode 100644 index 0000000..505c1f8 --- /dev/null +++ b/packages/core/src/values.ts @@ -0,0 +1,80 @@ +/** + * Finds the refs in YAML values. In the YAML files that the config names in `yaml-values`, a value + * can also be a ref, if the whole value is one ref. To know where each value starts and ends, the + * `yaml` parser reads the file: a value can be on the line under its key, come after an anchor or a + * tag, or be an item of a `[...]` list that goes across lines. + */ + +import { parseAllDocuments, Scalar, visit } from "yaml"; +import { scanRefs, type RefMatch } from "./syntax.js"; + +interface YamlScalar { + /** Where the scalar is written, with its quotes. */ + readonly start: number; + readonly end: number; + /** The scalar is in quotes. */ + readonly quoted: boolean; + /** The scalar is the key of a pair, not a value. */ + readonly key: boolean; + readonly value: unknown; +} + +/** + * Returns the plain and quoted scalars of every document in `text`, keys too. A block scalar (`|` or + * `>`) is not one of them. A file that is not valid YAML still has the scalars that the parser can + * read. + */ +function yamlScalars(text: string): YamlScalar[] { + const scalars: YamlScalar[] = []; + for (const document of parseAllDocuments(text)) { + visit(document, { + Scalar(key, node) { + const quoted = node.type === Scalar.QUOTE_DOUBLE || node.type === Scalar.QUOTE_SINGLE; + if (node.range == null || (!quoted && node.type !== Scalar.PLAIN)) return; + scalars.push({ start: node.range[0], end: node.range[1], quoted, key: key === "key", value: node.value }); + }, + }); + } + return scalars.sort((a, b) => a.start - b.start); +} + +/** + * Returns the refs of a YAML text that are the whole value of a scalar, plain or in quotes. The key + * of a pair is not a value. The text of the value must be the value itself, so a value with an + * escape or that goes on in the next line is not a ref. + */ +export function yamlValueRefs(text: string, protocols: readonly string[]): RefMatch[] { + const refs: RefMatch[] = []; + for (const scalar of yamlScalars(text)) { + if (scalar.key || typeof scalar.value !== "string") continue; + const quote = scalar.quoted ? 1 : 0; + // A quoted scalar with no closing quote is not a value: the parser still drops its last + // character, as if it were the quote. + if (scalar.quoted && (scalar.end - scalar.start < 2 || text[scalar.end - 1] !== text[scalar.start])) continue; + const start = scalar.start + quote; + if (text.slice(start, scalar.end - quote) !== scalar.value) continue; + const found = scanRefs(scalar.value, protocols); + const ref = found[0]; + if (found.length !== 1 || ref === undefined || ref.start !== 0 || ref.end !== scalar.value.length) continue; + refs.push({ ...ref, start, end: start + ref.end }); + } + return refs; +} + +/** + * Returns where the text of the last scalar that starts at or before `offset` starts, after its + * quote, if that scalar starts on the line of `offset`. Keys count too, since a ref that is still + * being typed, such as `- sync:`, reads as a key. The VS Code completion offers paths only for a ref + * that starts there, because only a ref that is the whole value counts. + */ +export function yamlValueStartAt(text: string, offset: number): number | undefined { + let found: number | undefined; + for (const scalar of yamlScalars(text)) { + const start = scalar.start + (scalar.quoted ? 1 : 0); + if (start > offset) break; + // Skip the empty value that the parser adds after a key, as after `- sync:`. + if (scalar.end > scalar.start) found = start; + } + if (found === undefined || /[\r\n]/u.test(text.slice(found, offset))) return undefined; + return found; +} diff --git a/packages/core/test/check.test.ts b/packages/core/test/check.test.ts index 73ff042..5974d85 100644 --- a/packages/core/test/check.test.ts +++ b/packages/core/test/check.test.ts @@ -129,6 +129,49 @@ describe("checkText", () => { }); }); +describe("refs in YAML values", () => { + let fixture: ReturnType; + + before(() => { + const yaml = [ + "# iref:/docs/spec.md", + "tokens:", + " spec: sync:/docs/spec.md#tokens", + ' quoted: "sync:/docs/spec.md#sessions"', + " list: [sync:/docs/spec.md, 'iref:/docs/spec.md#tokens']", + " items:", + " - sync:/docs/spec.md#sessions # a comment", + " text: see sync:/no/such/file", + ' partial: "sync:/no/such/file and more"', + " block: |", + " sync:/no/such/file", + "", + ].join("\n"); + fixture = makeRepo({ + ".interref.toml": 'yaml-values = ["model/**"]\n', + "docs/spec.md": "# Spec\n\n## Tokens\n\n## Sessions\n", + "model/limits.yaml": yaml, + "other.yaml": yaml, + }); + }); + after(() => fixture.dispose()); + + it("count when the value is one ref, in the YAML files that the config names", async () => { + const repo = await Repo.open(fixture.root); + const refs = (path: string): string[] => + scanRepo(repo, (candidate) => candidate === path).records.map((record) => `${record.source.line} ${record.raw} ${record.status}`); + assert.deepEqual(refs("model/limits.yaml"), [ + "1 iref:/docs/spec.md ok", + "3 sync:/docs/spec.md#tokens ok", + "4 sync:/docs/spec.md#sessions ok", + "5 sync:/docs/spec.md ok", + "5 iref:/docs/spec.md#tokens ok", + "7 sync:/docs/spec.md#sessions ok", + ]); + assert.deepEqual(refs("other.yaml"), ["1 iref:/docs/spec.md ok"]); + }); +}); + describe("a file moved without git", () => { let fixture: ReturnType; diff --git a/packages/core/test/comments.test.ts b/packages/core/test/comments.test.ts index 35f6916..b1a9779 100644 --- a/packages/core/test/comments.test.ts +++ b/packages/core/test/comments.test.ts @@ -1,6 +1,7 @@ import assert from "node:assert/strict"; import { describe, it } from "node:test"; -import { commentSpans, findRefs } from "../src/comments.js"; +import { commentSpans, findRefs, valueStartAt } from "../src/comments.js"; +import { DEFAULT_PROTOCOLS } from "../src/syntax.js"; // In each text, refs that must be found point at /yes…, and refs that must not be found point at /no. const raws = (path: string, ...lines: string[]): string[] => findRefs(path, lines.join("\n")).map((ref) => ref.raw); @@ -31,6 +32,104 @@ describe("findRefs", () => { }); }); +describe("findRefs in YAML values", () => { + const values = (...lines: string[]): string[] => + findRefs("a.yaml", lines.join("\n"), DEFAULT_PROTOCOLS, true).map((ref) => ref.raw); + + it("finds a ref that is a whole value, plain or in quotes, also an item of a flow collection", () => { + assert.deepEqual( + values( + "a: iref:/yes1", + 'b: "iref:/yes2" # a comment', + "c:", + " - - 'iref:/yes3'", + "d: [iref:/yes4,iref:/yes5, 'iref:/yes6']", + "e: {f: iref:/yes7, g: [x,", + " y, iref:/yes8]}", + "h: iref:/yes9", + "", + " # a comment", + "i:", + " - iref:/yes10", + " - x", + ), + ["iref:/yes1", "iref:/yes2", "iref:/yes3", "iref:/yes4", "iref:/yes5", "iref:/yes6", "iref:/yes7", "iref:/yes8", "iref:/yes9", "iref:/yes10"], + ); + }); + + it("finds a value under its key, after an anchor or a tag, and in a list that goes across lines", () => { + assert.deepEqual( + values("a:", " iref:/yes1", "b: &x iref:/yes2", "c: !!str iref:/yes3", "d: *x", "e: [", " iref:/yes4,", " iref:/yes5", "]"), + ["iref:/yes1", "iref:/yes2", "iref:/yes3", "iref:/yes4", "iref:/yes5"], + ); + }); + + it("keeps the offsets of the ref, also in quotes", () => { + const text = "\uFEFFa: 'iref:/yes'\r\n"; + const [ref] = findRefs("a.yaml", text, DEFAULT_PROTOCOLS, true); + assert.equal(ref?.start, text.indexOf("iref:/yes")); + assert.equal(ref?.end, text.indexOf("'\r")); + }); + + it("does not find a ref in a longer value, a block or a key", () => { + for (const text of [ + "key: sync:/docs/a.md, see also the model", + "note: Tokens, sync:/docs/a.md", + "note: foo {sync:/docs/a.md}", + 'note: a, "sync:/docs/a.md"', + 'key: foo - "sync:/docs/a.md"', + "key: a[sync:/docs/a.md]", + "key: [sync:/docs/a.md and more]", + "key: |-\n sync:/docs/a.md", + "sync:/docs/a.md: x", + "{sync:/docs/a.md}", + ]) { + assert.deepEqual(values(text), [], text); + } + }); + + it("does not find a plain ref that continues an earlier line or that the next lines continue", () => { + assert.deepEqual(values("a: iref:/no", " goes on", "b:", " - iref:/no", "", " goes on", "c: iref:/yes"), ["iref:/yes"]); + assert.deepEqual(values("a: some text", " - iref:/no", "b: x"), []); + assert.deepEqual(values("- some text", " - iref:/no"), []); + }); + + it("still finds the later values after a bracket that is not closed", () => { + assert.deepEqual(values("title: [draft", "k: iref:/yes"), ["iref:/yes"]); + }); + + it("does not find a ref in quotes that are not closed", () => { + for (const text of ["a: 'iref:/docs/no.md", 'a: "iref:/docs/no.md', "a: 'iref:/docs/no.md\n", "a: '", "a: \""]) { + assert.deepEqual(values(text), [], text); + } + }); +}); + +describe("valueStartAt", () => { + // The text before `|` is the text before the cursor. + const startAt = (path: string, marked: string): number | undefined => { + const offset = marked.indexOf("|"); + return valueStartAt(path, marked.slice(0, offset) + marked.slice(offset + 1), offset); + }; + + it("gives the start of the value that the cursor is in, after its quote", () => { + assert.equal(startAt("a.yaml", "spec: sync:/do|"), 6); + assert.equal(startAt("a.yaml", "spec: 'sync:/do|'"), 7); + assert.equal(startAt("a.yaml", 'spec: "sync:/do|'), 7); + assert.equal(startAt("a.yaml", "- sync:|"), 2); + }); + + it("gives the start of the list item that the cursor is in", () => { + assert.equal(startAt("a.yaml", "specs: [sync:/a.md,sync:/|]"), 19); + assert.equal(startAt("a.yaml", "specs: [sync:/a.md, sync:/|]"), 20); + }); + + it("gives no start for a value on an earlier line or in a file that is not YAML", () => { + assert.equal(startAt("a.yaml", "a: b\n|"), undefined); + assert.equal(startAt("a.ts", "spec: sync:/|"), undefined); + }); +}); + describe("comments by language", () => { it("JavaScript and TypeScript", () => { assert.deepEqual( diff --git a/packages/core/test/config.test.ts b/packages/core/test/config.test.ts index 5db7034..fcca4c3 100644 --- a/packages/core/test/config.test.ts +++ b/packages/core/test/config.test.ts @@ -27,6 +27,12 @@ describe("parseConfig", () => { assert.deepEqual(parseConfig('protocols = ["ref", "nref"]').protocols, ["ref", "nref"]); }); + it("reads yaml-values", () => { + assert.deepEqual(parseConfig('yaml-values = ["model/**",\n "config/*.yaml"]').yamlValues, ["model/**", "config/*.yaml"]); + assert.deepEqual(parseConfig("").yamlValues, []); + assert.throws(() => parseConfig('yaml-values = "model/**"'), ConfigError); + }); + it("rejects unknown keys, rules and settings", () => { assert.throws(() => parseConfig("include = []"), ConfigError); assert.throws(() => parseConfig('[rules]\nline-reff = "off"'), ConfigError); @@ -39,10 +45,15 @@ describe("parseConfig", () => { it("reads JSON when the file name ends in .json", () => { const config = parseConfig( - JSON.stringify({ exclude: ["vendor/**"], protocols: ["sync"], rules: { "target-ignored": "off" } }), + JSON.stringify({ exclude: ["vendor/**"], protocols: ["sync"], "yaml-values": ["model/**"], rules: { "target-ignored": "off" } }), ".interref.json", ); - assert.deepEqual(config, { exclude: ["vendor/**"], protocols: ["sync"], rules: { "target-ignored": "off" } }); + assert.deepEqual(config, { + exclude: ["vendor/**"], + protocols: ["sync"], + yamlValues: ["model/**"], + rules: { "target-ignored": "off" }, + }); assert.deepEqual(parseConfig("{}", "interref.json"), DEFAULT_CONFIG); }); diff --git a/packages/core/test/resolve.test.ts b/packages/core/test/resolve.test.ts index dd95a53..297fd0a 100644 --- a/packages/core/test/resolve.test.ts +++ b/packages/core/test/resolve.test.ts @@ -63,5 +63,6 @@ describe("formatRef", () => { it("encodes characters that would end the ref", () => { assert.equal(encodeRefPath("a b#(c).md"), "a%20b%23%28c%29.md"); + assert.equal(encodeRefPath("a,b.md"), "a%2Cb.md"); }); }); diff --git a/packages/vscode/.vscodeignore b/packages/vscode/.vscodeignore index 987cf68..9aad646 100644 --- a/packages/vscode/.vscodeignore +++ b/packages/vscode/.vscodeignore @@ -3,3 +3,4 @@ !package.json !README.md !LICENSE +!THIRD-PARTY-NOTICES diff --git a/packages/vscode/README.md b/packages/vscode/README.md index 2e74259..76867e6 100644 --- a/packages/vscode/README.md +++ b/packages/vscode/README.md @@ -6,16 +6,18 @@ This extension makes `iref:` links in comments clickable, and it shows broken li - Hover over a ref to see the start of its target. - Broken refs show in Problems. Cmd/Ctrl+. offers fixes. - "Copy ref" in the editor or explorer context menu copies `iref:/path#heading`. -- In a comment, type `iref:/`, `iref:./` or `#` to get completions for paths and headings. `iref:`, `sync:` and the - other protocols in the config file work the same way. +- 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 + work the same way. - "interref: Show ref graph" opens the link graph around a file, or for the whole repo. You must install a viewer extension first: Draw.io Integration (`hediet.vscode-drawio`, the default), or for Mermaid the official Mermaid extension (`MermaidChart.vscode-mermaid-chart`) or Mermaid Preview (`vstirbu.vscode-mermaid-preview`). If the viewer is missing, the command offers to install it. -A ref counts only in a comment, not in a string or in Markdown text. Only heading fragments are -supported for now. For the full syntax and the `interref` CLI, see the +A ref counts only in a comment, not in a string or in Markdown text. There is one exception: in the +YAML files that the `yaml-values` key of the config file names, a value can also be a ref. Only +heading fragments are supported for now. For the full syntax and the `interref` CLI, see the `README.md` of the interref repo. ## Settings diff --git a/packages/vscode/package.json b/packages/vscode/package.json index 340d3c4..72eb577 100644 --- a/packages/vscode/package.json +++ b/packages/vscode/package.json @@ -107,7 +107,7 @@ }, "scripts": { "bundle": "node esbuild.mjs", - "package": "cp ../../LICENSE . && vsce package --no-dependencies --out interref.vsix" + "package": "cp ../../LICENSE ../../THIRD-PARTY-NOTICES . && vsce package --no-dependencies --out interref.vsix" }, "devDependencies": { "@interref/core": "workspace:*", diff --git a/packages/vscode/src/features.ts b/packages/vscode/src/features.ts index 16ffd1b..9f19af2 100644 --- a/packages/vscode/src/features.ts +++ b/packages/vscode/src/features.ts @@ -8,6 +8,7 @@ import { isMarkdownPath, protocolPattern, resolveTarget, + valueStartAt, type RefRecord, type Repo, } from "@interref/core"; @@ -263,12 +264,22 @@ export class Completion implements vscode.CompletionItemProvider { const located = await this.repos.locate(document.uri); if (located === undefined) return undefined; const { repo, path: source } = located; - const partial = partialRef(repo.config.protocols).exec(before); - if (partial === null) return undefined; - // Only a ref in a comment counts, so offer nothing in code, strings or Markdown text. + // Only a ref in a comment counts, or a ref that is a whole YAML value in a file that the config + // names, so offer nothing in code, strings or Markdown text. const offset = document.offsetAt(position); - const comments = commentSpans(source, document.getText()) ?? []; - if (!comments.some((span) => span.start < offset && offset <= span.end)) return undefined; + const text = document.getText(); + const pattern = partialRef(repo.config.protocols); + let partial: RegExpExecArray | null = null; + if ((commentSpans(source, text) ?? []).some((span) => span.start < offset && offset <= span.end)) { + partial = pattern.exec(before); + } else if (repo.readsYamlValues(source)) { + // A ref in a YAML value is the whole value: it starts the value that the cursor is in, after + // its quote. Read from that start, so that an earlier item of a `[...]` list is not part of it. + const start = valueStartAt(source, text, offset); + const match = start === undefined ? null : pattern.exec(text.slice(start, offset)); + if (match?.index === 0) partial = match; + } + if (partial === null) return undefined; const typedPath = partial[2] ?? ""; const typedFragment = partial[3]; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 47fe4db..2dfdb4e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -204,6 +204,10 @@ importers: version: 0.28.2 packages/core: + dependencies: + yaml: + specifier: ^2.9.1 + version: 2.9.1 devDependencies: '@types/node': specifier: 'catalog:' @@ -1318,6 +1322,11 @@ packages: yallist@4.0.0: resolution: {integrity: sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==} + yaml@2.9.1: + resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==} + engines: {node: '>= 14.6'} + hasBin: true + yauzl@3.4.0: resolution: {integrity: sha512-jIH9yLR9wqr0wOS0TpBvo/g/2UgZH5qePVbjgRliiF0BYvOZyaBknKsF+x9Iht0O6sqgnB93rCICdOZFecJuDw==} engines: {node: '>=12'} @@ -2336,6 +2345,8 @@ snapshots: yallist@4.0.0: {} + yaml@2.9.1: {} + yauzl@3.4.0: dependencies: pend: 1.2.0 diff --git a/skills/iref/SKILL.md b/skills/iref/SKILL.md index 76c4e6f..1fd0f21 100644 --- a/skills/iref/SKILL.md +++ b/skills/iref/SKILL.md @@ -55,8 +55,9 @@ only to the page. ## Put the ref in a comment -A ref counts only in a comment. The same text in a string, in code or in -Markdown body text is not a ref. +A ref counts only in a comment, with one exception: in the YAML files that +the config names, a value can also be a ref (see below). The same text in a +string, in code or in Markdown body text is not a ref. | File | Where to put the ref | |---|---| @@ -69,6 +70,12 @@ Markdown body text is not a ref. Do not put a ref in a docstring that the program shows to users, for example an `argparse` description that uses `__doc__`. +In the YAML files that the `yaml-values` key of the config file names, a value +can also be a ref. The value must be exactly one ref, and it can be plain or in +quotes, for example `spec: sync:/docs/auth.md#token-lifetime`. An item of a +`[...]` list also counts. The ref must be the whole value, and the value must +be on one line. A key and a `|` or `>` block are not refs. + A file type that interref does not know (for example `.txt`) has no refs. ## Choose the protocol @@ -130,9 +137,10 @@ lines around each ref), `-T N` (show the first N lines of the target), ### Add refs -1. Read the config file at the repo root for `protocols` and `exclude`. Its - name is `interref.toml`, `.interref.toml`, `interref.json` or - `.interref.json`. It is an error to have two config files. +1. Read the config file at the repo root, and find the values of + `protocols`, `exclude` and `yaml-values`. Its name is `interref.toml`, + `.interref.toml`, `interref.json` or `.interref.json`. It is an error to + have two config files. 2. For each link, find the downstream file and the most specific target heading. 3. Write the ref in a comment in the downstream file. Match the comment style