Repository navigation
Expand file tree
/
Copy pathrun.ts
More file actions
327 lines (304 loc) · 12.6 KB
/
Copy pathrun.ts
File metadata and controls
327 lines (304 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
// Entry point for `pnpm check:affected --base <ref>`.
//
// Derives the affected local check set from the diff against <ref>, prints a
// stable machine-readable plan (with per-check reasoning), and optionally runs
// the locally-runnable checks. Fails open to the full set on anything it cannot
// classify. Existing GitHub CI stays authoritative.
import fs from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { runCmdSync } from '@agent-device/host-kit/command';
import {
checkLockfileInstallSync,
STALE_NODE_MODULES_MESSAGE,
type LockfileInstallSyncResult,
} from './lockfile-install-sync.ts';
import { runValidation, type ValidationContext } from './execution.ts';
import { packageEntrySources } from '../build-entries.ts';
import { parseScriptArgs } from '../lib/cli-args.ts';
import { runEntrypoint } from '../lib/cli-entrypoint.ts';
import {
assertCatalogComplete,
CHECK_CATALOG,
fullCheckPlan,
getCheckSpec,
resolveCommand,
type CheckSpec,
} from './checks.ts';
import { MANUAL_ONLY_OWNERS } from '../gate/declarations.ts';
import { loadModel, owningLanes } from '../gate/model.ts';
import { ALL_CHECKS, selectChecks, type CheckId, type CheckPlan } from './model.ts';
// Which GitHub jobs run each check, read off the workflows rather than declared
// next to the check. A skipped check tells the reader where it is authoritative,
// and that pointer is only useful if it cannot drift from the workflows.
function ciJobsByCheck(): Map<CheckId, string[]> {
return owningLanes(loadModel(repoRoot, []));
}
type Args = {
base: string;
head: string;
json: boolean;
run: boolean;
verbose?: boolean;
full?: boolean;
};
const repoRoot = runCmdSync('git', ['rev-parse', '--show-toplevel']).stdout.trim();
const USAGE =
'Usage: pnpm check:affected [--base <ref>] [--head <ref>] [--json] [--run] [--verbose] [--full]\n';
function parseArgs(argv: readonly string[]): Args {
const values = parseScriptArgs(argv, USAGE, {
base: { type: 'string', default: 'origin/main' },
head: { type: 'string', default: 'HEAD' },
json: { type: 'boolean', default: false },
run: { type: 'boolean', default: false },
verbose: { type: 'boolean', default: false },
full: { type: 'boolean', default: false },
});
return {
base: values.base ?? 'origin/main',
head: values.head ?? 'HEAD',
json: Boolean(values.json),
run: Boolean(values.run),
verbose: Boolean(values.verbose),
full: Boolean(values.full),
};
}
function gitLines(args: string[], cwd: string): string[] {
return runCmdSync('git', args, { cwd }).stdout.split('\n').filter(Boolean);
}
// Collect every changed file a local plan must account for. The committed diff
// (base..head via merge-base) is the baseline; `--no-renames` keeps BOTH sides
// of a rename so a moved file cannot look docs-only by its destination alone.
// In local mode (head === HEAD) we also fold in working-tree changes and
// untracked files, which the committed diff never sees — ignoring uncommitted
// edits would be an unsafe narrowing of the local feedback loop. The staged
// (`--cached`) and unstaged diffs are collected separately and unioned: a
// single `git diff HEAD` nets index against working tree, so a staged add and
// an unstaged delete of the same file would cancel and hide it.
export function readChangedFiles(base: string, head: string, cwd: string = repoRoot): string[] {
const files = new Set<string>(
gitLines(['diff', '--name-only', '--no-renames', '--merge-base', base, head], cwd),
);
if (head === 'HEAD') {
for (const args of [
['diff', '--name-only', '--no-renames', '--cached'], // staged vs HEAD
['diff', '--name-only', '--no-renames'], // unstaged (working tree vs index)
['ls-files', '--others', '--exclude-standard'], // untracked
]) {
for (const file of gitLines(args, cwd)) files.add(file);
}
}
return [...files].sort();
}
type PackageJson = {
scripts: Record<string, string>;
exports?: Record<string, { import?: string }>;
};
function loadPackageJson(): PackageJson {
return JSON.parse(fs.readFileSync(path.join(repoRoot, 'package.json'), 'utf8')) as PackageJson;
}
function printPlanJson(plan: CheckPlan, args: Args): void {
const ciJobs = ciJobsByCheck();
const checks = plan.checks.map((id) => {
const spec = getCheckSpec(id);
return {
id,
label: spec.label,
ciJobs: ciJobs.get(id) ?? [],
localRunnable: spec.localRunnable,
reasons: plan.reasons.filter((reason) => reason.check === id),
};
});
const notSelected = ALL_CHECKS.filter((id) => !plan.checks.includes(id));
process.stdout.write(
`${JSON.stringify(
{
base: args.base,
head: args.head,
failOpen: plan.failOpen,
failOpenReasons: plan.failOpenReasons,
docsOnlyPaths: plan.docsOnlyPaths,
checks,
notSelected,
},
null,
2,
)}\n`,
);
}
function writeLine(line: string): void {
process.stdout.write(`${line}\n`);
}
function printCheckLine(plan: CheckPlan, id: (typeof plan.checks)[number]): void {
const spec = getCheckSpec(id);
const local = spec.localRunnable ? '' : ' (GitHub-authoritative; not run locally)';
writeLine(` - ${id}: ${spec.label}${local}`);
if (plan.failOpen) return;
for (const reason of plan.reasons.filter((entry) => entry.check === id)) {
writeLine(` · ${reason.path} [${reason.rule}] — ${reason.detail}`);
}
}
function printFailOpen(plan: CheckPlan): void {
writeLine('Fail-open: selecting the full check set.');
for (const reason of plan.failOpenReasons) {
writeLine(` ! ${reason.path} [${reason.rule}] — ${reason.detail}`);
}
}
function printSelected(plan: CheckPlan): void {
if (plan.checks.length === 0) {
writeLine('No local checks selected.');
return;
}
writeLine(`Selected ${plan.checks.length} check(s):`);
for (const id of plan.checks) printCheckLine(plan, id);
}
function printPlanHuman(plan: CheckPlan, args: Args): void {
writeLine(`check:affected — diff ${args.base}...${args.head}`);
if (plan.failOpen) printFailOpen(plan);
printSelected(plan);
if (plan.docsOnlyPaths.length > 0) {
writeLine(`Docs-only changes ignored: ${plan.docsOnlyPaths.length} file(s).`);
}
}
// How a resolved command is executed. Injectable so the entrypoint's `--run`
// propagation (order, skip of GitHub-authoritative checks, stop-on-failure) is
// testable without spawning real processes.
export type CommandExecutor = (command: string[], cwd: string, id: string) => Promise<number>;
export async function runChecks(
plan: CheckPlan,
pkg: PackageJson,
args: { readonly base: string | undefined },
options: {
cwd?: string;
skip?: ValidationContext['skip'];
execute: CommandExecutor;
changedFiles?: readonly string[];
checkLockfileSync?: (cwd: string) => LockfileInstallSyncResult;
},
): Promise<number> {
const cwd = options.cwd ?? repoRoot;
const checkLockfileSync = options.checkLockfileSync ?? checkLockfileInstallSync;
// Fail before any gate can misdiagnose a stale worktree install (#1956).
const lockfileSync = checkLockfileSync(cwd);
if (lockfileSync.status === 'out-of-sync') {
reportStaleInstall(lockfileSync.reason, cwd);
return 1;
}
const execute = options.execute;
const runnable = plan.checks.map(getCheckSpec).filter((spec: CheckSpec) => spec.localRunnable);
const skipped = plan.checks.map(getCheckSpec).filter((spec: CheckSpec) => !spec.localRunnable);
// A fail-open plan could not narrow the change, so no check may stand in for another.
const relatedSelected = !plan.failOpen && plan.checks.includes('vitest-related');
// Leaving the unit projects to `unit` stands in for nothing, so fail-open plans do it too.
// The run stops at the first failure, so no pass skips the `unit` run.
const related = {
changedFiles: options.changedFiles ?? [],
unitSuiteRuns: runnable.some(
(spec) => spec.id === 'unit' && !isCoveredByRelatedTests(spec, relatedSelected),
),
};
const ciJobs = skipped.length > 0 ? ciJobsByCheck() : new Map<CheckId, string[]>();
for (const spec of skipped) {
const reason = describeOwner(spec.id, ciJobs);
options.skip?.(spec.id, reason, false);
process.stderr.write(`[skip] ${spec.id} — ${reason}\n`);
}
for (const spec of runnable) {
if (isCoveredByRelatedTests(spec, relatedSelected)) {
options.skip?.(spec.id, 'covered by related tests', true);
continue;
}
const command = resolveCommand(spec, pkg.scripts, args.base, related);
const exitCode = await execute(command, cwd, spec.id);
if (exitCode !== 0) {
process.stderr.write(`\ncheck:affected: ${spec.id} failed.\n`);
return exitCode;
}
}
process.stderr.write('check:affected: all runnable checks passed.\n');
return 0;
}
function reportStaleInstall(reason: 'install-missing' | 'stale', cwd: string): void {
process.stderr.write(`\ncheck:affected: ${STALE_NODE_MODULES_MESSAGE}\n`);
process.stderr.write(
reason === 'install-missing'
? '(no node_modules/.pnpm/lock.yaml found — this checkout was never installed)\n'
: '(node_modules/.pnpm/lock.yaml disagrees with pnpm-lock.yaml)\n',
);
process.stderr.write(`Worktree: ${cwd}\n`);
process.stderr.write('Run `pnpm install --frozen-lockfile` in this worktree, then retry.\n');
}
// Where a check the local run skips is authoritative. A parked check has no automatic
// lane; say so instead of printing an empty job list.
function describeOwner(id: CheckId, ciJobs: ReadonlyMap<CheckId, string[]>): string {
const parked = MANUAL_ONLY_OWNERS[id];
if (parked) return `parked, workflow_dispatch only (${parked.lane})`;
return `GitHub-authoritative (jobs: ${(ciJobs.get(id) ?? []).join(', ')})`;
}
// Only provider-integration defers to the related run. `unit` never does: its suite holds gates that
// read sources as text, which the related module graph cannot select.
function isCoveredByRelatedTests(spec: CheckSpec, relatedSelected: boolean): boolean {
return relatedSelected && spec.id === 'provider-integration';
}
async function main(argv = process.argv.slice(2)): Promise<number> {
assertCatalogComplete();
const args = parseArgs(argv);
if (args.full && !args.run) throw new Error('--full requires --run');
const pkg = loadPackageJson();
// Validate every catalog command resolves before selecting, so a broken
// catalog fails loudly rather than silently dropping a gate.
for (const spec of CHECK_CATALOG) resolveCommand(spec, pkg.scripts, args.base);
const prepare = (base = args.base, currentPackage = pkg) => {
const changedFiles = readChangedFiles(base, args.head);
return {
changedFiles,
plan: selectChecks({
changedFiles,
packageEntryFiles: packageEntrySources(currentPackage.exports),
}),
};
};
if (args.run)
return await runValidation(repoRoot, args, async ({ receipt, execute, skip }) => {
const currentPackage = loadPackageJson();
for (const spec of CHECK_CATALOG) resolveCommand(spec, currentPackage.scripts, args.base);
const install = checkLockfileInstallSync(repoRoot);
if (install.status === 'out-of-sync') {
reportStaleInstall(install.reason, repoRoot);
receipt.error = `${STALE_NODE_MODULES_MESSAGE}: ${install.reason}`;
return 1;
}
if (args.full) {
const plan = fullCheckPlan(currentPackage.scripts);
receipt.plan = plan;
receipt.results = plan.checks.map((id) => ({ id, status: 'not-run' }));
// A full run has no diff, so fallow takes its own merge-base instead of a --base.
return await runChecks(plan, currentPackage, { base: undefined }, { execute, skip });
}
const { changedFiles, plan } = prepare(receipt.refs.resolvedBase, currentPackage);
receipt.changedFiles = changedFiles;
receipt.plan = plan;
receipt.results = plan.checks.map((id) => ({ id, status: 'not-run' }));
process.stderr.write(
`Selected ${plan.checks.length} checks${plan.failOpen ? '; FAIL-OPEN: full set (see receipt.plan.failOpenReasons)' : ''}.\n`,
);
return await runChecks(
plan,
currentPackage,
{ ...args, base: receipt.refs.resolvedBase! },
{ changedFiles, execute, skip },
);
});
const { plan } = prepare();
if (args.json) printPlanJson(plan, args);
else if (args.verbose) printPlanHuman(plan, args);
else {
writeLine(`Selected ${plan.checks.length} checks: ${plan.checks.join(', ') || 'none'}`);
if (plan.failOpen) printFailOpen(plan);
writeLine('Use --verbose for selection reasons, --json for the plan, --run for execution.');
}
return 0;
}
if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
runEntrypoint('check:affected', () => main());
}