@crown3/repo-doctor 0.1.0 → 0.2.0

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
@@ -25,7 +25,10 @@ The commands, the units and file rules, and every key of `repo-doctor.config.mjs
25
25
  import { defineConfig } from '@crown3/repo-doctor';
26
26
 
27
27
  export default defineConfig({
28
- pipelines: { ci: { platform: 'github', files: ['.github/workflows/check.yml'] } },
28
+ pipelines: {
29
+ table: 'docs/ci.md', // optional: keep its "## Where checks run" table in sync
30
+ ci: { platform: 'github', files: ['.github/workflows/check.yml'] },
31
+ },
29
32
  quality: { mutate: { minScore: 80 } },
30
33
  });
31
34
  ```
@@ -18,6 +18,6 @@ export declare function table(markdown: string): Map<string, Where>;
18
18
  export declare function pipelineFiles(root: string, patterns: string[]): string[];
19
19
  /** How the error messages name the pipeline files: the one pattern, or `dir/{a,b}.ext`. */
20
20
  export declare function describeFiles(patterns: string[]): string;
21
- /** Hooks and CI steps call only package.json scripts, and the "Where checks run" table lists each where it runs. */
21
+ /** Hooks and CI steps call only package.json scripts, and the "Where checks run" table, when set, lists each where it runs. */
22
22
  export declare function checkRuns(root: string, config: Runs): string[];
23
23
  export {};
package/dist/cli.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type Shard } from './shard.js';
2
- export declare const USAGE = "usage: repo-doctor <command> [--config <file>] [options] [args...]\n\ncommands:\n check-comments [files...] comments the policy allows; no files: every file git does not ignore\n format-sh [--check] [files...] shfmt on shell files; --check only lists them\n check-docs [root] links, reachability, agent files, English, shared phrases, and check-runs\n check-runs [root] hooks and CI call package.json scripts the docs table lists\n review-comments [ref] external(...) comments added since the merge base with ref\n setup build the Python environment and fetch the parsers\n crap crapper on each unit: every function under the CRAP threshold\n dry dryer over every unit at once: no duplicates at the similarity threshold\n mutate mutator on each unit: every mutant killed, or the unit's minimum score\n ratio each unit's code and test lines, a report only\n config print the resolved config as JSON\n\noptions:\n --config <file> config module, from the working directory (default: repo-doctor.config.mjs in the root)\n --changed only files changed in the working tree, or since --base\n --base <ref> with --changed, files changed since the merge base with <ref>, committed or not\n --min-score <n> mutate passes when each unit scores at least n%, whatever the config says\n --shard <i/n> mutate only shard i of n\n\nOther arguments of setup, crap, dry, mutate and ratio go to the tool.";
2
+ export declare const USAGE = "usage: repo-doctor <command> [--config <file>] [options] [args...]\n\ncommands:\n check-comments [files...] comments the policy allows; no files: every file git does not ignore\n format-sh [--check] [files...] shfmt on shell files; --check only lists them\n check-docs [root] links, reachability, agent files, English, shared phrases, and check-runs\n check-runs [root] hooks and CI call package.json scripts (and the docs table lists them, with pipelines.table)\n review-comments [ref] external(...) comments added since the merge base with ref\n setup build the Python environment and fetch the parsers\n crap crapper on each unit: every function under the CRAP threshold\n dry dryer over every unit at once: no duplicates at the similarity threshold\n mutate mutator on each unit: every mutant killed, or the unit's minimum score\n ratio each unit's code and test lines, a report only\n config print the resolved config as JSON\n\noptions:\n --config <file> config module, from the working directory (default: repo-doctor.config.mjs in the root)\n --changed only files changed in the working tree, or since --base\n --base <ref> with --changed, files changed since the merge base with <ref>, committed or not\n --min-score <n> mutate passes when each unit scores at least n%, whatever the config says\n --shard <i/n> mutate only shard i of n\n\n[root] is any directory in the repo; every command works on its git top level.\nOther arguments of crap, dry, mutate and ratio go to the tool; any other unknown argument is a usage error.\n\nexit codes: 0 pass, 1 a finding or a failed gate, 2 an internal error, 64 a usage or config error";
3
3
  export interface Options {
4
4
  changed: boolean;
5
5
  base?: string;
package/dist/cli.js CHANGED
@@ -1,88 +1,13 @@
1
1
  import node_path from "node:path";
2
- import { execFileSync, spawn, spawnSync } from "node:child_process";
3
2
  import { createHash } from "node:crypto";
3
+ import { spawn, spawnSync } from "node:child_process";
4
4
  import node_os from "node:os";
5
5
  import { fileURLToPath, pathToFileURL } from "node:url";
6
6
  import { parseSync } from "oxc-parser";
7
7
  import { parse as external_yaml_parse } from "yaml";
8
8
  import { format as shfmt_format } from "@wasm-fmt/shfmt";
9
- import { ownChanges, isShell, repoFiles, check as config_check, ConfigError, matchesAny } from "./g.js";
9
+ import { ownChanges, repoRoot, repoFiles, matchesAny, listFiles, changedLines, withoutGitHookEnv, isShell, git, check as config_check, ConfigError } from "./g.js";
10
10
  import * as __rspack_external_node_fs_1b05aee1 from "node:fs";
11
- function withoutGitHookEnv(env = process.env) {
12
- return Object.fromEntries(Object.entries(env).filter(([k])=>!k.startsWith('GIT_')));
13
- }
14
- const git = (root, args)=>execFileSync('git', [
15
- '-c',
16
- 'core.quotePath=false',
17
- ...args
18
- ], {
19
- cwd: root,
20
- env: withoutGitHookEnv(),
21
- encoding: 'utf8',
22
- maxBuffer: 67108864
23
- }).split('\n').filter(Boolean);
24
- const since = (root, base)=>base ? git(root, [
25
- 'merge-base',
26
- base,
27
- 'HEAD'
28
- ])[0] ?? base : 'HEAD';
29
- const untracked = (root)=>git(root, [
30
- 'ls-files',
31
- '--others',
32
- '--exclude-standard'
33
- ]);
34
- function listFiles(root, { changed, base }) {
35
- const files = changed ? [
36
- ...git(root, [
37
- 'diff',
38
- '--name-only',
39
- '--diff-filter=AMR',
40
- since(root, base)
41
- ]),
42
- ...untracked(root)
43
- ] : git(root, [
44
- 'ls-files',
45
- '--cached',
46
- '--others',
47
- '--exclude-standard'
48
- ]);
49
- return [
50
- ...new Set(files)
51
- ].filter((f)=>__rspack_external_node_fs_1b05aee1.existsSync(node_path.join(root, f))).sort();
52
- }
53
- const HUNK = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;
54
- function addedLines(diff) {
55
- const lines = new Map();
56
- let added;
57
- for (const line of diff){
58
- if (line.startsWith('+++ ')) {
59
- added = new Set();
60
- lines.set(line.slice(4), added);
61
- continue;
62
- }
63
- const hunk = HUNK.exec(line);
64
- if (!hunk || !added) continue;
65
- const start = Number(hunk[1]);
66
- const size = void 0 === hunk[2] ? 1 : Number(hunk[2]);
67
- for(let n = start; n < start + size; n++)added.add(n);
68
- }
69
- return lines;
70
- }
71
- function changedLines(root, { base }) {
72
- const lines = addedLines(git(root, [
73
- 'diff',
74
- '-U0',
75
- '--no-color',
76
- '--no-prefix',
77
- since(root, base)
78
- ]));
79
- const fresh = new Set(untracked(root));
80
- return (file, line)=>fresh.has(file) || (lines.get(file)?.has(line) ?? false);
81
- }
82
- const repoRoot = (cwd)=>git(cwd, [
83
- 'rev-parse',
84
- '--show-toplevel'
85
- ])[0] ?? cwd;
86
11
  const SCRIPT_EXTENSIONS = [
87
12
  '.ts',
88
13
  '.tsx',
@@ -967,21 +892,25 @@ function check_runs_sites(root, config, errors) {
967
892
  kind: 'hooks',
968
893
  where: r.path[0] ?? '',
969
894
  command: r.command,
970
- script: r.command.trimEnd().match(HOOK_ENTRY)?.[1]
895
+ script: r.command.trimEnd().match(HOOK_ENTRY)?.[1],
896
+ hint: HOOK_HINT
971
897
  }));
972
898
  const { ci } = config;
899
+ if (!ci) return hooks;
973
900
  const find = 'github' === ci.platform ? runs : commands;
901
+ const allowed = (command)=>ci.allow.some((pattern)=>pattern.test(command.trim()));
974
902
  const jobs = pipelineFiles(root, ci.files).flatMap((file)=>read(file, 'YAML', find).map((r)=>({
975
903
  file,
976
904
  r
977
- }))).filter(({ r })=>'jobs' === r.path[0]).map(({ file, r })=>({
905
+ }))).filter(({ r })=>'jobs' === r.path[0] && !allowed(r.command)).map(({ file, r })=>({
978
906
  file,
979
907
  label: r.path.slice(0, 2).join('.'),
980
908
  kind: 'jobs',
981
909
  where: r.path[1] ?? '',
982
910
  command: r.command,
983
- script: r.command.trim().match(ci.entry)?.[1]
984
- })).filter((site)=>!ci.setup.includes(site.script ?? ''));
911
+ script: r.command.trim().match(ci.entry)?.[1],
912
+ hint: ci.hint
913
+ }));
985
914
  return [
986
915
  ...hooks,
987
916
  ...jobs
@@ -1005,8 +934,7 @@ function invoked(root, config, scripts, errors) {
1005
934
  for (const site of check_runs_sites(root, config, errors)){
1006
935
  const { script } = site;
1007
936
  if (void 0 === script || !Object.hasOwn(scripts, script)) {
1008
- const hint = 'hooks' === site.kind ? HOOK_HINT : config.ci.hint;
1009
- errors.push(`${site.file}: ${site.label} runs \`${check_runs_short(site.command)}\`; ${hint}`);
937
+ errors.push(`${site.file}: ${site.label} runs \`${check_runs_short(site.command)}\`; ${site.hint}`);
1010
938
  continue;
1011
939
  }
1012
940
  const entry = actual.get(script) ?? {
@@ -1018,7 +946,7 @@ function invoked(root, config, scripts, errors) {
1018
946
  }
1019
947
  return actual;
1020
948
  }
1021
- function checkRow(errors, config, script, row, entry) {
949
+ function checkRow(errors, config, table, script, row, entry) {
1022
950
  for (const [kind, file, column] of [
1023
951
  [
1024
952
  'hooks',
@@ -1027,14 +955,14 @@ function checkRow(errors, config, script, row, entry) {
1027
955
  ],
1028
956
  [
1029
957
  'jobs',
1030
- describeFiles(config.ci.files),
958
+ config.ci ? describeFiles(config.ci.files) : 'pipelines.ci (unset)',
1031
959
  'CI job'
1032
960
  ]
1033
961
  ]){
1034
962
  const want = [
1035
963
  ...new Set(entry[kind])
1036
964
  ].sort();
1037
- if (want.join() !== row[kind].join()) errors.push(`${config.table}: Where checks run table row \`${script}\` lists ${column} ${check_runs_names(row[kind])}; ${file} runs it in ${check_runs_names(want)}`);
965
+ if (want.join() !== row[kind].join()) errors.push(`${table}: Where checks run table row \`${script}\` lists ${column} ${check_runs_names(row[kind])}; ${file} runs it in ${check_runs_names(want)}`);
1038
966
  }
1039
967
  }
1040
968
  function packageScripts(pkg, errors) {
@@ -1045,11 +973,13 @@ function packageScripts(pkg, errors) {
1045
973
  function checkRuns(root, config) {
1046
974
  const errors = [];
1047
975
  const scripts = packageScripts(check_runs_text(node_path.join(root, 'package.json')), errors);
1048
- const rows = check_runs_table(check_runs_text(node_path.join(root, config.table)));
1049
976
  const actual = invoked(root, config, scripts, errors);
1050
- for (const [script, entry] of actual)if (!rows.has(script)) errors.push(`${config.table}: script \`${script}\` is run by ${where(entry)} but is missing from the Where checks run table`);
1051
- for (const [script, row] of rows)if (Object.hasOwn(scripts, script)) checkRow(errors, config, script, row, actual.get(script) ?? NONE);
1052
- else errors.push(`${config.table}: Where checks run table row \`${script}\` names a script package.json does not define`);
977
+ const { table: page } = config;
978
+ if (void 0 === page) return errors;
979
+ const rows = check_runs_table(check_runs_text(node_path.join(root, page)));
980
+ for (const [script, entry] of actual)if (!rows.has(script)) errors.push(`${page}: script \`${script}\` is run by ${where(entry)} but is missing from the Where checks run table`);
981
+ for (const [script, row] of rows)if (Object.hasOwn(scripts, script)) checkRow(errors, config, page, script, row, actual.get(script) ?? NONE);
982
+ else errors.push(`${page}: Where checks run table row \`${script}\` names a script package.json does not define`);
1053
983
  return errors;
1054
984
  }
1055
985
  const TOP = [
@@ -1332,15 +1262,10 @@ function parseDiff(diff) {
1332
1262
  ] : [];
1333
1263
  });
1334
1264
  }
1335
- const review_comments_git = (root, args)=>execFileSync('git', args, {
1336
- cwd: root,
1337
- encoding: 'utf8',
1338
- maxBuffer: 1073741824
1339
- });
1340
1265
  const isRegular = (root, file)=>__rspack_external_node_fs_1b05aee1.lstatSync(node_path.join(root, file)).isFile();
1341
1266
  const readText = (root, file)=>__rspack_external_node_fs_1b05aee1.readFileSync(node_path.join(root, file), 'utf8');
1342
- function review_comments_untracked(root) {
1343
- return review_comments_git(root, [
1267
+ function untracked(root) {
1268
+ return git(root, [
1344
1269
  'ls-files',
1345
1270
  '--others',
1346
1271
  '--exclude-standard'
@@ -1353,12 +1278,12 @@ function review_comments_untracked(root) {
1353
1278
  }));
1354
1279
  }
1355
1280
  function reviewComments(root, against, exclude = []) {
1356
- const base = review_comments_git(root, [
1281
+ const base = git(root, [
1357
1282
  'merge-base',
1358
1283
  against,
1359
1284
  'HEAD'
1360
1285
  ]).trim();
1361
- const diff = review_comments_git(root, [
1286
+ const diff = git(root, [
1362
1287
  'diff',
1363
1288
  '--unified=0',
1364
1289
  '--no-color',
@@ -1368,87 +1293,9 @@ function reviewComments(root, against, exclude = []) {
1368
1293
  const read = ({ file })=>!matchesAny(file, exclude);
1369
1294
  return [
1370
1295
  ...changed,
1371
- ...review_comments_untracked(root)
1296
+ ...untracked(root)
1372
1297
  ].filter(read).flatMap(({ file, added })=>reviewLines(file, readText(root, file), added.map((a)=>a.line)).map((line)=>`${file}:${line}: an external(...) comment`));
1373
1298
  }
1374
- function rules_report(errors, footer, ok) {
1375
- if (errors.length) {
1376
- console.error(`${errors.join('\n')}\n\n${footer}`);
1377
- return 1;
1378
- }
1379
- console.log(ok);
1380
- return 0;
1381
- }
1382
- const off = (command, section)=>{
1383
- console.log(`${command}: off (${section}: false in the config)`);
1384
- return 0;
1385
- };
1386
- const RULES = {
1387
- 'check-comments': async ({ cwd, args, load })=>{
1388
- const { comments, exclude } = await load(cwd);
1389
- if (!comments) return off('check-comments', 'comments');
1390
- const files = args.length ? ownChanges(cwd, args) : repoFiles(cwd);
1391
- const errors = checkComments(cwd, files, {
1392
- ...comments,
1393
- exclude: [
1394
- ...exclude,
1395
- ...comments.exclude
1396
- ]
1397
- });
1398
- return rules_report(errors, `${errors.length} comment(s) not allowed; see docs/code-standards.md#comments`, 'comments ok');
1399
- },
1400
- 'format-sh': async ({ cwd, args, load })=>{
1401
- const { exclude } = await load(cwd);
1402
- const check = args.includes('--check');
1403
- const named = args.filter((arg)=>'--check' !== arg);
1404
- const files = named.length ? ownChanges(cwd, named) : repoFiles(cwd);
1405
- const { changed, errors } = formatFiles(cwd, files.filter((file)=>!matchesAny(file, exclude)), !check);
1406
- if (errors.length) console.error(errors.join('\n'));
1407
- if (check && changed.length) {
1408
- console.error(`${changed.join('\n')}\n\n${changed.length} shell file(s) need formatting: run pnpm format:sh`);
1409
- return 1;
1410
- }
1411
- for (const file of changed)console.log(`formatted ${file}`);
1412
- return errors.length ? 1 : 0;
1413
- },
1414
- 'check-docs': async ({ cwd, args, load })=>{
1415
- const root = node_path.resolve(cwd, args[0] ?? '.');
1416
- const settings = await load(root);
1417
- const { docs, pipelines } = settings;
1418
- if (!docs) {
1419
- if (!pipelines) return off('check-docs', 'docs');
1420
- return rules_report(checkRuns(root, pipelines), 'Fix the files named above.', 'docs off; runs ok');
1421
- }
1422
- const { errors, count } = checkDocs(root, {
1423
- ...settings,
1424
- docs
1425
- });
1426
- if (errors.length) {
1427
- console.error(errors.join('\n'));
1428
- console.error(`\n${errors.length} problem(s). Fix the files named above.`);
1429
- return 1;
1430
- }
1431
- console.log(`docs ok: ${count} checked`);
1432
- return 0;
1433
- },
1434
- 'check-runs': async ({ cwd, args, load })=>{
1435
- const root = node_path.resolve(cwd, args[0] ?? '.');
1436
- const { pipelines } = await load(root);
1437
- if (!pipelines) return off('check-runs', 'pipelines');
1438
- return rules_report(checkRuns(root, pipelines), 'Fix the files named above.', 'runs ok');
1439
- },
1440
- 'review-comments': async ({ cwd, args, load })=>{
1441
- const { comments, exclude, baseRef } = await load(cwd);
1442
- if (!comments) return off('review-comments', 'comments');
1443
- const found = reviewComments(cwd, args[0] ?? baseRef, exclude);
1444
- if (!found.length) {
1445
- console.log('no comment needs /pstack:no-comments');
1446
- return 0;
1447
- }
1448
- console.log(`${found.join('\n')}\n\nrun /pstack:no-comments on this diff`);
1449
- return 1;
1450
- }
1451
- };
1452
1299
  const units_read = (file)=>__rspack_external_node_fs_1b05aee1.existsSync(file) ? __rspack_external_node_fs_1b05aee1.readFileSync(file, 'utf8') : '';
1453
1300
  function packageJson(dir) {
1454
1301
  const text = units_read(node_path.join(dir, 'package.json'));
@@ -1603,6 +1450,14 @@ function resolveSettings(root, config = {}) {
1603
1450
  }
1604
1451
  };
1605
1452
  }
1453
+ async function importConfig(target) {
1454
+ try {
1455
+ return await import(pathToFileURL(target).href);
1456
+ } catch (error) {
1457
+ const [line] = String(error?.message ?? error).split('\n');
1458
+ throw new ConfigError(`${node_path.basename(target)} failed to load: ${line}`);
1459
+ }
1460
+ }
1606
1461
  async function loadSettings(root, file, cwd = root) {
1607
1462
  const replaced = REPLACED.filter((f)=>__rspack_external_node_fs_1b05aee1.existsSync(node_path.join(root, f)));
1608
1463
  if (replaced.length) throw new ConfigError(`${replaced.join(' and ')} is no longer read: move its settings into ${CONFIG_FILE} and delete it`);
@@ -1611,17 +1466,116 @@ async function loadSettings(root, file, cwd = root) {
1611
1466
  if (file) throw new UsageError(`config not found: ${file}`);
1612
1467
  return resolveSettings(root);
1613
1468
  }
1614
- const module = await import(pathToFileURL(target).href);
1469
+ const module = await importConfig(target);
1615
1470
  return resolveSettings(root, module.default);
1616
1471
  }
1617
1472
  const settingsJson = (settings)=>JSON.stringify(settings, (_key, value)=>value instanceof RegExp || 'function' == typeof value ? String(value) : value, 2);
1473
+ function rules_report(errors, footer, ok) {
1474
+ if (errors.length) {
1475
+ console.error(`${errors.join('\n')}\n\n${footer}`);
1476
+ return 1;
1477
+ }
1478
+ console.log(ok);
1479
+ return 0;
1480
+ }
1481
+ function positional(args, max, flags = []) {
1482
+ const unknown = args.find((a)=>a.startsWith('-') && !flags.includes(a));
1483
+ if (void 0 !== unknown) throw new UsageError(`unknown option: ${unknown}`);
1484
+ const rest = args.filter((a)=>!flags.includes(a));
1485
+ if (rest.length > max) throw new UsageError(`unexpected argument: ${rest[max]}`);
1486
+ return rest;
1487
+ }
1488
+ function filesFrom(cwd, named) {
1489
+ const root = repoRoot(cwd);
1490
+ const here = __rspack_external_node_fs_1b05aee1.realpathSync(cwd);
1491
+ return {
1492
+ root,
1493
+ named: named.map((f)=>node_path.relative(root, node_path.resolve(here, f)))
1494
+ };
1495
+ }
1496
+ const rootOf = (cwd, args)=>repoRoot(node_path.resolve(cwd, positional(args, 1)[0] ?? '.'));
1497
+ const off = (command, section)=>{
1498
+ console.log(`${command}: off (${section}: false in the config)`);
1499
+ return 0;
1500
+ };
1501
+ const RULES = {
1502
+ 'check-comments': async ({ cwd, args, load })=>{
1503
+ const { root, named } = filesFrom(cwd, positional(args, 1 / 0));
1504
+ const { comments, exclude } = await load(root);
1505
+ if (!comments) return off('check-comments', 'comments');
1506
+ const files = named.length ? ownChanges(root, named) : repoFiles(root);
1507
+ const errors = checkComments(root, files, {
1508
+ ...comments,
1509
+ exclude: [
1510
+ ...exclude,
1511
+ ...comments.exclude
1512
+ ]
1513
+ });
1514
+ return rules_report(errors, `${errors.length} comment(s) not allowed; see docs/code-standards.md#comments`, 'comments ok');
1515
+ },
1516
+ 'format-sh': async ({ cwd, args, load })=>{
1517
+ const { root, named } = filesFrom(cwd, positional(args, 1 / 0, [
1518
+ '--check'
1519
+ ]));
1520
+ const { exclude } = await load(root);
1521
+ const check = args.includes('--check');
1522
+ const files = named.length ? ownChanges(root, named) : repoFiles(root);
1523
+ const { changed, errors } = formatFiles(root, files.filter((file)=>!matchesAny(file, exclude)), !check);
1524
+ if (errors.length) console.error(errors.join('\n'));
1525
+ if (check && changed.length) {
1526
+ console.error(`${changed.join('\n')}\n\n${changed.length} shell file(s) need formatting: run pnpm format:sh`);
1527
+ return 1;
1528
+ }
1529
+ for (const file of changed)console.log(`formatted ${file}`);
1530
+ return errors.length ? 1 : 0;
1531
+ },
1532
+ 'check-docs': async ({ cwd, args, load })=>{
1533
+ const root = rootOf(cwd, args);
1534
+ const settings = await load(root);
1535
+ const { docs, pipelines } = settings;
1536
+ if (!docs) {
1537
+ if (!pipelines) return off('check-docs', 'docs');
1538
+ return rules_report(checkRuns(root, pipelines), 'Fix the files named above.', 'docs off; runs ok');
1539
+ }
1540
+ const { errors, count } = checkDocs(root, {
1541
+ ...settings,
1542
+ docs
1543
+ });
1544
+ if (errors.length) {
1545
+ console.error(errors.join('\n'));
1546
+ console.error(`\n${errors.length} problem(s). Fix the files named above.`);
1547
+ return 1;
1548
+ }
1549
+ console.log(`docs ok: ${count} checked`);
1550
+ return 0;
1551
+ },
1552
+ 'check-runs': async ({ cwd, args, load })=>{
1553
+ const root = rootOf(cwd, args);
1554
+ const { pipelines } = await load(root);
1555
+ if (!pipelines) return off('check-runs', 'pipelines');
1556
+ return rules_report(checkRuns(root, pipelines), 'Fix the files named above.', 'runs ok');
1557
+ },
1558
+ 'review-comments': async ({ cwd, args, load })=>{
1559
+ const [ref] = positional(args, 1);
1560
+ const root = repoRoot(cwd);
1561
+ const { comments, exclude, baseRef } = await load(root);
1562
+ if (!comments) return off('review-comments', 'comments');
1563
+ const found = reviewComments(root, ref ?? baseRef, exclude);
1564
+ if (!found.length) {
1565
+ console.log('no comment needs /pstack:no-comments');
1566
+ return 0;
1567
+ }
1568
+ console.log(`${found.join('\n')}\n\nrun /pstack:no-comments on this diff`);
1569
+ return 1;
1570
+ }
1571
+ };
1618
1572
  const USAGE = `usage: repo-doctor <command> [--config <file>] [options] [args...]
1619
1573
 
1620
1574
  commands:
1621
1575
  check-comments [files...] comments the policy allows; no files: every file git does not ignore
1622
1576
  format-sh [--check] [files...] shfmt on shell files; --check only lists them
1623
1577
  check-docs [root] links, reachability, agent files, English, shared phrases, and check-runs
1624
- check-runs [root] hooks and CI call package.json scripts the docs table lists
1578
+ check-runs [root] hooks and CI call package.json scripts (and the docs table lists them, with pipelines.table)
1625
1579
  review-comments [ref] external(...) comments added since the merge base with ref
1626
1580
  setup build the Python environment and fetch the parsers
1627
1581
  crap crapper on each unit: every function under the CRAP threshold
@@ -1637,7 +1591,11 @@ options:
1637
1591
  --min-score <n> mutate passes when each unit scores at least n%, whatever the config says
1638
1592
  --shard <i/n> mutate only shard i of n
1639
1593
 
1640
- Other arguments of setup, crap, dry, mutate and ratio go to the tool.`;
1594
+ [root] is any directory in the repo; every command works on its git top level.
1595
+ Other arguments of crap, dry, mutate and ratio go to the tool; any other unknown argument is a usage error.
1596
+
1597
+ exit codes: 0 pass, 1 a finding or a failed gate, 2 an internal error, 64 a usage or config error`;
1598
+ const EXIT_INTERNAL = 2;
1641
1599
  const EXIT_USAGE = 64;
1642
1600
  const isPercent = (n)=>'number' == typeof n && Number.isInteger(n) && n >= 0 && n <= 100;
1643
1601
  function minScoreArg(text) {
@@ -1713,6 +1671,7 @@ function ignoreMetrics(root, dirs) {
1713
1671
  async function cli_quality(name, args, cwd, env, load) {
1714
1672
  const command = QUALITY[name];
1715
1673
  if (!command && 'setup' !== name) throw new UsageError(`unknown command: ${name}`);
1674
+ if (!command && args.length) throw new UsageError('setup takes no arguments');
1716
1675
  const options = parseArgs(args);
1717
1676
  const root = repoRoot(cwd);
1718
1677
  const settings = await load(root);
@@ -1772,9 +1731,13 @@ async function main(argv, { cwd = process.cwd(), env = process.env } = {}) {
1772
1731
  console.error(`repo-doctor: config: ${error.message}`);
1773
1732
  return EXIT_USAGE;
1774
1733
  }
1775
- if (!(error instanceof UsageError)) throw error;
1776
- console.error(`repo-doctor: ${error.message}\n\n${USAGE}`);
1777
- return EXIT_USAGE;
1734
+ if (error instanceof UsageError) {
1735
+ console.error(`repo-doctor: ${error.message}\n\n${USAGE}`);
1736
+ return EXIT_USAGE;
1737
+ }
1738
+ const [line] = String(error?.message ?? error).split('\n');
1739
+ console.error(`repo-doctor: ${line}`);
1740
+ return EXIT_INTERNAL;
1778
1741
  }
1779
1742
  }
1780
1743
  export { USAGE, main, parseArgs };
package/dist/config.d.ts CHANGED
@@ -58,22 +58,23 @@ export interface CiConfig {
58
58
  platform: Platform;
59
59
  /** Pipeline files, or globs, relative to the repo root. */
60
60
  files: string[];
61
- /** Codebase: the command, or commands, that run a package.json script; entry and hint derive from it. */
62
- runner?: string | string[];
63
- /** A CI command passes when it matches this; group 1 names the package.json script it runs. */
61
+ /**
62
+ * A CI command passes when it matches; its one capture group names the package.json script.
63
+ * No g or y flag. Default for github `/^pnpm (\S+)[^\n]*$/`; required for codebase.
64
+ */
64
65
  entry?: RegExp;
65
- /** Scripts a step may run as setup, which the "Where checks run" table does not list. */
66
- setup?: string[];
67
- /** How a failing CI step should be written instead, in the error message. */
66
+ /** Whole commands a step may run as they are, outside the script check; each matches as `^(?:source)$`. */
67
+ allow?: RegExp[];
68
+ /** How a failing CI step should be written instead, in the error message. Default: derived from entry. */
68
69
  hint?: string;
69
70
  }
70
- /** check-runs: hooks and CI call only package.json scripts, and the docs table says where. */
71
+ /** check-runs: hooks and CI call only package.json scripts, and, with a table, the docs table says where. */
71
72
  export interface PipelinesConfig {
72
73
  /** The hk config, relative to the repo root. Default `hk.pkl`. */
73
74
  hooks?: string;
74
- /** The page with the "## Where checks run" table. Default `docs/subsystems/checks-and-ci.md`. */
75
+ /** The page with the "## Where checks run" table. Omitted: no table is kept in sync. */
75
76
  table?: string;
76
- ci: CiConfig;
77
+ ci?: CiConfig;
77
78
  }
78
79
  /** Where AGENTS.md and CLAUDE.md may sit besides the repo root and skill trees. */
79
80
  export type AgentFiles = 'root' | 'workspaces' | 'anywhere';
@@ -129,15 +130,14 @@ export interface Docs {
129
130
  export interface Ci {
130
131
  platform: Platform;
131
132
  files: string[];
132
- runner: string[];
133
133
  entry: RegExp;
134
- setup: string[];
134
+ allow: RegExp[];
135
135
  hint: string;
136
136
  }
137
137
  export interface Pipelines {
138
138
  hooks: string;
139
- table: string;
140
- ci: Ci;
139
+ table: string | undefined;
140
+ ci: Ci | undefined;
141
141
  }
142
142
  export interface Checked {
143
143
  baseRef: string;
@@ -148,7 +148,5 @@ export interface Checked {
148
148
  pipelines: false | Pipelines;
149
149
  quality: false | QualityConfig;
150
150
  }
151
- /** The CI entry a Codebase runner gives: `<runner> run <script> [word]`. */
152
- export declare const runnerEntry: (runners: string[]) => RegExp;
153
151
  /** Checks a loaded config, naming the key path of anything wrong, and fills the defaults that need no repo. */
154
152
  export declare function check(config?: unknown): Checked;
package/dist/g.js CHANGED
@@ -1,5 +1,6 @@
1
- import { execFileSync } from "node:child_process";
2
1
  import node_path from "node:path";
2
+ import { execFileSync } from "node:child_process";
3
+ import * as __rspack_external_node_fs_1b05aee1 from "node:fs";
3
4
  const defineConfig = (config)=>config;
4
5
  class ConfigError extends Error {
5
6
  }
@@ -33,9 +34,9 @@ const COMMAND = {
33
34
  ok: (v)=>isString(v) || 'function' == typeof v,
34
35
  what: 'a string or a function'
35
36
  };
36
- const RUNNER = {
37
- ok: (v)=>isString(v) || STRINGS.ok(v),
38
- what: 'a string or a list of strings'
37
+ const REGEXPS = {
38
+ ok: (v)=>Array.isArray(v) && v.every((r)=>r instanceof RegExp),
39
+ what: 'a list of RegExps'
39
40
  };
40
41
  const oneOf = (...values)=>({
41
42
  ok: (v)=>values.includes(v),
@@ -93,62 +94,52 @@ function docs(value, at) {
93
94
  }
94
95
  const GITHUB_ENTRY = /^pnpm (\S+)[^\n]*$/;
95
96
  const GITHUB_HINT = "call a package.json script instead, or move setup into .github/actions/setup";
96
- const escaped = (text)=>text.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
97
- const runnerEntry = (runners)=>new RegExp(`^(?:${runners.map(escaped).join('|')}) run (\\S+)(?: [a-z][\\w-]*)?$`);
98
- function runnerHint(runner, setup) {
99
- const forSetup = setup.map((s)=>`, or \`${runner} run ${s}\` for setup`);
100
- return `call \`${runner} run <package.json script>\` instead${forSetup.join('')}`;
101
- }
97
+ const REMOVED = {
98
+ runner: "match the CI command with pipelines.ci.entry, whose one capture group names the package.json script",
99
+ setup: 'list whole setup commands in pipelines.ci.allow'
100
+ };
102
101
  function required(raw, at, key, rule) {
103
102
  const value = field(raw, at, key, rule, void 0);
104
103
  if (void 0 === value) throw new ConfigError(`${at}.${key} is required`);
105
104
  return value;
106
105
  }
107
- function config_runners(raw, at, platform) {
108
- const given = field(raw, at, 'runner', RUNNER, []);
109
- const runner = [
110
- given
111
- ].flat();
112
- if (runner.length && 'codebase' !== platform) throw new ConfigError(`${at}.runner is for platform "codebase" only`);
113
- return runner;
106
+ function plain(pattern, at) {
107
+ if (/[gy]/.test(pattern.flags)) throw new ConfigError(`${at} must not have the g or y flag, got ${pattern}`);
108
+ return pattern;
114
109
  }
115
- function derived(platform, runner, setup) {
116
- if ('github' === platform) return {
117
- entry: GITHUB_ENTRY,
118
- hint: GITHUB_HINT
119
- };
120
- const [first] = runner;
121
- if (void 0 === first) return {};
122
- return {
123
- entry: runnerEntry(runner),
124
- hint: runnerHint(first, setup)
125
- };
110
+ const groups = (pattern)=>(new RegExp(`${pattern.source}|`, pattern.flags).exec('')?.length ?? 1) - 1;
111
+ function entryOf(raw, at, platform) {
112
+ const entry = field(raw, at, 'entry', REGEXP, void 0);
113
+ if (void 0 === entry && 'github' === platform) return GITHUB_ENTRY;
114
+ if (void 0 === entry) throw new ConfigError(`${at}.entry is required for platform "codebase"`);
115
+ plain(entry, `${at}.entry`);
116
+ const count = groups(entry);
117
+ if (1 !== count) throw new ConfigError(`${at}.entry must have exactly one capture group, the package.json script name; ${entry} has ${count}`);
118
+ return entry;
126
119
  }
120
+ const allowOf = (raw, at)=>field(raw, at, 'allow', REGEXPS, []).map((pattern, i)=>new RegExp(`^(?:${plain(pattern, `${at}.allow[${i}]`).source})$`, pattern.flags));
127
121
  function ci(value, at) {
128
- if (void 0 === value) throw new ConfigError(`${at} is required`);
122
+ if (void 0 === value) return;
123
+ const given = object(value, at);
124
+ const gone = Object.keys(REMOVED).find((key)=>key in given);
125
+ if (void 0 !== gone) throw new ConfigError(`${at}.${gone} was removed in 0.2.0: ${REMOVED[gone]}`);
129
126
  const raw = object(value, at, [
130
127
  'platform',
131
128
  'files',
132
- 'runner',
133
129
  'entry',
134
- 'setup',
130
+ 'allow',
135
131
  'hint'
136
132
  ]);
137
133
  const platform = required(raw, at, 'platform', oneOf('github', 'codebase'));
138
134
  const files = required(raw, at, 'files', STRINGS);
139
- const runner = config_runners(raw, at, platform);
140
- const setup = field(raw, at, 'setup', STRINGS, []);
141
- const fallback = derived(platform, runner, setup);
142
- const entry = field(raw, at, 'entry', REGEXP, fallback.entry);
143
- if (!entry) throw new ConfigError(`${at} for codebase needs runner or entry`);
144
- const hint = field(raw, at, 'hint', STRING, fallback.hint);
145
- if (!hint) throw new ConfigError(`${at} for codebase needs hint when it has no runner`);
135
+ const entry = entryOf(raw, at, platform);
136
+ const fallback = void 0 === raw.entry ? GITHUB_HINT : `call a package.json script with a command pipelines.ci.entry matches: ${entry}`;
137
+ const hint = field(raw, at, 'hint', STRING, fallback);
146
138
  return {
147
139
  platform,
148
140
  files,
149
- runner,
150
141
  entry,
151
- setup,
142
+ allow: allowOf(raw, at),
152
143
  hint
153
144
  };
154
145
  }
@@ -160,7 +151,7 @@ function pipelines(value, at) {
160
151
  ]);
161
152
  return {
162
153
  hooks: field(raw, at, 'hooks', STRING, 'hk.pkl'),
163
- table: field(raw, at, 'table', STRING, 'docs/subsystems/checks-and-ci.md'),
154
+ table: field(raw, at, 'table', STRING, void 0),
164
155
  ci: ci(raw.ci, `${at}.ci`)
165
156
  };
166
157
  }
@@ -228,22 +219,104 @@ function check(config = {}) {
228
219
  quality: section(raw, 'quality', 'on', quality)
229
220
  };
230
221
  }
222
+ function withoutGitHookEnv(env = process.env) {
223
+ return Object.fromEntries(Object.entries(env).filter(([k])=>!k.startsWith('GIT_')));
224
+ }
225
+ function git(root, args, { hookEnv = false } = {}) {
226
+ try {
227
+ return execFileSync('git', [
228
+ '-c',
229
+ 'core.quotePath=false',
230
+ ...args
231
+ ], {
232
+ cwd: root,
233
+ env: hookEnv ? process.env : withoutGitHookEnv(),
234
+ encoding: 'utf8',
235
+ stdio: [
236
+ 'ignore',
237
+ 'pipe',
238
+ 'pipe'
239
+ ],
240
+ maxBuffer: 1073741824
241
+ });
242
+ } catch (error) {
243
+ const { stderr, message } = error;
244
+ const why = stderr?.trim().split('\n')[0] || message.split('\n')[0];
245
+ throw new Error(`git ${args.join(' ')}: ${why}`);
246
+ }
247
+ }
248
+ const gitLines = (root, args, options)=>git(root, args, options).split('\n').filter(Boolean);
249
+ const since = (root, base)=>base ? gitLines(root, [
250
+ 'merge-base',
251
+ base,
252
+ 'HEAD'
253
+ ])[0] ?? base : 'HEAD';
254
+ const untracked = (root)=>gitLines(root, [
255
+ 'ls-files',
256
+ '--others',
257
+ '--exclude-standard'
258
+ ]);
259
+ function listFiles(root, { changed, base }) {
260
+ const files = changed ? [
261
+ ...gitLines(root, [
262
+ 'diff',
263
+ '--name-only',
264
+ '--diff-filter=AMR',
265
+ since(root, base)
266
+ ]),
267
+ ...untracked(root)
268
+ ] : gitLines(root, [
269
+ 'ls-files',
270
+ '--cached',
271
+ '--others',
272
+ '--exclude-standard'
273
+ ]);
274
+ return [
275
+ ...new Set(files)
276
+ ].filter((f)=>__rspack_external_node_fs_1b05aee1.existsSync(node_path.join(root, f))).sort();
277
+ }
278
+ const HUNK = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;
279
+ function addedLines(diff) {
280
+ const lines = new Map();
281
+ let added;
282
+ for (const line of diff){
283
+ if (line.startsWith('+++ ')) {
284
+ added = new Set();
285
+ lines.set(line.slice(4), added);
286
+ continue;
287
+ }
288
+ const hunk = HUNK.exec(line);
289
+ if (!hunk || !added) continue;
290
+ const start = Number(hunk[1]);
291
+ const size = void 0 === hunk[2] ? 1 : Number(hunk[2]);
292
+ for(let n = start; n < start + size; n++)added.add(n);
293
+ }
294
+ return lines;
295
+ }
296
+ function changedLines(root, { base }) {
297
+ const lines = addedLines(gitLines(root, [
298
+ 'diff',
299
+ '-U0',
300
+ '--no-color',
301
+ '--no-prefix',
302
+ since(root, base)
303
+ ]));
304
+ const fresh = new Set(untracked(root));
305
+ return (file, line)=>fresh.has(file) || (lines.get(file)?.has(line) ?? false);
306
+ }
307
+ const repoRoot = (cwd)=>gitLines(cwd, [
308
+ 'rev-parse',
309
+ '--show-toplevel'
310
+ ])[0] ?? cwd;
231
311
  const SHEBANG = /^#!.*\b(?:ba)?sh(?:\s|$)/;
232
312
  function isShell(file, firstLine) {
233
313
  if (file.endsWith('.sh')) return true;
234
314
  return '' === node_path.extname(file) && SHEBANG.test(firstLine);
235
315
  }
236
- const git = (root, args)=>execFileSync('git', args, {
237
- cwd: root,
238
- encoding: 'utf8',
239
- stdio: [
240
- 'ignore',
241
- 'pipe',
242
- 'ignore'
243
- ],
244
- maxBuffer: 1073741824
245
- });
246
- const lines = (out)=>out.split('\n').filter(Boolean);
316
+ const HOOK = {
317
+ hookEnv: true
318
+ };
319
+ const files_lines = (out)=>out.split('\n').filter(Boolean);
247
320
  function matches(file, glob) {
248
321
  if (node_path.matchesGlob(file, glob)) return true;
249
322
  if (!glob.endsWith('/**')) return false;
@@ -252,12 +325,12 @@ function matches(file, glob) {
252
325
  return parts.slice(1).some((_, i)=>node_path.matchesGlob(parts.slice(0, i + 1).join('/'), dir));
253
326
  }
254
327
  const matchesAny = (file, globs)=>globs.some((glob)=>matches(file, glob));
255
- const repoFiles = (root)=>lines(git(root, [
328
+ const repoFiles = (root)=>files_lines(git(root, [
256
329
  'ls-files',
257
330
  '--cached',
258
331
  '--others',
259
332
  '--exclude-standard'
260
- ]));
333
+ ], HOOK));
261
334
  function merging(root) {
262
335
  try {
263
336
  git(root, [
@@ -265,7 +338,7 @@ function merging(root) {
265
338
  '-q',
266
339
  '--verify',
267
340
  'MERGE_HEAD'
268
- ]);
341
+ ], HOOK);
269
342
  return true;
270
343
  } catch {
271
344
  return false;
@@ -273,7 +346,7 @@ function merging(root) {
273
346
  }
274
347
  function ownChanges(root, files) {
275
348
  if (!files.length || !merging(root)) return files;
276
- const differ = new Set(lines(git(root, [
349
+ const differ = new Set(files_lines(git(root, [
277
350
  'diff',
278
351
  '--cached',
279
352
  '--name-only',
@@ -284,4 +357,4 @@ function ownChanges(root, files) {
284
357
  ])));
285
358
  return files.filter((f)=>differ.has(f));
286
359
  }
287
- export { ConfigError, check, defineConfig, isShell, matchesAny, ownChanges, repoFiles };
360
+ export { ConfigError, changedLines, check, defineConfig, git, isShell, listFiles, matchesAny, ownChanges, repoFiles, repoRoot, withoutGitHookEnv };
package/dist/git.d.ts CHANGED
@@ -1,4 +1,12 @@
1
1
  export declare function withoutGitHookEnv(env?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
2
+ export interface GitOptions {
3
+ /** Keep the GIT_* variables a hook exports, so git reads the index being committed. */
4
+ hookEnv?: boolean;
5
+ }
6
+ /** Runs git in root and returns its stdout; a failure throws one line naming the command and git's first error line. */
7
+ export declare function git(root: string, args: string[], { hookEnv }?: GitOptions): string;
8
+ /** git's stdout as its non-empty lines. */
9
+ export declare const gitLines: (root: string, args: string[], options?: GitOptions) => string[];
2
10
  export interface Scope {
3
11
  changed: boolean;
4
12
  base?: string;
package/dist/rules.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Settings } from './settings.js';
1
+ import { type Settings } from './settings.js';
2
2
  export interface Invocation {
3
3
  cwd: string;
4
4
  args: string[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crown3/repo-doctor",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Repo checks and ub-mode quality gates shared across repos, driven by one config file: the comment policy, shell formatting, agent docs, where hooks and CI run each script, CRAP scores, duplicate code and mutation testing.",
5
5
  "license": "0BSD",
6
6
  "type": "module",