@xemahq/repo-build-tooling 0.26.4 → 0.27.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 +0 -1
- package/package.json +3 -7
- package/src/composed-image-install.mjs +5 -2
- package/src/image-cpu-arch.test.mjs +65 -7
- package/src/prune-foreign-libc.mjs +96 -0
- package/src/scrub-swagger-plugin-paths.mjs +66 -8
- package/src/service-image-platform.mjs +10 -2
- package/src/service-image-stage.mjs +5 -2
- package/src/install-git-hooks.mjs +0 -323
- package/src/install-git-hooks.test.mjs +0 -85
- package/src/prepush-sanity.mjs +0 -473
- package/src/prepush-sanity.test.mjs +0 -205
package/src/prepush-sanity.mjs
DELETED
|
@@ -1,473 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
3
|
-
// Pre-push: cheap sanity on what the push changes. CI is the proof (owner
|
|
4
|
-
// 10-13/10-14). One verb for every repository's lefthook `pre-push`, so the
|
|
5
|
-
// logic is not copied per repo.
|
|
6
|
-
//
|
|
7
|
-
// With turbo (a `turbo.json` and a turbo dependency): turbo `lint`, `typecheck`,
|
|
8
|
-
// `test` (unit) and `openapi:current`, each where turbo.json defines it (D136: a cheap
|
|
9
|
-
// pre-push let a stale openapi spec through, and every red costs ~1h of CI). `lint` and
|
|
10
|
-
// `typecheck` run on the packages the pushed commits change plus their dependents; `test`
|
|
11
|
-
// and `openapi:current` only on the packages the push itself changes, and one line names the
|
|
12
|
-
// dependents whose tests are left to CI (an affected-set run took 36 min for a widely used package). A change to the lockfile,
|
|
13
|
-
// turbo.json, or anything in the root package.json other than its `scripts`
|
|
14
|
-
// table invalidates everything and runs the full graph. A repo whose turbo carries no `lint` task also runs its root `lint`
|
|
15
|
-
// script. Without turbo: the root `lint` script only (typecheck needs a build, which the hook never runs; CI has it).
|
|
16
|
-
//
|
|
17
|
-
// The pushed SHA is what is graded. In place when the tree is clean and the SHA
|
|
18
|
-
// is HEAD, or when no differing path lies in a package the run reads or at the
|
|
19
|
-
// repository root; otherwise from a `git archive` export. A delete-only push
|
|
20
|
-
// (or no ref on stdin) grades nothing. A push whose every remote ref is a
|
|
21
|
-
// session park (`refs/xema-session/*`) grades nothing either: a park is not a
|
|
22
|
-
// landing, and the work is graded when it lands on a branch.
|
|
23
|
-
//
|
|
24
|
-
// A fleet-wide change runs `lint` and `typecheck` on the full graph and says it
|
|
25
|
-
// leaves `test` and `openapi:current` to CI: never the full suite. Never builds
|
|
26
|
-
// for its own sake, never runs docker, image builds or `pnpm check`.
|
|
27
|
-
//
|
|
28
|
-
// Usage (lefthook `pre-push` with `use_stdin: true`):
|
|
29
|
-
// xema-prepush-sanity
|
|
30
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
31
|
-
import { spawnSync } from 'node:child_process';
|
|
32
|
-
import { existsSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync } from 'node:fs';
|
|
33
|
-
import { tmpdir } from 'node:os';
|
|
34
|
-
import { dirname, join, delimiter } from 'node:path';
|
|
35
|
-
import { fileURLToPath } from 'node:url';
|
|
36
|
-
|
|
37
|
-
const ZERO_SHA = /^0+$/;
|
|
38
|
-
const GIT_ENV = [
|
|
39
|
-
'GIT_DIR',
|
|
40
|
-
'GIT_WORK_TREE',
|
|
41
|
-
'GIT_COMMON_DIR',
|
|
42
|
-
'GIT_INDEX_FILE',
|
|
43
|
-
'GIT_OBJECT_DIRECTORY',
|
|
44
|
-
'GIT_ALTERNATE_OBJECT_DIRECTORIES',
|
|
45
|
-
'GIT_PREFIX',
|
|
46
|
-
];
|
|
47
|
-
|
|
48
|
-
/** turbo.json is JSONC: strip comments outside strings. */
|
|
49
|
-
export function stripJsonc(text) {
|
|
50
|
-
let out = '';
|
|
51
|
-
for (let i = 0; i < text.length; i++) {
|
|
52
|
-
const c = text[i];
|
|
53
|
-
if (c === '"') {
|
|
54
|
-
let j = i + 1;
|
|
55
|
-
while (j < text.length && text[j] !== '"') j += text[j] === '\\' ? 2 : 1;
|
|
56
|
-
out += text.slice(i, j + 1);
|
|
57
|
-
i = j;
|
|
58
|
-
} else if (c === '/' && text[i + 1] === '/') {
|
|
59
|
-
while (i < text.length && text[i] !== '\n') i++;
|
|
60
|
-
out += '\n';
|
|
61
|
-
} else if (c === '/' && text[i + 1] === '*') {
|
|
62
|
-
const end = text.indexOf('*/', i + 2);
|
|
63
|
-
i = end === -1 ? text.length : end + 1;
|
|
64
|
-
} else {
|
|
65
|
-
out += c;
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
return out;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/** The tasks pre-push runs on the affected packages, in this order, where turbo.json defines them. */
|
|
72
|
-
export const SANITY_TASKS = ['lint', 'typecheck', 'test', 'openapi:current'];
|
|
73
|
-
/** The subset that also runs on the full graph and on dependents; the rest would be the full suite, which is CI's. */
|
|
74
|
-
export const FULL_GRAPH_TASKS = ['lint', 'typecheck'];
|
|
75
|
-
|
|
76
|
-
/** Package directories (a package.json below the root) among tracked file paths; node_modules never counts. */
|
|
77
|
-
export function packageDirs(files) {
|
|
78
|
-
return [...new Set(files.filter((f) => f.endsWith('/package.json') && !f.includes('node_modules/')).map((f) => f.slice(0, -'/package.json'.length)))];
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/** Paths no task reads: root-level markdown and changesets. */
|
|
82
|
-
export function isInert(path) {
|
|
83
|
-
return /^[^/]*\.md$/.test(path) || path.startsWith('.changeset/');
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/** Changed paths that sit in no workspace package and that some task may read (tsconfig.base.json, biome.json, tooling/**). They invalidate every package. */
|
|
87
|
-
export function outsidePackages(changed, dirs) {
|
|
88
|
-
return changed.filter((p) => !isInert(p) && !dirs.some((d) => p.startsWith(`${d}/`)));
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
/** A push with changes whose plan holds no task checked nothing, and must say so rather than pass; null when it is fine. */
|
|
92
|
-
export function emptyPlanFailure(changed, plannedTasks) {
|
|
93
|
-
if (changed.length === 0 || plannedTasks > 0) return null;
|
|
94
|
-
return `no task was planned for a push that changes ${changed.slice(0, 10).join(', ')}${changed.length > 10 ? ` (+${changed.length - 10} more)` : ''} — nothing was checked`;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/**
|
|
98
|
-
* The turbo runs for a push. `range` '' is the full graph: lint and typecheck only. Otherwise lint and
|
|
99
|
-
* typecheck run on the affected set (changed packages plus dependents), while test and openapi:current
|
|
100
|
-
* run only on the packages the push itself changed: a widely used package has dozens of dependents and
|
|
101
|
-
* their tests cost ~36 min (authorization-nest: 78 packages, 195 tasks). CI runs those.
|
|
102
|
-
*/
|
|
103
|
-
export function planRuns(tasks, range) {
|
|
104
|
-
if (!range) {
|
|
105
|
-
const full = tasks.filter((t) => FULL_GRAPH_TASKS.includes(t));
|
|
106
|
-
return { runs: full.length > 0 ? [{ tasks: full, filter: null }] : [], leftToCi: tasks.filter((t) => !FULL_GRAPH_TASKS.includes(t)) };
|
|
107
|
-
}
|
|
108
|
-
const affected = tasks.filter((t) => FULL_GRAPH_TASKS.includes(t));
|
|
109
|
-
const changedOnly = tasks.filter((t) => !FULL_GRAPH_TASKS.includes(t));
|
|
110
|
-
const runs = [];
|
|
111
|
-
if (affected.length > 0) runs.push({ tasks: affected, filter: `...[${range}]` });
|
|
112
|
-
if (changedOnly.length > 0) runs.push({ tasks: changedOnly, filter: `[${range}]` });
|
|
113
|
-
return { runs, leftToCi: [] };
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
/** Package names in `affected` that are not in `changed`, sorted; the root workspace `//` is never a package. */
|
|
117
|
-
export function dependentsOnly(affected, changed) {
|
|
118
|
-
const own = new Set(changed);
|
|
119
|
-
return [...new Set(affected)].filter((n) => n !== '//' && !own.has(n)).sort();
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
/** The one line naming the dependents whose test and openapi:current are left to CI. */
|
|
123
|
-
export function dependentsLine(dependents, tasks) {
|
|
124
|
-
if (dependents.length === 0 || tasks.length === 0) return '';
|
|
125
|
-
return `pre-push: ${tasks.join(' ')} ran only on the changed packages; ${dependents.length} dependent(s) are left to CI: ${dependents.join(', ')}`;
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
/** The sanity tasks a turbo.json defines. An unparsable file throws: "no tasks" would report green. */
|
|
129
|
-
export function turboTasks(text) {
|
|
130
|
-
const cfg = JSON.parse(stripJsonc(text));
|
|
131
|
-
const defined = cfg.tasks ?? cfg.pipeline ?? {};
|
|
132
|
-
return SANITY_TASKS.filter((t) => t in defined);
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
/** The refs git writes on a pre-push hook's stdin, one sha graded once, deletes dropped. */
|
|
136
|
-
export function parseRefs(stdin) {
|
|
137
|
-
const seen = new Set();
|
|
138
|
-
const refs = [];
|
|
139
|
-
for (const line of stdin.split('\n')) {
|
|
140
|
-
const [, sha, remoteRef, remoteSha] = line.trim().split(/\s+/);
|
|
141
|
-
if (!sha || !/^[0-9a-f]+$/.test(sha) || ZERO_SHA.test(sha) || seen.has(sha)) continue;
|
|
142
|
-
seen.add(sha);
|
|
143
|
-
refs.push({ sha, remoteRef: remoteRef ?? '', remoteSha: remoteSha ?? '' });
|
|
144
|
-
}
|
|
145
|
-
return refs;
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
/** Remote refs under this prefix are session parks, not landings. */
|
|
149
|
-
export const PARK_REF_PREFIX = 'refs/xema-session/';
|
|
150
|
-
|
|
151
|
-
/** True when stdin names at least one ref and every remote ref is a session park. A branch anywhere in the push grades the push. */
|
|
152
|
-
export function parkOnly(stdin) {
|
|
153
|
-
const remoteRefs = stdin
|
|
154
|
-
.split('\n')
|
|
155
|
-
.map((line) => line.trim().split(/\s+/)[2])
|
|
156
|
-
.filter(Boolean);
|
|
157
|
-
return remoteRefs.length > 0 && remoteRefs.every((ref) => ref.startsWith(PARK_REF_PREFIX));
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
/** True when two root package.json texts differ only in the top-level `scripts` key; a missing side or unparseable JSON is false. */
|
|
161
|
-
export function scriptsOnlyChange(baseText, tipText) {
|
|
162
|
-
try {
|
|
163
|
-
const { scripts: _baseScripts, ...base } = JSON.parse(baseText);
|
|
164
|
-
const { scripts: _tipScripts, ...tip } = JSON.parse(tipText);
|
|
165
|
-
return JSON.stringify(base) === JSON.stringify(tip);
|
|
166
|
-
} catch {
|
|
167
|
-
return false;
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
/** True when a changed path invalidates every package. `rootScriptsOnly`: the root package.json change is the `scripts` table alone. */
|
|
172
|
-
export function isFleetWide(changedPaths, rootScriptsOnly = false) {
|
|
173
|
-
return changedPaths.some((p) => p === 'pnpm-lock.yaml' || p === 'turbo.json' || (p === 'package.json' && !rootScriptsOnly));
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
/**
|
|
177
|
-
* First differing path that stops the working tree standing in for the pushed
|
|
178
|
-
* SHA, or null. `taskDirs` are the package directories the run reads;
|
|
179
|
-
* `isOwned(path)` says a package.json sits above the path. Root-level *.md files
|
|
180
|
-
* are the one root exception: no task reads them.
|
|
181
|
-
*/
|
|
182
|
-
export function blockingPath(paths, taskDirs, isOwned) {
|
|
183
|
-
const dirs = taskDirs.filter((d) => d && d !== '.');
|
|
184
|
-
for (const p of paths) {
|
|
185
|
-
if (dirs.some((d) => p === d || p.startsWith(`${d}/`))) return { path: p, why: 'is in a package this run reads' };
|
|
186
|
-
if (!isOwned(p) && !/^[^/]*\.md$/.test(p)) return { path: p, why: 'is at the repository root' };
|
|
187
|
-
}
|
|
188
|
-
return null;
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
/** One turbo cache for the in-place run and every scratch export; an inherited value wins. */
|
|
192
|
-
export function turboCacheDir(inherited, root) {
|
|
193
|
-
return inherited || join(root, '.turbo', 'cache');
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
function cleanEnv(root) {
|
|
197
|
-
const env = { ...process.env };
|
|
198
|
-
for (const k of GIT_ENV) delete env[k];
|
|
199
|
-
env.TURBO_CACHE_DIR = turboCacheDir(env.TURBO_CACHE_DIR, root);
|
|
200
|
-
// Appended, never prepended: it only fills a gap (the aggregator owns node_modules).
|
|
201
|
-
const sup = spawnSync('git', ['rev-parse', '--show-superproject-working-tree'], { cwd: root, env, encoding: 'utf8' });
|
|
202
|
-
const superproject = sup.status === 0 ? sup.stdout.trim() : '';
|
|
203
|
-
if (superproject && existsSync(join(superproject, 'node_modules', '.bin'))) {
|
|
204
|
-
env.PATH = `${env.PATH ?? ''}${delimiter}${join(superproject, 'node_modules', '.bin')}`;
|
|
205
|
-
}
|
|
206
|
-
return env;
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
function createContext(root) {
|
|
210
|
-
const env = cleanEnv(root);
|
|
211
|
-
const git = (args, cwd = root) => spawnSync('git', args, { cwd, env, encoding: 'utf8', maxBuffer: 1 << 28 });
|
|
212
|
-
const gitOut = (args, cwd = root) => {
|
|
213
|
-
const r = git(args, cwd);
|
|
214
|
-
return r.status === 0 ? r.stdout : null;
|
|
215
|
-
};
|
|
216
|
-
const inherit = (cmd, args, cwd) => spawnSync(cmd, args, { cwd, env, stdio: ['ignore', 'inherit', 'inherit'] }).status === 0;
|
|
217
|
-
return { root, env, git, gitOut, inherit };
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
function pickBase(ctx, { remoteSha, remoteRef }) {
|
|
221
|
-
if (remoteSha && /^[0-9a-f]+$/.test(remoteSha) && !ZERO_SHA.test(remoteSha) && ctx.git(['cat-file', '-e', `${remoteSha}^{commit}`]).status === 0) {
|
|
222
|
-
return remoteSha;
|
|
223
|
-
}
|
|
224
|
-
const target = remoteRef.replace(/^refs\/heads\//, '');
|
|
225
|
-
for (const cand of [`origin/${target}`, 'origin/develop']) {
|
|
226
|
-
const out = ctx.gitOut(['rev-parse', '--verify', '-q', `${cand}^{commit}`]);
|
|
227
|
-
if (out) return out.trim();
|
|
228
|
-
}
|
|
229
|
-
return '';
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
/** `A...B` naming the change, or '' for the full graph. */
|
|
233
|
-
function rangeFor(ctx, base, sha) {
|
|
234
|
-
if (!base) {
|
|
235
|
-
console.error('pre-push: no base to diff against — running the FULL graph.');
|
|
236
|
-
return '';
|
|
237
|
-
}
|
|
238
|
-
const changed = (ctx.gitOut(['diff', '--name-only', `${base}...${sha}`]) ?? '').split('\n').filter(Boolean);
|
|
239
|
-
const rootScriptsOnly = changed.includes('package.json') && scriptsOnlyChange(ctx.gitOut(['show', `${base}:package.json`]) ?? '', ctx.gitOut(['show', `${sha}:package.json`]) ?? '');
|
|
240
|
-
if (isFleetWide(changed, rootScriptsOnly)) {
|
|
241
|
-
console.error('pre-push: lockfile, turbo.json or root package.json beyond its scripts changed — fleet-wide, running the FULL graph.');
|
|
242
|
-
return '';
|
|
243
|
-
}
|
|
244
|
-
const files = (rev) => (ctx.gitOut(['ls-tree', '-r', '--name-only', rev]) ?? '').split('\n').filter(Boolean);
|
|
245
|
-
const outside = outsidePackages(changed, packageDirs([...files(base), ...files(sha)]));
|
|
246
|
-
if (outside.length > 0) {
|
|
247
|
-
console.error(`pre-push: ${outside.slice(0, 10).join(', ')}${outside.length > 10 ? ` (+${outside.length - 10} more)` : ''} sit outside any workspace package — fleet-wide, running the FULL graph.`);
|
|
248
|
-
return '';
|
|
249
|
-
}
|
|
250
|
-
return `${base}...${sha}`;
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
function changedPaths(ctx, base, sha) {
|
|
254
|
-
return base ? (ctx.gitOut(['diff', '--name-only', `${base}...${sha}`]) ?? '').split('\n').filter(Boolean) : [];
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
function turboBin(root, env) {
|
|
258
|
-
const local = join(root, 'node_modules', '.bin', 'turbo');
|
|
259
|
-
if (existsSync(local)) return local;
|
|
260
|
-
const r = spawnSync('sh', ['-c', 'command -v turbo'], { env, encoding: 'utf8' });
|
|
261
|
-
return r.status === 0 ? r.stdout.trim() : '';
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
function declaresTurbo(dir) {
|
|
265
|
-
try {
|
|
266
|
-
const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
|
|
267
|
-
return Boolean(pkg.dependencies?.turbo ?? pkg.devDependencies?.turbo);
|
|
268
|
-
} catch {
|
|
269
|
-
return false;
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
function hasRootLint(dir) {
|
|
274
|
-
try {
|
|
275
|
-
return Boolean(JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).scripts?.lint);
|
|
276
|
-
} catch {
|
|
277
|
-
return false;
|
|
278
|
-
}
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
/** How many tasks turbo plans for `tasks` under `filter`. */
|
|
282
|
-
function dryTaskCount(ctx, bin, dir, tasks, filter) {
|
|
283
|
-
const dry = spawnSync(bin, ['run', ...tasks, `--filter=${filter}`, '--dry=json'], { cwd: dir, env: ctx.env, encoding: 'utf8', maxBuffer: 1 << 28 });
|
|
284
|
-
if (dry.status !== 0) throw new Error(`turbo --dry=json failed for --filter=${filter}`);
|
|
285
|
-
return (JSON.parse(dry.stdout).tasks ?? []).length;
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
/** Package names turbo would run `tasks` for under `filter`; an unreadable plan throws rather than hide a dependent. */
|
|
289
|
-
function dryPackages(ctx, bin, dir, tasks, filter) {
|
|
290
|
-
const dry = spawnSync(bin, ['run', ...tasks, `--filter=${filter}`, '--dry=json'], { cwd: dir, env: ctx.env, encoding: 'utf8', maxBuffer: 1 << 28 });
|
|
291
|
-
if (dry.status !== 0) throw new Error(`turbo --dry=json failed for --filter=${filter}`);
|
|
292
|
-
return JSON.parse(dry.stdout).packages ?? [];
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
/** Run the sanity tasks in `dir`; `range` '' is the full graph. Returns the verdict. */
|
|
296
|
-
function runHere(ctx, dir, range, bin, changed) {
|
|
297
|
-
if (!bin) {
|
|
298
|
-
// Without turbo nothing orders the builds a workspace typecheck needs, and the hook never
|
|
299
|
-
// builds: typecheck there is CI's.
|
|
300
|
-
console.log('pre-push: pnpm run lint (this repository declares no turbo; typecheck is CI-only)');
|
|
301
|
-
return ctx.inherit('pnpm', ['run', 'lint'], dir);
|
|
302
|
-
}
|
|
303
|
-
let tasks;
|
|
304
|
-
try {
|
|
305
|
-
tasks = turboTasks(readFileSync(join(dir, 'turbo.json'), 'utf8'));
|
|
306
|
-
} catch (error) {
|
|
307
|
-
console.log(`pre-push: could not read the tasks from turbo.json (${error.message}) — FAILED`);
|
|
308
|
-
return false;
|
|
309
|
-
}
|
|
310
|
-
if (tasks.length === 0) {
|
|
311
|
-
console.log(`pre-push: turbo.json defines none of ${SANITY_TASKS.join(', ')} — FAILED`);
|
|
312
|
-
return false;
|
|
313
|
-
}
|
|
314
|
-
if (range) {
|
|
315
|
-
const failure = emptyPlanFailure(changed, dryTaskCount(ctx, bin, dir, tasks, `...[${range}]`));
|
|
316
|
-
if (failure) {
|
|
317
|
-
console.log(`pre-push: ${failure} — FAILED`);
|
|
318
|
-
return false;
|
|
319
|
-
}
|
|
320
|
-
}
|
|
321
|
-
const { runs, leftToCi } = planRuns(tasks, range);
|
|
322
|
-
if (leftToCi.length > 0) console.log(`pre-push: ${leftToCi.join(' ')} not run on the full graph — that is the full suite, CI runs it.`);
|
|
323
|
-
let ok = true;
|
|
324
|
-
for (const run of runs) {
|
|
325
|
-
const where = run.filter ? (run.filter.startsWith('...') ? `affected by ${range}, plus dependents` : `only the packages ${range} changes`) : 'full graph';
|
|
326
|
-
console.log(`pre-push: turbo run ${run.tasks.join(' ')} (${where})`);
|
|
327
|
-
const filterArgs = run.filter ? [`--filter=${run.filter}`] : [];
|
|
328
|
-
ok = ctx.inherit(bin, ['run', ...run.tasks, ...filterArgs, '--continue=dependencies-successful'], dir) && ok;
|
|
329
|
-
}
|
|
330
|
-
if (range) {
|
|
331
|
-
const changedOnly = tasks.filter((t) => !FULL_GRAPH_TASKS.includes(t));
|
|
332
|
-
const line = dependentsLine(dependentsOnly(dryPackages(ctx, bin, dir, tasks, `...[${range}]`), dryPackages(ctx, bin, dir, tasks, `[${range}]`)), changedOnly);
|
|
333
|
-
if (line) console.log(line);
|
|
334
|
-
}
|
|
335
|
-
// Lint that turbo does not carry is the root `lint` script CI runs.
|
|
336
|
-
if (!tasks.includes('lint') && hasRootLint(dir)) {
|
|
337
|
-
console.log('pre-push: pnpm run lint');
|
|
338
|
-
ok = ctx.inherit('pnpm', ['run', 'lint'], dir) && ok;
|
|
339
|
-
}
|
|
340
|
-
return ok;
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
function inPlaceSafe(ctx, sha, range, tasks, bin) {
|
|
344
|
-
if (!range || !bin) return false;
|
|
345
|
-
const dry = spawnSync(bin, ['run', ...tasks, `--filter=...[${range}]`, '--dry=json'], { cwd: ctx.root, env: ctx.env, encoding: 'utf8', maxBuffer: 1 << 28 });
|
|
346
|
-
if (dry.status !== 0) return false;
|
|
347
|
-
let taskDirs;
|
|
348
|
-
try {
|
|
349
|
-
taskDirs = (JSON.parse(dry.stdout).tasks ?? []).map((t) => t.directory);
|
|
350
|
-
} catch {
|
|
351
|
-
return false;
|
|
352
|
-
}
|
|
353
|
-
const paths = [
|
|
354
|
-
ctx.gitOut(['diff', '--name-only', '-z', 'HEAD']) ?? '',
|
|
355
|
-
ctx.gitOut(['ls-files', '-z', '--others', '--exclude-standard']) ?? '',
|
|
356
|
-
ctx.gitOut(['diff', '--name-only', '-z', 'HEAD', sha]) ?? '',
|
|
357
|
-
].flatMap((s) => s.split('\0').filter(Boolean));
|
|
358
|
-
const isOwned = (p) => {
|
|
359
|
-
let dir = dirname(p);
|
|
360
|
-
while (dir !== '.' && dir !== '/') {
|
|
361
|
-
if (existsSync(join(ctx.root, dir, 'package.json'))) return true;
|
|
362
|
-
dir = dirname(dir);
|
|
363
|
-
}
|
|
364
|
-
return false;
|
|
365
|
-
};
|
|
366
|
-
const blocked = blockingPath(paths, taskDirs, isOwned);
|
|
367
|
-
if (blocked) console.error(`pre-push: ${blocked.path} ${blocked.why}`);
|
|
368
|
-
return blocked === null;
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
function exportTo(ctx, rev, dir) {
|
|
372
|
-
return spawnSync('sh', ['-c', 'git archive "$1" | tar -x -C "$2"', 'sh', rev, dir], { cwd: ctx.root, env: ctx.env }).status === 0;
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
function gradeFromExport(ctx, sha, base, range, bin, changed) {
|
|
376
|
-
const scratch = mkdtempSync(join(tmpdir(), 'xema-prepush-'));
|
|
377
|
-
try {
|
|
378
|
-
const sh = (args) => ctx.git(['-c', 'user.email=gate@local', '-c', 'user.name=gate', ...args], scratch).status === 0;
|
|
379
|
-
if (!sh(['init', '-q', '.'])) return false;
|
|
380
|
-
let exportRange = '';
|
|
381
|
-
if (range) {
|
|
382
|
-
// Two commits (base, then the graded tree) so turbo can diff them as it would a checkout.
|
|
383
|
-
if (!exportTo(ctx, base, scratch) || !sh(['add', '-A']) || !sh(['commit', '-qm', 'base'])) return false;
|
|
384
|
-
for (const name of readdirSync(scratch)) if (name !== '.git') rmSync(join(scratch, name), { recursive: true, force: true });
|
|
385
|
-
exportRange = 'HEAD~1...HEAD';
|
|
386
|
-
}
|
|
387
|
-
if (!exportTo(ctx, sha, scratch) || !sh(['add', '-A']) || !sh(['commit', '-qm', 'graded', '--allow-empty'])) return false;
|
|
388
|
-
if (!ctx.inherit('pnpm', ['install', '--frozen-lockfile', '--prefer-offline'], scratch)) {
|
|
389
|
-
console.log('pre-push: install of the export failed');
|
|
390
|
-
return false;
|
|
391
|
-
}
|
|
392
|
-
return runHere(ctx, scratch, exportRange, bin, changed);
|
|
393
|
-
} finally {
|
|
394
|
-
rmSync(scratch, { recursive: true, force: true });
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
function gradeSha(ctx, ref, bin) {
|
|
399
|
-
const { sha } = ref;
|
|
400
|
-
const base = pickBase(ctx, ref);
|
|
401
|
-
const range = rangeFor(ctx, base, sha);
|
|
402
|
-
const changed = changedPaths(ctx, base, sha);
|
|
403
|
-
if (range && changed.length > 0 && changed.every(isInert)) {
|
|
404
|
-
console.log(`pre-push: only paths no task reads changed (${changed.slice(0, 10).join(', ')}) — nothing to grade.`);
|
|
405
|
-
return true;
|
|
406
|
-
}
|
|
407
|
-
const head = (ctx.gitOut(['rev-parse', 'HEAD']) ?? '').trim();
|
|
408
|
-
const short = (rev) => (ctx.gitOut(['rev-parse', '--short', rev]) ?? rev).trim();
|
|
409
|
-
const clean = (ctx.gitOut(['status', '--porcelain']) ?? '') === '';
|
|
410
|
-
if (sha === head && clean) {
|
|
411
|
-
console.log(`pre-push: grading HEAD ${short(head)} in place (clean tree).`);
|
|
412
|
-
return runHere(ctx, ctx.root, range, bin, changed);
|
|
413
|
-
}
|
|
414
|
-
if (bin) {
|
|
415
|
-
let tasks = [];
|
|
416
|
-
try {
|
|
417
|
-
tasks = turboTasks(readFileSync(join(ctx.root, 'turbo.json'), 'utf8'));
|
|
418
|
-
} catch {
|
|
419
|
-
// runHere reports an unreadable turbo.json as the failure it is.
|
|
420
|
-
}
|
|
421
|
-
if (tasks.length > 0 && inPlaceSafe(ctx, sha, range, tasks, bin)) {
|
|
422
|
-
console.log(`pre-push: grading ${short(sha)} in place — no differing path is in a package this run reads.`);
|
|
423
|
-
return runHere(ctx, ctx.root, range, bin, changed);
|
|
424
|
-
}
|
|
425
|
-
}
|
|
426
|
-
console.log(
|
|
427
|
-
sha === head
|
|
428
|
-
? `pre-push: grading ${short(sha)} from an export — the tree is dirty, so it is not what is being pushed.`
|
|
429
|
-
: `pre-push: grading ${short(sha)} from an export — the commit being PUSHED, which is not HEAD ${short(head)}.`,
|
|
430
|
-
);
|
|
431
|
-
return gradeFromExport(ctx, sha, base, bin ? range : '', bin, changed);
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
export function main(stdin) {
|
|
435
|
-
const top = spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8', env: Object.fromEntries(Object.entries(process.env).filter(([k]) => !GIT_ENV.includes(k))) });
|
|
436
|
-
if (top.status !== 0) {
|
|
437
|
-
console.error('pre-push: not inside a git repository — FAILED');
|
|
438
|
-
return 1;
|
|
439
|
-
}
|
|
440
|
-
if (parkOnly(stdin)) {
|
|
441
|
-
console.log(`pre-push: skipped — every ref is a session park under ${PARK_REF_PREFIX}; parks are not landings, the gate runs when the work lands.`);
|
|
442
|
-
return 0;
|
|
443
|
-
}
|
|
444
|
-
const ctx = createContext(top.stdout.trim());
|
|
445
|
-
const refs = parseRefs(stdin);
|
|
446
|
-
if (refs.length === 0) {
|
|
447
|
-
console.log('pre-push: no ref on stdin — this push updates nothing, nothing to grade.');
|
|
448
|
-
return 0;
|
|
449
|
-
}
|
|
450
|
-
// Turbo is used only where the repository declares it; a declared turbo that does not
|
|
451
|
-
// resolve is an uninstalled checkout, and fails rather than skipping the proof.
|
|
452
|
-
let bin = '';
|
|
453
|
-
if (existsSync(join(ctx.root, 'turbo.json')) && declaresTurbo(ctx.root)) {
|
|
454
|
-
bin = turboBin(ctx.root, ctx.env);
|
|
455
|
-
if (!bin) {
|
|
456
|
-
console.log('pre-push: no turbo binary resolves — run `pnpm install --frozen-lockfile` — FAILED');
|
|
457
|
-
console.log('::error::pre-push FAILED — turbo:unavailable');
|
|
458
|
-
return 1;
|
|
459
|
-
}
|
|
460
|
-
}
|
|
461
|
-
const failed = refs.filter((ref) => !gradeSha(ctx, ref, bin)).map((ref) => ctx.gitOut(['rev-parse', '--short', ref.sha])?.trim() ?? ref.sha);
|
|
462
|
-
if (failed.length === 0) {
|
|
463
|
-
console.log(`pre-push: GREEN — sanity passed on ${refs.length} pushed commit(s).`);
|
|
464
|
-
return 0;
|
|
465
|
-
}
|
|
466
|
-
console.log(`::error::pre-push FAILED — ${failed.join(' ')}`);
|
|
467
|
-
console.log(`pre-push: FAILED — ${failed.join(' ')}`);
|
|
468
|
-
return 1;
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
472
|
-
process.exitCode = main(process.stdin.isTTY ? '' : readFileSync(0, 'utf8'));
|
|
473
|
-
}
|