- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/scripts/check-changed.mjs?version=136&format=json
253 linesspeed 100% · rename 1%Last change rename in version 100, 3 versions changed it
You're reading version 136. The newest is 318, and 1 version since then changed this file.
1// The check for what a change reaches, for running by hand before a publish. The full check (abso.json's)
2// still runs on every publish, in the merge queue; this one is only the quick local run, so agents don't run
3// the whole suite by hand.
4//
5// npm run check:changed [-- file ...] (paths from the repo root; none: this folder's draft, from abso diff
6// and abso status) --list says what it would run and runs nothing.
7//
8// What it runs, for the changed files:
9// - tests: every test file that imports a changed file, through any number of imports, plus changed test
10// files themselves. A changed file that isn't code (a fixture, a saved log) brings in the test files that
11// name it.
12// - typecheck: tsconfig.json, when it includes a changed file or anything that imports one, incrementally
13// (its build info under node_modules/.cache), so a second run reads only what changed.
14// - biome: the changed files only.
15// A change to setup (package.json, the lockfile, tsconfig.json, abso.json, biome.json) runs the full check.
16import { spawn, spawnSync } from "node:child_process";
17import { mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
18import { createRequire } from "node:module";
19import { availableParallelism } from "node:os";
20import { dirname, extname, join, matchesGlob, relative, resolve, sep } from "node:path";
21import { fileURLToPath } from "node:url";
23const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
25/** Test runs: a folder, the test globs its npm test uses (from that folder), and node's extra arguments. */
26const TESTS = [
27 {
28 cwd: ".",
29 globs: ["src/**/*.test.ts", "worker/project/**/*.test.ts", "client/test/**/*.test.ts", "scripts/**/*.test.ts"],
30 args: ["--import", "./client/test/setup.ts"],
31 },
32];
33/** Typechecks: a tsconfig, from the repo root. */
34const TYPECHECKS = [{ tsconfig: "tsconfig.json" }];
35/** Files whose change can reach anything: the full check runs instead. */
36const SETUP = [
37 "**/package.json",
38 "**/package-lock.json",
39 "**/tsconfig*.json",
40 "abso.json",
41 "biome.json",
42 "biome.jsonc",
43 "client/test/setup.ts",
44];
45const SKIP_DIRS = new Set(["node_modules", ".abso", ".wrangler", "dist", ".git"]);
46const CODE = new Set([".ts", ".tsx", ".mts", ".mjs", ".js", ".cjs"]);
48const posix = (p) => p.split(sep).join("/");
49const matches = (path, globs) => globs.some((g) => matchesGlob(path, g));
51/** Every file under the repo, posix paths from the root, skipping dependency and build folders. */
52function allFiles(dir = root, out = []) {
53 for (const name of readdirSync(dir)) {
54 if (SKIP_DIRS.has(name)) continue;
55 const p = join(dir, name);
56 const s = statSync(p);
57 if (s.isDirectory()) allFiles(p, out);
58 else out.push(posix(relative(root, p)));
59 }
60 return out;
61}
63/**
64 * Each code file's imports, kept between runs in node_modules/.cache by the file's time and size, so a run
65 * reads only the files that changed since the last one.
66 */
67const CACHE = join(root, "node_modules/.cache/check-changed.json");
68function importGraph(code, known) {
69 let cache = {};
70 try {
71 cache = JSON.parse(readFileSync(CACHE, "utf8"));
72 } catch {}
73 const next = {};
74 const importers = new Map();
75 for (const f of code) {
76 const s = statSync(join(root, f));
77 const hit = cache[f];
78 const imports = hit && hit.t === s.mtimeMs && hit.n === s.size ? hit.i : importsOf(f, known);
79 next[f] = { t: s.mtimeMs, n: s.size, i: imports };
80 for (const i of imports) (importers.get(i) ?? importers.set(i, new Set()).get(i)).add(f);
81 }
82 try {
83 mkdirSync(dirname(CACHE), { recursive: true });
84 writeFileSync(CACHE, JSON.stringify(next));
85 } catch {}
86 return importers;
87}
89/** The files a code file imports, as repo paths (relative imports only; packages can't change in a draft). */
90function importsOf(file, known) {
91 const text = readFileSync(join(root, file), "utf8");
92 const out = [];
93 const re = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)["'](\.{1,2}\/[^"']+)["']/g;
94 for (const m of text.matchAll(re)) {
95 const base = posix(join(dirname(file), m[1]));
96 const stem = base.replace(/\.(m?js|cjs)$/, "");
97 for (const c of [base, `${stem}.ts`, `${stem}.tsx`, `${stem}.mts`, `${base}.ts`, `${base}.tsx`, `${base}/index.ts`])
98 if (known.has(c)) {
99 out.push(c);
100 break;
101 }
102 }
103 return out;
104}
106/** This folder's changed files: the draft's, from abso diff, and edits not yet recorded, from abso status. */
107function draftFiles() {
108 const run = (args) => {
109 // One command string: abso is a .cmd on Windows, which needs a shell, and the args are fixed words.
110 const r = spawnSync(`abso ${args.join(" ")}`, { cwd: root, encoding: "utf8", shell: true });
111 if (r.status !== 0) throw new Error(`abso ${args.join(" ")} failed: ${(r.stderr || r.stdout).trim()}`);
112 return r.stdout;
113 };
114 const files = new Set();
115 for (const m of run(["diff"]).matchAll(/^(?:\+\+\+ b|--- a)\/(.+)$/gm)) files.add(m[1].trim());
116 const unrecorded = /^Not yet recorded[^:]*:\s*(.+)$/m.exec(run(["status"]));
117 if (unrecorded) for (const f of unrecorded[1].split(/,\s*/)) files.add(f.trim());
118 return [...files].filter(Boolean);
119}
121/**
122 * A tsconfig's JSON. Plain JSON is read as it is; one with comments goes through TypeScript's reader, loaded
123 * only then, since loading TypeScript takes seconds on a busy machine.
124 */
125function readTsconfig(path) {
126 const text = readFileSync(path, "utf8");
127 try {
128 return JSON.parse(text);
129 } catch {
130 const ts = createRequire(join(root, "package.json"))("typescript");
131 return ts.parseConfigFileTextToJson(path, text).config ?? {};
132 }
133}
135/** What the changed files reach: test files to run per test group, tsconfigs to check, files for biome. */
136export function plan(changed, files = allFiles()) {
137 const known = new Set(files);
138 if (changed.some((f) => matches(f, SETUP))) return { full: changed.filter((f) => matches(f, SETUP)) };
139 const code = files.filter((f) => CODE.has(extname(f)) && !f.endsWith(".d.ts"));
140 const importers = importGraph(code, known);
141 // Everything that imports a changed file, through any number of imports.
142 const reached = new Set(changed.filter((f) => known.has(f)));
143 const queue = [...reached];
144 while (queue.length)
145 for (const by of importers.get(queue.pop()) ?? []) if (!reached.has(by)) reached.add(by), queue.push(by);
146 // A changed file that isn't code: the test files that name it.
147 const tests = TESTS.map((t) => ({ ...t, files: [] }));
148 const owner = (f) =>
149 tests.find(
150 (t) =>
151 (t.cwd === "." || f.startsWith(`${t.cwd}/`)) && matches(t.cwd === "." ? f : f.slice(t.cwd.length + 1), t.globs),
152 );
153 const allTests = files.filter((f) => owner(f));
154 for (const f of changed.filter((c) => known.has(c) && !CODE.has(extname(c)))) {
155 const name = f.split("/").pop();
156 for (const t of allTests) if (readFileSync(join(root, t), "utf8").includes(name)) reached.add(t);
157 }
158 for (const f of reached) {
159 const t = owner(f);
160 if (t) t.files.push(t.cwd === "." ? f : f.slice(t.cwd.length + 1));
161 }
162 const typechecks = TYPECHECKS.filter((c) => {
163 const cfg = readTsconfig(join(root, c.tsconfig));
164 const dir = posix(dirname(c.tsconfig));
165 const inc = (cfg.include ?? ["**/*"]).map((g) => posix(join(dir, g)));
166 const exc = (cfg.exclude ?? []).map((g) => posix(join(dir, g)));
167 return [...reached].some((f) => matches(f, inc) && !matches(f, exc));
168 });
169 const lint = changed.filter((f) => known.has(f) && /\.(m?[jt]sx?|cjs|json|jsonc|css)$/.test(f));
170 return { tests: tests.filter((t) => t.files.length), typechecks, lint };
171}
173/** Runs one command, its output kept, and resolves with its exit and time. */
174function runOne(name, cmd, args, cwd) {
175 const started = Date.now();
176 return new Promise((done) => {
177 const child = spawn(cmd, args, { cwd: join(root, cwd) });
178 let out = "";
179 child.stdout.on("data", (d) => (out += d));
180 child.stderr.on("data", (d) => (out += d));
181 child.on("close", (code) => done({ name, code, out, ms: Date.now() - started }));
182 });
183}
185async function main() {
186 const argv = process.argv.slice(2);
187 const listOnly = argv.includes("--list");
188 const given = argv.filter((a) => a !== "--list").map((a) => posix(a).replace(/^\.\//, ""));
189 const changed = given.length ? given : draftFiles();
190 if (!changed.length) {
191 console.log("Nothing changed in this folder: nothing to check.");
192 return;
193 }
194 const p = plan(changed);
195 if (p.full) {
196 console.log(`Setup changed (${p.full.join(", ")}): running the full check.`);
197 if (listOnly) return;
198 const { check } = JSON.parse(readFileSync(join(root, "abso.json"), "utf8"));
199 const r = spawnSync(check, { cwd: root, stdio: "inherit", shell: true });
200 process.exit(r.status ?? 1);
201 }
202 const jobs = [];
203 for (const t of p.tests)
204 jobs.push({
205 name: `test ${t.cwd} (${t.files.length} files)`,
206 cmd: process.execPath,
207 args: [...t.args, "--test", ...t.files],
208 cwd: t.cwd,
209 });
210 for (const c of p.typechecks) {
211 const info = `node_modules/.cache/tsc/${c.tsconfig.replace(/[/\\]/g, "_")}.tsbuildinfo`;
212 jobs.push({
213 name: `typecheck ${c.tsconfig}`,
214 cmd: process.execPath,
215 args: [
216 join(root, "node_modules/typescript/bin/tsc"),
217 "--noEmit",
218 "-p",
219 c.tsconfig,
220 "--incremental",
221 "--tsBuildInfoFile",
222 info,
223 ],
224 cwd: ".",
225 });
226 }
227 if (p.lint.length)
228 jobs.push({
229 name: `biome (${p.lint.length} files)`,
230 cmd: process.execPath,
231 args: [join(root, "node_modules/@biomejs/biome/bin/biome"), "check", "--no-errors-on-unmatched", ...p.lint],
232 cwd: ".",
233 });
234 console.log(`Changed: ${changed.join(", ")}`);
235 for (const j of jobs)
236 console.log(
237 ` ${j.name}${j.name.startsWith("test") ? `: ${j.args.filter((a) => /\.test\./.test(a)).join(" ")}` : ""}`,
238 );
239 if (listOnly || !jobs.length) return;
240 const started = Date.now();
241 const slots = Math.max(1, Number(process.env.ABSO_CHECK_SLOTS) || availableParallelism());
242 const results = [];
243 for (let i = 0; i < jobs.length; i += slots)
244 results.push(...(await Promise.all(jobs.slice(i, i + slots).map((j) => runOne(j.name, j.cmd, j.args, j.cwd)))));
245 for (const r of results.filter((r) => r.code !== 0)) console.log(`\n--- ${r.name} failed ---\n${r.out.trimEnd()}`);
246 console.log("");
247 for (const r of results)
248 console.log(`${r.code === 0 ? "ok " : "FAIL"} ${(r.ms / 1000).toFixed(1).padStart(6)} s ${r.name}`);
249 console.log(`${((Date.now() - started) / 1000).toFixed(1)} s in all. The full check runs when you push.`);
250 if (results.some((r) => r.code !== 0)) process.exitCode = 1;
251}
253if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) await main();