@alxwlw/repo-rules 0.0.0-stage → 1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 alxwlw
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,78 @@
1
- # Temporary Holding Version
1
+ # @alxwlw/repo-rules
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Whole-repository checks that came out of a defect corpus: each one is a class of defect that already cost a review round. They run in CI and locally, on Node ≥ 20, with no dependencies.
4
+
5
+ ```bash
6
+ pnpm add -D @alxwlw/repo-rules
7
+ pnpm exec repo-rules baseline --init # once: record what is already there
8
+ pnpm exec repo-rules check # every run: nothing new, nothing stale
9
+ pnpm exec repo-rules diff --base origin/main
10
+ ```
11
+
12
+ ```
13
+ repo-rules [-C <dir>] check [--json]
14
+ repo-rules [-C <dir>] diff [--base <ref>] [--json]
15
+ repo-rules [-C <dir>] baseline [--init] [--allow-grow]
16
+ ```
17
+
18
+ `-C <dir>` runs in that directory (any place inside the repository). `--json` prints `{ violations, stale, notes }` instead of text lines. `--help` prints the usage; a missing or unknown command prints it on stderr and exits 2.
19
+
20
+ ## Rules
21
+
22
+ | Rule | Flags |
23
+ | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
24
+ | `max-lines` | a tracked text file over 800 lines (plans, lockfiles, JSON, snapshots, generated and vendored files excluded) |
25
+ | `suppression-reason` | `eslint-disable*` / `oxlint-disable*` / `solhint-disable*` without ` -- reason`; `@ts-expect-error` / `@ts-ignore` without trailing text; `biome-ignore` without text after `:`; Python `# noqa` / `# type: ignore` without ` -- reason` |
26
+ | `focused-skipped-tests` | in JS/TS test files: `.only(` on any line (the scan is line-based, see Limits); `.skip(` / `.todo(` / `xit(` / `xdescribe(` / `xtest(` without a ` -- reason` comment on the line or the comment line above. `.skipIf` / `.runIf` and Playwright's `test.skip(condition, reason)` are fine |
27
+ | `number-or-default` | in non-test JS/TS files: `Number(…)`, `Number.parseInt(…)`, `Number.parseFloat(…)`, `parseInt(…)`, `parseFloat(…)` followed by `\|\| <non-zero literal>`: a real 0 silently becomes the default |
28
+ | `removed-assertions` (`diff`) | a test file whose diff removes more `expect(` / `assert…` than it adds; an assertion inside a comment counts as neither removed nor added (comments recognised: `//`, `/* … */` on the line, a line starting with `*`; `#` in Python; an unclosed `/*` and a line starting with `*` hide the rest of the line, including code after a `*/`). `exclude` (`*` or `removed-assertions`) applies. A `Tests-Removed: <reason>` commit trailer in the range accepts it |
29
+
30
+ A reason is at least three non-space characters.
31
+
32
+ ## Baseline
33
+
34
+ `.repo-rules-baseline.json` records the violations that already exist: line count per long file, hit count per file for the other rules. `check` fails when a file goes over its entry, and also when an entry is higher than reality (stale), so a fixed place cannot be reused by a new one. `baseline` only lowers entries; raising one takes `--allow-grow`, which shows in the PR diff.
35
+
36
+ ## Configuration
37
+
38
+ Optional `.repo-rules.json`:
39
+
40
+ ```json
41
+ {
42
+ "maxLines": 800,
43
+ "exclude": { "*": ["public/vendor/**"], "max-lines": ["docs/*.html"] },
44
+ "testGlobs": [
45
+ "**/*.{test,spec}.*",
46
+ "**/__tests__/**",
47
+ "**/test/**",
48
+ "**/tests/**",
49
+ "**/*.t.sol",
50
+ "**/test_*.py",
51
+ "**/*_test.py"
52
+ ]
53
+ }
54
+ ```
55
+
56
+ `testGlobs` replaces the default list, shown in full above; it does not add to it. `exclude` takes `*` or a rule name — the four rules above and `removed-assertions`.
57
+
58
+ ## Limits
59
+
60
+ - Comments are found by a line heuristic, not a parser: a quote inside a regex literal or JSX text can hide a directive later on that line.
61
+ - `<!-- -->` comments in `.vue` and `.svelte` files are not read.
62
+ - `number-or-default` misses `|| .5`, and a `||=` default applied to a variable that holds a `Number(…)` result.
63
+ - `removed-assertions` does not see a test disabled by a rename with no content change (for example `a.test.ts` → `a.test.ts.off`).
64
+ - `removed-assertions` reads a line inside a multi-line `/* … */` block that does not start with `*` (for example a re-indented one) as code.
65
+ - Assertions moved into a helper count as removed; the `Tests-Removed` trailer is the way out.
66
+ - The scan is line-based and does not know whether a line sits inside a string or a template literal, so `.only(` or `.skip(` inside a fixture string is flagged.
67
+
68
+ ## CI
69
+
70
+ ```yaml
71
+ - uses: actions/checkout@v5
72
+ with:
73
+ fetch-depth: 0 # diff needs the merge-base
74
+ - run: pnpm exec repo-rules check
75
+ - run: pnpm exec repo-rules diff # base = origin/$GITHUB_BASE_REF in a pull_request job, skipped otherwise
76
+ ```
77
+
78
+ Exit codes: 0 clean, 1 violations or stale baseline, 2 error (never read as clean).
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
- "name": "@alxwlw/repo-rules",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@alxwlw/repo-rules",
3
+ "version": "1.6.1",
4
+ "description": "Whole-repo lint rules from the alxwlw defect corpus — long files, unjustified suppressions, skipped/focused tests, Number(x) || <default>, removed assertions — with a shrink-only baseline.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/alxwlw/stack.git"
9
+ },
10
+ "bin": {
11
+ "repo-rules": "src/cli.mjs"
12
+ },
13
+ "files": [
14
+ "src",
15
+ "!src/**/*.test.ts",
16
+ "!src/testkit.ts"
17
+ ],
18
+ "type": "module",
19
+ "engines": {
20
+ "node": ">=20"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public",
24
+ "provenance": true
25
+ }
26
+ }
@@ -0,0 +1,139 @@
1
+ // @ts-check
2
+ /** `.repo-rules-baseline.json` (spec § 3). */
3
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+
6
+ import { REPO_RULES } from './config.mjs';
7
+ import { RepoRulesError } from './git.mjs';
8
+
9
+ export const BASELINE_FILE = '.repo-rules-baseline.json';
10
+
11
+ /** @typedef {import('./config.mjs').RepoRule} RepoRule */
12
+ /** @typedef {Record<RepoRule, Record<string, number>>} Counts */
13
+ /** @typedef {import('./scan.mjs').Violation} Violation */
14
+
15
+ /** @returns {Counts} */
16
+ export const emptyCounts = () => ({
17
+ 'max-lines': {},
18
+ 'suppression-reason': {},
19
+ 'focused-skipped-tests': {},
20
+ 'number-or-default': {},
21
+ });
22
+
23
+ /**
24
+ * @param {string} root
25
+ * @returns {Counts | null} null when the file does not exist
26
+ */
27
+ export function loadBaseline(root) {
28
+ const path = join(root, BASELINE_FILE);
29
+ if (!existsSync(path)) return null;
30
+ let raw;
31
+ try {
32
+ raw = JSON.parse(readFileSync(path, 'utf8'));
33
+ } catch (e) {
34
+ throw new RepoRulesError(`${BASELINE_FILE}: not JSON (${/** @type {Error} */ (e).message})`);
35
+ }
36
+ if (raw === null || typeof raw !== 'object' || raw.version !== 1) {
37
+ throw new RepoRulesError(`${BASELINE_FILE}: version must be 1`);
38
+ }
39
+ for (const key of Object.keys(raw)) {
40
+ if (key !== 'version' && key !== 'rules')
41
+ throw new RepoRulesError(`${BASELINE_FILE}: unknown field «${key}»`);
42
+ }
43
+ const rules = 'rules' in raw ? raw.rules : {};
44
+ if (rules === null || typeof rules !== 'object' || Array.isArray(rules))
45
+ throw new RepoRulesError(`${BASELINE_FILE}: rules must be an object`);
46
+ const counts = emptyCounts();
47
+ for (const [rule, files] of Object.entries(rules)) {
48
+ if (!REPO_RULES.includes(/** @type {RepoRule} */ (rule))) {
49
+ throw new RepoRulesError(`${BASELINE_FILE}: unknown rule «${rule}»`);
50
+ }
51
+ if (files === null || typeof files !== 'object' || Array.isArray(files)) {
52
+ throw new RepoRulesError(`${BASELINE_FILE}: rules.${rule} must map paths to counts`);
53
+ }
54
+ for (const [path, n] of Object.entries(files)) {
55
+ if (!Number.isInteger(n) || n < 1) {
56
+ throw new RepoRulesError(
57
+ `${BASELINE_FILE}: rules.${rule}["${path}"] must be a positive integer`,
58
+ );
59
+ }
60
+ counts[/** @type {RepoRule} */ (rule)][path] = n;
61
+ }
62
+ }
63
+ return counts;
64
+ }
65
+
66
+ /**
67
+ * @typedef {object} Comparison
68
+ * @property {Violation[]} violations places in files over their baseline
69
+ * @property {{ rule: RepoRule, path: string, baseline: number, actual: number }[]} stale
70
+ */
71
+
72
+ /**
73
+ * @param {Counts} actual
74
+ * @param {Violation[]} hits
75
+ * @param {Counts} baseline
76
+ * @returns {Comparison}
77
+ */
78
+ export function compare(actual, hits, baseline) {
79
+ /** @type {Comparison} */
80
+ const out = { violations: [], stale: [] };
81
+ for (const rule of REPO_RULES) {
82
+ for (const [path, n] of Object.entries(actual[rule])) {
83
+ const b = baseline[rule][path];
84
+ if (b === undefined || n > b) {
85
+ for (const h of hits) {
86
+ if (h.rule === rule && h.path === path) {
87
+ out.violations.push(
88
+ b === undefined ? h : { ...h, message: `${h.message} (baseline ${b})` },
89
+ );
90
+ }
91
+ }
92
+ }
93
+ }
94
+ for (const [path, b] of Object.entries(baseline[rule])) {
95
+ const n = actual[rule][path] ?? 0;
96
+ if (n < b) out.stale.push({ rule, path, baseline: b, actual: n });
97
+ }
98
+ }
99
+ return out;
100
+ }
101
+
102
+ /**
103
+ * Entries that would rise or appear if `next` replaced `prev`.
104
+ * @param {Counts} prev
105
+ * @param {Counts} next
106
+ * @returns {{ rule: RepoRule, path: string, from: number, to: number }[]}
107
+ */
108
+ export function growth(prev, next) {
109
+ /** @type {{ rule: RepoRule, path: string, from: number, to: number }[]} */
110
+ const up = [];
111
+ for (const rule of REPO_RULES) {
112
+ for (const [path, n] of Object.entries(next[rule])) {
113
+ const b = prev[rule][path] ?? 0;
114
+ if (n > b) up.push({ rule, path, from: b, to: n });
115
+ }
116
+ }
117
+ return up;
118
+ }
119
+
120
+ /**
121
+ * Keys sorted, the existing file's indentation kept (tab or two spaces), trailing newline.
122
+ * @param {string} root
123
+ * @param {Counts} counts
124
+ */
125
+ export function writeBaseline(root, counts) {
126
+ const path = join(root, BASELINE_FILE);
127
+ let indent = ' ';
128
+ if (existsSync(path) && /^\t/m.test(readFileSync(path, 'utf8'))) indent = '\t';
129
+ /** @type {Record<string, Record<string, number>>} */
130
+ const rules = {};
131
+ for (const rule of REPO_RULES) {
132
+ const files = Object.keys(counts[rule]).sort();
133
+ if (!files.length) continue;
134
+ rules[rule] = Object.fromEntries(
135
+ files.map((f) => [f, /** @type {number} */ (counts[rule][f])]),
136
+ );
137
+ }
138
+ writeFileSync(path, `${JSON.stringify({ version: 1, rules }, null, indent)}\n`);
139
+ }
package/src/cli.mjs ADDED
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env node
2
+ // @ts-check
3
+ /** Bin entry: `repo-rules check | diff --base <ref> | baseline [--init] [--allow-grow]`. */
4
+ import { RepoRulesError } from './git.mjs';
5
+ import { run } from './main.mjs';
6
+
7
+ // Attached before the first write: a closed pipe (EPIPE) or a full disk (ENOSPC) on stdout is one
8
+ // error line and exit 2, never an unhandled 'error' stack that exits 1.
9
+ let stdoutFailed = false;
10
+ process.stdout.on('error', (e) => {
11
+ if (!stdoutFailed) process.stderr.write(`repo-rules: ${e.message}\n`);
12
+ stdoutFailed = true;
13
+ process.exitCode = 2;
14
+ });
15
+
16
+ try {
17
+ process.exitCode = run(
18
+ process.argv.slice(2),
19
+ process.env,
20
+ (s) => process.stdout.write(`${s}\n`),
21
+ (s) => process.stderr.write(`${s}\n`),
22
+ );
23
+ } catch (e) {
24
+ // 2, never 0 or 1: an error must not read as «clean» or as «violations found».
25
+ if (e instanceof RepoRulesError) process.stderr.write(`repo-rules: ${e.message}\n`);
26
+ else process.stderr.write(`repo-rules: internal error: ${/** @type {Error} */ (e).stack ?? e}\n`);
27
+ process.exitCode = 2;
28
+ }
package/src/config.mjs ADDED
@@ -0,0 +1,143 @@
1
+ // @ts-check
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+
5
+ import { RepoRulesError } from './git.mjs';
6
+ import { globToRegExp } from './glob.mjs';
7
+
8
+ export const CONFIG_FILE = '.repo-rules.json';
9
+
10
+ /** Rules that scan the whole repository (spec § 2). */
11
+ export const REPO_RULES = /** @type {const} */ ([
12
+ 'max-lines',
13
+ 'suppression-reason',
14
+ 'focused-skipped-tests',
15
+ 'number-or-default',
16
+ ]);
17
+
18
+ /** @typedef {(typeof REPO_RULES)[number]} RepoRule */
19
+
20
+ /** `exclude` also takes the `diff` rule (spec § 5): it is not a whole-repo rule, so not in `REPO_RULES`. */
21
+ const EXCLUDE_KEYS = ['*', 'removed-assertions', ...REPO_RULES];
22
+
23
+ export const DEFAULT_MAX_LINES = 800;
24
+
25
+ /** Spec § 2, `max-lines` default exclusions. */
26
+ export const MAX_LINES_EXCLUDE = [
27
+ 'docs/**/plans/**',
28
+ '**/pnpm-lock.yaml',
29
+ '**/package-lock.json',
30
+ '**/yarn.lock',
31
+ '**/bun.lock',
32
+ '**/*.lock',
33
+ '**/*.json',
34
+ '**/*.d.ts',
35
+ '**/*.snap',
36
+ '**/__snapshots__/**',
37
+ '**/*.min.*',
38
+ '**/*.map',
39
+ '**/*.svg',
40
+ '**/generated/**',
41
+ '**/*.gen.*',
42
+ '**/dist/**',
43
+ '**/build/**',
44
+ '**/coverage/**',
45
+ '**/vendor/**',
46
+ '**/third_party/**',
47
+ '**/CHANGELOG.md',
48
+ '**/migrations/**/*.sql',
49
+ ];
50
+
51
+ /** Spec § 5, default `testGlobs`. */
52
+ export const DEFAULT_TEST_GLOBS = [
53
+ '**/*.{test,spec}.*',
54
+ '**/__tests__/**',
55
+ '**/test/**',
56
+ '**/tests/**',
57
+ '**/*.t.sol',
58
+ '**/test_*.py',
59
+ '**/*_test.py',
60
+ ];
61
+
62
+ /**
63
+ * @typedef {object} Config
64
+ * @property {number} maxLines
65
+ * @property {Record<string, string[]>} exclude key `*` or a rule name
66
+ * @property {string[]} testGlobs
67
+ */
68
+
69
+ /**
70
+ * @param {unknown} v
71
+ * @returns {v is string[]}
72
+ */
73
+ const isStringArray = (v) => Array.isArray(v) && v.every((x) => typeof x === 'string');
74
+
75
+ /**
76
+ * Compile every glob once, so a malformed one is a config error naming its field.
77
+ * @param {string[]} globs
78
+ * @param {string} field
79
+ * @returns {void}
80
+ */
81
+ function checkGlobs(globs, field) {
82
+ for (const g of globs) {
83
+ try {
84
+ globToRegExp(g);
85
+ } catch (e) {
86
+ throw new RepoRulesError(`${CONFIG_FILE}: ${field}: ${/** @type {Error} */ (e).message}`);
87
+ }
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Read `.repo-rules.json` (optional) and merge it over the defaults.
93
+ * @param {string} root
94
+ * @returns {Config}
95
+ */
96
+ export function loadConfig(root) {
97
+ /** @type {Config} */
98
+ const cfg = { maxLines: DEFAULT_MAX_LINES, exclude: {}, testGlobs: DEFAULT_TEST_GLOBS };
99
+ const path = join(root, CONFIG_FILE);
100
+ if (!existsSync(path)) return cfg;
101
+ let raw;
102
+ try {
103
+ raw = JSON.parse(readFileSync(path, 'utf8'));
104
+ } catch (e) {
105
+ throw new RepoRulesError(`${CONFIG_FILE}: not JSON (${/** @type {Error} */ (e).message})`);
106
+ }
107
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
108
+ throw new RepoRulesError(`${CONFIG_FILE}: top level is not an object`);
109
+ }
110
+ for (const key of Object.keys(raw)) {
111
+ if (!['maxLines', 'exclude', 'testGlobs'].includes(key)) {
112
+ throw new RepoRulesError(`${CONFIG_FILE}: unknown field «${key}»`);
113
+ }
114
+ }
115
+ if ('maxLines' in raw) {
116
+ if (!Number.isInteger(raw.maxLines) || raw.maxLines < 1) {
117
+ throw new RepoRulesError(`${CONFIG_FILE}: maxLines must be a positive integer`);
118
+ }
119
+ cfg.maxLines = raw.maxLines;
120
+ }
121
+ if ('exclude' in raw) {
122
+ const ex = raw.exclude;
123
+ if (ex === null || typeof ex !== 'object' || Array.isArray(ex)) {
124
+ throw new RepoRulesError(`${CONFIG_FILE}: exclude must map «*» or a rule name to globs`);
125
+ }
126
+ for (const [k, v] of Object.entries(ex)) {
127
+ if (!EXCLUDE_KEYS.includes(k)) {
128
+ throw new RepoRulesError(`${CONFIG_FILE}: exclude: unknown rule «${k}»`);
129
+ }
130
+ if (!isStringArray(v))
131
+ throw new RepoRulesError(`${CONFIG_FILE}: exclude.${k} must be a list of globs`);
132
+ }
133
+ for (const [k, v] of Object.entries(ex)) checkGlobs(v, `exclude.${k}`);
134
+ cfg.exclude = ex;
135
+ }
136
+ if ('testGlobs' in raw) {
137
+ if (!isStringArray(raw.testGlobs))
138
+ throw new RepoRulesError(`${CONFIG_FILE}: testGlobs must be a list of globs`);
139
+ checkGlobs(raw.testGlobs, 'testGlobs');
140
+ cfg.testGlobs = raw.testGlobs;
141
+ }
142
+ return cfg;
143
+ }
package/src/diff.mjs ADDED
@@ -0,0 +1,230 @@
1
+ // @ts-check
2
+ /** `removed-assertions` (DP-014, spec § 4). */
3
+ import { git, RepoRulesError } from './git.mjs';
4
+ import { matcher } from './glob.mjs';
5
+ import { commentStart, familyOf, hasReason } from './source.mjs';
6
+
7
+ /** @typedef {import('./config.mjs').Config} Config */
8
+
9
+ const JS_ASSERT = /\bexpect\s*\(|\bassert\s*\(|\bassert\.\w+\s*\(/g;
10
+ const SOL_ASSERT = /\bassert[A-Z]\w*\s*\(/g;
11
+ const PY_ASSERT = /^\s*assert\b|\bself\.assert[A-Z]\w*\s*\(/g;
12
+
13
+ /**
14
+ * @param {string} path
15
+ * @returns {RegExp | null}
16
+ */
17
+ function assertionPattern(path) {
18
+ if (/\.(?:ts|tsx|js|jsx|mjs|cjs|mts|cts)$/.test(path)) return JS_ASSERT;
19
+ if (path.endsWith('.sol')) return SOL_ASSERT;
20
+ if (path.endsWith('.py')) return PY_ASSERT;
21
+ return null;
22
+ }
23
+
24
+ /**
25
+ * The code of a diff line: its comments cut out (DP-030). A `/* … *\/` closed on the same line is
26
+ * whitespace and the code after it stays; `//`, an unclosed `/*`, a leading `*` and Python `#` cut to the end.
27
+ * @param {string} text
28
+ * @param {import('./source.mjs').Family} family
29
+ * @returns {string}
30
+ */
31
+ function codeOf(text, family) {
32
+ let code = '';
33
+ let rest = text;
34
+ // After the first span the rest is no line start: the `;` keeps a `*` there from reading as a continuation.
35
+ let pad = '';
36
+ for (;;) {
37
+ const c = commentStart(pad + rest, family);
38
+ if (c < 0) return code + rest;
39
+ const cut = c - pad.length;
40
+ const end = !rest.startsWith('/*', cut) ? -1 : rest.indexOf('*/', cut + 2);
41
+ if (end < 0) return code + rest.slice(0, cut);
42
+ code += `${rest.slice(0, cut)} `;
43
+ rest = rest.slice(end + 2);
44
+ pad = ';';
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Assertions in the code part of a diff line: a commented-out `// expect(…)` is not one (DP-030).
50
+ * @param {string} text
51
+ * @param {Side} side
52
+ */
53
+ function countIn(text, side) {
54
+ return [...(side.family ? codeOf(text, side.family) : text).matchAll(side.re)].length;
55
+ }
56
+
57
+ /** @type {Record<string, string>} */
58
+ const C_ESCAPES = { a: '\x07', b: '\b', t: '\t', n: '\n', v: '\v', f: '\f', r: '\r' };
59
+
60
+ /**
61
+ * A name as git prints it on a header line: C-quoted (`"…"`, `\` escapes) when it holds a control
62
+ * character, `"` or `\`; a `---`/`+++` name with a space is followed by a TAB.
63
+ * @param {string} text
64
+ * @returns {string}
65
+ */
66
+ function gitPath(text) {
67
+ const t = text.endsWith('\t') ? text.slice(0, -1) : text;
68
+ if (!t.startsWith('"')) return t;
69
+ return t
70
+ .slice(1, -1)
71
+ .replace(/\\([0-7]{3}|.)/g, (_, /** @type {string} */ esc) =>
72
+ esc.length === 3 ? String.fromCharCode(Number.parseInt(esc, 8)) : (C_ESCAPES[esc] ?? esc),
73
+ );
74
+ }
75
+
76
+ /** @typedef {{ re: RegExp, family: import('./source.mjs').Family | null }} Side */
77
+
78
+ /**
79
+ * The counting rule of one side of a pair, by that side's own path; null when it is no test.
80
+ * @param {string | null} path
81
+ * @param {boolean} tested
82
+ * @returns {Side | null}
83
+ */
84
+ function sideOf(path, tested) {
85
+ const re = path !== null && tested ? assertionPattern(path) : null;
86
+ return re && path !== null ? { re, family: familyOf(path) } : null;
87
+ }
88
+
89
+ /**
90
+ * @typedef {object} PairCount
91
+ * @property {string | null} from
92
+ * @property {string | null} to
93
+ * @property {number} removed
94
+ * @property {number} added
95
+ */
96
+
97
+ /**
98
+ * Parse `git diff -M --unified=0` into per-pair assertion counts for test files.
99
+ * @param {string} diff
100
+ * @param {(path: string) => boolean} isTest
101
+ * @returns {PairCount[]}
102
+ */
103
+ export function countPairs(diff, isTest) {
104
+ /** @type {PairCount[]} */
105
+ const pairs = [];
106
+ /** @type {PairCount | null} */
107
+ let cur = null;
108
+ /** @type {Side | null} */
109
+ let del = null;
110
+ /** @type {Side | null} */
111
+ let ins = null;
112
+ let inHunk = false;
113
+ for (const line of diff.split('\n')) {
114
+ if (line.startsWith('diff --git ')) {
115
+ cur = { from: null, to: null, removed: 0, added: 0 };
116
+ pairs.push(cur);
117
+ del = ins = null;
118
+ inHunk = false;
119
+ continue;
120
+ }
121
+ if (!cur) continue;
122
+ if (!inHunk) {
123
+ // `a/` and `b/` are set explicitly in `removedAssertions`, whatever `diff.noprefix` says.
124
+ if (line.startsWith('--- '))
125
+ cur.from = line === '--- /dev/null' ? null : gitPath(line.slice(4)).slice(2);
126
+ else if (line.startsWith('+++ ')) {
127
+ cur.to = line === '+++ /dev/null' ? null : gitPath(line.slice(4)).slice(2);
128
+ } else if (line.startsWith('rename from ')) cur.from = gitPath(line.slice(12));
129
+ else if (line.startsWith('rename to ')) cur.to = gitPath(line.slice(10));
130
+ else if (line.startsWith('@@')) {
131
+ inHunk = true;
132
+ // Each side is read in its own language: a rename may change it, e.g. a Python test ported to TypeScript.
133
+ const tested =
134
+ (cur.from !== null && isTest(cur.from)) || (cur.to !== null && isTest(cur.to));
135
+ del = sideOf(cur.from, tested);
136
+ ins = sideOf(cur.to, tested);
137
+ }
138
+ continue;
139
+ }
140
+ if (line.startsWith('@@')) continue;
141
+ if (line.startsWith('-') && del) cur.removed += countIn(line.slice(1), del);
142
+ else if (line.startsWith('+') && ins) cur.added += countIn(line.slice(1), ins);
143
+ }
144
+ return pairs.filter((p) => p.removed > 0 || p.added > 0);
145
+ }
146
+
147
+ /**
148
+ * @typedef {object} DiffResult
149
+ * @property {{ path: string, removed: number, added: number }[]} violations
150
+ * @property {string[]} reasons `Tests-Removed` trailers of the range
151
+ * @property {boolean} skipped
152
+ */
153
+
154
+ /**
155
+ * @param {string} root
156
+ * @param {Config} cfg
157
+ * @param {string | undefined} base
158
+ * @param {NodeJS.ProcessEnv} env
159
+ * @returns {DiffResult}
160
+ */
161
+ export function removedAssertions(root, cfg, base, env) {
162
+ if (!base) {
163
+ const actions = env.GITHUB_ACTIONS === 'true';
164
+ const pr =
165
+ env.GITHUB_EVENT_NAME === 'pull_request' || env.GITHUB_EVENT_NAME === 'pull_request_target';
166
+ if (actions && !pr) return { violations: [], reasons: [], skipped: true };
167
+ // In a pull_request job the base is known: the same command line works in every repo's CI.
168
+ if (actions && env.GITHUB_BASE_REF) base = `origin/${env.GITHUB_BASE_REF}`;
169
+ else throw new RepoRulesError('diff needs --base <ref>');
170
+ }
171
+ const mb = git(root, ['merge-base', base, 'HEAD']).trim();
172
+ const diff = git(root, [
173
+ 'diff',
174
+ '-M',
175
+ '--unified=0',
176
+ '--no-color',
177
+ '--src-prefix=a/',
178
+ '--dst-prefix=b/',
179
+ '--no-ext-diff',
180
+ '--no-textconv',
181
+ mb,
182
+ 'HEAD',
183
+ ]);
184
+ const excluded = matcher([
185
+ ...(cfg.exclude['*'] ?? []),
186
+ ...(cfg.exclude['removed-assertions'] ?? []),
187
+ ]);
188
+ const pairs = countPairs(diff, matcher(cfg.testGlobs)).filter(
189
+ (p) => ![p.from, p.to].every((path) => path === null || excluded(path)),
190
+ );
191
+ const reasons = git(root, [
192
+ 'log',
193
+ // `log.showSignature` would print «Good signature» lines on stdout: not a trailer.
194
+ '--no-show-signature',
195
+ '--format=%(trailers:key=Tests-Removed,valueonly,separator=%x00)',
196
+ `${mb}..HEAD`,
197
+ ])
198
+ .split(/\0|\n/)
199
+ .map((s) => s.trim())
200
+ .filter((s) => hasReason(s));
201
+ return { violations: reasons.length ? [] : judge(pairs), reasons, skipped: false };
202
+ }
203
+
204
+ /**
205
+ * Modified and renamed pairs are judged one by one. Deleted test files are judged together
206
+ * against the new test files of the range: a module moved under a new name (too changed for
207
+ * rename detection) shows up as one deletion plus one addition.
208
+ * @param {PairCount[]} pairs
209
+ * @returns {{ path: string, removed: number, added: number }[]}
210
+ */
211
+ export function judge(pairs) {
212
+ /** @type {{ path: string, removed: number, added: number }[]} */
213
+ const out = [];
214
+ for (const p of pairs) {
215
+ if (p.from !== null && p.to !== null && p.removed > p.added) {
216
+ out.push({
217
+ path: p.from === p.to ? p.from : `${p.from} → ${p.to}`,
218
+ removed: p.removed,
219
+ added: p.added,
220
+ });
221
+ }
222
+ }
223
+ const deleted = pairs.filter((p) => p.to === null);
224
+ const removed = deleted.reduce((n, p) => n + p.removed, 0);
225
+ const added = pairs.filter((p) => p.from === null).reduce((n, p) => n + p.added, 0);
226
+ if (removed > added) {
227
+ for (const p of deleted) out.push({ path: `${p.from} (deleted)`, removed: p.removed, added });
228
+ }
229
+ return out;
230
+ }
package/src/git.mjs ADDED
@@ -0,0 +1,81 @@
1
+ // @ts-check
2
+ import { execFileSync } from 'node:child_process';
3
+ import { readFileSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+
6
+ export class RepoRulesError extends Error {}
7
+
8
+ /**
9
+ * @param {string} root
10
+ * @param {string[]} args
11
+ * @returns {string}
12
+ */
13
+ export function git(root, args) {
14
+ try {
15
+ return execFileSync('git', ['-c', 'core.quotePath=false', ...args], {
16
+ cwd: root,
17
+ encoding: 'utf8',
18
+ maxBuffer: 256 * 1024 * 1024,
19
+ stdio: ['ignore', 'pipe', 'pipe'],
20
+ });
21
+ } catch (e) {
22
+ const err = /** @type {{ stderr?: string, message: string }} */ (e);
23
+ throw new RepoRulesError(`git ${args[0]} failed: ${(err.stderr || err.message).trim()}`);
24
+ }
25
+ }
26
+
27
+ /**
28
+ * The repository root containing `dir`.
29
+ * @param {string} dir
30
+ * @returns {string}
31
+ */
32
+ export function repoRoot(dir) {
33
+ return git(dir, ['rev-parse', '--show-toplevel']).trim();
34
+ }
35
+
36
+ /**
37
+ * Tracked paths; gitlinks (submodules) and symlinks (mode 120000) left out.
38
+ * @param {string} root
39
+ * @returns {string[]}
40
+ */
41
+ export function trackedFiles(root) {
42
+ const out = git(root, ['ls-files', '-s', '-z']);
43
+ /** @type {string[]} */
44
+ const files = [];
45
+ for (const rec of out.split('\0')) {
46
+ if (!rec) continue;
47
+ const tab = rec.indexOf('\t');
48
+ if (rec.startsWith('160000 ')) continue;
49
+ if (rec.startsWith('120000 ')) continue;
50
+ files.push(rec.slice(tab + 1));
51
+ }
52
+ return [...new Set(files)];
53
+ }
54
+
55
+ /**
56
+ * File text, or null when it is missing on disk or binary (NUL in the first 8 KiB).
57
+ * @param {string} root
58
+ * @param {string} path
59
+ * @returns {string | null}
60
+ */
61
+ export function readText(root, path) {
62
+ let buf;
63
+ try {
64
+ buf = readFileSync(join(root, path));
65
+ } catch {
66
+ return null;
67
+ }
68
+ if (buf.subarray(0, 8192).includes(0)) return null;
69
+ return buf.toString('utf8');
70
+ }
71
+
72
+ /**
73
+ * @param {string} text
74
+ * @returns {number}
75
+ */
76
+ export function countLines(text) {
77
+ if (text === '') return 0;
78
+ let n = 0;
79
+ for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) === 10) n++;
80
+ return text.endsWith('\n') ? n : n + 1;
81
+ }
package/src/glob.mjs ADDED
@@ -0,0 +1,65 @@
1
+ // @ts-check
2
+ /**
3
+ * Minimal glob → RegExp for repo-relative POSIX paths: `**`, `*`, `?`, `{a,b}`.
4
+ * Node 20 has neither `path.matchesGlob` nor `fs.globSync`, so the package carries its own.
5
+ */
6
+
7
+ import { RepoRulesError } from './git.mjs';
8
+
9
+ /**
10
+ * @param {string} glob
11
+ * @returns {RegExp}
12
+ */
13
+ export function globToRegExp(glob) {
14
+ let re = '';
15
+ let i = 0;
16
+ /** @type {number} */
17
+ let braces = 0;
18
+ while (i < glob.length) {
19
+ const c = glob[i];
20
+ if (c === '*') {
21
+ if (glob[i + 1] === '*') {
22
+ const atStart = i === 0 || glob[i - 1] === '/';
23
+ const slashAfter = glob[i + 2] === '/';
24
+ if (atStart && slashAfter) {
25
+ re += '(?:.*/)?';
26
+ i += 3;
27
+ continue;
28
+ }
29
+ if (atStart && i + 2 === glob.length) {
30
+ re += '.*';
31
+ i += 2;
32
+ continue;
33
+ }
34
+ re += '.*';
35
+ i += 2;
36
+ continue;
37
+ }
38
+ re += '[^/]*';
39
+ } else if (c === '?') {
40
+ re += '[^/]';
41
+ } else if (c === '{') {
42
+ re += '(?:';
43
+ braces += 1;
44
+ } else if (c === '}' && braces > 0) {
45
+ re += ')';
46
+ braces -= 1;
47
+ } else if (c === ',' && braces > 0) {
48
+ re += '|';
49
+ } else {
50
+ re += /** @type {string} */ (c).replace(/[.+^$()|[\]\\]/g, '\\$&');
51
+ }
52
+ i += 1;
53
+ }
54
+ if (braces > 0) throw new RepoRulesError(`glob «${glob}»: unclosed {`);
55
+ return new RegExp(`^${re}$`);
56
+ }
57
+
58
+ /**
59
+ * @param {string[]} globs
60
+ * @returns {(path: string) => boolean}
61
+ */
62
+ export function matcher(globs) {
63
+ const res = globs.map(globToRegExp);
64
+ return (path) => res.some((r) => r.test(path));
65
+ }
package/src/main.mjs ADDED
@@ -0,0 +1,137 @@
1
+ // @ts-check
2
+ /** The CLI as a function: `run(argv, env, out, err)` → exit code (spec § 1). */
3
+ import { readFileSync } from 'node:fs';
4
+ import { parseArgs } from 'node:util';
5
+
6
+ import {
7
+ BASELINE_FILE,
8
+ compare,
9
+ emptyCounts,
10
+ growth,
11
+ loadBaseline,
12
+ writeBaseline,
13
+ } from './baseline.mjs';
14
+ import { loadConfig, REPO_RULES } from './config.mjs';
15
+ import { removedAssertions } from './diff.mjs';
16
+ import { repoRoot, RepoRulesError } from './git.mjs';
17
+ import { scan } from './scan.mjs';
18
+
19
+ const USAGE = `usage: repo-rules [-C <dir>] check [--json]
20
+ repo-rules [-C <dir>] diff [--base <ref>] [--json]
21
+ repo-rules [-C <dir>] baseline [--init] [--allow-grow]`;
22
+
23
+ /** @param {string[]} argv */
24
+ function parseOptions(argv) {
25
+ return parseArgs({
26
+ args: argv,
27
+ allowPositionals: true,
28
+ options: {
29
+ C: { type: 'string', short: 'C' },
30
+ json: { type: 'boolean' },
31
+ base: { type: 'string' },
32
+ init: { type: 'boolean' },
33
+ 'allow-grow': { type: 'boolean' },
34
+ help: { type: 'boolean', short: 'h' },
35
+ version: { type: 'boolean' },
36
+ },
37
+ });
38
+ }
39
+
40
+ /**
41
+ * @param {string[]} argv
42
+ * @param {NodeJS.ProcessEnv} env
43
+ * @param {(s: string) => void} out stdout line
44
+ * @param {(s: string) => void} err stderr line: the usage after a wrong command line
45
+ * @returns {number} exit code
46
+ */
47
+ export function run(argv, env, out, err) {
48
+ /** @type {ReturnType<typeof parseOptions>} */
49
+ let parsed;
50
+ try {
51
+ parsed = parseOptions(argv);
52
+ } catch (e) {
53
+ throw new RepoRulesError(`${/** @type {Error} */ (e).message}\n${USAGE}`);
54
+ }
55
+ const { values, positionals } = parsed;
56
+ if (values.version) {
57
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
58
+ out(pkg.version);
59
+ return 0;
60
+ }
61
+ const cmd = positionals[0];
62
+ if (values.help) {
63
+ out(USAGE);
64
+ return 0;
65
+ }
66
+ if (!cmd || !['check', 'diff', 'baseline'].includes(cmd)) {
67
+ err(USAGE);
68
+ return 2;
69
+ }
70
+ const root = repoRoot(values.C ?? process.cwd());
71
+ const cfg = loadConfig(root);
72
+
73
+ if (cmd === 'check') {
74
+ const res = scan(root, cfg);
75
+ const baseline = loadBaseline(root) ?? emptyCounts();
76
+ const cmp = compare(res.actual, res.hits, baseline);
77
+ if (values.json) {
78
+ out(JSON.stringify({ violations: cmp.violations, stale: cmp.stale, notes: [] }, null, 2));
79
+ } else {
80
+ for (const v of cmp.violations) out(`${v.path}:${v.line} ${v.rule} ${v.message}`);
81
+ for (const s of cmp.stale) {
82
+ out(
83
+ `${s.path} ${s.rule} baseline ${s.baseline}, now ${s.actual} — исключения устарели: repo-rules baseline`,
84
+ );
85
+ }
86
+ out(
87
+ `repo-rules: ${cmp.violations.length} violation(s), ${cmp.stale.length} stale, ${REPO_RULES.length} rule(s) checked`,
88
+ );
89
+ }
90
+ return cmp.violations.length || cmp.stale.length ? 1 : 0;
91
+ }
92
+
93
+ if (cmd === 'diff') {
94
+ const res = removedAssertions(root, cfg, values.base, env);
95
+ const notes = [
96
+ ...(res.skipped ? ['skipped (not a pull request)'] : []),
97
+ ...res.reasons.map((r) => `Tests-Removed: ${r}`),
98
+ ];
99
+ const violations = res.violations.map((v) => ({
100
+ rule: 'removed-assertions',
101
+ path: v.path,
102
+ line: 0,
103
+ message: `−${v.removed} / +${v.added} assertions`,
104
+ }));
105
+ if (values.json) out(JSON.stringify({ violations, stale: [], notes }, null, 2));
106
+ else {
107
+ for (const v of violations) out(`${v.path} removed-assertions ${v.message}`);
108
+ for (const n of notes) out(`note ${n}`);
109
+ if (violations.length) {
110
+ out('hint intended? add a commit trailer «Tests-Removed: <reason>» in the range');
111
+ }
112
+ out(
113
+ res.skipped
114
+ ? 'repo-rules diff: skipped (not a pull request)'
115
+ : `repo-rules diff: ${violations.length} violation(s)`,
116
+ );
117
+ }
118
+ return violations.length ? 1 : 0;
119
+ }
120
+
121
+ // Last command: `baseline`.
122
+ const prev = loadBaseline(root);
123
+ if (values.init && prev) throw new RepoRulesError(`${BASELINE_FILE} already exists`);
124
+ if (!values.init && !prev)
125
+ throw new RepoRulesError(`no ${BASELINE_FILE}: run repo-rules baseline --init`);
126
+ const next = scan(root, cfg).actual;
127
+ const up = prev ? growth(prev, next) : [];
128
+ if (up.length && !values['allow-grow']) {
129
+ for (const g of up) out(`${g.path} ${g.rule} ${g.from} → ${g.to}`);
130
+ out(`repo-rules baseline: ${up.length} entr(ies) would grow — fix them or pass --allow-grow`);
131
+ return 1;
132
+ }
133
+ writeBaseline(root, next);
134
+ const total = REPO_RULES.reduce((n, r) => n + Object.keys(next[r]).length, 0);
135
+ out(`repo-rules baseline: wrote ${BASELINE_FILE} (${total} entr(ies))`);
136
+ return 0;
137
+ }
package/src/rules.mjs ADDED
@@ -0,0 +1,149 @@
1
+ // @ts-check
2
+ /** The whole-repo rules of spec § 2. Each returns `{ line, message }` hits, with `line` 1-based. */
3
+ import { commentStart, dashReason, hasReason } from './source.mjs';
4
+
5
+ /** @typedef {import('./source.mjs').Family} Family */
6
+ /** @typedef {{ line: number, message: string }} Hit */
7
+
8
+ // A directive counts only right after the comment opener, as eslint/oxlint/tsc/solhint require.
9
+ const OPENER = String.raw`^(?:\/\/+|\/\*+|\*|\{\/\*)\s*`;
10
+ const LINT_DISABLE = new RegExp(
11
+ `${OPENER}((?:eslint|oxlint)-disable(?:-next-line|-line)?)\\b(.*)$`,
12
+ );
13
+ const SOL_DISABLE = new RegExp(`${OPENER}(solhint-disable(?:-next-line|-line)?)\\b(.*)$`);
14
+ const BIOME = new RegExp(`${OPENER}(biome-ignore)\\b(.*)$`);
15
+ const TS_DIRECTIVE = new RegExp(`${OPENER}(@ts-(?:expect-error|ignore))\\b(.*)$`);
16
+ const PY_NOQA = /#\s*(noqa)(?::\s*[A-Z]+\d+(?:\s*,\s*[A-Z]+\d+)*)?(.*)$/;
17
+ const PY_TYPE_IGNORE = /#\s*(type:\s*ignore)(?:\[[^\]]*\])?(.*)$/;
18
+
19
+ /**
20
+ * `suppression-reason` (DP-024).
21
+ * @param {string[]} lines
22
+ * @param {Family} family
23
+ * @returns {Hit[]}
24
+ */
25
+ export function suppressionReason(lines, family) {
26
+ /** @type {Hit[]} */
27
+ const hits = [];
28
+ lines.forEach((raw, i) => {
29
+ const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw;
30
+ const c = commentStart(line, family);
31
+ if (c < 0) return;
32
+ const comment = line.slice(c);
33
+ /** @type {[string, boolean] | null} */
34
+ let found = null;
35
+ if (family === 'py') {
36
+ const m = PY_NOQA.exec(comment) ?? PY_TYPE_IGNORE.exec(comment);
37
+ if (m)
38
+ found = [
39
+ /** @type {string} */ (m[1]).replace(/\s+/g, ' '),
40
+ hasReason(dashReason(m[2] ?? '')),
41
+ ];
42
+ } else {
43
+ const lint = (family === 'sol' ? SOL_DISABLE : LINT_DISABLE).exec(comment);
44
+ if (lint) found = [/** @type {string} */ (lint[1]), hasReason(dashReason(lint[2] ?? ''))];
45
+ const biome = family === 'js' ? BIOME.exec(comment) : null;
46
+ if (biome) {
47
+ const colon = (biome[2] ?? '').indexOf(':');
48
+ found = ['biome-ignore', colon >= 0 && hasReason((biome[2] ?? '').slice(colon + 1))];
49
+ }
50
+ const ts = family === 'js' ? TS_DIRECTIVE.exec(comment) : null;
51
+ if (ts) found = [/** @type {string} */ (ts[1]), hasReason(ts[2])];
52
+ }
53
+ if (found && !found[1]) hits.push({ line: i + 1, message: `${found[0]} without a reason` });
54
+ });
55
+ return hits;
56
+ }
57
+
58
+ const TEST_NAMES = '(?:describe|it|test|suite|context|bench)';
59
+ const ONLY = new RegExp(`\\b${TEST_NAMES}\\.only(?:\\.each)?\\s*[(\`]`);
60
+ const SKIP = new RegExp(
61
+ `\\b${TEST_NAMES}\\.(skip|todo)(?:\\.each)?\\s*[(\`]|\\b(xit|xdescribe|xtest)\\s*\\(`,
62
+ );
63
+
64
+ /**
65
+ * `focused-skipped-tests` (DP-014, static part). JS/TS test files only.
66
+ * @param {string[]} lines
67
+ * @returns {Hit[]}
68
+ */
69
+ export function focusedSkippedTests(lines) {
70
+ /** @type {Hit[]} */
71
+ const hits = [];
72
+ lines.forEach((raw, i) => {
73
+ const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw;
74
+ const c = commentStart(line, 'js');
75
+ const code = c < 0 ? line : line.slice(0, c);
76
+ if (ONLY.test(code)) {
77
+ hits.push({ line: i + 1, message: '.only in a test file' });
78
+ return;
79
+ }
80
+ const m = SKIP.exec(code);
81
+ if (!m) return;
82
+ // `test.skip(cond, reason)` (Playwright) is a conditional skip, like `skipIf`: the first
83
+ // argument is neither empty nor a title literal. An argument list that starts on the
84
+ // next line is read from there.
85
+ let arg = code.slice((m.index ?? 0) + m[0].length).trimStart();
86
+ if (arg === '' && i + 1 < lines.length) arg = /** @type {string} */ (lines[i + 1]).trimStart();
87
+ if (m[1] === 'skip' && !m[0].includes('.each') && arg !== '' && !/^[)'"`]/.test(arg)) return;
88
+ const own = c < 0 ? '' : line.slice(c);
89
+ const prev = i > 0 ? /** @type {string} */ (lines[i - 1]).replace(/\r$/, '') : '';
90
+ const prevIsComment = /^\s*(?:\/\/|\/\*|\*)/.test(prev);
91
+ if (hasReason(dashReason(own)) || (prevIsComment && hasReason(dashReason(prev)))) return;
92
+ hits.push({ line: i + 1, message: `${m[1] ? `.${m[1]}` : m[2]} without a reason` });
93
+ });
94
+ return hits;
95
+ }
96
+
97
+ const NUMBER_CALL = /(?<![\w$.])(?:Number(?:\.parse(?:Int|Float))?|parseInt|parseFloat)\s*\(/g;
98
+ const LITERAL =
99
+ /^\s*\|\|\s*(?:-?(?:0[xXbBoO][\da-fA-F_]+|\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?)|'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`[^`]*`|null\b|undefined\b)/;
100
+
101
+ /**
102
+ * Index of the `)` closing the `(` at `open`, strings respected; -1 when it is not on this line.
103
+ * @param {string} line
104
+ * @param {number} open
105
+ * @returns {number}
106
+ */
107
+ function closingParen(line, open) {
108
+ let depth = 0;
109
+ /** @type {string | null} */
110
+ let quote = null;
111
+ for (let i = open; i < line.length; i++) {
112
+ const c = line[i];
113
+ if (quote) {
114
+ if (c === '\\') i++;
115
+ else if (c === quote) quote = null;
116
+ } else if (c === '"' || c === "'" || c === '`') quote = c;
117
+ else if (c === '(') depth++;
118
+ else if (c === ')' && --depth === 0) return i;
119
+ }
120
+ return -1;
121
+ }
122
+
123
+ /**
124
+ * `number-or-default` (DP-037, narrow pattern). JS/TS non-test files.
125
+ * @param {string[]} lines
126
+ * @returns {Hit[]}
127
+ */
128
+ export function numberOrDefault(lines) {
129
+ /** @type {Hit[]} */
130
+ const hits = [];
131
+ lines.forEach((raw, i) => {
132
+ const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw;
133
+ const c = commentStart(line, 'js');
134
+ const code = c < 0 ? line : line.slice(0, c);
135
+ for (const m of code.matchAll(NUMBER_CALL)) {
136
+ const close = closingParen(code, (m.index ?? 0) + m[0].length - 1);
137
+ if (close < 0) continue;
138
+ const lit = LITERAL.exec(code.slice(close + 1));
139
+ // `|| 0` conflates nothing: NaN and a real 0 both become 0.
140
+ if (lit && !/\|\|\s*-?0(?:\.0+)?$/.test(lit[0])) {
141
+ hits.push({
142
+ line: i + 1,
143
+ message: `${m[0].replace(/\s*\($/, '')}(…) || <literal> treats 0/NaN as missing`,
144
+ });
145
+ }
146
+ }
147
+ });
148
+ return hits;
149
+ }
package/src/scan.mjs ADDED
@@ -0,0 +1,91 @@
1
+ // @ts-check
2
+ /** Run the § 2 rules over every tracked file. */
3
+ import { MAX_LINES_EXCLUDE } from './config.mjs';
4
+ import { countLines, readText, trackedFiles } from './git.mjs';
5
+ import { matcher } from './glob.mjs';
6
+ import { focusedSkippedTests, numberOrDefault, suppressionReason } from './rules.mjs';
7
+ import { familyOf } from './source.mjs';
8
+
9
+ /** @typedef {import('./config.mjs').Config} Config */
10
+ /** @typedef {import('./config.mjs').RepoRule} RepoRule */
11
+ /** @typedef {{ rule: RepoRule, path: string, line: number, message: string }} Violation */
12
+
13
+ /**
14
+ * @typedef {object} ScanResult
15
+ * @property {Violation[]} hits every flagged place
16
+ * @property {Record<RepoRule, Record<string, number>>} actual rule → path → value (line count for max-lines, else hits)
17
+ */
18
+
19
+ /**
20
+ * @param {string} root
21
+ * @param {Config} cfg
22
+ * @returns {ScanResult}
23
+ */
24
+ export function scan(root, cfg) {
25
+ const anyExcluded = matcher(cfg.exclude['*'] ?? []);
26
+ /** @type {(rule: RepoRule) => (path: string) => boolean} */
27
+ const excludedFor = (rule) => {
28
+ const own = matcher([
29
+ ...(rule === 'max-lines' ? MAX_LINES_EXCLUDE : []),
30
+ ...(cfg.exclude[rule] ?? []),
31
+ ]);
32
+ return (path) => anyExcluded(path) || own(path);
33
+ };
34
+ const ex = {
35
+ 'max-lines': excludedFor('max-lines'),
36
+ 'suppression-reason': excludedFor('suppression-reason'),
37
+ 'focused-skipped-tests': excludedFor('focused-skipped-tests'),
38
+ 'number-or-default': excludedFor('number-or-default'),
39
+ };
40
+ const isTest = matcher(cfg.testGlobs);
41
+ /** @type {ScanResult} */
42
+ const res = {
43
+ hits: [],
44
+ actual: {
45
+ 'max-lines': {},
46
+ 'suppression-reason': {},
47
+ 'focused-skipped-tests': {},
48
+ 'number-or-default': {},
49
+ },
50
+ };
51
+ /**
52
+ * @param {RepoRule} rule
53
+ * @param {string} path
54
+ * @param {{ line: number, message: string }[]} hits
55
+ */
56
+ const add = (rule, path, hits) => {
57
+ if (!hits.length) return;
58
+ res.actual[rule][path] = hits.length;
59
+ for (const h of hits) res.hits.push({ rule, path, ...h });
60
+ };
61
+ for (const path of trackedFiles(root)) {
62
+ const family = familyOf(path);
63
+ const wantLines = !ex['max-lines'](path);
64
+ if (!wantLines && !family) continue;
65
+ const text = readText(root, path);
66
+ if (text === null) continue;
67
+ if (wantLines) {
68
+ const n = countLines(text);
69
+ if (n > cfg.maxLines) {
70
+ res.actual['max-lines'][path] = n;
71
+ res.hits.push({
72
+ rule: 'max-lines',
73
+ path,
74
+ line: cfg.maxLines + 1,
75
+ message: `${n} lines (limit ${cfg.maxLines})`,
76
+ });
77
+ }
78
+ }
79
+ if (!family) continue;
80
+ const lines = text.split('\n');
81
+ if (!ex['suppression-reason'](path))
82
+ add('suppression-reason', path, suppressionReason(lines, family));
83
+ if (family !== 'js') continue;
84
+ const test = isTest(path);
85
+ if (test && !ex['focused-skipped-tests'](path))
86
+ add('focused-skipped-tests', path, focusedSkippedTests(lines));
87
+ if (!test && !ex['number-or-default'](path))
88
+ add('number-or-default', path, numberOrDefault(lines));
89
+ }
90
+ return res;
91
+ }
package/src/source.mjs ADDED
@@ -0,0 +1,69 @@
1
+ // @ts-check
2
+ /** Language families and the comment/code split of one line (spec § 2). */
3
+
4
+ /** @typedef {'js' | 'sol' | 'py'} Family */
5
+
6
+ const JS_EXT = /\.(?:ts|tsx|js|jsx|mjs|cjs|mts|cts|vue|svelte)$/;
7
+
8
+ /**
9
+ * @param {string} path
10
+ * @returns {Family | null}
11
+ */
12
+ export function familyOf(path) {
13
+ if (path.endsWith('.d.ts')) return null;
14
+ if (JS_EXT.test(path)) return 'js';
15
+ if (path.endsWith('.sol')) return 'sol';
16
+ if (path.endsWith('.py')) return 'py';
17
+ return null;
18
+ }
19
+
20
+ /**
21
+ * Index where the line's comment starts, outside string literals; -1 when there is none.
22
+ * A line that starts with `*` (block-comment continuation, JS/Sol) is a comment from 0.
23
+ * Strings are tracked within the line only: `'`, `"`, and `` ` `` (not for Python) with `\` escapes.
24
+ * @param {string} line
25
+ * @param {Family} family
26
+ * @returns {number}
27
+ */
28
+ export function commentStart(line, family) {
29
+ if (family !== 'py' && /^\s*\*/.test(line)) return line.search(/\*/);
30
+ /** @type {string | null} */
31
+ let quote = null;
32
+ for (let i = 0; i < line.length; i++) {
33
+ const c = line[i];
34
+ if (quote) {
35
+ if (c === '\\') i++;
36
+ else if (c === quote) quote = null;
37
+ continue;
38
+ }
39
+ if (c === '"' || c === "'" || (c === '`' && family !== 'py')) {
40
+ quote = c;
41
+ continue;
42
+ }
43
+ if (family === 'py') {
44
+ if (c === '#') return i;
45
+ } else if (c === '/' && (line[i + 1] === '/' || line[i + 1] === '*')) {
46
+ return i;
47
+ }
48
+ }
49
+ return -1;
50
+ }
51
+
52
+ /**
53
+ * At least three non-space characters.
54
+ * @param {string | undefined} text
55
+ * @returns {boolean}
56
+ */
57
+ export function hasReason(text) {
58
+ return (text ?? '').replace(/\*\/|-->|\}/g, '').replace(/\s/g, '').length >= 3;
59
+ }
60
+
61
+ /**
62
+ * The reason after a ` -- ` separator, if any.
63
+ * @param {string} text
64
+ * @returns {string | undefined}
65
+ */
66
+ export function dashReason(text) {
67
+ const m = /(?:^|\s)--\s(.*)$/.exec(text);
68
+ return m ? m[1] : undefined;
69
+ }