@kaynooo/cli-wt 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +17 -10
  2. package/dist/cli-02xxc9xk.js +67 -0
  3. package/dist/cli-5khwxy5g.js +36 -0
  4. package/dist/cli-6k7xzgw2.js +519 -0
  5. package/dist/cli-96wy1q8e.js +97 -0
  6. package/dist/cli-9m1jyyrf.js +69 -0
  7. package/dist/cli-fa4fh6ex.js +37 -0
  8. package/dist/cli-fdwwsds1.js +153 -0
  9. package/dist/cli-jb9a8d46.js +674 -0
  10. package/dist/cli-k4471y24.js +779 -0
  11. package/dist/cli-kt6d30zz.js +106 -0
  12. package/dist/cli-q7e6gegw.js +105 -0
  13. package/dist/cli-qwe5ykfs.js +313 -0
  14. package/dist/cli-tp4q5w5x.js +251 -0
  15. package/dist/cli.js +228 -2809
  16. package/dist/commands-jqr92tk6.js +222 -0
  17. package/dist/init-0ws4c883.js +166 -0
  18. package/dist/list-83vq4jng.js +88 -0
  19. package/dist/print-d4aq2eqw.js +77 -0
  20. package/dist/prompt-y71tp3f5.js +436 -0
  21. package/dist/prune-7ex1qyd3.js +17 -0
  22. package/dist/run-jrmm9gg8.js +18 -0
  23. package/dist/shell-1smv2vf9.js +55 -0
  24. package/dist/stack-2zj6r6py.js +20 -0
  25. package/dist/tools-c4m5037s.js +13 -0
  26. package/package.json +4 -4
  27. package/src/cli.ts +250 -69
  28. package/src/commands.ts +51 -38
  29. package/src/compose.ts +37 -14
  30. package/src/config.ts +8 -1
  31. package/src/errors.ts +16 -6
  32. package/src/files.ts +14 -15
  33. package/src/git.ts +53 -7
  34. package/src/index.ts +2 -1
  35. package/src/init.ts +56 -10
  36. package/src/jobs.ts +54 -15
  37. package/src/list.ts +26 -13
  38. package/src/print.ts +76 -0
  39. package/src/project.ts +129 -28
  40. package/src/proxy.ts +5 -5
  41. package/src/prune.ts +149 -0
  42. package/src/queue.ts +27 -3
  43. package/src/run.ts +82 -23
  44. package/src/shell.ts +34 -7
  45. package/src/stack.ts +10 -12
  46. package/src/sync.ts +28 -3
  47. package/src/tools.ts +91 -0
@@ -0,0 +1,106 @@
1
+ // @bun
2
+ import {
3
+ WtError
4
+ } from "./cli-6k7xzgw2.js";
5
+
6
+ // src/git.ts
7
+ import { existsSync, mkdirSync, readdirSync, rmdirSync } from "fs";
8
+ import { basename, dirname, join } from "path";
9
+ var {$ } = globalThis.Bun;
10
+ async function git(cwd, ...args) {
11
+ const result = await $`git -C ${cwd} ${args}`.quiet().nothrow();
12
+ return { ok: result.exitCode === 0, out: `${result.stdout.toString()}${result.stderr.toString()}`.trim() };
13
+ }
14
+ async function branchExists(repo, branch) {
15
+ if ((await git(repo, "show-ref", "--quiet", "--verify", `refs/heads/${branch}`)).ok)
16
+ return true;
17
+ return (await git(repo, "for-each-ref", "--format=%(refname)", `refs/remotes/*/${branch}`)).out !== "";
18
+ }
19
+ async function forkPoint(repo, from) {
20
+ const sha = await git(repo, "rev-parse", "--short", `${from ?? "HEAD"}^{commit}`);
21
+ if (!sha.ok)
22
+ return;
23
+ if (from !== undefined)
24
+ return `${from} (${sha.out})`;
25
+ const name = (await git(repo, "rev-parse", "--abbrev-ref", "HEAD")).out;
26
+ return name === "HEAD" ? `a detached HEAD (${sha.out})` : `${name} (${sha.out})`;
27
+ }
28
+ async function onBranch(repo, dir, branch, from) {
29
+ if (await branchExists(repo, branch))
30
+ return { ...await git(repo, "worktree", "add", dir, branch), start: `on ${branch} as it is` };
31
+ const point = await forkPoint(repo, from);
32
+ if (point === undefined)
33
+ return { ok: false, out: `no commit ${from ?? "HEAD"} in ${repo}`, start: "" };
34
+ return { ...await git(repo, "worktree", "add", "-b", branch, dir, ...from === undefined ? [] : [from]), start: `on ${branch}, forked from ${point}` };
35
+ }
36
+ async function addWorktrees(worktree, branch, from) {
37
+ const { project, dir } = worktree;
38
+ if (existsSync(dir))
39
+ throw new WtError(`${dir} already exists`, `\`wt sync ${worktree.task} -p ${project.name}\` finishes it, \`wt rm ${worktree.task} -p ${project.name}\` removes it`);
40
+ if (from !== undefined) {
41
+ for (const repo of project.repos.length ? project.repos : ["."]) {
42
+ if (await branchExists(join(project.root, repo), branch))
43
+ throw new WtError(`${branch} already exists${repo === "." ? "" : ` in ${repo}`}, so it is checked out as it is`, "drop --from, or name a new branch");
44
+ }
45
+ }
46
+ mkdirSync(dirname(dir), { recursive: true });
47
+ if (!project.repos.length) {
48
+ const root = await onBranch(project.root, dir, branch, from);
49
+ if (!root.ok)
50
+ throw new WtError(`git worktree add failed for the root:
51
+ ${root.out}`);
52
+ return [root.start];
53
+ }
54
+ const root = await git(project.root, "worktree", "add", "--detach", dir);
55
+ if (!root.ok)
56
+ throw new WtError(`git worktree add failed for the root:
57
+ ${root.out}`);
58
+ const starts = [];
59
+ for (const repo of project.repos) {
60
+ const added = await onBranch(join(project.root, repo), join(dir, repo), branch, from);
61
+ if (!added.ok) {
62
+ await removeWorktrees(worktree);
63
+ throw new WtError(`git worktree add failed for ${repo}, rolled back:
64
+ ${added.out}`);
65
+ }
66
+ starts.push(`${repo} ${added.start}`);
67
+ }
68
+ return starts;
69
+ }
70
+ async function removeWorktrees(worktree) {
71
+ const { project, dir } = worktree;
72
+ await Promise.all(project.repos.map(async (repo) => git(join(project.root, repo), "worktree", "remove", "--force", join(dir, repo))));
73
+ await git(project.root, "worktree", "remove", "--force", dir);
74
+ if (existsSync(dir))
75
+ await $`docker run --rm -v ${`${dirname(dir)}:/parent`} alpine rm -rf ${`/parent/${basename(dir)}`}`.quiet();
76
+ await Promise.all([".", ...project.repos].map(async (repo) => git(join(project.root, repo), "worktree", "prune")));
77
+ if (existsSync(dirname(dir)) && !readdirSync(dirname(dir)).length)
78
+ rmdirSync(dirname(dir));
79
+ }
80
+ async function dirtyRepos(worktree) {
81
+ const repos = [".", ...worktree.project.repos];
82
+ const statuses = await Promise.all(repos.map(async (repo) => git(join(worktree.dir, repo), "status", "--porcelain")));
83
+ return repos.filter((_, index) => statuses[index].ok && statuses[index].out !== "").map((repo) => repo === "." ? "root" : repo);
84
+ }
85
+ async function unreachableByRepo(dir, repos) {
86
+ const all = [".", ...repos];
87
+ const counts = await Promise.all(all.map(async (repo) => git(join(dir, repo), "rev-list", "--count", "HEAD", "--not", "--branches", "--remotes", "--tags")));
88
+ return all.map((repo, index) => ({ repo: repo === "." ? "root" : repo, count: Number(counts[index].ok ? counts[index].out : 0) })).filter(({ count }) => count > 0);
89
+ }
90
+ async function unreachableCommits(worktree) {
91
+ return (await unreachableByRepo(worktree.dir, worktree.project.repos)).map(({ repo, count }) => `${repo} (${count} commit${count === 1 ? "" : "s"})`);
92
+ }
93
+ async function unreachableCount(dir, repos) {
94
+ return (await unreachableByRepo(dir, repos)).reduce((total, { count }) => total + count, 0);
95
+ }
96
+ async function isRegistered(worktree) {
97
+ const listed = await git(worktree.project.root, "worktree", "list", "--porcelain");
98
+ return listed.out.split(`
99
+ `).includes(`worktree ${worktree.dir}`);
100
+ }
101
+ async function currentBranch(dir) {
102
+ const result = await git(dir, "rev-parse", "--abbrev-ref", "HEAD");
103
+ return result.ok ? result.out : "?";
104
+ }
105
+
106
+ export { git, addWorktrees, removeWorktrees, dirtyRepos, unreachableCommits, unreachableCount, isRegistered, currentBranch };
@@ -0,0 +1,105 @@
1
+ // @bun
2
+ import {
3
+ wtConfig,
4
+ loadProjects,
5
+ stackName,
6
+ worktreeOf,
7
+ listTasks,
8
+ currentDir,
9
+ locate
10
+ } from "./cli-6k7xzgw2.js";
11
+ import {
12
+ git
13
+ } from "./cli-kt6d30zz.js";
14
+
15
+ // src/prune.ts
16
+ import { existsSync, readdirSync, rmSync } from "fs";
17
+ import { join } from "path";
18
+ var {$ } = globalThis.Bun;
19
+ async function leftBehind2(options) {
20
+ const projects = options.all ? await loadProjects() : [(await locate(currentDir(), options.project)).project];
21
+ const { jobs } = await wtConfig();
22
+ const found = await Promise.all(projects.map(async (project) => ({ project, orphans: await orphansOf(project, jobs), stale: await staleRegistrations(project) })));
23
+ return found.filter((each) => each.orphans.length > 0 || each.stale > 0);
24
+ }
25
+ function describeLeftBehind2(found) {
26
+ return found.flatMap(({ project, orphans, stale }) => [
27
+ ...orphans.map(({ worktree, left }) => `${project.name}/${worktree.task}: ${left.join(", ")}`),
28
+ ...stale > 0 ? [`${project.name}: ${stale} git worktree registration${stale === 1 ? "" : "s"} for a folder gone`] : []
29
+ ]);
30
+ }
31
+ var EXTENSION = /\.[^.]*$/;
32
+ var STATE_KINDS = [
33
+ [/^\.setup$/, "setup marker"],
34
+ [/^\.clones-pending$/, "pending clones"],
35
+ [/^\.test-/, "test database marker"]
36
+ ];
37
+ function namesIn(dir) {
38
+ return existsSync(dir) ? readdirSync(dir) : [];
39
+ }
40
+ function taskOf(name, prefix, end) {
41
+ if (!name.startsWith(prefix))
42
+ return;
43
+ const rest = name.slice(prefix.length);
44
+ const stop = rest.indexOf(end);
45
+ return stop > 0 ? rest.slice(0, stop) : undefined;
46
+ }
47
+ async function dockerLines(argv) {
48
+ if (Bun.which("docker") === null)
49
+ return [];
50
+ const listed = await $`docker ${argv}`.quiet().nothrow();
51
+ return listed.exitCode === 0 ? listed.text().split(`
52
+ `).filter(Boolean) : [];
53
+ }
54
+ async function orphansOf(project, jobsDir) {
55
+ const live = new Set(listTasks(project));
56
+ const stack = `${stackName(project)}--`;
57
+ const left = new Map;
58
+ const note = (task, what) => {
59
+ if (task !== undefined && what !== undefined && !live.has(task))
60
+ left.set(task, [...left.get(task) ?? [], what]);
61
+ };
62
+ const { overrides, state } = project.settings;
63
+ for (const name of namesIn(overrides))
64
+ note(taskOf(name, stack, ".override.yml"), "compose override");
65
+ for (const name of namesIn(state)) {
66
+ const task = taskOf(name, stack, ".");
67
+ note(task, STATE_KINDS.find(([suffix]) => suffix.test(name.slice(stack.length + (task?.length ?? 0))))?.[1]);
68
+ }
69
+ for (const name of namesIn(join(state, "queues")))
70
+ note(taskOf(name, stack, "."), "queue");
71
+ for (const name of new Set(namesIn(jobsDir).map((name) => name.replace(EXTENSION, ""))))
72
+ note(taskOf(`${name}.`, `${project.name}--`, "."), "job record");
73
+ for (const volume of await dockerLines(["volume", "ls", "-q"]))
74
+ note(taskOf(volume, stack, "_"), "volume");
75
+ for (const label of await dockerLines(["ps", "-a", "--format", '{{.Label "com.docker.compose.project"}}']))
76
+ note(label.startsWith(stack) ? label.slice(stack.length) : undefined, "container");
77
+ const orphans = [];
78
+ for (const [task, what] of [...left].sort(([a], [b]) => a.localeCompare(b))) {
79
+ try {
80
+ orphans.push({ worktree: worktreeOf(project, task), left: counted(what) });
81
+ } catch {}
82
+ }
83
+ return orphans;
84
+ }
85
+ function counted(what) {
86
+ const counts = new Map;
87
+ for (const each of what)
88
+ counts.set(each, (counts.get(each) ?? 0) + 1);
89
+ return [...counts].map(([each, count]) => count === 1 ? each : `${count} ${each}s`);
90
+ }
91
+ async function staleRegistrations(project) {
92
+ const runs = await Promise.all([".", ...project.repos].map(async (repo) => git(join(project.root, repo), "worktree", "prune", "--dry-run", "--verbose")));
93
+ return runs.filter((run) => run.ok).flatMap((run) => run.out.split(`
94
+ `).filter(Boolean)).length;
95
+ }
96
+ async function pruneRegistrations2(project) {
97
+ await Promise.all([".", ...project.repos].map(async (repo) => git(join(project.root, repo), "worktree", "prune")));
98
+ }
99
+ function removeQueues2(worktree) {
100
+ const queues = join(worktree.project.settings.state, "queues");
101
+ for (const name of namesIn(queues).filter((each) => each.startsWith(`${worktree.id}.`)))
102
+ rmSync(join(queues, name), { recursive: true, force: true });
103
+ }
104
+
105
+ export { leftBehind2, describeLeftBehind2, pruneRegistrations2, removeQueues2 };
@@ -0,0 +1,313 @@
1
+ // @bun
2
+ import {
3
+ holdSignals
4
+ } from "./cli-jb9a8d46.js";
5
+ import {
6
+ wtConfig,
7
+ WtError,
8
+ assertWorktreeExists,
9
+ currentDir,
10
+ locateWorktree
11
+ } from "./cli-6k7xzgw2.js";
12
+ import {
13
+ queueDir,
14
+ holding,
15
+ inLine
16
+ } from "./cli-9m1jyyrf.js";
17
+ import {
18
+ composeConfig,
19
+ baseComposeFiles
20
+ } from "./cli-fdwwsds1.js";
21
+
22
+ // src/run.ts
23
+ import { existsSync as existsSync2, mkdirSync, readdirSync, readFileSync as readFileSync2, rmSync, statSync, writeFileSync } from "fs";
24
+ import { userInfo } from "os";
25
+ import { join, resolve } from "path";
26
+ var {$ } = globalThis.Bun;
27
+
28
+ // src/env_file.ts
29
+ import { existsSync, readFileSync } from "fs";
30
+
31
+ // ../env/src/dotenv.ts
32
+ var ASSIGNMENT = /^\s*(?:export\s+)?([A-Z_][\w.-]*)\s*=(.*)$/i;
33
+ var INLINE_COMMENT = /\s+#.*$/;
34
+ var CARRIAGE_RETURN = /\r$/;
35
+ var ESCAPES = { n: `
36
+ `, r: "\r", t: "\t", '"': '"', "\\": "\\", $: "$" };
37
+ function closingQuote(text, quote) {
38
+ for (let index = 0;index < text.length; index++) {
39
+ if (quote === '"' && text[index] === "\\")
40
+ index++;
41
+ else if (text[index] === quote)
42
+ return index;
43
+ }
44
+ return -1;
45
+ }
46
+ function unescapeDollar(text) {
47
+ return text.replaceAll("\\$", "$");
48
+ }
49
+ function unescapeDouble(text) {
50
+ let out = "";
51
+ for (let index = 0;index < text.length; index++) {
52
+ const next = text[index + 1];
53
+ if (text[index] === "\\" && next !== undefined && next in ESCAPES) {
54
+ out += ESCAPES[next];
55
+ index++;
56
+ } else {
57
+ out += text[index];
58
+ }
59
+ }
60
+ return out;
61
+ }
62
+ function parseDotenv(text) {
63
+ const physical = text.split(`
64
+ `);
65
+ const lines = [];
66
+ for (let index = 0;index < physical.length; index++) {
67
+ const line = physical[index] ?? "";
68
+ const match = ASSIGNMENT.exec(line.replace(CARRIAGE_RETURN, ""));
69
+ if (match === null) {
70
+ lines.push({ raw: line });
71
+ continue;
72
+ }
73
+ const [, key = "", rest = ""] = match;
74
+ const start = rest.trimStart();
75
+ const quote = start[0];
76
+ if (quote !== '"' && quote !== "'" && quote !== "`") {
77
+ lines.push({ raw: line, key, value: unescapeDollar(start.replace(INLINE_COMMENT, "").trim()) });
78
+ continue;
79
+ }
80
+ let body = start.slice(1);
81
+ let raw = line;
82
+ let end = closingQuote(body, quote);
83
+ const first = index;
84
+ while (end === -1 && index + 1 < physical.length) {
85
+ index++;
86
+ body += `
87
+ ${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
88
+ raw += `
89
+ ${physical[index] ?? ""}`;
90
+ end = closingQuote(body, quote);
91
+ }
92
+ if (end === -1) {
93
+ index = first;
94
+ lines.push({ raw: line, key, value: unescapeDollar(start.replace(INLINE_COMMENT, "").trim()), unterminated: true });
95
+ continue;
96
+ }
97
+ const inner = body.slice(0, end);
98
+ lines.push({ raw, key, value: quote === '"' ? unescapeDouble(inner) : unescapeDollar(inner) });
99
+ }
100
+ return { lines };
101
+ }
102
+ function entries(file) {
103
+ const map = new Map;
104
+ for (const line of file.lines) {
105
+ if (line.key !== undefined)
106
+ map.set(line.key, line.value ?? "");
107
+ }
108
+ return map;
109
+ }
110
+
111
+ // src/env_file.ts
112
+ function readEnvFile(path) {
113
+ return existsSync(path) ? Object.fromEntries(entries(parseDotenv(readFileSync(path, "utf8")))) : {};
114
+ }
115
+
116
+ // src/run.ts
117
+ var POSTGRES = /^postgres(?:ql)?:$/;
118
+ var DEFAULT_PORT = 5432;
119
+ var READY_TRIES = 60;
120
+ var testContainer = (worktree) => `wt-${worktree.project.name}-test-db`;
121
+ function testDatabase(dir) {
122
+ const base = existsSync2(join(dir, ".env")) ? ".env" : ".env.dist";
123
+ const env = Object.assign({}, ...[base, ".env.test", ".env.test.local"].map((file) => readEnvFile(join(dir, file))));
124
+ if (env.DATABASE_URL === undefined || env.DATABASE_URL === "")
125
+ throw new WtError(`no DATABASE_URL in the test env files of ${dir}`);
126
+ const url = new URL(env.DATABASE_URL);
127
+ if (!POSTGRES.test(url.protocol))
128
+ throw new WtError(`wt run only starts Postgres, and ${dir} tests against ${url.protocol.slice(0, -1)}`);
129
+ return { host: url.hostname, port: Number(url.port || DEFAULT_PORT), user: decodeURIComponent(url.username), password: decodeURIComponent(url.password) };
130
+ }
131
+ function testToken(task) {
132
+ return task.replaceAll("-", "_");
133
+ }
134
+ function databaseImage(config, host) {
135
+ const service = config.services[host] ?? Object.values(config.services).find((each) => Object.values(each.networks ?? {}).some((network) => network?.aliases?.includes(host)));
136
+ if (service?.image === undefined || service.image === "")
137
+ throw new WtError(`no service of ${config.name} answers to ${host}, the test database host, with an image to start`);
138
+ return service.image;
139
+ }
140
+ function runInputs(root, run, config, host) {
141
+ const service = config.services[run.service];
142
+ if (!service)
143
+ throw new WtError(`${config.name} has no service ${run.service}`);
144
+ const source = join(root, run.dir);
145
+ const target = service.volumes?.find((volume) => volume.type === "bind" && volume.source === source)?.target;
146
+ if (target === undefined)
147
+ throw new WtError(`${run.service} does not bind-mount ${source}, so wt cannot tell where the worktree's copy goes`);
148
+ return { target, image: service.image ?? `${config.name}-${run.service}`, databaseImage: databaseImage(config, host) };
149
+ }
150
+ function inputsKey(root, overrides, run, host) {
151
+ const files = [".env", ...baseComposeFiles(root, overrides)].map((file) => resolve(root, file));
152
+ return JSON.stringify([run.service, run.dir, host, ...files.map((file) => {
153
+ const stat = statSync(file, { throwIfNoEntry: false });
154
+ return [file, stat?.mtimeMs ?? null, stat?.size ?? null];
155
+ })]);
156
+ }
157
+ async function cachedRunInputs(worktree, run, host) {
158
+ const { root, name, settings } = worktree.project;
159
+ const file = join(settings.state, `${name}.run.json`);
160
+ const key = inputsKey(root, settings.overrides, run, host);
161
+ try {
162
+ const cached = JSON.parse(readFileSync2(file, "utf8"));
163
+ if (cached.key === key)
164
+ return cached.inputs;
165
+ } catch {}
166
+ const inputs = runInputs(root, run, await composeConfig(root), host);
167
+ mkdirSync(settings.state, { recursive: true });
168
+ writeFileSync(file, JSON.stringify({ key, inputs }));
169
+ return inputs;
170
+ }
171
+ function runPlan(worktree, run, inputs, database, ids = userInfo(), tty = false) {
172
+ const { target } = inputs;
173
+ const network = `wt-${worktree.project.name}-test`;
174
+ const container = testContainer(worktree);
175
+ return {
176
+ network,
177
+ container,
178
+ database: [
179
+ "run",
180
+ "-d",
181
+ "--name",
182
+ container,
183
+ "--network",
184
+ network,
185
+ "--network-alias",
186
+ database.host,
187
+ "--tmpfs",
188
+ "/var/lib/postgresql/data",
189
+ "-e",
190
+ `POSTGRES_USER=${database.user}`,
191
+ "-e",
192
+ "POSTGRES_PASSWORD",
193
+ "-e",
194
+ `PGPORT=${database.port}`,
195
+ inputs.databaseImage
196
+ ],
197
+ runner: (command) => [
198
+ "run",
199
+ "--rm",
200
+ "-i",
201
+ ...tty ? ["-t"] : [],
202
+ "--pull",
203
+ "never",
204
+ "--network",
205
+ network,
206
+ ...run.dns !== undefined ? ["--dns", run.dns] : [],
207
+ "-u",
208
+ `${ids.uid}:${ids.gid}`,
209
+ "-e",
210
+ "HOME=/tmp",
211
+ ...Object.entries(run.env ?? {}).flatMap(([key, value]) => ["-e", `${key}=${value}`]),
212
+ "-e",
213
+ `TEST_TOKEN=${testToken(worktree.task)}`,
214
+ "-v",
215
+ `${join(worktree.dir, run.dir)}:${target}`,
216
+ "-w",
217
+ target,
218
+ inputs.image,
219
+ ...command
220
+ ]
221
+ };
222
+ }
223
+ async function runningId(container) {
224
+ const result = await $`docker inspect --format ${"{{if .State.Running}}{{.Id}}{{end}}"} ${container}`.quiet().nothrow();
225
+ return result.text().trim() || undefined;
226
+ }
227
+ async function answeringDatabase(plan, database) {
228
+ const result = await $`docker exec ${plan.container} sh -c ${'pg_isready -q -h 127.0.0.1 -U "$1" && hostname'} sh ${database.user}`.quiet().nothrow();
229
+ return result.exitCode === 0 ? result.text().trim() || undefined : undefined;
230
+ }
231
+ async function ensureDatabase(plan, database) {
232
+ if ((await $`docker network inspect ${plan.network}`.quiet().nothrow()).exitCode !== 0)
233
+ await $`docker network create ${plan.network}`.quiet().nothrow();
234
+ let id = await runningId(plan.container);
235
+ if (id === undefined) {
236
+ await $`docker rm -f ${plan.container}`.quiet().nothrow();
237
+ const started = await $`docker ${plan.database}`.env({ ...process.env, POSTGRES_PASSWORD: database.password }).quiet().nothrow();
238
+ id = await runningId(plan.container);
239
+ if (id === undefined)
240
+ throw new WtError(`${plan.container} did not start:
241
+ ${started.stderr.toString().trim()}`);
242
+ }
243
+ for (let tries = 0;tries < READY_TRIES; tries++) {
244
+ if ((await $`docker exec ${plan.container} pg_isready -q -h 127.0.0.1 -U ${database.user}`.quiet().nothrow()).exitCode === 0)
245
+ return id;
246
+ await Bun.sleep(1000);
247
+ }
248
+ throw new WtError(`${plan.container} is not accepting connections after ${READY_TRIES} s: docker logs ${plan.container}`);
249
+ }
250
+ async function runInherit(command) {
251
+ const held = holdSignals();
252
+ const child = Bun.spawn(command, { stdio: ["inherit", "inherit", "inherit"] });
253
+ held.forward(child);
254
+ try {
255
+ return await child.exited;
256
+ } finally {
257
+ held.release();
258
+ }
259
+ }
260
+ async function forgetTestDatabases2(worktree) {
261
+ const container = testContainer(worktree);
262
+ if (await runningId(container) !== undefined) {
263
+ const listed = await $`docker exec ${container} sh -c ${'psql -U "$POSTGRES_USER" -d postgres -Atc "select datname from pg_database"'}`.quiet().nothrow();
264
+ const ours = listed.text().split(`
265
+ `).filter((name) => name.endsWith(`_test${testToken(worktree.task)}`));
266
+ for (const name of ours)
267
+ await $`docker exec ${container} sh -c ${'dropdb -U "$POSTGRES_USER" --force "$0"'} ${name}`.quiet().nothrow();
268
+ }
269
+ const markers = worktree.project.settings.state;
270
+ if (!existsSync2(markers))
271
+ return;
272
+ for (const file of readdirSync(markers).filter((name) => name.startsWith(`${worktree.id}.test-`)))
273
+ rmSync(join(markers, file), { force: true });
274
+ }
275
+ async function provision(worktree, run, plan, databaseId) {
276
+ const markers = worktree.project.settings.state;
277
+ const marker = join(markers, `${worktree.id}.test-${databaseId.slice(0, 12)}`);
278
+ if (existsSync2(marker))
279
+ return;
280
+ await inLine(queueDir(worktree.project.settings, `${worktree.id}.provision`), "provisioning", () => console.error(`wt run: waiting for ${worktree.task}'s test database to be provisioned`), async () => {
281
+ if (existsSync2(marker))
282
+ return;
283
+ console.error(`wt run: provisioning ${worktree.task}'s test database`);
284
+ for (const step of run.provision) {
285
+ if (await runInherit(["docker", ...plan.runner(["sh", "-c", step])]) !== 0)
286
+ throw new WtError(`provisioning failed on \`${step}\``, `run it again with \`wt run ${worktree.task} -- sh -c '${step}'\``);
287
+ }
288
+ mkdirSync(markers, { recursive: true });
289
+ writeFileSync(marker, "");
290
+ });
291
+ }
292
+ async function runTask2(task, command, project) {
293
+ const worktree = await locateWorktree(currentDir(), task, project);
294
+ const { run, name } = worktree.project;
295
+ assertWorktreeExists(worktree);
296
+ if (!run)
297
+ throw new WtError(`${name} has no \`run\` in its manifest, so wt cannot tell which service runs its tests`);
298
+ return holding(runsDir2(worktree), command.join(" "), async () => {
299
+ const database = testDatabase(join(worktree.dir, run.dir));
300
+ const plan = runPlan(worktree, run, await cachedRunInputs(worktree, run, database.host), database, userInfo(), Boolean(process.stdin.isTTY && process.stdout.isTTY));
301
+ await provision(worktree, run, plan, await answeringDatabase(plan, database) ?? await ensureDatabase(plan, database));
302
+ return runInherit(["docker", ...plan.runner(command)]);
303
+ });
304
+ }
305
+ function runsDir2(worktree) {
306
+ return queueDir(worktree.project.settings, `${worktree.id}.runs`);
307
+ }
308
+ async function runHeavy2(command) {
309
+ const label = `${command.join(" ")} (in ${currentDir()})`;
310
+ return inLine(queueDir(await wtConfig(), "heavy"), label, (ahead, running) => console.error(`wt heavy: ${ahead} ahead, running ${running}`), async () => runInherit(command));
311
+ }
312
+
313
+ export { forgetTestDatabases2, runTask2, runsDir2, runHeavy2 };