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