Repository navigation
Expand file tree
/
Copy pathpreflight.mjs
More file actions
283 lines (242 loc) · 8.54 KB
/
Copy pathpreflight.mjs
File metadata and controls
283 lines (242 loc) · 8.54 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
import { spawnSync } from "node:child_process";
import {
cpSync,
existsSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
rmSync,
} from "node:fs";
import { join, posix } from "node:path";
import { fileURLToPath } from "node:url";
import ts from "typescript";
import { trackedRegistrarDifferences } from "./preflight-registrars.mjs";
const repoRoot = fileURLToPath(new URL(".", import.meta.url));
const scratchRoot = join(repoRoot, ".tmp-scratch");
// The relocated runtime: builder trust is physical identity to the *running* package's modules, so
// the clean-room must carry its own `dist/` and `package.json` and execute those. Running the
// repo's binary against a copied tree would lawfully lose every relative-import anchor and make the
// comparison meaningless; running the copy's binary proves the regeneration is relocation-independent.
const runtimePaths = ["dist", "package.json", "preflight-registrars.mjs", "projection-suite.mjs"];
// The check pipeline owns precisely these outputs. Root dist/ is package assembly rather than
// generated truth; broader ignored runtime garbage remains a manual inspection responsibility.
const generationTargets = [
{
name: "self-hosting",
rootPath: ".",
generatedPath: "generated",
sourcePaths: ["specs", "src", "test"],
command: [
".",
"--exclude",
"explorations",
"--exclude",
"examples",
"--exclude",
"test/fixtures/import/parity",
],
},
{
name: "checkout-v1",
rootPath: "examples/checkout-v1",
generatedPath: "examples/checkout-v1/generated",
sourcePaths: [
"examples/checkout-v1/specs",
"examples/checkout-v1/src",
"examples/checkout-v1/test",
],
command: ["examples/checkout-v1"],
},
];
function run(command, args, options = {}) {
const result = spawnSync(command, args, { encoding: "utf8", ...options });
if (result.error !== undefined) {
throw result.error;
}
if (result.status !== 0) {
throw new Error(`${command} ${args.join(" ")} failed:\n${result.stderr}`);
}
return result.stdout;
}
function readTree(root) {
const files = new Map();
if (!existsSync(root)) {
return files;
}
for (const entry of readdirSync(root, { withFileTypes: true })) {
// Finder drops .DS_Store into any browsed directory; it is OS metadata, never generated content.
if (entry.name === ".DS_Store") {
continue;
}
const relativePath = entry.name;
const absolutePath = join(root, relativePath);
if (entry.isDirectory()) {
for (const [childPath, content] of readTree(absolutePath)) {
files.set(join(relativePath, childPath), content);
}
} else if (entry.isFile()) {
files.set(relativePath, readFileSync(absolutePath, "utf8"));
}
}
return files;
}
function compareGeneratedTree(target, actual, expected) {
const paths = new Set([...actual.keys(), ...expected.keys()]);
return [...paths]
.sort()
.filter((path) => actual.get(path) !== expected.get(path))
.map((path) => join(target.generatedPath, path));
}
function regenerateExpectedTree(target) {
mkdirSync(scratchRoot, { recursive: true });
const temporaryRoot = mkdtempSync(join(scratchRoot, "preflight-"));
try {
for (const sourcePath of [...runtimePaths, ...target.sourcePaths]) {
cpSync(join(repoRoot, sourcePath), join(temporaryRoot, sourcePath), { recursive: true });
}
run(process.execPath, [join(temporaryRoot, "projection-suite.mjs"), ...target.command], {
cwd: temporaryRoot,
});
const expectedGenerated = readTree(join(temporaryRoot, target.generatedPath));
const manifestText = expectedGenerated.get("registrars.json");
const expectedRegistrars = new Map();
if (manifestText !== undefined) {
const manifest = JSON.parse(manifestText);
for (const registrarPath of manifest.files ?? []) {
expectedRegistrars.set(
join(target.rootPath, registrarPath).replaceAll("\\", "/").replace(/^\.\//u, ""),
readFileSync(join(temporaryRoot, target.rootPath, registrarPath), "utf8"),
);
}
}
return {
generatedDrift: compareGeneratedTree(
target,
readTree(join(repoRoot, target.generatedPath)),
expectedGenerated,
),
expectedRegistrars,
};
} finally {
// Finder/Spotlight can drop metadata into the tree mid-delete; retry the transient ENOTEMPTY.
rmSync(temporaryRoot, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
}
function isGeneratedPath(path) {
return generationTargets.some(
(target) => path === target.generatedPath || path.startsWith(`${target.generatedPath}/`),
);
}
function gitLines(args) {
const output = run("git", args, { cwd: repoRoot });
return output.split("\n").filter(Boolean);
}
function semanticPaths() {
return [
...new Set([
...gitLines(["diff", "--name-only"]),
...gitLines(["diff", "--cached", "--name-only"]),
]),
]
.filter((path) => !isGeneratedPath(path))
.sort();
}
// Every TypeScript and JavaScript module extension a test runner may load.
const importerSource = /\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs)$/u;
const generatedImporter = /\.test\.generated\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs)$/u;
function untrackedAdoptedRegistrars(trackedPaths) {
const tracked = new Set(trackedPaths);
const missing = new Set();
for (const importer of trackedPaths) {
if (
!importerSource.test(importer) ||
generatedImporter.test(importer) ||
isGeneratedPath(importer) ||
!existsSync(join(repoRoot, importer))
) {
continue;
}
const source = readFileSync(join(repoRoot, importer), "utf8");
for (const { fileName: specifier } of ts.preProcessFile(source, true, true).importedFiles) {
if (
!specifier.startsWith(".") ||
!/\.test\.generated(?:\.(?:js|ts|mjs|mts))?$/u.test(specifier)
) {
continue;
}
const sibling = specifier.replace(/\.js$/u, ".ts").replace(/\.mjs$/u, ".mts");
const path = posix.normalize(
posix.join(
posix.dirname(importer),
sibling.endsWith(".test.generated") ? `${sibling}.ts` : sibling,
),
);
if (!tracked.has(path)) missing.add(path);
}
}
return [...missing].sort();
}
function main() {
const status = gitLines(["status", "--short", "--untracked-files=all"]);
const nonignoredUntracked = gitLines(["ls-files", "--others", "--exclude-standard"])
.filter((path) => !isGeneratedPath(path))
.sort();
const trackedGeneratedWrites = [
...new Set([
...gitLines(["diff", "--name-only"]),
...gitLines(["diff", "--cached", "--name-only"]),
]),
]
.filter(isGeneratedPath)
.sort();
const regenerated = generationTargets.map((target) => regenerateExpectedTree(target));
const generatedDrift = regenerated.flatMap((result) => result.generatedDrift);
const expectedRegistrars = new Map(
regenerated.flatMap((result) => [...result.expectedRegistrars.entries()]),
);
const trackedRegistrars = gitLines(["ls-files", "--", ":(glob)**/*.test.generated.ts"]).sort();
const registrarDrift = trackedRegistrars.flatMap((path) =>
trackedRegistrarDifferences(
path,
expectedRegistrars.get(path),
existsSync(join(repoRoot, path)) ? readFileSync(join(repoRoot, path), "utf8") : undefined,
run("git", ["show", `:${path}`], { cwd: repoRoot }),
),
);
const failures = [];
for (const path of untrackedAdoptedRegistrars(gitLines(["ls-files"]))) {
failures.push(`preflight: adopted registrar imported by tracked code is not tracked: ${path}`);
}
if (trackedGeneratedWrites.length > 0) {
failures.push(
`preflight: tracked writes inside script-owned generated paths:\n${trackedGeneratedWrites.join(
"\n",
)}`,
);
}
if (generatedDrift.length > 0) {
failures.push(
`preflight: generated drift not attributable to the generation scripts:\n${generatedDrift.join(
"\n",
)}`,
);
}
if (registrarDrift.length > 0) {
failures.push(`preflight: tracked adopted registrar drift:\n${registrarDrift.join("\n")}`);
}
if (nonignoredUntracked.length > 0) {
failures.push(`preflight: nonignored runtime garbage:\n${nonignoredUntracked.join("\n")}`);
}
const semantic = semanticPaths();
console.log("preflight: semantic diff summary");
console.log(semantic.length === 0 ? "clean" : semantic.join("\n"));
if (status.length > 0) {
console.log("preflight: tracked/untracked status inspected");
}
if (failures.length > 0) {
console.error(failures.join("\n\n"));
process.exit(1);
}
}
main();