@zgeoff/chex 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -16,8 +16,7 @@ Run each shared check of a zgeoff repo as one subcommand, and take the lefthook
16
16
  that calls them with one `extends` line.
17
17
 
18
18
  Each check prints its own findings, then `cleared: <check>` when it passes or `bounced: <check>`
19
- when it fails, so a run of several checks names each one that failed. To start, run `chex init`,
20
- then `chex length links`.
19
+ when it fails, so a run of several checks shows each one that failed.
21
20
 
22
21
  ## Install
23
22
 
@@ -26,43 +25,43 @@ bun add -d @zgeoff/chex @zgeoff/rig @zgeoff/diet @commitlint/cli @zgeoff/commitl
26
25
  bun x --no-install chex init
27
26
  ```
28
27
 
29
- `chex` runs under Bun. The baseline runs the related tests through [`@zgeoff/rig`](../rig/README.md)
30
- and each job under the memory cap of [`@zgeoff/diet`](../diet/README.md), so a repo that takes it
31
- installs both, and `chex init` fails until it does. `chex commits` lints commit messages with
32
- `@commitlint/cli` and `@zgeoff/commitlint-config`; in a repo that lacks either one, it prints a
33
- notice and passes.
28
+ `chex` runs under Bun. The pre-push baseline runs the related tests through
29
+ [`@zgeoff/rig`](../rig/README.md) and each job under the memory cap of
30
+ [`@zgeoff/diet`](../diet/README.md), so a repo that takes the baseline installs both, and
31
+ `chex init` fails until it does. In a repo that lacks `@commitlint/cli` or
32
+ `@zgeoff/commitlint-config`, `chex commits` prints a notice and passes.
34
33
 
35
34
  ## Commands
36
35
 
37
- `chex <check>...` runs each check in turn, even after one bounces, and exits with the highest exit
38
- code among them: 0 when each clears, 1 when a check finds a fault, and 2 when a check cannot run.
36
+ `chex <check>...` runs each check in turn, even after one fails, and exits with the highest exit
37
+ code among them: 0 when each passes, 1 when a check finds a fault, and 2 when a check cannot run.
39
38
  chex also exits 2 for a check that throws or exits with any other code, such as 127 for a missing
40
39
  program. `chex <check> <args...>` hands the arguments to that one check.
41
40
 
42
- The docs checks read the repo's READMEs, its `docs/` tree and its skills:
41
+ Run these docs checks on a repo's READMEs, its `docs/` tree and its skills:
43
42
 
44
43
  | Check | Fails on | Arguments |
45
44
  | --------- | ----------------------------------------------------------------------------------------------------------------------------------------- | -------------- |
46
- | `prose` | banned words, process residue and over-long paragraphs | the paths |
45
+ | `prose` | banned words, notes about how the doc was made and over-long paragraphs (needs `perl` and a `git` with PCRE, else exit 2) | the paths |
47
46
  | `length` | a README over its line limit, and warns on a doc over its cap | none |
48
47
  | `links` | a relative link or anchor that does not resolve | the paths |
49
48
  | `readmes` | a README of none of the [five kinds](https://github.com/zgeoff/skills/blob/main/skills/docs-writing/references/readmes.md#the-five-kinds) | none |
50
49
  | `vision` | a missing `docs/vision.md`, or one past 60 lines | none |
51
- | `skill` | a skill's frontmatter, its word limit, a link with a line anchor, and a coined term such as "the unit limit" | the skill dirs |
52
-
53
- The repo checks read the branch, the pushed commits and the repo's config:
54
-
55
- | Check | Fails on | Arguments |
56
- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
57
- | `commits` | a pushed commit whose message fails `@zgeoff/commitlint-config` | `--pushed-refs` |
58
- | `local-paths` | a line a pushed commit adds that holds the home folder or the host name | `--pushed-refs` |
59
- | `test-timeouts` | a `bun test` timeout above its lane's limit, in a script or a `bunfig.toml` | none |
60
- | `lint-overrides` | an `.oxlintrc*.json` that turns a `zgeoff/*` rule, `consistent-type-assertions` or `ban-ts-comment` off or down to a warning | none |
61
- | `test-layout` | a test folder, file name or import outside [the test layout](../../docs/guides/test-layout.md); test code includes a relative `[test] preload` file, a `.nix`-only `tests/` folder and a private workspace that only test code imports | none |
62
- | `workflows` | nothing: it prints each fault of the shared workflow lint, and fails when there is one | the paths |
63
- | `dependency-gates` | a stale age-gate exclude, an override or an audit ignore that nothing needs, a first-party package with no age-gate exclude, or a pinned release younger than the age gate ([details](../../docs/architecture/dependency-updates.md#the-dependency-gates-check)) | none |
64
- | `uncommitted` | a file the branch changes that holds a change the push does not send | none |
65
- | `pr-body` | a PR description with a heading, a label, a code block or a prose-check commit that the [PR template](../../.github/PULL_REQUEST_TEMPLATE.md) doesn't allow ([details](../../docs/architecture/pr-body-check.md)) | `--body-file`, then `--base` and `--head` for the commit checks |
50
+ | `skill` | a skill's frontmatter, its word limit, a link with a line anchor, and a made-up label for a rule, such as "the unit limit" | the skill dirs |
51
+
52
+ Run these repo checks on the branch, the pushed commits and the repo's config:
53
+
54
+ | Check | Fails on | Arguments |
55
+ | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
56
+ | `commits` | a pushed commit whose message fails `@zgeoff/commitlint-config` | `--pushed-refs` |
57
+ | `local-paths` | a line a pushed commit adds that holds the home folder or the host name | `--pushed-refs` |
58
+ | `test-timeouts` | a `bun test` timeout above its lane's limit, in a script or a `bunfig.toml` | none |
59
+ | `lint-overrides` | an oxlint config that turns a `zgeoff/*` rule, `consistent-type-assertions` or `ban-ts-comment` off or down to a warning, a config in code (`oxlint.config.ts` or `.mts`), or a config that the last commit does not hold as a plain file or that does not parse; it reads each file or symlink named `.oxlintrc*.json` or `.oxlintrc*.jsonc`, each path a `package.json` script gives `oxlint` with `-c` or `--config`, the file each symlink reaches, and each file a config extends by a relative path | none |
60
+ | `test-layout` | a test folder, file name or import outside [the test layout](../../docs/guides/test-layout.md), where test code covers a relative `[test] preload` file, a `.nix`-only `tests/` folder and a private workspace that only test code imports | none |
61
+ | `workflows` | nothing: it prints each fault of the shared workflow lint, and fails when there is one | the paths |
62
+ | `dependency-gates` | a stale age-gate exclude, an override or an audit ignore that nothing needs, a first-party package with no age-gate exclude, or a pinned release younger than the age gate ([details](../../docs/architecture/dependency-updates.md#the-dependency-gates-check)) | none |
63
+ | `uncommitted` | a file the branch changes that has an uncommitted edit, which the push does not send | none |
64
+ | `pr-body` | a PR description with a heading, a label or a code block that the [PR template](../../.github/PULL_REQUEST_TEMPLATE.md) doesn't allow, or a Deslop or Cold read line with a commit hash the branch lacks or a later doc change outdates ([details](../../docs/architecture/pr-body-check.md)) | `--body-file`, then `--base` and `--head` for the commit checks |
66
65
 
67
66
  With no path, `prose` and `links` read every README outside `.claude/` and `.agents/`, every file
68
67
  under `docs/`, each spike's `results.md`, and the Markdown under `.agents/skills/`,
@@ -72,29 +71,29 @@ commits since its base.
72
71
 
73
72
  Some docs checks skip files even when you name them:
74
73
 
75
- - `prose` needs `perl` and a `git` with PCRE, and fails with exit 2 when it lacks one.
76
74
  - `prose` skips the `docs-writing`, `project-docs-writing`, `skill-writing` and `deslop` skills
77
- under `.agents/skills/`, `.claude/skills/`, `skills/` and `sync/skills/`, which hold the banned
78
- patterns as examples.
75
+ under `.agents/skills/`, `.claude/skills/`, `skills/` and `sync/skills/`, because those skills
76
+ hold the banned patterns as examples.
79
77
  - `links` skips `project-docs-writing` under `.agents/skills/` and `.claude/skills/`, and
80
78
  `docs-writing` and `skill-writing` under `.agents/skills/`, `.claude/skills/` and `sync/skills/`,
81
- which link to placeholder targets as examples.
79
+ because those skills link to placeholder targets as examples.
82
80
  - `prose`, `links`, `readmes` and `skill` skip each file that `.gitattributes` marks
83
81
  `linguist-vendored`.
84
82
 
85
83
  `chex init` writes the `extends` line and a
86
84
  [`chex-baseline` job](../../docs/architecture/pre-push-baseline.md#a-checkout-without-the-baseline)
87
85
  into `lefthook.yml`, adds a `check:docs` script of `chex prose length links readmes skill` when the
88
- repo has none, and changes nothing on a second run. `chex ci-plan` plans a run of `bun-checks`.
86
+ repo has none, and changes nothing on a second run. `chex ci-plan` plans a `bun-checks` run.
89
87
 
90
88
  ## The pre-push baseline
91
89
 
92
- A repo's `lefthook.yml` takes the baseline with one line, which `chex init` writes:
90
+ Add one line to a repo's `lefthook.yml` to take the baseline; `chex init` writes it:
93
91
 
94
92
  ```yaml
95
93
  extends:
96
94
  - node_modules/@zgeoff/chex/lefthook.yml
97
95
  ```
98
96
 
99
- Its jobs, [each described here](../../docs/architecture/pre-push-baseline.md), call `chex <check>`,
100
- `bun run check:docs`, `rig related` and the repo's own `format:check` and `typecheck` scripts.
97
+ The baseline's jobs, which [its doc](../../docs/architecture/pre-push-baseline.md) describes, call
98
+ `chex <check>`, `bun run check:docs`, `rig related` and the repo's own `format:check` and
99
+ `typecheck` scripts.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zgeoff/chex",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "description": "Run each shared docs and repo check as one subcommand, with the lefthook pre-push baseline that calls them",
5
5
  "keywords": [
6
6
  "checks",
@@ -0,0 +1,25 @@
1
+ import { posix } from 'node:path';
2
+ import type { TrackedTree, TreeEntry } from './types.ts';
3
+
4
+ export function buildTrackedTree(
5
+ entries: readonly TreeEntry[],
6
+ linkTargets: ReadonlyMap<string, string>,
7
+ ): TrackedTree {
8
+ const directories = new Set<string>();
9
+
10
+ for (const entry of entries) {
11
+ for (
12
+ let folder = posix.dirname(entry.path);
13
+ folder !== '.' && !directories.has(folder);
14
+ folder = posix.dirname(folder)
15
+ ) {
16
+ directories.add(folder);
17
+ }
18
+ }
19
+
20
+ return {
21
+ links: linkTargets,
22
+ files: new Set(entries.filter((entry) => !entry.isLink).map((entry) => entry.path)),
23
+ directories,
24
+ };
25
+ }
@@ -0,0 +1,193 @@
1
+ import { basename, posix } from 'node:path';
2
+ import { collectExtendsPaths } from './collect-extends-paths.ts';
3
+ import { collectLintOverrideFindings } from './collect-lint-override-findings.ts';
4
+ import { collectScriptConfigPaths } from './collect-script-config-paths.ts';
5
+ import { findLastEntry } from './find-last-entry.ts';
6
+ import type { JSONCTreeResult } from './parse-jsonc-tree.ts';
7
+ import { parseJSONCTree } from './parse-jsonc-tree.ts';
8
+ import { resolveTrackedPath } from './resolve-tracked-path.ts';
9
+ import type { ConfigReference, LintOverrideFinding, TrackedTree } from './types.ts';
10
+
11
+ export interface ConfigReport {
12
+ readonly findings: LintOverrideFinding[];
13
+
14
+ // The tracked files that the walk needs and `texts` lacks. The walk stops short at each of them,
15
+ // so the caller reads them and calls again.
16
+ readonly missing: string[];
17
+ }
18
+
19
+ const configPattern = /^\.?oxlintrc(?:\.[\w-]+)*\.jsonc?$/u;
20
+
21
+ // oxlint loads these configs in code, which chex cannot read.
22
+ const codeConfigNamePattern = /^oxlint\.config\.m?ts$/u;
23
+
24
+ // Walks every config that oxlint may read, as the files of HEAD. Each file is checked once, however
25
+ // many paths lead to it, and reported under the first of those paths in sorted order.
26
+ export function collectConfigReport(
27
+ tree: Readonly<TrackedTree>,
28
+ texts: ReadonlyMap<string, string>,
29
+ ): ConfigReport {
30
+ const missing = new Set<string>();
31
+
32
+ const findings: LintOverrideFinding[] = [];
33
+
34
+ const manifests = new Map<string, JSONCTreeResult>();
35
+
36
+ for (const path of [...tree.files].filter((file) => basename(file) === 'package.json')) {
37
+ const text = texts.get(path);
38
+
39
+ if (text === undefined) {
40
+ missing.add(path);
41
+ continue;
42
+ }
43
+
44
+ const result = parseJSONCTree(text);
45
+
46
+ manifests.set(path, result);
47
+
48
+ if (!result.isValid) {
49
+ findings.push({ path, message: unparseableMessage(result.reason) });
50
+ }
51
+ }
52
+
53
+ const isToolsRepo =
54
+ getManifestName(manifests, 'package.json') === 'tools' &&
55
+ getManifestName(manifests, 'packages/std/package.json') === '@zgeoff/std';
56
+
57
+ const scriptPaths = [...manifests].flatMap(([path, result]) =>
58
+ result.isValid ? collectScriptConfigPaths(path, result.root) : [],
59
+ );
60
+
61
+ const discovered = [...tree.files, ...tree.links.keys()]
62
+ .filter(
63
+ (path) => configPattern.test(basename(path)) || codeConfigNamePattern.test(basename(path)),
64
+ )
65
+ .map((path) => ({ path, isOptional: false }));
66
+
67
+ const walk = walkConfigs(tree, texts, [...discovered, ...scriptPaths]);
68
+
69
+ for (const file of walk.missing) {
70
+ missing.add(file);
71
+ }
72
+
73
+ for (const [file, labels] of walk.reached) {
74
+ const path = labels.toSorted()[0] ?? file;
75
+
76
+ findings.push(...collectFileFindings(path, file, walk.parsed.get(file), isToolsRepo));
77
+ }
78
+
79
+ findings.push(...walk.unreadable);
80
+
81
+ return {
82
+ findings: findings.toSorted(
83
+ (left, right) => Number(left.path > right.path) - Number(left.path < right.path),
84
+ ),
85
+ missing: [...missing],
86
+ };
87
+ }
88
+
89
+ function unparseableMessage(reason: string): string {
90
+ return `chex cannot parse this file (${reason}), and oxlint may read it; commit the config as a plain \`.oxlintrc.json\` file that parses`;
91
+ }
92
+
93
+ function getManifestName(manifests: ReadonlyMap<string, JSONCTreeResult>, path: string): string {
94
+ const result = manifests.get(path);
95
+
96
+ const name =
97
+ result?.isValid === true && result.root.kind === 'object'
98
+ ? findLastEntry(result.root.entries, 'name')?.value
99
+ : undefined;
100
+
101
+ return name?.kind === 'literal' ? name.text : '';
102
+ }
103
+
104
+ interface Walk {
105
+ readonly reached: ReadonlyMap<string, string[]>;
106
+ readonly parsed: ReadonlyMap<string, JSONCTreeResult>;
107
+ readonly unreadable: LintOverrideFinding[];
108
+ readonly missing: string[];
109
+ }
110
+
111
+ const codeFilePattern = /\.[cm]?[jt]s$/u;
112
+
113
+ const unreadableMessage =
114
+ 'oxlint may read this config, but chex cannot read it from HEAD; commit the config as a plain `.oxlintrc.json` file that HEAD holds';
115
+
116
+ // Follows each path through its links, then the `extends` of each file it reaches.
117
+ function walkConfigs(
118
+ tree: Readonly<TrackedTree>,
119
+ texts: ReadonlyMap<string, string>,
120
+ roots: readonly ConfigReference[],
121
+ ): Walk {
122
+ const reached = new Map<string, string[]>();
123
+ const parsed = new Map<string, JSONCTreeResult>();
124
+ const unreadable = new Map<string, LintOverrideFinding>();
125
+ const missing = new Set<string>();
126
+ const visited = new Set<string>();
127
+
128
+ const pending = [...roots];
129
+
130
+ for (let item = pending.pop(); item !== undefined; item = pending.pop()) {
131
+ if (visited.has(item.path)) {
132
+ continue;
133
+ }
134
+
135
+ visited.add(item.path);
136
+
137
+ const label = posix.normalize(item.path);
138
+ const file = resolveTrackedPath(item.path, tree);
139
+
140
+ if (file === null) {
141
+ if (!item.isOptional) {
142
+ unreadable.set(label, { path: label, message: unreadableMessage });
143
+ }
144
+
145
+ continue;
146
+ }
147
+
148
+ reached.set(file, [...(reached.get(file) ?? []), label]);
149
+
150
+ const text = texts.get(file);
151
+
152
+ if (codeFilePattern.test(basename(file))) {
153
+ continue;
154
+ }
155
+
156
+ if (text === undefined) {
157
+ missing.add(file);
158
+ continue;
159
+ }
160
+
161
+ const result = parsed.get(file) ?? parseJSONCTree(text);
162
+
163
+ parsed.set(file, result);
164
+
165
+ if (result.isValid) {
166
+ pending.push(...collectExtendsPaths(item.path, result.root));
167
+ }
168
+ }
169
+
170
+ return { reached, parsed, unreadable: [...unreadable.values()], missing: [...missing] };
171
+ }
172
+
173
+ const codeConfigMessage =
174
+ 'chex reads only JSON configs, so write the config as a plain `.oxlintrc.json` file that HEAD holds';
175
+
176
+ function collectFileFindings(
177
+ path: string,
178
+ file: string,
179
+ result: JSONCTreeResult | undefined,
180
+ isToolsRepo: boolean,
181
+ ): LintOverrideFinding[] {
182
+ if (codeFilePattern.test(basename(file))) {
183
+ return [{ path, message: codeConfigMessage }];
184
+ }
185
+
186
+ if (result === undefined) {
187
+ return [];
188
+ }
189
+
190
+ return result.isValid
191
+ ? collectLintOverrideFindings(path, result.root, isToolsRepo)
192
+ : [{ path, message: unparseableMessage(result.reason) }];
193
+ }
@@ -0,0 +1,31 @@
1
+ import { posix } from 'node:path';
2
+ import { findLastEntry } from './find-last-entry.ts';
3
+ import { joinRawPath } from './join-raw-path.ts';
4
+ import type { JSONCNode } from './parse-jsonc-tree.ts';
5
+ import type { ConfigReference } from './types.ts';
6
+
7
+ // oxlint resolves each entry against the folder of the config, so a link counts by its own folder.
8
+ // An entry that is no path, such as a package specifier, may name a tracked file, and otherwise
9
+ // names a package whose shared config sets the rules.
10
+ export function collectExtendsPaths(path: string, root: JSONCNode): ConfigReference[] {
11
+ const extendsEntry = root.kind === 'object' ? findLastEntry(root.entries, 'extends') : undefined;
12
+
13
+ if (extendsEntry?.value.kind !== 'array') {
14
+ return [];
15
+ }
16
+
17
+ return extendsEntry.value.items.flatMap((item) =>
18
+ item.kind === 'literal'
19
+ ? [
20
+ {
21
+ path: joinRawPath(posix.dirname(path), item.text),
22
+ isOptional: isPackageLike(item.text),
23
+ },
24
+ ]
25
+ : [],
26
+ );
27
+ }
28
+
29
+ function isPackageLike(entry: string): boolean {
30
+ return !/^(?:\.{1,2}(?:\/|$)|\/)/u.test(entry) || entry.split('/').includes('node_modules');
31
+ }
@@ -1,20 +1,14 @@
1
+ import { findLastEntry } from './find-last-entry.ts';
1
2
  import type { JSONCEntry, JSONCNode } from './parse-jsonc-tree.ts';
2
- import { parseJSONCTree } from './parse-jsonc-tree.ts';
3
3
  import { stdHelperPaths } from './std-helper-paths.ts';
4
-
5
- export interface LintOverrideFinding {
6
- // Relative to the repo root.
7
- readonly path: string;
8
-
9
- readonly message: string;
10
- }
4
+ import type { LintOverrideFinding } from './types.ts';
11
5
 
12
6
  export function collectLintOverrideFindings(
13
7
  path: string,
14
- text: string,
8
+ root: JSONCNode,
15
9
  isToolsRepo: boolean,
16
10
  ): LintOverrideFinding[] {
17
- return collectSettings(parseJSONCTree(path, text), isToolsRepo).map((setting) => ({
11
+ return collectSettings(root, isToolsRepo).map((setting) => ({
18
12
  path,
19
13
  message: `line ${setting.line} sets ${setting.rule} to ${setting.severity}; ${pickFix(setting.rule)}`,
20
14
  }));
@@ -33,7 +27,7 @@ function collectSettings(root: JSONCNode, isToolsRepo: boolean): WeakSetting[] {
33
27
  return [];
34
28
  }
35
29
 
36
- const overrides = findEntry(root.entries, 'overrides')?.value;
30
+ const overrides = findLastEntry(root.entries, 'overrides')?.value;
37
31
  const items = overrides?.kind === 'array' ? overrides.items : [];
38
32
 
39
33
  return [
@@ -46,15 +40,11 @@ function collectSettings(root: JSONCNode, isToolsRepo: boolean): WeakSetting[] {
46
40
  ];
47
41
  }
48
42
 
49
- function findEntry(entries: readonly JSONCEntry[], key: string): JSONCEntry | undefined {
50
- return entries.find((entry) => entry.key === key);
51
- }
52
-
53
43
  function collectRuleSettings(
54
44
  entries: readonly JSONCEntry[],
55
45
  isHelperOverride: boolean,
56
46
  ): WeakSetting[] {
57
- const rules = findEntry(entries, 'rules')?.value;
47
+ const rules = findLastEntry(entries, 'rules')?.value;
58
48
 
59
49
  return rules?.kind === 'object'
60
50
  ? rules.entries.flatMap((rule) => collectWeakSettings(rule, isHelperOverride))
@@ -97,7 +87,7 @@ function isBareOff(value: JSONCNode): boolean {
97
87
  }
98
88
 
99
89
  function isStdHelperFiles(entries: readonly JSONCEntry[]): boolean {
100
- const files = entries.find((entry) => entry.key === 'files')?.value;
90
+ const files = findLastEntry(entries, 'files')?.value;
101
91
 
102
92
  return (
103
93
  files?.kind === 'array' &&
@@ -0,0 +1,97 @@
1
+ import { posix } from 'node:path';
2
+ import { findLastEntry } from './find-last-entry.ts';
3
+ import { joinRawPath } from './join-raw-path.ts';
4
+ import type { JSONCNode } from './parse-jsonc-tree.ts';
5
+ import { parseShellCommands } from './parse-shell-commands.ts';
6
+ import type { ConfigReference } from './types.ts';
7
+
8
+ // npm runs a script from its package.json's folder, so a relative path resolves there, or in the
9
+ // folder an earlier `cd` in the same script moved to.
10
+ export function collectScriptConfigPaths(path: string, root: JSONCNode): ConfigReference[] {
11
+ return collectScripts(root).flatMap((script) => {
12
+ const folders = { current: posix.dirname(path) };
13
+
14
+ return parseShellCommands(script).flatMap((words) => collectCommandPaths(words, folders));
15
+ });
16
+ }
17
+
18
+ function collectScripts(root: JSONCNode): string[] {
19
+ const scripts =
20
+ root.kind === 'object' ? findLastEntry(root.entries, 'scripts')?.value : undefined;
21
+
22
+ return scripts?.kind === 'object'
23
+ ? scripts.entries.flatMap((entry) => (entry.value.kind === 'literal' ? [entry.value.text] : []))
24
+ : [];
25
+ }
26
+
27
+ interface Folders {
28
+ current: string;
29
+ }
30
+
31
+ // Words that may stand before the program in a command: they run it, and add no `-c` of their own.
32
+ const launcherWords = new Set([
33
+ 'bun',
34
+ 'bunx',
35
+ 'command',
36
+ 'dlx',
37
+ 'env',
38
+ 'exec',
39
+ 'nohup',
40
+ 'npx',
41
+ 'pnpm',
42
+ 'run',
43
+ 'time',
44
+ 'x',
45
+ 'yarn',
46
+ ]);
47
+
48
+ function collectCommandPaths(words: readonly string[], folders: Folders): ConfigReference[] {
49
+ const start = words.findIndex((word) => !/^\w+=/u.test(word));
50
+ const first = words[start];
51
+
52
+ if (first === 'cd') {
53
+ const target = words[start + 1];
54
+
55
+ if (target !== undefined) {
56
+ folders.current = joinRawPath(folders.current, target);
57
+ }
58
+
59
+ return [];
60
+ }
61
+
62
+ const program = words.findIndex(
63
+ (word, index) => index >= start && posix.basename(word) === 'oxlint',
64
+ );
65
+
66
+ const isOxlintCommand =
67
+ program !== -1 &&
68
+ words
69
+ .slice(start, program)
70
+ .every((word) => launcherWords.has(posix.basename(word)) || word.startsWith('-'));
71
+
72
+ return isOxlintCommand
73
+ ? words.slice(program + 1).flatMap((word, index, rest) => {
74
+ const value = pickFlagValue(word, rest[index + 1]);
75
+
76
+ return value === null
77
+ ? []
78
+ : [
79
+ {
80
+ path: joinRawPath(folders.current, value),
81
+ isOptional: value.split('/').includes('node_modules'),
82
+ },
83
+ ];
84
+ })
85
+ : [];
86
+ }
87
+
88
+ // `-c file`, `-c=file`, `-cfile`, `--config file` and `--config=file`
89
+ function pickFlagValue(word: string, following: string | undefined): string | null {
90
+ if (word === '-c' || word === '--config') {
91
+ return following ?? null;
92
+ }
93
+
94
+ const match = /^(?:--config=|-c=?)(?<value>.+)$/u.exec(word);
95
+
96
+ return match?.groups?.['value'] ?? null;
97
+ }
@@ -0,0 +1,6 @@
1
+ import type { JSONCEntry } from './parse-jsonc-tree.ts';
2
+
3
+ // oxlint keeps the last of two equal keys in an object.
4
+ export function findLastEntry(entries: readonly JSONCEntry[], key: string): JSONCEntry | undefined {
5
+ return entries.findLast((entry) => entry.key === key);
6
+ }
@@ -0,0 +1,16 @@
1
+ // Joins an entry of a config or a script to the folder it resolves against, and keeps each `..`
2
+ // where it stands, since a link on the way changes what it means. An absolute entry stays absolute.
3
+ // A `.` or an empty segment goes, except at the end, where it still demands a folder.
4
+ export function joinRawPath(folder: string, entry: string): string {
5
+ if (entry.startsWith('/')) {
6
+ return entry;
7
+ }
8
+
9
+ const segments = entry
10
+ .split('/')
11
+ .filter(
12
+ (segment, index, all) => index === all.length - 1 || (segment !== '' && segment !== '.'),
13
+ );
14
+
15
+ return folder === '.' || folder === '' ? segments.join('/') : `${folder}/${segments.join('/')}`;
16
+ }
@@ -0,0 +1,3 @@
1
+ export class JSONCSyntaxError extends Error {
2
+ override name = 'JSONCSyntaxError';
3
+ }
@@ -1,3 +1,5 @@
1
+ import { JSONCSyntaxError } from './jsonc-syntax-error.ts';
2
+
1
3
  export interface JSONCToken {
2
4
  readonly kind: 'string' | 'other';
3
5
 
@@ -10,7 +12,7 @@ export interface JSONCToken {
10
12
 
11
13
  // Reads the tokens of a JSON file that holds comments and trailing commas, as oxlint accepts. The
12
14
  // comments are dropped.
13
- export function parseJSONCTokens(path: string, text: string): JSONCToken[] {
15
+ export function parseJSONCTokens(text: string): JSONCToken[] {
14
16
  const tokens: JSONCToken[] = [];
15
17
  let line = 1;
16
18
  let index = 0;
@@ -42,8 +44,8 @@ export function parseJSONCTokens(path: string, text: string): JSONCToken[] {
42
44
 
43
45
  advance(after);
44
46
  } else if (character === '"') {
45
- const end = getStringEnd(path, text, index);
46
- const body = parseString(path, text.slice(index, end));
47
+ const end = getStringEnd(text, index);
48
+ const body = parseString(text.slice(index, end));
47
49
  const start = advance(end);
48
50
 
49
51
  tokens.push({ kind: 'string', text: body, line: start });
@@ -58,7 +60,7 @@ export function parseJSONCTokens(path: string, text: string): JSONCToken[] {
58
60
  return tokens;
59
61
  }
60
62
 
61
- function getStringEnd(path: string, text: string, start: number): number {
63
+ function getStringEnd(text: string, start: number): number {
62
64
  for (let index = start + 1; index < text.length; index += 1) {
63
65
  const character = text.charAt(index);
64
66
 
@@ -69,16 +71,15 @@ function getStringEnd(path: string, text: string, start: number): number {
69
71
  }
70
72
  }
71
73
 
72
- throw new Error(`cannot parse ${path}: a string never closes`);
74
+ throw new JSONCSyntaxError('a string never closes');
73
75
  }
74
76
 
75
- function parseString(path: string, literal: string): string {
77
+ function parseString(literal: string): string {
76
78
  try {
77
79
  return String(JSON.parse(literal));
78
80
  } catch (error) {
79
- throw new Error(
80
- `cannot parse ${path}: ${error instanceof Error ? error.message : String(error)}`,
81
- { cause: error },
82
- );
81
+ const reason = error instanceof Error ? error.message : String(error);
82
+
83
+ throw new JSONCSyntaxError(reason, { cause: error });
83
84
  }
84
85
  }
@@ -1,3 +1,4 @@
1
+ import { JSONCSyntaxError } from './jsonc-syntax-error.ts';
1
2
  import type { JSONCToken } from './parse-jsonc-tokens.ts';
2
3
  import { parseJSONCTokens } from './parse-jsonc-tokens.ts';
3
4
 
@@ -6,38 +7,57 @@ export type JSONCNode =
6
7
  | { readonly kind: 'array'; readonly items: readonly JSONCNode[] }
7
8
  | { readonly kind: 'literal'; readonly text: string; readonly line: number };
8
9
 
9
- // Reads a JSON file that holds comments and trailing commas into a tree that keeps each key's line.
10
- export function parseJSONCTree(path: string, text: string): JSONCNode {
11
- const tokens = parseJSONCTokens(path, text);
12
- const cursor = { index: 0 };
13
- const root = parseNode(path, tokens, cursor);
10
+ export type JSONCTreeResult =
11
+ | { readonly isValid: true; readonly root: JSONCNode }
12
+ | { readonly isValid: false; readonly reason: string };
14
13
 
15
- if (cursor.index < tokens.length) {
16
- throw new Error(`cannot parse ${path}: unexpected text after the first value`);
17
- }
14
+ // Reads a JSON file that holds comments and trailing commas into a tree that keeps each key's line,
15
+ // and refuses what oxlint refuses, such as `undefined` or a missing comma.
16
+ export function parseJSONCTree(text: string): JSONCTreeResult {
17
+ try {
18
+ const tokens = parseJSONCTokens(text);
19
+ const cursor = { index: 0 };
20
+ const root = parseNode(tokens, cursor);
21
+
22
+ if (cursor.index < tokens.length) {
23
+ throw new JSONCSyntaxError('unexpected text after the first value');
24
+ }
25
+
26
+ return { isValid: true, root };
27
+ } catch (error) {
28
+ if (error instanceof JSONCSyntaxError) {
29
+ return { isValid: false, reason: error.message };
30
+ }
18
31
 
19
- return root;
32
+ throw error;
33
+ }
20
34
  }
21
35
 
22
36
  interface Cursor {
23
37
  index: number;
24
38
  }
25
39
 
26
- function parseNode(path: string, tokens: readonly JSONCToken[], cursor: Cursor): JSONCNode {
40
+ const bareValuePattern = /^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)$/u;
41
+
42
+ function parseNode(tokens: readonly JSONCToken[], cursor: Cursor): JSONCNode {
27
43
  const token = tokens[cursor.index];
28
44
 
29
45
  if (token === undefined) {
30
- throw new Error(`cannot parse ${path}: the file ends inside a value`);
46
+ throw new JSONCSyntaxError('the file ends inside a value');
31
47
  }
32
48
 
33
49
  cursor.index += 1;
34
50
 
35
51
  if (token.kind === 'other' && token.text === '{') {
36
- return { kind: 'object', entries: parseEntries(path, tokens, cursor) };
52
+ return { kind: 'object', entries: parseEntries(tokens, cursor) };
37
53
  }
38
54
 
39
55
  if (token.kind === 'other' && token.text === '[') {
40
- return { kind: 'array', items: parseItems(path, tokens, cursor) };
56
+ return { kind: 'array', items: parseItems(tokens, cursor) };
57
+ }
58
+
59
+ if (token.kind === 'other' && !bareValuePattern.test(token.text)) {
60
+ throw new JSONCSyntaxError(`line ${token.line} holds \`${token.text}\`, which is no value`);
41
61
  }
42
62
 
43
63
  return { kind: 'literal', text: token.text, line: token.line };
@@ -49,14 +69,14 @@ export interface JSONCEntry {
49
69
  readonly value: JSONCNode;
50
70
  }
51
71
 
52
- function parseEntries(path: string, tokens: readonly JSONCToken[], cursor: Cursor): JSONCEntry[] {
72
+ function parseEntries(tokens: readonly JSONCToken[], cursor: Cursor): JSONCEntry[] {
53
73
  const entries: JSONCEntry[] = [];
54
74
 
55
75
  for (;;) {
56
76
  const key = tokens[cursor.index];
57
77
 
58
78
  if (key === undefined) {
59
- throw new Error(`cannot parse ${path}: an object never closes`);
79
+ throw new JSONCSyntaxError('an object never closes');
60
80
  }
61
81
 
62
82
  cursor.index += 1;
@@ -65,28 +85,38 @@ function parseEntries(path: string, tokens: readonly JSONCToken[], cursor: Curso
65
85
  return entries;
66
86
  }
67
87
 
68
- if (key.kind === 'other' && key.text === ',') {
69
- continue;
70
- }
71
-
72
88
  if (key.kind !== 'string' || tokens[cursor.index]?.text !== ':') {
73
- throw new Error(`cannot parse ${path}: line ${key.line} holds no key`);
89
+ throw new JSONCSyntaxError(`line ${key.line} holds no key`);
74
90
  }
75
91
 
76
92
  cursor.index += 1;
77
93
 
78
- entries.push({ key: key.text, line: key.line, value: parseNode(path, tokens, cursor) });
94
+ entries.push({ key: key.text, line: key.line, value: parseNode(tokens, cursor) });
95
+
96
+ skipSeparator(tokens, cursor, '}');
97
+ }
98
+ }
99
+
100
+ // After a value, takes the comma that separates it from the next one, and leaves the closing token
101
+ // for the caller.
102
+ function skipSeparator(tokens: readonly JSONCToken[], cursor: Cursor, closer: string): void {
103
+ const next = tokens[cursor.index];
104
+
105
+ if (next?.kind === 'other' && next.text === ',') {
106
+ cursor.index += 1;
107
+ } else if (next !== undefined && !(next.kind === 'other' && next.text === closer)) {
108
+ throw new JSONCSyntaxError(`line ${next.line} holds no comma or \`${closer}\``);
79
109
  }
80
110
  }
81
111
 
82
- function parseItems(path: string, tokens: readonly JSONCToken[], cursor: Cursor): JSONCNode[] {
112
+ function parseItems(tokens: readonly JSONCToken[], cursor: Cursor): JSONCNode[] {
83
113
  const items: JSONCNode[] = [];
84
114
 
85
115
  for (;;) {
86
116
  const next = tokens[cursor.index];
87
117
 
88
118
  if (next === undefined) {
89
- throw new Error(`cannot parse ${path}: an array never closes`);
119
+ throw new JSONCSyntaxError('an array never closes');
90
120
  }
91
121
 
92
122
  if (next.kind === 'other' && next.text === ']') {
@@ -95,10 +125,8 @@ function parseItems(path: string, tokens: readonly JSONCToken[], cursor: Cursor)
95
125
  return items;
96
126
  }
97
127
 
98
- if (next.kind === 'other' && next.text === ',') {
99
- cursor.index += 1;
100
- } else {
101
- items.push(parseNode(path, tokens, cursor));
102
- }
128
+ items.push(parseNode(tokens, cursor));
129
+
130
+ skipSeparator(tokens, cursor, ']');
103
131
  }
104
132
  }
@@ -0,0 +1,57 @@
1
+ // Splits a shell script into its commands, each as its words with the quotes taken off. An unquoted
2
+ // `&&`, `||`, `;`, `|`, `&`, a parenthesis or a line break ends a command.
3
+ export function parseShellCommands(script: string): string[][] {
4
+ const commands: string[][] = [];
5
+ let words: string[] = [];
6
+ let word: string | null = null;
7
+ let quote: string | null = null;
8
+
9
+ const endWord = (): void => {
10
+ if (word !== null) {
11
+ words.push(word);
12
+
13
+ word = null;
14
+ }
15
+ };
16
+
17
+ const endCommand = (): void => {
18
+ endWord();
19
+
20
+ if (words.length > 0) {
21
+ commands.push(words);
22
+
23
+ words = [];
24
+ }
25
+ };
26
+
27
+ for (let index = 0; index < script.length; index += 1) {
28
+ const character = script.charAt(index);
29
+
30
+ if (quote !== null) {
31
+ if (character === quote) {
32
+ quote = null;
33
+ } else if (character === '\\' && quote === '"' && index + 1 < script.length) {
34
+ index += 1;
35
+ word = (word ?? '') + script.charAt(index);
36
+ } else {
37
+ word = (word ?? '') + character;
38
+ }
39
+ } else if (character === '"' || character === "'") {
40
+ quote = character;
41
+ word ??= '';
42
+ } else if (character === '\\' && index + 1 < script.length) {
43
+ index += 1;
44
+ word = (word ?? '') + script.charAt(index);
45
+ } else if (/\s/u.test(character) && character !== '\n') {
46
+ endWord();
47
+ } else if (/[\n;&|()]/u.test(character)) {
48
+ endCommand();
49
+ } else {
50
+ word = (word ?? '') + character;
51
+ }
52
+ }
53
+
54
+ endCommand();
55
+
56
+ return commands;
57
+ }
@@ -0,0 +1,19 @@
1
+ import type { TreeEntry } from './types.ts';
2
+
3
+ // git ls-tree -z prints "<mode> <type> <object>\t<path>" per entry; mode 120000 is a link. An entry
4
+ // that is no file and no link, such as a submodule, drops out.
5
+ export function parseTreeEntries(output: string): TreeEntry[] {
6
+ return output
7
+ .split('\0')
8
+ .filter((line) => line.includes('\t'))
9
+ .flatMap((line): TreeEntry[] => {
10
+ const tabIndex = line.indexOf('\t');
11
+ const path = line.slice(tabIndex + 1);
12
+
13
+ if (line.startsWith('120000 ')) {
14
+ return [{ path, isLink: true }];
15
+ }
16
+
17
+ return / blob /u.test(line.slice(0, tabIndex)) ? [{ path, isLink: false }] : [];
18
+ });
19
+ }
@@ -0,0 +1,59 @@
1
+ import type { TrackedTree } from './types.ts';
2
+
3
+ const maxLinkHops = 40;
4
+
5
+ // Follows each tracked link on the way, a linked folder in the middle too, as the operating system
6
+ // would. Returns the tracked file the path ends at, or null when the path ends at no file, leaves
7
+ // the repo, loops, is absolute, or treats a file as a folder.
8
+ export function resolveTrackedPath(path: string, tree: Readonly<TrackedTree>): string | null {
9
+ if (path.startsWith('/')) {
10
+ return null;
11
+ }
12
+
13
+ const done: string[] = [];
14
+ const pending = path.split('/');
15
+ let hops = 0;
16
+
17
+ while (pending.length > 0) {
18
+ const segment = pending.shift();
19
+
20
+ if (segment === undefined) {
21
+ continue;
22
+ }
23
+
24
+ if (segment === '' || segment === '.' || segment === '..') {
25
+ if (done.length > 0 && !tree.directories.has(done.join('/'))) {
26
+ return null;
27
+ }
28
+
29
+ if (segment === '..') {
30
+ if (done.length === 0) {
31
+ return null;
32
+ }
33
+
34
+ done.pop();
35
+ }
36
+
37
+ continue;
38
+ }
39
+
40
+ done.push(segment);
41
+
42
+ const target = tree.links.get(done.join('/'));
43
+
44
+ if (target !== undefined) {
45
+ hops += 1;
46
+
47
+ if (hops > maxLinkHops || target.startsWith('/')) {
48
+ return null;
49
+ }
50
+
51
+ done.pop();
52
+ pending.unshift(...target.split('/'));
53
+ }
54
+ }
55
+
56
+ const resolved = done.join('/');
57
+
58
+ return tree.files.has(resolved) ? resolved : null;
59
+ }
@@ -1,8 +1,9 @@
1
- import { basename } from 'node:path';
2
1
  import type { RunProgram } from '../program/run-program.ts';
3
2
  import { runProgram } from '../program/run-program.ts';
4
- import { collectLintOverrideFindings } from './collect-lint-override-findings.ts';
5
- import type { LintOverrideFinding } from './collect-lint-override-findings.ts';
3
+ import { buildTrackedTree } from './build-tracked-tree.ts';
4
+ import { collectConfigReport } from './collect-config-report.ts';
5
+ import { parseTreeEntries } from './parse-tree-entries.ts';
6
+ import type { LintOverrideFinding } from './types.ts';
6
7
 
7
8
  export interface LintOverridesCheckOptions {
8
9
  readonly cwd: string;
@@ -10,23 +11,34 @@ export interface LintOverridesCheckOptions {
10
11
  readonly runProgram: RunProgram;
11
12
  }
12
13
 
13
- const configPattern = /^\.?oxlintrc(?:\.[\w-]+)*\.jsonc?$/u;
14
-
15
- // The check reads the files as HEAD holds them, so a push checks what it sends.
14
+ // The check reads the files as HEAD holds them, so a push checks what it sends. Each file is read
15
+ // once: the report names the files it still needs, and the loop reads them and asks again.
16
16
  export function runLintOverridesCheck(
17
17
  options: Readonly<LintOverridesCheckOptions>,
18
18
  ): LintOverrideFinding[] {
19
- const paths = runGit(options, ['ls-tree', '-r', '-z', '--name-only', 'HEAD']).split('\0');
19
+ const entries = parseTreeEntries(runGit(options, ['ls-tree', '-r', '-z', 'HEAD']));
20
20
 
21
- const isToolsRepo =
22
- readManifestName(options, paths, 'package.json') === 'tools' &&
23
- readManifestName(options, paths, 'packages/std/package.json') === '@zgeoff/std';
21
+ const linkTargets = new Map(
22
+ entries
23
+ .filter((entry) => entry.isLink)
24
+ .map((entry) => [entry.path, runGit(options, ['show', `HEAD:${entry.path}`])]),
25
+ );
24
26
 
25
- return paths
26
- .filter((path) => configPattern.test(basename(path)))
27
- .flatMap((path) =>
28
- collectLintOverrideFindings(path, runGit(options, ['show', `HEAD:${path}`]), isToolsRepo),
29
- );
27
+ const tree = buildTrackedTree(entries, linkTargets);
28
+
29
+ const texts = new Map<string, string>();
30
+
31
+ for (;;) {
32
+ const report = collectConfigReport(tree, texts);
33
+
34
+ if (report.missing.length === 0) {
35
+ return report.findings;
36
+ }
37
+
38
+ for (const file of report.missing) {
39
+ texts.set(file, runGit(options, ['show', `HEAD:${file}`]));
40
+ }
41
+ }
30
42
  }
31
43
 
32
44
  function runGit(options: Readonly<LintOverridesCheckOptions>, args: readonly string[]): string {
@@ -39,24 +51,6 @@ function runGit(options: Readonly<LintOverridesCheckOptions>, args: readonly str
39
51
  return result.stdout;
40
52
  }
41
53
 
42
- function readManifestName(
43
- options: Readonly<LintOverridesCheckOptions>,
44
- paths: readonly string[],
45
- manifestPath: string,
46
- ): unknown {
47
- if (!paths.includes(manifestPath)) {
48
- return null;
49
- }
50
-
51
- try {
52
- const manifest: unknown = JSON.parse(runGit(options, ['show', `HEAD:${manifestPath}`]));
53
-
54
- return typeof manifest === 'object' && manifest !== null ? Reflect.get(manifest, 'name') : null;
55
- } catch {
56
- return null;
57
- }
58
- }
59
-
60
54
  // Returns the exit code: 0 when clean, 1 with a finding, and 2 when the check cannot run.
61
55
  export function runLintOverridesCommand(): number {
62
56
  try {
@@ -0,0 +1,30 @@
1
+ export interface TrackedTree {
2
+ // Each tracked link, with the target text it holds.
3
+ readonly links: ReadonlyMap<string, string>;
4
+
5
+ // Each tracked file that is no link.
6
+ readonly files: ReadonlySet<string>;
7
+
8
+ // Each folder that holds a tracked file or link, at any depth.
9
+ readonly directories: ReadonlySet<string>;
10
+ }
11
+
12
+ export interface TreeEntry {
13
+ readonly path: string;
14
+ readonly isLink: boolean;
15
+ }
16
+
17
+ export interface LintOverrideFinding {
18
+ // Relative to the repo root.
19
+ readonly path: string;
20
+
21
+ readonly message: string;
22
+ }
23
+
24
+ export interface ConfigReference {
25
+ // The path as written against the folder of the referring file, with each `..` kept in place.
26
+ readonly path: string;
27
+
28
+ // True for a reference that may name a package, and so may leave no tracked file.
29
+ readonly isOptional: boolean;
30
+ }