@vaultcompass/conductor 0.7.0 → 0.8.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/dist/cli.js CHANGED
@@ -6,19 +6,62 @@
6
6
  // parses arguments and prints. That split is what lets every one of those
7
7
  // decisions be tested without a subprocess.
8
8
  import { Command, CommanderError } from 'commander';
9
- import { execFileSync } from 'node:child_process';
10
- import { readFileSync, realpathSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
9
+ import { closeSync, constants as fsConstants, lstatSync, openSync, readFileSync, realpathSync, statSync, unlinkSync, writeSync, } from 'node:fs';
10
+ import os from 'node:os';
11
11
  import path from 'node:path';
12
12
  import { fileURLToPath } from 'node:url';
13
13
  import { EXIT_BLOCKED, EXIT_COULD_NOT_RUN, EXIT_OK } from './exit-codes.js';
14
+ import { absolutePathEntries, createGitShim, pinGitOutside, pinnedGitInside, realPathInside, removeGitShim, runGit, tempInsideTreeMessage, workTreeAbove, } from './git.js';
14
15
  import { applyInit, planInit, renderInitHuman, renderRevertHuman, revertInit, } from './init.js';
15
16
  import { renderSarif } from './output-sarif.js';
16
- import { jobLogSummary, renderText, verdictToken } from './output-text.js';
17
+ import { gateLogLines, jobLogSummary, renderText, verdictToken, versionSkewWarnings, } from './output-text.js';
17
18
  import { GATE_ROLES, GATE_STAGES, POLICY_FILE_NAME, PolicyError, applyCliOverrides, loadPolicy, parsePolicy, } from './policy.js';
18
19
  import { refusedTrustBase, runAll } from './run.js';
19
- import { headTreeEqualsBase, policyDiffers, readPolicyAtRef, refuseTrustBaseForPullRequest, refuseTrustBaseRef, } from './trust-base.js';
20
+ import { headTreeEqualsBase, policyDiffers, readFileAtRef, refuseTrustBaseForPullRequest, unreadableBaseRemedy, refuseTrustBaseRef, } from './trust-base.js';
20
21
  const pkgPath = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'package.json');
21
22
  const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
23
+ /**
24
+ * Refuses a report path that is a symbolic link, dangling or not.
25
+ *
26
+ * --output defaults to conductor.sarif in the checkout, and a pull request can
27
+ * commit a symlink by that name. writeFileSync follows it, so the run would
28
+ * overwrite whatever it points at (a hook, .git/config, a runner file) with
29
+ * report text. lstat, never stat: stat follows the link and reports the
30
+ * target. A missing path is fine, and so is an ordinary file.
31
+ */
32
+ function refuseSymlinkReportPath(target, what) {
33
+ let info;
34
+ try {
35
+ info = lstatSync(target);
36
+ }
37
+ catch (err) {
38
+ if (err.code === 'ENOENT') {
39
+ return;
40
+ }
41
+ throw err;
42
+ }
43
+ if (info.isSymbolicLink()) {
44
+ throw new PolicyError(`refusing to write ${what} to ${target}: it is a symbolic link, and writing would follow it ` +
45
+ 'to whatever it points at. Remove the link or choose another path.');
46
+ }
47
+ }
48
+ /**
49
+ * Writes a report file without ever following a symbolic link at the final
50
+ * path: the lstat refusal above for the message, plus O_NOFOLLOW where the
51
+ * platform has it so a link swapped in between the check and the open is
52
+ * refused by the kernel rather than followed.
53
+ */
54
+ function writeReportFile(target, what, body) {
55
+ refuseSymlinkReportPath(target, what);
56
+ const noFollow = fsConstants.O_NOFOLLOW ?? 0;
57
+ const fd = openSync(target, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_TRUNC | noFollow, 0o666);
58
+ try {
59
+ writeSync(fd, body);
60
+ }
61
+ finally {
62
+ closeSync(fd);
63
+ }
64
+ }
22
65
  /**
23
66
  * The working-tree root, or a thrown one-line diagnosis of why there is none.
24
67
  *
@@ -52,31 +95,21 @@ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
52
95
  * the path's spelling.
53
96
  */
54
97
  function isGitDirectory(cwd) {
55
- try {
56
- return (execFileSync('git', ['rev-parse', '--is-inside-git-dir'], {
57
- cwd,
58
- encoding: 'utf8',
59
- stdio: ['ignore', 'pipe', 'ignore'],
60
- }).trim() === 'true');
61
- }
62
- catch {
63
- return false;
64
- }
98
+ const result = runGit(cwd, ['rev-parse', '--is-inside-git-dir']);
99
+ return result.error === undefined && result.status === 0 && result.stdout.trim() === 'true';
65
100
  }
66
101
  function repoRoot(cwd) {
67
- try {
68
- return execFileSync('git', ['rev-parse', '--show-toplevel'], {
69
- cwd,
70
- encoding: 'utf8',
71
- stdio: ['ignore', 'pipe', 'ignore'],
72
- }).trim();
102
+ const result = runGit(cwd, ['rev-parse', '--show-toplevel']);
103
+ if (result.error === undefined && result.status === 0) {
104
+ return result.stdout.trim();
73
105
  }
74
- catch (err) {
75
- if (err.code === 'ENOENT') {
106
+ {
107
+ const err = result.error;
108
+ if (err?.code === 'ENOENT') {
76
109
  throw new Error('git is not on PATH, so the repository root could not be found. Install git, or ' +
77
110
  'run conductor from a shell that has it.');
78
111
  }
79
- if (typeof err.status === 'number') {
112
+ if (err === undefined && typeof result.status === 'number') {
80
113
  // git ran and refused. The directory is named because it is the one
81
114
  // thing the reader has to check, and it is the directory they typed
82
115
  // the command in rather than anything internal to this tool.
@@ -90,7 +123,7 @@ function repoRoot(cwd) {
90
123
  // git is there and never got as far as an exit code: a permissions
91
124
  // problem, or a machine out of processes. Neither of the two sentences
92
125
  // above would be true, so this says what actually happened.
93
- throw new Error(`git could not be run to find the repository root: ${err.message}`);
126
+ throw new Error(`git could not be run to find the repository root: ${err?.message ?? 'it did not exit normally'}`);
94
127
  }
95
128
  }
96
129
  /**
@@ -203,8 +236,31 @@ function inventoryFromHead(root, overrides) {
203
236
  return { version: 1, gates: {}, report: { format: 'text' } };
204
237
  }
205
238
  }
206
- function policyForRun(root, trustBase, overrides, githubBaseRef) {
239
+ function policyForRun(root, trustBase, overrides, githubBaseRef, githubActions) {
207
240
  if (trustBase === undefined) {
241
+ // A PULL-REQUEST JOB WITH NO TRUST BASE would take its rules from the
242
+ // tree being judged. In Actions (GITHUB_ACTIONS and GITHUB_BASE_REF both
243
+ // set) that is refused, could-not-run, naming the two ways to clear it.
244
+ // Outside Actions one notice line, and the run goes on as before: a local
245
+ // shell that happens to export GITHUB_BASE_REF is the user's own tree.
246
+ if (githubBaseRef !== undefined && githubBaseRef !== '') {
247
+ const why = `GITHUB_BASE_REF is set to "${githubBaseRef}", so this is a pull-request job, and no ` +
248
+ '--trust-base was given: the policy would come from the tree being judged.';
249
+ if (githubActions === 'true') {
250
+ return {
251
+ kind: 'refused',
252
+ ref: '',
253
+ notGiven: true,
254
+ detail: `${why} Pass --trust-base refs/remotes/origin/${githubBaseRef} (check out with ` +
255
+ 'fetch-depth: 0), or use the Action, which passes it. A pre-commit hook run inside ' +
256
+ 'a pull-request job (conductor run --staged) hits this too: skip the hook in CI, ' +
257
+ 'or pass --trust-base to it. Nothing was checked.',
258
+ inventory: inventoryFromHead(root, overrides),
259
+ };
260
+ }
261
+ process.stderr.write(`conductor: ${why} Outside GitHub Actions the run goes on with the working tree policy; ` +
262
+ 'in Actions it is refused. Pass --trust-base for pull-request mode.\n');
263
+ }
208
264
  return { kind: 'policy', policy: applyCliOverrides(loadPolicy(root), overrides) };
209
265
  }
210
266
  // DEFENCE IN DEPTH, ISSUE #58. action.yml's validate step already refuses
@@ -212,8 +268,8 @@ function policyForRun(root, trustBase, overrides, githubBaseRef) {
212
268
  // the same rule for anyone invoking the CLI directly in CI, bypassing that
213
269
  // step. Checked BEFORE refuseTrustBaseRef and deliberately narrower than
214
270
  // it: it says nothing about HEAD or about tree equality, only about
215
- // whether the given ref agrees with origin/<GITHUB_BASE_REF>, which is
216
- // exactly what the composite action itself always passes. So on an
271
+ // whether the given ref agrees with the base branch (the full commit id the
272
+ // composite action's fetch step published). So on an
217
273
  // ordinary pull-request run this returns null immediately and
218
274
  // refuseTrustBaseRef runs its own checks unchanged, the equal-tree
219
275
  // first-parent exception (issue #69/#73) included.
@@ -227,8 +283,24 @@ function policyForRun(root, trustBase, overrides, githubBaseRef) {
227
283
  inventory: inventoryFromHead(root, overrides),
228
284
  };
229
285
  }
230
- const baseText = readPolicyAtRef(root, trustBase);
231
- const headText = readPolicyAtRef(root, 'HEAD');
286
+ const baseRead = readFileAtRef(root, trustBase, POLICY_FILE_NAME);
287
+ const headRead = readFileAtRef(root, 'HEAD', POLICY_FILE_NAME);
288
+ if (baseRead.kind === 'error') {
289
+ // UNREADABLE IS NOT ABSENT. The base may carry a policy, and nothing was
290
+ // judged against it, so this is the could-not-run refusal with git's own
291
+ // reason, never the "run conductor init" sentence below and never a run
292
+ // under any other policy.
293
+ return {
294
+ kind: 'refused',
295
+ ref: trustBase,
296
+ detail: `cannot read ${POLICY_FILE_NAME} at "${trustBase}": ${baseRead.detail}. On a pull-request ` +
297
+ `run every rule comes from the base ref, so nothing was checked. ` +
298
+ unreadableBaseRemedy(POLICY_FILE_NAME),
299
+ inventory: inventoryFromHead(root, overrides),
300
+ };
301
+ }
302
+ const baseText = baseRead.kind === 'file' ? baseRead.text : null;
303
+ const headText = headRead.kind === 'file' ? headRead.text : null;
232
304
  if (baseText === null) {
233
305
  // CONFIG ABSENT ON THE BASE, not a policy error thrown from here. The old
234
306
  // shape threw a PolicyError, which the run command's catch prints as one
@@ -276,7 +348,9 @@ function policyForRun(root, trustBase, overrides, githubBaseRef) {
276
348
  policy: applyCliOverrides(parsePolicy(baseText, `${trustBase}:${POLICY_FILE_NAME}`), overrides),
277
349
  trustBase: {
278
350
  ref: trustBase,
279
- policyChanged: policyDiffers(baseText, headText),
351
+ // A head file git could not read is reported as a change, the
352
+ // fail-closed direction: it is never taken to match the base.
353
+ policyChanged: headRead.kind === 'error' ? true : policyDiffers(baseText, headText),
280
354
  refusal: null,
281
355
  // Computed AFTER refuseTrustBaseRef has already returned null, on the
282
356
  // one shape that check accepts despite an identical tree: a merge
@@ -287,6 +361,63 @@ function policyForRun(root, trustBase, overrides, githubBaseRef) {
287
361
  },
288
362
  };
289
363
  }
364
+ /**
365
+ * On a run with a trust base: removes every PATH entry that resolves against
366
+ * the working directory, for this process and for every child it starts,
367
+ * says what it removed, and pins git to the first git on PATH whose real path
368
+ * is outside the repository's work tree.
369
+ *
370
+ * Nearly every child runs with the repository root as its working directory,
371
+ * and that tree is the one under judgment, so every PATH lookup resolves
372
+ * against an absolute directory, and conductor's own git is never a program
373
+ * inside that tree. An absolute PATH entry inside the tree is kept: a gate
374
+ * installed as a dependency is reached that way, and the program check
375
+ * (refuseHeadControlledProgram) governs it. Runs without a trust base keep
376
+ * PATH exactly as given: a local hook commonly relies on a relative entry,
377
+ * and the tree there is the user's own. A gate that can no longer be found
378
+ * is the ordinary gate-missing outcome, cleared with an absolute PATH entry
379
+ * or an absolute command:.
380
+ *
381
+ * The work tree is found without running git (`workTreeAbove`), from the
382
+ * directory the run starts in; the caller checks the pinned git again
383
+ * against the root git then reports.
384
+ *
385
+ * Then puts a private directory first on PATH for this process and every
386
+ * child (`createGitShim`): a directory outside the tree holding only a link
387
+ * named git to the pinned program, so a gate, or anything a gate starts, that
388
+ * looks git up by name runs the pinned git even when an absolute PATH entry
389
+ * inside the tree holds a git of its own. Returns that directory, for the
390
+ * caller to remove when the run ends, or null on Windows, where none is made.
391
+ */
392
+ function pinPathForTrustBase(start) {
393
+ const { value, removed } = absolutePathEntries(process.env.PATH ?? '');
394
+ if (removed.length > 0) {
395
+ process.env.PATH = value;
396
+ process.stderr.write(`conductor: pull-request mode removed ${removed.length} PATH ` +
397
+ `${removed.length === 1 ? 'entry' : 'entries'} that resolve against the working ` +
398
+ `directory (${removed.map((entry) => JSON.stringify(entry)).join(', ')}), which on a ` +
399
+ 'pull-request run is the tree being judged. Use absolute PATH entries for any tool a ' +
400
+ 'gate needs.\n');
401
+ }
402
+ const workTree = workTreeAbove(start);
403
+ const excluded = workTree === null ? [start] : [workTree];
404
+ const pinned = pinGitOutside(value, excluded);
405
+ if (pinned === null) {
406
+ throw new Error(noGitOutsideMessage());
407
+ }
408
+ const shim = createGitShim(pinned, os.tmpdir(), excluded);
409
+ if (shim !== null) {
410
+ // Never a trailing separator: an empty entry would mean the working
411
+ // directory, which is the tree being judged.
412
+ process.env.PATH = value === '' ? shim : `${shim}${path.delimiter}${value}`;
413
+ }
414
+ return shim;
415
+ }
416
+ function noGitOutsideMessage() {
417
+ return ('no git outside the repository was found on PATH. On a pull-request run conductor runs ' +
418
+ 'git only from a directory outside the tree being judged. Put the directory that holds ' +
419
+ 'your git installation on PATH as an absolute entry. Nothing was checked.');
420
+ }
290
421
  function parseFormat(value) {
291
422
  if (value !== 'text' && value !== 'sarif') {
292
423
  throw new PolicyError(`--format must be "text" or "sarif", got "${value}".`);
@@ -432,11 +563,11 @@ export function buildProgram() {
432
563
  .option('--staged', 'gate the git index against HEAD, the way the pre-commit hook does')
433
564
  .option('--format <format>', 'output format: text or sarif')
434
565
  .option('--stage <stage>', `which stopping point this run is: ${GATE_STAGES.join(', ')}. Stages are cumulative, so a gate runs at its own stage and every later one. Omit it to run every enabled gate.`)
435
- .option('--base <ref>', 'measure the intent gate against what this branch changed since <ref>, rather than against the index. In Actions this defaults to origin/<GITHUB_BASE_REF> when it is set.')
436
- .option('--trust-base <ref>', 'pull-request mode: read .guardrails.yaml from this ref instead of from the tree being judged, and pass the same ref to every gate that supports it. A policy change in the pull request is reported as a proposal and never takes effect for the run, so a pull request cannot change the rules it is judged by. In Actions the composite action passes origin/<GITHUB_BASE_REF> on a pull_request event.')
566
+ .option('--base <ref>', 'measure the intent gate against what this branch changed since <ref>, rather than against the index. In Actions this defaults to the base branch (refs/conductor/trust-base, else refs/remotes/origin/<GITHUB_BASE_REF>, as a commit id) when GITHUB_BASE_REF is set.')
567
+ .option('--trust-base <ref>', 'pull-request mode: read .guardrails.yaml from this ref instead of from the tree being judged, and pass the same ref to every gate that supports it. A policy change in the pull request is reported as a proposal and never takes effect for the run, so a pull request cannot change the rules it is judged by. In Actions the composite action fetches the base branch and passes its full commit id on a pull_request event.')
437
568
  .option('--output <path>', 'write the report to this file instead of to stdout, for a CI step that uploads it')
438
- .option('--text-report <path>', 'with --format sarif, also write the text report to this file, from the same run: exactly what --format text would have rendered for this result, --verbose, --compact-on-refusal and --advisory respected, and no gate is run a second time. In a full report (any run that is not fully clean, or any run with --verbose) the second line is "verdict-token: <token>"; the one-line summary of a clean run without --verbose has none. The token is a label for this run\'s own exit decision: pass, advisory-blocked (N), unenforced-findings (N), blocked (N) or could-not-run. Only meaningful with --format sarif: with --format text the text report is already the output, so the combination is a usage error (exit 2).')
439
- .option('--spec <path>', 'the spec the intent gate imports its contract from, outranking a Spec: line in the pull request body and the branch-name convention')
569
+ .option('--text-report <path>', 'with --format sarif, also write the text report to this file, from the same run: exactly what --format text would have rendered for this result, --verbose, --compact-on-refusal and --advisory respected, and no gate is run a second time. In a full report (any run that is not fully clean, or any run with --verbose) the second line is "verdict-token: <token>"; the one-line summary of a clean run without --verbose has none. The token is a label for this run\'s own exit decision: pass, nothing-checked (exit 0 but no gate ran), advisory-blocked (N), unenforced-findings (N), blocked (N) or could-not-run. Only meaningful with --format sarif: with --format text the text report is already the output, so the combination is a usage error (exit 2).')
570
+ .option('--spec <path>', 'the spec the intent gate imports its contract from, outranking a Spec: line in the pull request body and the branch-name convention. On a pull-request run (--trust-base) the spec is read from the base ref, and a frozen contract on the base takes precedence over it')
440
571
  .option('--verbose', 'print the full per-gate report even when the run is clean. A clean run prints one summary line by default, because a pre-commit hook that prints a screenful on every commit is a hook a team switches off. Text output only; SARIF is unaffected.')
441
572
  .option('--compact-on-refusal', 'when the trust base was refused and no gate ran, print a short body instead of the full refusal report: the version, the verdict, and the refusal reason (with its remedy, when one applies), never the full per-gate report. Built for the pull-request-comment step; every other run is unaffected, whatever --verbose says. Text output only; SARIF is unaffected.')
442
573
  .option('--gate <role>', 'restrict the run to this role; repeatable', (value, previous = []) => [...previous, value])
@@ -446,19 +577,35 @@ export function buildProgram() {
446
577
  .action((options) => {
447
578
  const cwd = process.cwd();
448
579
  let textReportPath;
580
+ // The private git directory of a trust-base run, removed in the
581
+ // finally below on every way out of this action.
582
+ let gitShim = null;
449
583
  try {
584
+ // BEFORE ANY GIT CALL, including the one that finds the repository.
585
+ if (options.trustBase !== undefined) {
586
+ gitShim = pinPathForTrustBase(options.project === undefined ? cwd : path.resolve(cwd, options.project));
587
+ }
450
588
  // Inside the try, because resolveProjectRoot (like repoRoot before
451
589
  // it) reports rather than guesses, and the catch below is what turns
452
590
  // any of its sentences into one line on stderr and the could-not-run
453
591
  // exit code.
454
592
  const root = resolveProjectRoot(cwd, options.project);
593
+ // And once more against the root git reported, which is the tree the
594
+ // gates judge: the pinned git is never a program inside it.
595
+ if (options.trustBase !== undefined && pinnedGitInside(root)) {
596
+ throw new Error(noGitOutsideMessage());
597
+ }
598
+ // The same for the private git directory: never inside that tree.
599
+ if (gitShim !== null && realPathInside(root, gitShim)) {
600
+ throw new Error(tempInsideTreeMessage(os.tmpdir()));
601
+ }
455
602
  const overrides = {
456
603
  ...(parseRoles(options.gate) === undefined
457
604
  ? {}
458
605
  : { gates: parseRoles(options.gate) }),
459
606
  };
460
607
  const stage = parseStage(options.stage);
461
- const source = policyForRun(root, options.trustBase, overrides, process.env.GITHUB_BASE_REF);
608
+ const source = policyForRun(root, options.trustBase, overrides, process.env.GITHUB_BASE_REF, process.env.GITHUB_ACTIONS);
462
609
  const policy = source.kind === 'policy' ? source.policy : source.inventory;
463
610
  const format = parseFormat(options.format ?? policy.report.format);
464
611
  // BEFORE ANY GATE RUNS. With --format text the text report already is
@@ -472,6 +619,7 @@ export function buildProgram() {
472
619
  const result = source.kind === 'refused'
473
620
  ? refusedTrustBase(source.inventory, source.ref, source.detail, {
474
621
  ...(stage === undefined ? {} : { stage }),
622
+ ...(source.notGiven === true ? { notGiven: true } : {}),
475
623
  })
476
624
  : runAll(source.policy, {
477
625
  repoRoot: root,
@@ -507,7 +655,7 @@ export function buildProgram() {
507
655
  // own. Reporting exit 0 next to a report nobody can read is the
508
656
  // worst of the available answers: the upload step downstream would
509
657
  // fail on a missing file with no explanation here.
510
- writeFileSync(options.output, rendered);
658
+ writeReportFile(options.output, 'the report', rendered);
511
659
  }
512
660
  // WRITTEN LAST, after the SARIF log or stdout, and removed again in
513
661
  // the catch below if anything after it throws. A run that exits 2
@@ -516,8 +664,11 @@ export function buildProgram() {
516
664
  // post it as a comment, beside a red job. A text report that cannot
517
665
  // be written takes the could-not-run code, like an unwritable --output.
518
666
  if (options.textReport !== undefined && textReport !== undefined) {
667
+ // Checked BEFORE textReportPath is set, so the catch below never
668
+ // unlinks a path this run refused to touch.
669
+ refuseSymlinkReportPath(options.textReport, 'the text report');
519
670
  textReportPath = options.textReport;
520
- writeFileSync(options.textReport, textReport);
671
+ writeReportFile(options.textReport, 'the text report', textReport);
521
672
  }
522
673
  if (options.output !== undefined) {
523
674
  // One line, so a CI job whose only product is an uploaded artifact
@@ -531,6 +682,17 @@ export function buildProgram() {
531
682
  process.stdout.write(`conductor run: ${jobLogSummary(result)}; verdict-token ${verdictToken(result, advisory)}; ` +
532
683
  `${format} report written to ${options.output}\n`);
533
684
  }
685
+ // One plain line per gate on stderr, on every run and after the report
686
+ // is out, so the job log says which gate did what and why without
687
+ // anybody opening a report. stderr rather than stdout so that stdout
688
+ // stays exactly the report (SARIF or text) for a caller that pipes it.
689
+ // Written after the report file, so a failure above still takes the
690
+ // catch below and these lines never describe a run that then exits 2
691
+ // for an unwritable file.
692
+ const logLines = [...gateLogLines(result), ...versionSkewWarnings(result)];
693
+ if (logLines.length > 0) {
694
+ process.stderr.write(`${logLines.join('\n')}\n`);
695
+ }
534
696
  process.exitCode = applyAdvisory(result.exitCode, advisory);
535
697
  }
536
698
  catch (err) {
@@ -561,6 +723,11 @@ export function buildProgram() {
561
723
  ? err.message
562
724
  : `conductor: ${err instanceof Error ? err.message : String(err)}`);
563
725
  }
726
+ finally {
727
+ if (gitShim !== null) {
728
+ removeGitShim(gitShim);
729
+ }
730
+ }
564
731
  });
565
732
  return program;
566
733
  }
@@ -41,7 +41,8 @@ export declare function extendPath(config: string): string | null;
41
41
  * a nested file added or edited by the pull request has no effect on the run
42
42
  * (measured against 2.6.0: a nested file ignoring lodash passes without
43
43
  * --config and blocks with it). It is still a change to how the tool behaves
44
- * once merged, so it is reported the way the root config is.
44
+ * once merged, so it is reported the way the root config is. A base copy git
45
+ * could not read throws ExternalConfigError, like every other base read here.
45
46
  */
46
47
  export declare function nestedConfigProposals(repoRoot: string, trustBase: string, trackedFiles: readonly string[], configFile: string): string[];
47
48
  export declare function materializeExternalConfig(args: {
@@ -15,9 +15,9 @@
15
15
  // head's file on its own. A head-side difference is not an error: it is
16
16
  // reported as a proposal, which takes effect once it merges and the base
17
17
  // carries it.
18
- import { spawnSync } from 'node:child_process';
19
18
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
20
19
  import path from 'node:path';
20
+ import { readFileAtRef, unreadableBaseRemedy } from './trust-base.js';
21
21
  /** The base ref's config cannot be materialised; the gate cannot run safely. */
22
22
  export class ExternalConfigError extends Error {
23
23
  constructor(message) {
@@ -60,20 +60,38 @@ export function extendPath(config) {
60
60
  }
61
61
  return null;
62
62
  }
63
- /** A file's contents at a ref, or null when the ref does not have it. */
64
- function showAtRef(repoRoot, ref, file) {
65
- const child = spawnSync('git', ['show', `${ref}:${file}`], { cwd: repoRoot, encoding: 'utf8' });
66
- return child.status === 0 && typeof child.stdout === 'string' ? child.stdout : null;
63
+ /**
64
+ * A file's contents at the base ref, or null when the base does not carry
65
+ * it. A read git could not make THROWS: it is never null, because null
66
+ * selects the neutral config, and a trusted file that exists but could not
67
+ * be read must not be replaced by a default (src/trust-base.ts,
68
+ * readFileAtRef).
69
+ */
70
+ function baseCopy(repoRoot, ref, file) {
71
+ const read = readFileAtRef(repoRoot, ref, file);
72
+ if (read.kind === 'error') {
73
+ throw new ExternalConfigError(`${file} could not be read from the base ref: ${read.detail}. Nothing was checked by this ` +
74
+ `gate. ${unreadableBaseRemedy(file)}`);
75
+ }
76
+ return read.kind === 'file' ? read.text : null;
67
77
  }
68
78
  function headCopy(repoRoot, file) {
69
79
  const full = path.join(repoRoot, file);
70
80
  return existsSync(full) ? readFileSync(full, 'utf8') : null;
71
81
  }
72
- function differs(file, base, head) {
82
+ /**
83
+ * The proposal line for a head-side difference, or null. It says which copy
84
+ * was actually used: the base's own, or, when the base carries none, the
85
+ * stand-in the umbrella wrote. Saying "the base's copy" for a stand-in would
86
+ * claim a file the base does not have.
87
+ */
88
+ function differs(file, base, head, standIn = "conductor's neutral stand-in") {
73
89
  if (head === null || head === base) {
74
90
  return null;
75
91
  }
76
- return `${file} differs from the base ref; the base's copy was used and this change takes effect after merge.`;
92
+ return base === null
93
+ ? `${file} is not on the base ref; ${standIn} was used and this file takes effect after merge.`
94
+ : `${file} differs from the base ref; the base's copy was used and this change takes effect after merge.`;
77
95
  }
78
96
  /**
79
97
  * Copies one relative file from the base ref into the run directory, at the
@@ -87,7 +105,7 @@ function materializeRelative(repoRoot, trustBase, cwd, file, what) {
87
105
  throw new ExternalConfigError(`${what} ${file} is not a path inside the repository, so conductor cannot read it from ` +
88
106
  'the base ref; name it relative to the repository root.');
89
107
  }
90
- const base = showAtRef(repoRoot, trustBase, path.relative(cwd, target).split(path.sep).join('/'));
108
+ const base = baseCopy(repoRoot, trustBase, path.relative(cwd, target).split(path.sep).join('/'));
91
109
  if (base === null) {
92
110
  throw new ExternalConfigError(`${what} ${file} does not exist on the base ref ${trustBase}, so there is no approved copy ` +
93
111
  'to read; commit it to the base branch or remove the reference.');
@@ -104,12 +122,13 @@ function materializeRelative(repoRoot, trustBase, cwd, file, what) {
104
122
  * a nested file added or edited by the pull request has no effect on the run
105
123
  * (measured against 2.6.0: a nested file ignoring lodash passes without
106
124
  * --config and blocks with it). It is still a change to how the tool behaves
107
- * once merged, so it is reported the way the root config is.
125
+ * once merged, so it is reported the way the root config is. A base copy git
126
+ * could not read throws ExternalConfigError, like every other base read here.
108
127
  */
109
128
  export function nestedConfigProposals(repoRoot, trustBase, trackedFiles, configFile) {
110
129
  return trackedFiles
111
130
  .filter((file) => file !== configFile && path.posix.basename(file) === configFile)
112
- .map((file) => differs(file, showAtRef(repoRoot, trustBase, file), headCopy(repoRoot, file)))
131
+ .map((file) => differs(file, baseCopy(repoRoot, trustBase, file), headCopy(repoRoot, file), 'the root config'))
113
132
  .filter((proposal) => proposal !== null);
114
133
  }
115
134
  export function materializeExternalConfig(args) {
@@ -117,7 +136,9 @@ export function materializeExternalConfig(args) {
117
136
  if (profile.configFile === null) {
118
137
  return null;
119
138
  }
120
- const base = showAtRef(repoRoot, trustBase, profile.configFile);
139
+ // Only an ABSENT base config selects the neutral one. An unreadable one has
140
+ // already thrown, so the tool never runs under a default in its place.
141
+ const base = baseCopy(repoRoot, trustBase, profile.configFile);
121
142
  const ext = path.extname(profile.configFile) || '.toml';
122
143
  const out = path.join(tempRoot, `${profile.product}-config${ext}`);
123
144
  writeFileSync(out, base ?? profile.neutralConfig ?? '');
@@ -152,13 +173,13 @@ export function materializeExternalConfig(args) {
152
173
  let ignore = null;
153
174
  if (profile.ignoreFile !== null) {
154
175
  const name = profile.ignoreFile.name;
155
- const baseIgnore = showAtRef(repoRoot, trustBase, name);
176
+ const baseIgnore = baseCopy(repoRoot, trustBase, name);
156
177
  const dir = path.join(tempRoot, `${profile.product}-ignore`);
157
178
  mkdirSync(dir, { recursive: true });
158
179
  // An empty file when the base has none, for the reason the neutral
159
180
  // config exists: pointing the tool anywhere else lets it find the head's.
160
181
  writeFileSync(path.join(dir, name), baseIgnore ?? '');
161
- ignore = { dir, proposal: differs(name, baseIgnore, headCopy(repoRoot, name)) };
182
+ ignore = { dir, proposal: differs(name, baseIgnore, headCopy(repoRoot, name), 'an empty one') };
162
183
  }
163
184
  return {
164
185
  path: out,