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

check-changed.ts

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