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

setup-worktree.ts

128 lines5.3 KB

1// @effect-diagnostics nodeBuiltinImport:off - runs before `vp i`, so only Node built-ins exist.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFS from "node:fs";
4import * as NodePath from "node:path";
5​
6const ENV_FILES = [".env", NodePath.join("infra", "relay", ".env")];
7​
8const worktree = NodePath.dirname(import.meta.dirname);
9​
10// T3 runs setup in the background, so agents can start before it ends.
11// `setup-running` holds this PID until setup ends with `setup-done` or
12// `setup-failed`, so agents wait instead of racing it with their own `vp i`.
13const markerDir = NodePath.join(worktree, ".t3");
14const runningMarker = NodePath.join(markerDir, "setup-running");
15const doneMarker = NodePath.join(markerDir, "setup-done");
16const failedMarker = NodePath.join(markerDir, "setup-failed");
17NodeFS.rmSync(doneMarker, { force: true });
18NodeFS.rmSync(failedMarker, { force: true });
19NodeFS.mkdirSync(markerDir, { recursive: true });
20NodeFS.writeFileSync(runningMarker, `${process.pid}\n`);
21let failureDetail = "";
22process.on("uncaughtExceptionMonitor", (error) => {
23 failureDetail = error.stack ?? String(error);
24});
25process.on("exit", (code) => {
26 if (code === 0) NodeFS.writeFileSync(doneMarker, "");
27 else NodeFS.writeFileSync(failedMarker, `Setup exited with code ${code}.\n${failureDetail}\n`);
28 NodeFS.rmSync(runningMarker, { force: true });
29});
30// A cancelled setup must still leave a marker, or agents would wait forever.
31// During install, the signal goes on to the installer and setup exits when the
32// install output closes. Any child the shell leaves behind holds that output
33// open, so no marker appears while `vp i` can still write node_modules.
34let cancelSignal: NodeJS.Signals | undefined;
35let activeInstall: NodeChildProcess.ChildProcess | undefined;
36for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) {
37 process.on(signal, () => {
38 cancelSignal = signal;
39 if (activeInstall) activeInstall.kill(signal);
40 else process.exit(1);
41 });
43​
44const projectRoot = process.env.T3CODE_PROJECT_ROOT;
45if (!projectRoot) {
46 throw new Error("T3CODE_PROJECT_ROOT is not set. Run this through the t3.json setup action.");
48​
49// `shell` resolves `vp` through PATH, including Windows command shims.
50// Setup has no one answering install prompts. Pass pnpm's confirmation flag
51// through vp and leave stdin closed so other prompts fail instead of hanging.
52// Install exactly the locked dependencies so setup never rewrites the lockfile.
53// A stale lockfile must fail setup rather than silently resolving a new one.
54// Output is piped, not inherited, so a failure can keep its tail in the marker.
55const install = NodeChildProcess.spawn("vp i --frozen-lockfile -- --yes", {
56 cwd: worktree,
57 shell: true,
58 stdio: ["ignore", "pipe", "pipe"],
59});
60activeInstall = install;
61let installOutput = "";
62for (const [source, target] of [
63 [install.stdout, process.stdout],
64 [install.stderr, process.stderr],
65] as const) {
66 source.setEncoding("utf8");
67 source.on("data", (chunk: string) => {
68 target.write(chunk);
69 installOutput = (installOutput + chunk).slice(-8_000);
70 });
72const installStatus = await new Promise<number | null>((resolve) => install.on("close", resolve));
73activeInstall = undefined;
74if (installStatus !== 0 || cancelSignal) {
75 failureDetail = cancelSignal
76 ? `Cancelled by ${cancelSignal}.`
77 : installOutput.trimEnd().split("\n").slice(-30).join("\n");
78 process.exit(installStatus || 1);
80​
81// pnpm cannot clone or hardlink across filesystems, so a store on another
82// device silently turns every worktree install into a full copy.
83const storeDir: unknown = JSON.parse(
84 NodeFS.readFileSync(NodePath.join(worktree, "node_modules", ".modules.yaml"), "utf8"),
85).storeDir;
86if (
87 typeof storeDir === "string" &&
88 NodeFS.statSync(storeDir).dev !== NodeFS.statSync(NodePath.join(worktree, "node_modules")).dev
89) {
90 process.stderr.write(
91 [
92 "",
93 "WARNING: the pnpm store is on a different filesystem than this worktree.",
94 ` store: ${storeDir}`,
95 ` worktree: ${worktree}`,
96 "pnpm cannot hardlink or clone across filesystems, so it copied every package into node_modules.",
97 "Fix: put the store on the worktree's filesystem, for example:",
98 ` pnpm config set store-dir ${JSON.stringify(NodePath.join(NodePath.dirname(worktree), ".pnpm-store"))} --global`,
99 "",
100 "",
101 ].join("\n"),
102 );
104​
105// Env files live as real files in the main checkout; worktrees only get
106// symlinks to them. Only a symlink is ever replaced, so a real env file is
107// never deleted, including when this runs in the main checkout itself.
108for (const file of ENV_FILES) {
109 const source = NodePath.join(projectRoot, file);
110 const sourceStat = NodeFS.lstatSync(source, { throwIfNoEntry: false });
111 if (!sourceStat) continue;
112 if (!sourceStat.isFile()) {
113 process.stderr.write(`Skipping ${file}: ${source} is not a regular file.\n`);
114 continue;
115 }
116 const target = NodePath.join(worktree, file);
117 const existing = NodeFS.lstatSync(target, { throwIfNoEntry: false });
118 if (existing && !existing.isSymbolicLink()) continue;
119 if (existing) NodeFS.rmSync(target);
120 NodeFS.symlinkSync(source, target);
122​
123const warm = NodeChildProcess.spawnSync(
124 process.execPath,
125 [NodePath.join(worktree, "apps", "web", "scripts", "warm-dep-cache.ts")],
126 { cwd: worktree, stdio: "inherit" },
127);
128process.exit(warm.status ?? 1);