Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

check-changed.ts

375 lines15.6 KB

1// @effect-diagnostics nodeBuiltinImport:off globalConsole:off
2// Runs CI's fast checks for this branch's changes: format and lint of the
3// changed files, knip, generated GraphQL operations, typecheck of the affected
4// packages and their dependents, the test files beside the changed files, and
5// the cross-file checks those miss (agent context budget, React Compiler
6// coverage of the changed client files).
7// A dependency change also gets the unused-patch install check below. CI still
8// runs the full test suites and the jobs listed in the summary.
9//
10// vp run check:changed compare against the merge base with origin/main
11// vp run check:changed <ref> compare against the merge base with <ref>
12//
13// Uncommitted and untracked files count. Affected packages come from
14// .github/scripts/ci-changes.cjs, the same mapping CI uses to gate its jobs.
15// The steps run side by side; each prints its output when it finishes. A
16// rerun on exactly the files of the last passing run prints that run's summary.
17import * as NodeChildProcess from "node:child_process";
18import * as NodeCrypto from "node:crypto";
19import * as NodeFS from "node:fs";
20import * as NodeOS from "node:os";
21import * as NodePath from "node:path";
22import { decide, readWorkspace } from "../.github/scripts/ci-changes.cjs";
23​
24const root = NodePath.resolve(import.meta.dirname, "..");
25const CODE = /\.[cm]?[jt]sx?$/;
26​
27// quotePath=false keeps non-ASCII paths as real paths instead of quoted escapes.
28const git = (...args: Array<string>) =>
29 NodeChildProcess.execFileSync("git", ["-c", "core.quotePath=false", ...args], {
30 cwd: root,
31 encoding: "utf8",
32 maxBuffer: 64 * 1024 * 1024,
33 })
34 .split("\n")
35 .filter(Boolean);
36​
37const ref = process.argv[2] ?? "origin/main";
38const mergeBase = NodeChildProcess.spawnSync("git", ["merge-base", "HEAD", ref], {
39 cwd: root,
40 encoding: "utf8",
41});
42if (mergeBase.status !== 0) {
43 console.error(
44 `check:changed: no merge base with ${ref}. Run \`git fetch origin\` or pass a ref.`,
45 );
46 process.exit(1);
48const base = mergeBase.stdout.trim();
49// --no-renames lists a rename as its old and new path, as CI does.
50const untracked = git("ls-files", "--others", "--exclude-standard");
51const files = [
52 ...new Set([...git("diff", "--name-only", "--no-renames", base, "--"), ...untracked]),
53].sort();
54​
55if (files.length === 0) {
56 console.log(`check:changed: no changes since ${base.slice(0, 12)}.`);
57 process.exit(0);
59console.log(`check:changed: ${files.length} files since ${base.slice(0, 12)}`);
60​
61// Ignored generated sources, declarations, env files, and install state affect check results.
62// Include them in the key, but skip large ignored folders that no check reads.
63// Recompute after a passing run so edits made during it are never cached as passing.
64const inputKey = () => {
65 const hash = NodeCrypto.createHash("sha256");
66 // CI changes test behavior (vite.config.ts rejects .only under CI).
67 hash.update(`${process.version}\0${base}\0${process.env.CI ?? ""}\0`);
68 hash.update(
69 NodeChildProcess.execFileSync(
70 "git",
71 ["diff", "--binary", "--no-renames", "--no-ext-diff", "--no-textconv", base, "--"],
72 { cwd: root, maxBuffer: 1024 * 1024 * 1024 },
73 ),
74 );
75 const ignored = git(
76 "ls-files",
77 "--others",
78 "--ignored",
79 "--exclude-standard",
80 "--",
81 ":(glob)**/.generated/**",
82 ":(glob)**/.astro/**",
83 ":(glob)**/*.d.ts",
84 ":(glob)**/.env*",
85 ":(exclude,glob)**/node_modules/**",
86 );
87 for (const file of [
88 // Raw bytes of changed files too: .gitattributes normalizes line endings in
89 // the diff, but the formatter reads the file as it is on disk.
90 ...git("diff", "--name-only", "--no-renames", base, "--"),
91 ...git("ls-files", "--others", "--exclude-standard"),
92 ...ignored,
93 "node_modules/.modules.yaml",
94 "node_modules/.pnpm/lock.yaml",
95 ]) {
96 hash.update(`\0${file}\0`);
97 const path = NodePath.join(root, file);
98 // Untracked nested repositories are listed as directories.
99 if (NodeFS.statSync(path, { throwIfNoEntry: false })?.isFile()) {
100 hash.update(NodeFS.readFileSync(path));
101 }
102 }
103 return hash.digest("hex");
104};
105const key = inputKey();
106const cachePath = NodePath.join(root, "node_modules/.cache/check-changed.json");
107// A missing or unreadable cache is a miss, never a failure.
108const readCache = () => {
109 try {
110 return JSON.parse(NodeFS.readFileSync(cachePath, "utf8")) as {
111 key: string;
112 summary: Array<string>;
113 };
114 } catch {
115 return undefined;
116 }
117};
118const cached = readCache();
119if (cached?.key === key) {
120 console.log("Nothing changed since the last passing run.\n");
121 for (const line of cached.summary) console.log(line);
122 process.exit(0);
124​
125const present = files.filter((file) => NodeFS.existsSync(NodePath.join(root, file)));
126const code = present.filter((file) => CODE.test(file));
127const packages = readWorkspace();
128const { affected, outputs } = decide(files, packages, false);
129​
130// Changed test files, and the test files beside a changed source file
131// (foo.ts -> foo.test.ts, foo.browser.test.tsx). Vitest's import-graph
132// `related` reaches most of a package: one leaf server file pulled in 252 of
133// 406 server test files and took 7 minutes. CI runs the rest.
134const TEST = /\.test\.[cm]?[jt]sx?$/;
135const tests = new Set(code.filter((file) => TEST.test(file)));
136for (const file of code) {
137 const dir = NodePath.dirname(file);
138 const prefix = `${NodePath.basename(file).replace(CODE, "")}.`;
139 for (const entry of NodeFS.readdirSync(NodePath.join(root, dir))) {
140 if (entry.startsWith(prefix) && TEST.test(entry)) tests.add(NodePath.join(dir, entry));
141 }
143// It reads files other than the ones beside it, so no changed file selects it.
144if (affected.includes("t3")) tests.add("apps/server/src/provider/AgentContextBudget.test.ts");
145​
146// React Compiler coverage compiles every client source file, so run only the
147// changed files' cases, in one extra step: a -t filter in the main test step
148// would drop every other test. An app is skipped when the main step already
149// runs its coverage file unfiltered. File filters mirror each coverage test.
150const escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
151const compilerApps = [
152 {
153 test: "apps/web/src/reactCompilerCoverage.test.ts",
154 root: "apps/web/src/",
155 // Test names keep the repo-relative path.
156 name: (file: string) => file,
157 compiled: (file: string) =>
158 /\.tsx?$/.test(file) && !/\.(test|browser)\.tsx?$/.test(file) && !file.endsWith(".gen.ts"),
159 // Web has only per-file cases.
160 always: [],
161 },
162 {
163 test: "apps/mobile/src/reactCompilerCoverage.test.ts",
164 root: "apps/mobile/src/",
165 name: (file: string) => file.slice("apps/mobile/".length),
166 compiled: (file: string) => /\.tsx?$/.test(file) && !/\.(test\.tsx?|d\.ts)$/.test(file),
167 // The Metro, cache, and stale-allowlist cases check more than one file, deletions included.
168 always: ["^(?!.*compiles )"],
169 },
170].flatMap(({ test, root: appRoot, name, compiled, always }) => {
171 const changed = files.filter((file) => file.startsWith(appRoot) && compiled(file));
172 if (changed.length === 0 || tests.has(test)) return [];
173 const names = changed
174 .filter((file) => present.includes(file))
175 .map((file) => `compiles ${escapeRegExp(name(file))}$`);
176 const pattern = [...names, ...always];
177 return pattern.length > 0 ? [{ test, names, pattern }] : [];
178});
179const compilerCoverage = compilerApps.length > 0 && {
180 name: `react compiler (${compilerApps.reduce((count, app) => count + app.names.length, 0)} files)`,
181 args: [
182 "test",
183 "run",
184 ...compilerApps.map((app) => app.test),
185 "-t",
186 compilerApps.flatMap((app) => app.pattern).join("|"),
187 ],
188};
189​
190// knip:check cannot be scoped to a package. Any code change can leave a file,
191// export, or dependency unused (removing the last import of a helper does), so
192// it runs whenever code or a manifest changes.
193const runKnip = files.some(
194 (file) => CODE.test(file) || NodePath.basename(file) === "package.json" || file === "knip.jsonc",
195);
196// CI runs knip:check as one script of `knip ... && knip ...` passes. The passes
197// do not depend on each other, so they run side by side here.
198const knipCheck: string = JSON.parse(
199 NodeFS.readFileSync(NodePath.join(root, "package.json"), "utf8"),
200).scripts["knip:check"];
201const knipPasses = knipCheck.split(" && ").map((command, index, all) => {
202 const [bin, ...args] = command.trim().split(/\s+/);
203 if (bin !== "knip" || /["'$\\|;&<>]/.test(command)) {
204 throw new Error(`check:changed cannot split knip:check: ${command}`);
205 }
206 return { name: `knip ${index + 1}/${all.length}`, args: ["exec", "knip", ...args] };
207});
208​
209// A version bump can leave a patch unused, causing pnpm to reject the install
210// with ERR_PNPM_UNUSED_PATCH. Check it here as Release Smoke does in CI.
211const runPatchCheck = files.some(
212 (file) =>
213 file === "pnpm-workspace.yaml" ||
214 file === "pnpm-lock.yaml" ||
215 file === ".pnpmfile.cjs" ||
216 file.startsWith("patches/") ||
217 file.startsWith("apps/mobile/deps/") ||
218 NodePath.basename(file) === "package.json",
219);
220​
221// Resolve without the lockfile in a temp copy to preserve the working tree and lockfile.
222// Copy mobile modules too: they are file: dependencies, not workspace packages.
223// Cached registry metadata limits this to patches stranded by local changes, not registry drift.
224const checkPatches = (): boolean => {
225 const temp = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-patch-check-"));
226 try {
227 const copy = (relative: string) => {
228 const dest = NodePath.join(temp, relative);
229 NodeFS.mkdirSync(NodePath.dirname(dest), { recursive: true });
230 NodeFS.cpSync(NodePath.join(root, relative), dest, { recursive: true });
231 };
232 copy("package.json");
233 copy("pnpm-workspace.yaml");
234 for (const pkg of packages) copy(`${pkg.dir}/package.json`);
235 const modulesDir = NodePath.join(root, "apps/mobile/modules");
236 if (NodeFS.existsSync(modulesDir)) {
237 for (const entry of NodeFS.readdirSync(modulesDir)) {
238 const manifest = `apps/mobile/modules/${entry}/package.json`;
239 if (NodeFS.existsSync(NodePath.join(root, manifest))) copy(manifest);
240 }
241 }
242 for (const extra of ["apps/mobile/deps", "patches", ".pnpmfile.cjs"]) {
243 if (NodeFS.existsSync(NodePath.join(root, extra))) copy(extra);
244 }
245 const { status, stdout, stderr, error } = NodeChildProcess.spawnSync(
246 "vp",
247 ["install", "--lockfile-only", "--ignore-scripts"],
248 { cwd: temp, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 },
249 );
250 if (status === 0) return true;
251 if (stdout) console.log(stdout);
252 if (stderr) console.error(stderr);
253 if (error) console.error(error.message);
254 if (`${stdout ?? ""}${stderr ?? ""}`.includes("ERR_PNPM_UNUSED_PATCH")) {
255 console.error(
256 "Unused dependency patches: remove each patch named above from " +
257 "patchedDependencies in pnpm-workspace.yaml and from patches/, " +
258 "update it to the version the install resolves, " +
259 "or pin the dependency that pulls it in to the patched version.",
260 );
261 }
262 return false;
263 } finally {
264 NodeFS.rmSync(temp, { recursive: true, force: true });
265 }
266};
267​
268// CI's Lint job checks that generated GraphQL operations match their sources.
269const graphql = ["apps/server", "packages/source-control-github"].filter((dir) =>
270 files.some((file) => file.startsWith(`${dir}/`)),
271);
272​
273const filters = (names: ReadonlyArray<string>) => names.flatMap((name) => ["--filter", name]);
274const steps = [
275 // Runs first; it takes about a second.
276 runPatchCheck && { name: "unused patches", run: checkPatches },
277 present.length > 0 && {
278 name: "format",
279 args: ["fmt", "--check", "--no-error-on-unmatched-pattern", ...present],
280 },
281 code.length > 0 && { name: "lint", args: ["lint", ...code] },
282 ...(runKnip ? knipPasses : []),
283 ...graphql.map((dir) => ({
284 name: `graphql (${dir})`,
285 args: ["run", "--filter", `./${dir}`, "generate", "--check"],
286 })),
287 affected.length > 0 && {
288 name: `typecheck (${affected.length} packages)`,
289 // `tsc --noEmit` writes nothing another package reads, so dependency order
290 // only made dependents wait: --parallel cut a contracts change from 13 s to 9 s.
291 args: [
292 "run",
293 "--cache",
294 "--parallel",
295 "--concurrency-limit",
296 "4",
297 ...filters(affected),
298 "typecheck",
299 ],
300 },
301 // From the repo root, the root vite.config.ts hands each file to its package's config.
302 tests.size > 0 && {
303 name: `test (${tests.size} files)`,
304 args: ["test", "run", "--passWithNoTests", ...tests],
305 },
306 compilerCoverage,
307].filter((step) => step !== false);
308​
309// Output is piped, so keep the colors a terminal would get.
310const env = process.stdout.isTTY ? { ...process.env, FORCE_COLOR: "1" } : process.env;
311const runStep = (step: (typeof steps)[number]) =>
312 new Promise<{ name: string; ok: boolean; seconds: string }>((resolve) => {
313 const started = performance.now();
314 const finish = (ok: boolean, output?: Buffer) => {
315 const seconds = ((performance.now() - started) / 1000).toFixed(1);
316 console.log(`\n> vp ${step.name} ${ok ? "pass" : "FAIL"} ${seconds}s`);
317 if (output) process.stdout.write(output);
318 resolve({ name: step.name, ok, seconds });
319 };
320 // In-process steps print their own output. The patch check is first and
321 // takes about a second, so the commands start right after it.
322 if ("run" in step) return finish(step.run());
323 const output: Array<Buffer> = [];
324 const child = NodeChildProcess.spawn("vp", step.args, { cwd: root, env });
325 child.stdout.on("data", (chunk: Buffer) => output.push(chunk));
326 child.stderr.on("data", (chunk: Buffer) => output.push(chunk));
327 // A failed spawn emits "error", then "close" with a nonzero code.
328 child.on("error", (error) => output.push(Buffer.from(`${error.message}\n`)));
329 child.on("close", (status) => finish(status === 0, Buffer.concat(output)));
330 });
331​
332// Vitest runs started together race to rebuild node_modules/.vitest-cache after
333// an install (ENOTEMPTY), so they run one after another.
334let previousVitest: Promise<unknown> = Promise.resolve();
335const results = await Promise.all(
336 steps.map((step) => {
337 if (!("args" in step) || step.args[0] !== "test") return runStep(step);
338 const result = previousVitest.then(() => runStep(step));
339 previousVitest = result;
340 return result;
341 }),
342);
343​
344const summary = ["check:changed summary"];
345for (const result of results) {
346 summary.push(` ${result.ok ? "pass" : "FAIL"} ${result.name} ${result.seconds}s`);
348const ciOnly = Object.entries({
349 "full test suites": outputs.test || outputs.test_web || outputs.test_server,
350 build: outputs.build,
351 rust: outputs.rust,
352 "mobile native lint": outputs.mobile_native,
353 "release smoke": outputs.release_smoke,
354}).flatMap(([job, runs]) => (runs ? [job] : []));
355if (ciOnly.length > 0) summary.push(` CI also runs: ${ciOnly.join(", ")}`);
356if (!runPatchCheck) summary.push(" unused patch check skipped: no dependency files changed");
357if (!runKnip) summary.push(" knip skipped: no code or manifest changed");
358console.log(`\n${summary.join("\n")}`);
359// exitCode, not exit(): piped stdout is asynchronous on macOS, and exit()
360// would cut off a failing step's output.
361if (results.some((result) => !result.ok)) {
362 process.exitCode = 1;
363} else if (inputKey() !== key) {
364 console.log(" pass not cached: files changed during the run");
365} else {
366 try {
367 // Write then rename, so a concurrent run never reads half a file.
368 const temp = `${cachePath}.${process.pid}`;
369 NodeFS.mkdirSync(NodePath.dirname(cachePath), { recursive: true });
370 NodeFS.writeFileSync(temp, JSON.stringify({ key, summary }));
371 NodeFS.renameSync(temp, cachePath);
372 } catch (error) {
373 console.warn(` pass not cached: ${error instanceof Error ? error.message : String(error)}`);
374 }