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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
10 changes: 8 additions & 2 deletions DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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
Expand Down
30 changes: 24 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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"
Expand All @@ -273,6 +290,7 @@ The same config as JSON:
{
"exclude": ["vendor/**", "**/*.min.js"],
"protocols": ["iref", "sync"],
"yaml-values": ["config/**/*.yaml"],
"rules": { "target-ignored": "off" }
}
```
Expand All @@ -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
Expand Down
21 changes: 21 additions & 0 deletions THIRD-PARTY-NOTICES
Original file line number Diff line number Diff line change
@@ -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 <eemeli@gmail.com>

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.
3 changes: 3 additions & 0 deletions packages/cli/esbuild.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
});
5 changes: 3 additions & 2 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
"iref": "./dist/interref.mjs"
},
"files": [
"dist/interref.mjs"
"dist/interref.mjs",
"THIRD-PARTY-NOTICES"
],
"publishConfig": {
"access": "public"
Expand All @@ -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": {
Expand Down
3 changes: 3 additions & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
"scripts": {
"test": "node --test \"dist/test/**/*.test.js\""
},
"dependencies": {
"yaml": "^2.9.1"
},
"devDependencies": {
"@types/node": "catalog:"
}
Expand Down
7 changes: 4 additions & 3 deletions packages/core/src/check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
29 changes: 25 additions & 4 deletions packages/core/src/comments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -682,14 +684,33 @@ 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) ?? []) {
for (const ref of scanRefs(text.slice(span.start, span.end), protocols)) {
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);
}
22 changes: 16 additions & 6 deletions packages/core/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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<Partial<Record<RuleId, RuleSetting>>>;
}

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 {}

Expand Down Expand Up @@ -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<Record<RuleId, RuleSetting>> = {};
let table = "";
const lines = text.split(/\r?\n/u);
Expand All @@ -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++;
Expand All @@ -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;
Expand All @@ -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[] =>
Expand All @@ -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<Record<RuleId, RuleSetting>> = {};
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;
Expand All @@ -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 };
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/index.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down
12 changes: 11 additions & 1 deletion packages/core/src/repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -64,6 +64,7 @@ export class Repo {
private readonly children = new Map<string, Map<string, EntryKind>>();
private readonly headingCache = new Map<string, readonly Heading[]>();
private readonly excluded: (path: string) => boolean;
private readonly yamlValues: readonly RegExp[];

/**
* @param root absolute path of the repo top level
Expand All @@ -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) {
Expand Down Expand Up @@ -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);
Expand Down
7 changes: 5 additions & 2 deletions packages/core/src/resolve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,12 @@ export function parseFragment(encoded: string): Result<HeadingFragment> {
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(""),
Expand Down
Loading
Loading