@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.
- package/README.md +17 -10
- package/dist/cli-02xxc9xk.js +67 -0
- package/dist/cli-5khwxy5g.js +36 -0
- package/dist/cli-6k7xzgw2.js +519 -0
- package/dist/cli-96wy1q8e.js +97 -0
- package/dist/cli-9m1jyyrf.js +69 -0
- package/dist/cli-fa4fh6ex.js +37 -0
- package/dist/cli-fdwwsds1.js +153 -0
- package/dist/cli-jb9a8d46.js +674 -0
- package/dist/cli-k4471y24.js +779 -0
- package/dist/cli-kt6d30zz.js +106 -0
- package/dist/cli-q7e6gegw.js +105 -0
- package/dist/cli-qwe5ykfs.js +313 -0
- package/dist/cli-tp4q5w5x.js +251 -0
- package/dist/cli.js +228 -2809
- package/dist/commands-jqr92tk6.js +222 -0
- package/dist/init-0ws4c883.js +166 -0
- package/dist/list-83vq4jng.js +88 -0
- package/dist/print-d4aq2eqw.js +77 -0
- package/dist/prompt-y71tp3f5.js +436 -0
- package/dist/prune-7ex1qyd3.js +17 -0
- package/dist/run-jrmm9gg8.js +18 -0
- package/dist/shell-1smv2vf9.js +55 -0
- package/dist/stack-2zj6r6py.js +20 -0
- package/dist/tools-c4m5037s.js +13 -0
- package/package.json +4 -4
- package/src/cli.ts +250 -69
- package/src/commands.ts +51 -38
- package/src/compose.ts +37 -14
- package/src/config.ts +8 -1
- package/src/errors.ts +16 -6
- package/src/files.ts +14 -15
- package/src/git.ts +53 -7
- package/src/index.ts +2 -1
- package/src/init.ts +56 -10
- package/src/jobs.ts +54 -15
- package/src/list.ts +26 -13
- package/src/print.ts +76 -0
- package/src/project.ts +129 -28
- package/src/proxy.ts +5 -5
- package/src/prune.ts +149 -0
- package/src/queue.ts +27 -3
- package/src/run.ts +82 -23
- package/src/shell.ts +34 -7
- package/src/stack.ts +10 -12
- package/src/sync.ts +28 -3
- package/src/tools.ts +91 -0
|
@@ -0,0 +1,519 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import {
|
|
3
|
+
configBase,
|
|
4
|
+
warn,
|
|
5
|
+
formatAge
|
|
6
|
+
} from "./cli-k4471y24.js";
|
|
7
|
+
import {
|
|
8
|
+
printError,
|
|
9
|
+
KnownError,
|
|
10
|
+
bootTime,
|
|
11
|
+
alive,
|
|
12
|
+
knownMessage,
|
|
13
|
+
knownHint,
|
|
14
|
+
failureText,
|
|
15
|
+
failKnown
|
|
16
|
+
} from "./cli-jb9a8d46.js";
|
|
17
|
+
|
|
18
|
+
// src/config.ts
|
|
19
|
+
import { existsSync } from "fs";
|
|
20
|
+
import { homedir } from "os";
|
|
21
|
+
import { join as join2 } from "path";
|
|
22
|
+
|
|
23
|
+
// src/jobs.ts
|
|
24
|
+
import { closeSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync } from "fs";
|
|
25
|
+
import { join } from "path";
|
|
26
|
+
var {$ } = globalThis.Bun;
|
|
27
|
+
var HELD_ENV = "WT_JOBS_HELD";
|
|
28
|
+
var STARTING_MS = 30000;
|
|
29
|
+
var TAKEOVER_MS = 5000;
|
|
30
|
+
var TAIL_BYTES = 4096;
|
|
31
|
+
var DOING = { up: "coming up", down: "stopping", add: "being made", "add --up": "being made and brought up", sync: "syncing", rm: "being removed" };
|
|
32
|
+
var DONE = { up: ["is up", "Its stack came up"], add: ["is ready", "The worktree is made, its stack still down"], "add --up": ["is up", "The worktree is made and its stack came up"] };
|
|
33
|
+
var OUTCOMES = { 0: "ok", null: "killed" };
|
|
34
|
+
var LEADING_ROOT = /^[/~]+/;
|
|
35
|
+
var UNSAFE_IN_FILE_NAME = /[^\w.-]+/g;
|
|
36
|
+
function slugOf(ref) {
|
|
37
|
+
return ref.replace(LEADING_ROOT, "").replace(UNSAFE_IN_FILE_NAME, "--");
|
|
38
|
+
}
|
|
39
|
+
function writeJob(file, job) {
|
|
40
|
+
const partial = `${file}.${process.pid}.tmp`;
|
|
41
|
+
writeFileSync(partial, JSON.stringify(job));
|
|
42
|
+
renameSync(partial, file);
|
|
43
|
+
}
|
|
44
|
+
function readJob(file) {
|
|
45
|
+
try {
|
|
46
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
47
|
+
} catch {
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
function doing(table, job) {
|
|
52
|
+
const words = job === undefined ? "busy" : table[job.verb] ?? `busy with ${job.verb}`;
|
|
53
|
+
return job?.service !== undefined ? `${words} ${job.service}` : words;
|
|
54
|
+
}
|
|
55
|
+
function held(lock, now = Date.now()) {
|
|
56
|
+
try {
|
|
57
|
+
const pid = Number(readFileSync(lock, "utf8").trim());
|
|
58
|
+
const writtenAt = statSync(lock, { throwIfNoEntry: false })?.mtimeMs ?? 0;
|
|
59
|
+
if (writtenAt < bootTime())
|
|
60
|
+
return false;
|
|
61
|
+
return pid ? alive(pid) : now - writtenAt < STARTING_MS;
|
|
62
|
+
} catch {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function takeOver(lock) {
|
|
67
|
+
const guard = `${lock}.takeover`;
|
|
68
|
+
try {
|
|
69
|
+
writeFileSync(guard, "", { flag: "wx" });
|
|
70
|
+
} catch (error) {
|
|
71
|
+
if (error.code !== "EEXIST")
|
|
72
|
+
throw error;
|
|
73
|
+
if (Date.now() - (statSync(guard, { throwIfNoEntry: false })?.mtimeMs ?? 0) < TAKEOVER_MS)
|
|
74
|
+
return false;
|
|
75
|
+
rmSync(guard, { force: true });
|
|
76
|
+
return takeOver(lock);
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
if (!held(lock))
|
|
80
|
+
rmSync(lock, { force: true });
|
|
81
|
+
return true;
|
|
82
|
+
} finally {
|
|
83
|
+
rmSync(guard, { force: true });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
var heldHere = () => (process.env[HELD_ENV] ?? "").split(`
|
|
87
|
+
`).filter(Boolean);
|
|
88
|
+
var heldEntry = (lock) => `${process.pid} ${lock}`;
|
|
89
|
+
function stillHeldBy(entry) {
|
|
90
|
+
const space = entry.indexOf(" ");
|
|
91
|
+
const lock = entry.slice(space + 1);
|
|
92
|
+
try {
|
|
93
|
+
return readFileSync(lock, "utf8").trim() === entry.slice(0, space) && held(lock);
|
|
94
|
+
} catch {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
function logTail(file, lines = 5) {
|
|
99
|
+
try {
|
|
100
|
+
const fd = openSync(file, "r");
|
|
101
|
+
try {
|
|
102
|
+
const size = fstatSync(fd).size;
|
|
103
|
+
const buffer = Buffer.alloc(Math.min(size, TAIL_BYTES));
|
|
104
|
+
readSync(fd, buffer, 0, buffer.length, size - buffer.length);
|
|
105
|
+
return buffer.toString("utf8").trim().split(`
|
|
106
|
+
`).slice(-lines).join(`
|
|
107
|
+
`);
|
|
108
|
+
} finally {
|
|
109
|
+
closeSync(fd);
|
|
110
|
+
}
|
|
111
|
+
} catch {
|
|
112
|
+
return "";
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
var OSASCRIPT_NOTIFY = ["-e", "on run argv", "-e", "display notification (item 2 of argv) with title (item 1 of argv)", "-e", "end run"];
|
|
116
|
+
function canNotify() {
|
|
117
|
+
return Bun.which("notify-send") !== null || Bun.which("osascript") !== null;
|
|
118
|
+
}
|
|
119
|
+
async function notify(app, title, body, critical = false) {
|
|
120
|
+
if (Bun.which("notify-send") !== null)
|
|
121
|
+
await $`notify-send -a ${app} ${critical ? ["-u", "critical"] : []} ${title} ${body}`.quiet().nothrow();
|
|
122
|
+
else if (Bun.which("osascript") !== null)
|
|
123
|
+
await $`osascript ${OSASCRIPT_NOTIFY} ${`${app}: ${title}`} ${body}`.quiet().nothrow();
|
|
124
|
+
}
|
|
125
|
+
async function notifyRefused(app, what, message) {
|
|
126
|
+
await notify(app, `${what} not started`, message, true);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
class Jobs {
|
|
130
|
+
dir;
|
|
131
|
+
app;
|
|
132
|
+
env;
|
|
133
|
+
doing;
|
|
134
|
+
done;
|
|
135
|
+
constructor({ dir, app, words = {} }) {
|
|
136
|
+
this.dir = dir;
|
|
137
|
+
this.app = app;
|
|
138
|
+
this.env = `${app.toUpperCase()}_JOB`;
|
|
139
|
+
this.doing = { ...DOING, ...words.doing };
|
|
140
|
+
this.done = { ...DONE, ...words.done };
|
|
141
|
+
}
|
|
142
|
+
paths(slug) {
|
|
143
|
+
return { job: join(this.dir, `${slug}.json`), lock: join(this.dir, `${slug}.lock`), log: join(this.dir, `${slug}.log`) };
|
|
144
|
+
}
|
|
145
|
+
holds(stack) {
|
|
146
|
+
const { lock } = this.paths(stack.slug);
|
|
147
|
+
return heldHere().some((entry) => entry.endsWith(` ${lock}`) && stillHeldBy(entry));
|
|
148
|
+
}
|
|
149
|
+
claim(stack, verb, detached, service) {
|
|
150
|
+
const { job: jobFile, lock, log } = this.paths(stack.slug);
|
|
151
|
+
mkdirSync(this.dir, { recursive: true });
|
|
152
|
+
for (let attempt = 0;; attempt++) {
|
|
153
|
+
try {
|
|
154
|
+
writeFileSync(lock, detached ? "" : String(process.pid), { flag: "wx" });
|
|
155
|
+
break;
|
|
156
|
+
} catch (error) {
|
|
157
|
+
if (error.code !== "EEXIST")
|
|
158
|
+
throw error;
|
|
159
|
+
if (attempt > 0 || held(lock) || !takeOver(lock)) {
|
|
160
|
+
const running = readJob(jobFile);
|
|
161
|
+
throw new KnownError(`${stack.ref} is already ${doing(this.doing, running)}${running !== undefined && running.log !== "" ? `, see ${running.log}` : ""}`);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
const job = { ref: stack.ref, verb, ...service !== undefined && { service }, pid: detached ? null : process.pid, startedAt: Date.now(), log: detached ? log : "" };
|
|
166
|
+
writeJob(jobFile, job);
|
|
167
|
+
return job;
|
|
168
|
+
}
|
|
169
|
+
adopt(stack) {
|
|
170
|
+
const { job: jobFile, lock } = this.paths(stack.slug);
|
|
171
|
+
const job = readJob(jobFile);
|
|
172
|
+
if (!job)
|
|
173
|
+
throw new KnownError(`no job claimed for ${stack.slug}`);
|
|
174
|
+
job.pid = process.pid;
|
|
175
|
+
writeFileSync(lock, String(process.pid));
|
|
176
|
+
writeJob(jobFile, job);
|
|
177
|
+
return job;
|
|
178
|
+
}
|
|
179
|
+
finish(stack, job, code) {
|
|
180
|
+
const { job: jobFile, lock } = this.paths(stack.slug);
|
|
181
|
+
writeJob(jobFile, { ...job, endedAt: Date.now(), code });
|
|
182
|
+
rmSync(lock, { force: true });
|
|
183
|
+
}
|
|
184
|
+
states() {
|
|
185
|
+
const states = new Map;
|
|
186
|
+
let files;
|
|
187
|
+
try {
|
|
188
|
+
files = readdirSync(this.dir).filter((file) => file.endsWith(".json"));
|
|
189
|
+
} catch {
|
|
190
|
+
return states;
|
|
191
|
+
}
|
|
192
|
+
for (const file of files) {
|
|
193
|
+
const slug = file.slice(0, -".json".length);
|
|
194
|
+
const job = readJob(join(this.dir, file));
|
|
195
|
+
if (!job)
|
|
196
|
+
continue;
|
|
197
|
+
if (job.endedAt !== undefined)
|
|
198
|
+
states.set(slug, { last: job });
|
|
199
|
+
else if (held(this.paths(slug).lock))
|
|
200
|
+
states.set(slug, { running: job });
|
|
201
|
+
else
|
|
202
|
+
states.set(slug, { last: { ...job, code: null, endedAt: statSync(join(this.dir, file), { throwIfNoEntry: false })?.mtimeMs ?? job.startedAt } });
|
|
203
|
+
}
|
|
204
|
+
return states;
|
|
205
|
+
}
|
|
206
|
+
summary({ running, last }, now = Date.now()) {
|
|
207
|
+
if (running !== undefined)
|
|
208
|
+
return doing(this.doing, running);
|
|
209
|
+
if (last === undefined)
|
|
210
|
+
return "";
|
|
211
|
+
return [last.verb, last.service, OUTCOMES[String(last.code)] ?? "failed", formatAge(last.endedAt ?? last.startedAt, now)].filter((word) => word !== undefined).join(" ");
|
|
212
|
+
}
|
|
213
|
+
forget(stack) {
|
|
214
|
+
for (const file of Object.values(this.paths(stack.slug)))
|
|
215
|
+
rmSync(file, { force: true });
|
|
216
|
+
}
|
|
217
|
+
async run(stack, verb, work, service) {
|
|
218
|
+
if (this.holds(stack))
|
|
219
|
+
return attempt(`${this.app} ${verb}`, async () => work(false));
|
|
220
|
+
const detached = process.env[this.env] === stack.slug;
|
|
221
|
+
const job = detached ? this.adopt(stack) : this.claim(stack, verb, false, service);
|
|
222
|
+
const before = process.env[HELD_ENV];
|
|
223
|
+
delete process.env[this.env];
|
|
224
|
+
process.env[HELD_ENV] = [...heldHere(), heldEntry(this.paths(stack.slug).lock)].join(`
|
|
225
|
+
`);
|
|
226
|
+
let code = 1;
|
|
227
|
+
try {
|
|
228
|
+
code = await attempt(`${this.app} ${verb}`, async () => work(detached));
|
|
229
|
+
} finally {
|
|
230
|
+
if (before === undefined)
|
|
231
|
+
delete process.env[HELD_ENV];
|
|
232
|
+
else
|
|
233
|
+
process.env[HELD_ENV] = before;
|
|
234
|
+
this.finish(stack, job, code);
|
|
235
|
+
}
|
|
236
|
+
if (detached)
|
|
237
|
+
await this.notifyEnd(stack, job, code);
|
|
238
|
+
return code;
|
|
239
|
+
}
|
|
240
|
+
async failDetached(message) {
|
|
241
|
+
const slug = process.env[this.env];
|
|
242
|
+
if (slug === undefined || slug === "")
|
|
243
|
+
return;
|
|
244
|
+
delete process.env[this.env];
|
|
245
|
+
const job = readJob(this.paths(slug).job);
|
|
246
|
+
if (!job || job.endedAt !== undefined)
|
|
247
|
+
return;
|
|
248
|
+
this.finish({ slug }, job, 1);
|
|
249
|
+
await notify(this.app, `${this.what(job)} failed`, message, true);
|
|
250
|
+
}
|
|
251
|
+
async guarded(action, bg) {
|
|
252
|
+
try {
|
|
253
|
+
return await action() ?? 0;
|
|
254
|
+
} catch (error) {
|
|
255
|
+
const message = failureText(error);
|
|
256
|
+
await this.failDetached(message);
|
|
257
|
+
if (bg !== undefined)
|
|
258
|
+
await notifyRefused(this.app, bg, message);
|
|
259
|
+
return failKnown(error);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
detach(stack, verb, argv, service) {
|
|
263
|
+
const job = this.claim(stack, verb, true, service);
|
|
264
|
+
let out;
|
|
265
|
+
try {
|
|
266
|
+
out = openSync(job.log, "w");
|
|
267
|
+
Bun.spawn([process.execPath, "--no-env-file", ...argv], { stdio: ["ignore", out, out], env: { ...process.env, [this.env]: stack.slug }, detached: true }).unref();
|
|
268
|
+
} catch (error) {
|
|
269
|
+
this.finish(stack, job, 1);
|
|
270
|
+
throw error;
|
|
271
|
+
} finally {
|
|
272
|
+
if (out !== undefined)
|
|
273
|
+
closeSync(out);
|
|
274
|
+
}
|
|
275
|
+
return job;
|
|
276
|
+
}
|
|
277
|
+
what(job) {
|
|
278
|
+
return [this.app, job.verb, job.ref, ...job.service !== undefined ? [job.service] : []].join(" ");
|
|
279
|
+
}
|
|
280
|
+
async notifyEnd(stack, job, code) {
|
|
281
|
+
const done = job.service !== undefined ? undefined : this.done[job.verb];
|
|
282
|
+
if (code === 0) {
|
|
283
|
+
if (done)
|
|
284
|
+
await notify(this.app, `${stack.ref} ${done[0]}`, done[1]);
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
await notify(this.app, `${this.what(job)} failed`, logTail(job.log) || `see ${job.log}`, true);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
async function attempt(prefix, work) {
|
|
291
|
+
try {
|
|
292
|
+
await work();
|
|
293
|
+
return 0;
|
|
294
|
+
} catch (error) {
|
|
295
|
+
const message = knownMessage(error);
|
|
296
|
+
if (message !== undefined)
|
|
297
|
+
printError(prefix, message, knownHint(error));
|
|
298
|
+
else
|
|
299
|
+
console.error(error);
|
|
300
|
+
return 1;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// src/config.ts
|
|
305
|
+
var LEADING_TILDE = /^~(?=\/|$)/;
|
|
306
|
+
function expandHome(path) {
|
|
307
|
+
return path.replace(LEADING_TILDE, homedir());
|
|
308
|
+
}
|
|
309
|
+
var configPath = () => process.env.WT_CONFIG ?? join2(configBase(), "wt", "config.ts");
|
|
310
|
+
function resolveConfig(config = {}) {
|
|
311
|
+
const configDir = join2(configPath(), "..");
|
|
312
|
+
const state = expandHome(config.state ?? join2(homedir(), ".cache", "wt"));
|
|
313
|
+
return {
|
|
314
|
+
manifests: expandHome(config.manifests ?? join2(configDir, "projects")),
|
|
315
|
+
worktrees: expandHome(config.worktrees ?? "{root}/.worktrees/{repo}"),
|
|
316
|
+
overrides: expandHome(config.overrides ?? join2(homedir(), ".local", "share", "wt", "overrides")),
|
|
317
|
+
state,
|
|
318
|
+
jobs: expandHome(config.jobs ?? join2(state, "jobs")),
|
|
319
|
+
proxyNetwork: config.proxyNetwork ?? "proxy",
|
|
320
|
+
runner: config.runner ?? {}
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
var loaded;
|
|
324
|
+
async function wtConfig() {
|
|
325
|
+
if (loaded)
|
|
326
|
+
return loaded;
|
|
327
|
+
const path = configPath();
|
|
328
|
+
if (!existsSync(path))
|
|
329
|
+
return loaded = resolveConfig();
|
|
330
|
+
try {
|
|
331
|
+
const { default: config } = await import(path);
|
|
332
|
+
return loaded = resolveConfig(config);
|
|
333
|
+
} catch (error) {
|
|
334
|
+
throw new KnownError(`${path} does not load: ${error instanceof Error ? error.message : String(error)}`);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
function fillTemplate(argv, values) {
|
|
338
|
+
return argv.map((arg) => arg.replaceAll(/\{(\w+)\}/g, (match, key) => values[key] ?? match));
|
|
339
|
+
}
|
|
340
|
+
async function wtJobs() {
|
|
341
|
+
return new Jobs({ dir: (await wtConfig()).jobs, app: "wt" });
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// src/project.ts
|
|
345
|
+
import { existsSync as existsSync2, readdirSync as readdirSync2, realpathSync } from "fs";
|
|
346
|
+
import { basename, dirname, join as join3 } from "path";
|
|
347
|
+
|
|
348
|
+
// src/port.ts
|
|
349
|
+
function stringToPort(s, min = 1024, max = 65535) {
|
|
350
|
+
let hash = 2166136261;
|
|
351
|
+
for (let i = 0;i < s.length; i++) {
|
|
352
|
+
hash ^= s.charCodeAt(i);
|
|
353
|
+
hash = hash * 16777619 >>> 0;
|
|
354
|
+
}
|
|
355
|
+
return min + hash % (max - min + 1);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// src/project.ts
|
|
359
|
+
class WtError extends KnownError {
|
|
360
|
+
}
|
|
361
|
+
var TASK_PATTERN = /^(?!.*--)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
362
|
+
var ROUTE_TARGET = /^client$|^[\w.-]+:\d+$/;
|
|
363
|
+
var NOT_IN_STACK_NAME = /[^\w-]/g;
|
|
364
|
+
var LEADING_SEPARATORS = /^[_-]+/;
|
|
365
|
+
function worktreeFiles(settings, id) {
|
|
366
|
+
return {
|
|
367
|
+
override: join3(settings.overrides, `${id}.override.yml`),
|
|
368
|
+
setupMarker: join3(settings.state, `${id}.setup`),
|
|
369
|
+
clonesPending: join3(settings.state, `${id}.clones-pending`)
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
function worktreeHost(host, task) {
|
|
373
|
+
return host.startsWith("*.") ? `*.${task}.${host.slice(2)}` : `${task}.${host}`;
|
|
374
|
+
}
|
|
375
|
+
var PROJECT_KEYS = new Set(Object.keys({ root: 0, repos: 0, copy: 0, clone: 0, link: 0, skip: 0, routeHosts: 0, env: 0, ports: 0, certs: 0, setup: 0, run: 0, routes: 0 }));
|
|
376
|
+
var RUN_KEYS = new Set(Object.keys({ service: 0, dir: 0, provision: 0, dns: 0, env: 0 }));
|
|
377
|
+
function warnUnknownKeys(name, config) {
|
|
378
|
+
const unknown = [
|
|
379
|
+
...Object.keys(config).filter((key) => !PROJECT_KEYS.has(key)),
|
|
380
|
+
...Object.keys(config.run ?? {}).filter((key) => !RUN_KEYS.has(key)).map((key) => `run.${key}`)
|
|
381
|
+
];
|
|
382
|
+
for (const key of unknown)
|
|
383
|
+
warn(`${name}.ts: unknown key ${key}, ignored`);
|
|
384
|
+
}
|
|
385
|
+
function assertValid(project) {
|
|
386
|
+
for (const repo of [".", ...project.repos]) {
|
|
387
|
+
const dir = join3(project.root, repo);
|
|
388
|
+
if (!existsSync2(join3(dir, ".git")))
|
|
389
|
+
throw new WtError(`${project.name}: ${repo === "." ? `root ${dir}` : `repo ${repo}`} is not a git checkout${existsSync2(dir) ? "" : ", the folder is missing"}`);
|
|
390
|
+
}
|
|
391
|
+
for (const [task, port] of Object.entries(project.ports ?? {})) {
|
|
392
|
+
if (!Number.isInteger(port) || port < 1024 || port > 65535)
|
|
393
|
+
throw new WtError(`${project.name}: ports gives ${task} ${String(port)}, expected a whole number from 1024 to 65535`);
|
|
394
|
+
}
|
|
395
|
+
for (const route of project.routes) {
|
|
396
|
+
if (!ROUTE_TARGET.test(route.to))
|
|
397
|
+
throw new WtError(`${project.name}: route ${route.host} goes to "${route.to}", expected "client" or "<service>:<port>"`);
|
|
398
|
+
if (route.passthrough && project.certs === undefined)
|
|
399
|
+
throw new WtError(`${project.name}: passthrough route ${route.host} needs \`certs\``);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
async function loadManifest(settings, file) {
|
|
403
|
+
const path = join3(settings.manifests, file);
|
|
404
|
+
let config;
|
|
405
|
+
try {
|
|
406
|
+
config = (await import(path)).default;
|
|
407
|
+
} catch (error) {
|
|
408
|
+
throw new WtError(`${path} does not load: ${error instanceof Error ? error.message : String(error)}`);
|
|
409
|
+
}
|
|
410
|
+
if (typeof config !== "object" || config === null || typeof config.root !== "string")
|
|
411
|
+
throw new WtError(`${path} has no default export with a \`root\``, "export default { root: '~/Workspace/<checkout>', ... } satisfies ProjectConfig");
|
|
412
|
+
const manifest = config;
|
|
413
|
+
const project = { ...manifest, repos: manifest.repos ?? [], routes: manifest.routes ?? [], root: expandHome(manifest.root), name: basename(file, ".ts"), settings };
|
|
414
|
+
warnUnknownKeys(project.name, manifest);
|
|
415
|
+
assertValid(project);
|
|
416
|
+
if (stackName(project) === "")
|
|
417
|
+
throw new WtError(`${project.name}.ts: the checkout folder ${basename(project.root)} holds no letter or digit to name its compose stacks after`, "rename the folder");
|
|
418
|
+
return project;
|
|
419
|
+
}
|
|
420
|
+
async function loadProjects(skipped = warn) {
|
|
421
|
+
const settings = await wtConfig();
|
|
422
|
+
const files = existsSync2(settings.manifests) ? readdirSync2(settings.manifests).filter((file) => file.endsWith(".ts")).sort() : [];
|
|
423
|
+
const loaded = await Promise.allSettled(files.map(async (file) => loadManifest(settings, file)));
|
|
424
|
+
const projects = [];
|
|
425
|
+
for (const result of loaded) {
|
|
426
|
+
if (result.status === "rejected") {
|
|
427
|
+
skipped(`manifest skipped, ${failureText(result.reason)}`);
|
|
428
|
+
continue;
|
|
429
|
+
}
|
|
430
|
+
const project = result.value;
|
|
431
|
+
const twin = projects.find((other) => stackName(other) === stackName(project));
|
|
432
|
+
if (twin)
|
|
433
|
+
skipped(`${twin.name}.ts and ${project.name}.ts both have a checkout compose names ${stackName(project)}, so their worktrees would share stacks and volumes: ${project.name} skipped, rename the folder of a checkout that has no worktrees yet, or remove one of the files`);
|
|
434
|
+
else
|
|
435
|
+
projects.push(project);
|
|
436
|
+
}
|
|
437
|
+
return projects;
|
|
438
|
+
}
|
|
439
|
+
async function findProject(name) {
|
|
440
|
+
const settings = await wtConfig();
|
|
441
|
+
if (!existsSync2(join3(settings.manifests, `${name}.ts`)))
|
|
442
|
+
throw new WtError(`no project named ${name} in ${settings.manifests}`);
|
|
443
|
+
return loadManifest(settings, `${name}.ts`);
|
|
444
|
+
}
|
|
445
|
+
var tasksDir = (project) => fillTemplate([project.settings.worktrees], { root: dirname(project.root), repo: basename(project.root) })[0];
|
|
446
|
+
function stackName(project) {
|
|
447
|
+
return basename(project.root).toLowerCase().replace(NOT_IN_STACK_NAME, "").replace(LEADING_SEPARATORS, "");
|
|
448
|
+
}
|
|
449
|
+
function worktreeOf(project, task) {
|
|
450
|
+
if (task === "main" || !TASK_PATTERN.test(task))
|
|
451
|
+
throw new WtError(`invalid task name "${task}": lowercase letters, digits and single inner dashes, at most 63, and not "main"`);
|
|
452
|
+
const mainHosts = new Set(project.routes.map((route) => route.host));
|
|
453
|
+
const taken = project.routes.find((route) => mainHosts.has(worktreeHost(route.host, task)));
|
|
454
|
+
if (taken)
|
|
455
|
+
throw new WtError(`invalid task name "${task}": the worktree's ${worktreeHost(taken.host, task)} would be one of main's hosts`);
|
|
456
|
+
const id = `${stackName(project)}--${task}`;
|
|
457
|
+
return {
|
|
458
|
+
project,
|
|
459
|
+
task,
|
|
460
|
+
dir: join3(tasksDir(project), task),
|
|
461
|
+
id,
|
|
462
|
+
clientPort: project.ports?.[task] ?? stringToPort(`${project.name}--${task}`),
|
|
463
|
+
files: worktreeFiles(project.settings, id)
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
function assertWorktreeExists(worktree) {
|
|
467
|
+
if (!existsSync2(worktree.dir))
|
|
468
|
+
throw new WtError(`no worktree ${worktree.task}`, `create it with \`wt add ${worktree.task}\``);
|
|
469
|
+
}
|
|
470
|
+
function listTasks(project) {
|
|
471
|
+
const dir = tasksDir(project);
|
|
472
|
+
return existsSync2(dir) ? readdirSync2(dir).filter((task) => TASK_PATTERN.test(task)).sort() : [];
|
|
473
|
+
}
|
|
474
|
+
function currentDir() {
|
|
475
|
+
try {
|
|
476
|
+
return process.cwd();
|
|
477
|
+
} catch {
|
|
478
|
+
const pwd = process.env.PWD ?? "";
|
|
479
|
+
if (pwd === "")
|
|
480
|
+
throw new WtError("the current directory is gone", "cd elsewhere");
|
|
481
|
+
return pwd;
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
function resolved(path) {
|
|
485
|
+
try {
|
|
486
|
+
return realpathSync(path);
|
|
487
|
+
} catch {
|
|
488
|
+
return path;
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
async function locate(cwd, projectName) {
|
|
492
|
+
const here = resolved(cwd);
|
|
493
|
+
const projects = projectName !== undefined ? [await findProject(projectName)] : await loadProjects();
|
|
494
|
+
for (const project of projects) {
|
|
495
|
+
const dir = resolved(tasksDir(project));
|
|
496
|
+
const root = resolved(project.root);
|
|
497
|
+
if (here.startsWith(`${dir}/`)) {
|
|
498
|
+
const rest = here.slice(dir.length + 1);
|
|
499
|
+
const slash = rest.indexOf("/");
|
|
500
|
+
return { project, task: slash === -1 ? rest : rest.slice(0, slash) };
|
|
501
|
+
}
|
|
502
|
+
if (here === root || here.startsWith(`${root}/`))
|
|
503
|
+
return { project, task: "main" };
|
|
504
|
+
}
|
|
505
|
+
if (projects.length === 1)
|
|
506
|
+
return { project: projects[0], task: "main" };
|
|
507
|
+
if (!existsSync2(cwd))
|
|
508
|
+
throw new WtError(`the current directory ${cwd} is gone`, "cd into a project or worktree, or pass --project");
|
|
509
|
+
throw new WtError("not inside a known project or worktree (cd into one, or pass --project)");
|
|
510
|
+
}
|
|
511
|
+
async function locateWorktree(cwd, task, projectName) {
|
|
512
|
+
const here = await locate(cwd, projectName);
|
|
513
|
+
const name = task ?? here.task;
|
|
514
|
+
if (name === "main")
|
|
515
|
+
throw new WtError("this is the main checkout, name a task");
|
|
516
|
+
return worktreeOf(here.project, name);
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
export { slugOf, canNotify, notifyRefused, configPath, wtConfig, fillTemplate, wtJobs, stringToPort, WtError, worktreeHost, loadProjects, stackName, worktreeOf, assertWorktreeExists, listTasks, currentDir, locate, locateWorktree };
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import {
|
|
3
|
+
warn
|
|
4
|
+
} from "./cli-k4471y24.js";
|
|
5
|
+
import {
|
|
6
|
+
configPath,
|
|
7
|
+
fillTemplate,
|
|
8
|
+
WtError
|
|
9
|
+
} from "./cli-6k7xzgw2.js";
|
|
10
|
+
import {
|
|
11
|
+
hasDevproxy,
|
|
12
|
+
devproxyUp
|
|
13
|
+
} from "./cli-fa4fh6ex.js";
|
|
14
|
+
import {
|
|
15
|
+
composeEnv
|
|
16
|
+
} from "./cli-fdwwsds1.js";
|
|
17
|
+
|
|
18
|
+
// src/stack.ts
|
|
19
|
+
import { existsSync, mkdirSync, writeFileSync } from "fs";
|
|
20
|
+
import { homedir } from "os";
|
|
21
|
+
import { dirname } from "path";
|
|
22
|
+
var {$ } = globalThis.Bun;
|
|
23
|
+
async function spawnInherit(argv, cwd, env = process.env) {
|
|
24
|
+
return Bun.spawn(argv, { cwd, env, stdio: ["inherit", "inherit", "inherit"] }).exited;
|
|
25
|
+
}
|
|
26
|
+
async function spawnRunner(role, argv, cwd) {
|
|
27
|
+
try {
|
|
28
|
+
return await spawnInherit(argv, cwd);
|
|
29
|
+
} catch (error) {
|
|
30
|
+
if (error.code === "ENOENT")
|
|
31
|
+
throw new WtError(`\`${argv[0]}\` is not on PATH`, `fix runner.${role} in ${configPath()}`);
|
|
32
|
+
throw error;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
var argvOf = (template, worktree) => fillTemplate(template, { project: worktree.project.name, task: worktree.task, dir: worktree.dir, id: worktree.id });
|
|
36
|
+
async function runTemplate(role, template, worktree) {
|
|
37
|
+
const argv = argvOf(template, worktree);
|
|
38
|
+
if (await spawnRunner(role, argv, worktree.dir) !== 0)
|
|
39
|
+
throw new WtError(`\`${argv.join(" ")}\` failed`);
|
|
40
|
+
}
|
|
41
|
+
async function runSetup(worktree, env = composeEnv()) {
|
|
42
|
+
const setup = worktree.project.setup ?? [];
|
|
43
|
+
const marker = worktree.files.setupMarker;
|
|
44
|
+
if (!setup.length || existsSync(marker))
|
|
45
|
+
return;
|
|
46
|
+
for (const command of setup) {
|
|
47
|
+
if (await spawnInherit(["sh", "-c", command], worktree.dir, env) !== 0)
|
|
48
|
+
throw new WtError(`the worktree setup failed on \`${command}\``);
|
|
49
|
+
}
|
|
50
|
+
mkdirSync(dirname(marker), { recursive: true });
|
|
51
|
+
writeFileSync(marker, "");
|
|
52
|
+
}
|
|
53
|
+
async function stackUp2(worktree) {
|
|
54
|
+
const { up } = worktree.project.settings.runner;
|
|
55
|
+
if (up)
|
|
56
|
+
return runTemplate("up", up, worktree);
|
|
57
|
+
if (hasDevproxy())
|
|
58
|
+
await devproxyUp();
|
|
59
|
+
const network = worktree.project.settings.proxyNetwork;
|
|
60
|
+
if (worktree.project.routes.length > 0 && (await $`docker network inspect ${network}`.quiet().nothrow()).exitCode !== 0)
|
|
61
|
+
throw new WtError(`the routed services join the ${network} network, which does not exist: install and configure devproxy, or set proxyNetwork in ${configPath()} to the network your proxy dials stacks on`);
|
|
62
|
+
if (await spawnInherit(["docker", "compose", "up", "-d", "--build"], worktree.dir, composeEnv()) !== 0)
|
|
63
|
+
throw new WtError(`docker compose up failed in ${worktree.dir}`);
|
|
64
|
+
await runSetup(worktree);
|
|
65
|
+
}
|
|
66
|
+
async function stackDown2(worktree) {
|
|
67
|
+
const { down } = worktree.project.settings.runner;
|
|
68
|
+
if (down && existsSync(worktree.dir))
|
|
69
|
+
return runTemplate("down", down, worktree);
|
|
70
|
+
const here = existsSync(worktree.dir);
|
|
71
|
+
const argv = here ? ["docker", "compose", "down", "--remove-orphans"] : ["docker", "compose", "-p", worktree.id, "down", "--remove-orphans"];
|
|
72
|
+
if (await spawnInherit(argv, here ? worktree.dir : homedir(), composeEnv()) !== 0)
|
|
73
|
+
throw new WtError(`docker compose down failed for ${worktree.id}`);
|
|
74
|
+
}
|
|
75
|
+
async function followLogs2(worktree) {
|
|
76
|
+
return spawnInherit(["docker", "compose", "logs", "--follow", "--tail", "100"], worktree.dir, composeEnv());
|
|
77
|
+
}
|
|
78
|
+
async function afterRemove2(worktree) {
|
|
79
|
+
const { removed } = worktree.project.settings.runner;
|
|
80
|
+
if (!removed)
|
|
81
|
+
return;
|
|
82
|
+
const argv = argvOf(removed, worktree);
|
|
83
|
+
try {
|
|
84
|
+
if (await spawnRunner("removed", argv, worktree.project.root) !== 0)
|
|
85
|
+
warn(`\`${argv.join(" ")}\` failed after removing ${worktree.id}`);
|
|
86
|
+
} catch (error) {
|
|
87
|
+
if (!(error instanceof WtError))
|
|
88
|
+
throw error;
|
|
89
|
+
warn(`${error.message}, after removing ${worktree.id}`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
async function hasContainers2(composeName) {
|
|
93
|
+
const found = await $`docker ps -aq --filter ${`label=com.docker.compose.project=${composeName}`}`.quiet().nothrow();
|
|
94
|
+
return found.stdout.toString().trim() !== "";
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export { stackUp2, stackDown2, followLogs2, afterRemove2, hasContainers2 };
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import {
|
|
3
|
+
bootTime,
|
|
4
|
+
alive
|
|
5
|
+
} from "./cli-jb9a8d46.js";
|
|
6
|
+
|
|
7
|
+
// src/queue.ts
|
|
8
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "fs";
|
|
9
|
+
import { join } from "path";
|
|
10
|
+
var queueDir = (settings, name) => join(settings.state, "queues", name);
|
|
11
|
+
var POLL_MS = 1000;
|
|
12
|
+
function liveTickets(dir) {
|
|
13
|
+
const names = readdirSync(dir).sort();
|
|
14
|
+
return names.filter((name) => {
|
|
15
|
+
const dash = name.indexOf("-");
|
|
16
|
+
if (Number(name.slice(0, dash)) >= bootTime() && alive(Number(name.slice(dash + 1))))
|
|
17
|
+
return true;
|
|
18
|
+
rmSync(join(dir, name), { force: true });
|
|
19
|
+
return false;
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
function labelOf(ticket) {
|
|
23
|
+
try {
|
|
24
|
+
return readFileSync(ticket, "utf8");
|
|
25
|
+
} catch {
|
|
26
|
+
return "";
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function takeTicket(dir, label) {
|
|
30
|
+
mkdirSync(dir, { recursive: true });
|
|
31
|
+
const name = `${String(Date.now()).padStart(15, "0")}-${process.pid}`;
|
|
32
|
+
const ticket = join(dir, name);
|
|
33
|
+
const release = () => rmSync(ticket, { force: true });
|
|
34
|
+
writeFileSync(ticket, label);
|
|
35
|
+
process.once("exit", release);
|
|
36
|
+
return { name, release };
|
|
37
|
+
}
|
|
38
|
+
function holders(dir) {
|
|
39
|
+
return existsSync(dir) ? liveTickets(dir).map((ticket) => labelOf(join(dir, ticket))) : [];
|
|
40
|
+
}
|
|
41
|
+
async function holding(dir, label, work) {
|
|
42
|
+
const { release } = takeTicket(dir, label);
|
|
43
|
+
try {
|
|
44
|
+
return await work();
|
|
45
|
+
} finally {
|
|
46
|
+
release();
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
async function inLine(dir, label, waiting, work) {
|
|
50
|
+
const { name, release } = takeTicket(dir, label);
|
|
51
|
+
try {
|
|
52
|
+
let shown = -1;
|
|
53
|
+
for (;; ) {
|
|
54
|
+
const ahead = liveTickets(dir).filter((other) => other < name);
|
|
55
|
+
if (ahead.length === 0)
|
|
56
|
+
break;
|
|
57
|
+
if (ahead.length !== shown) {
|
|
58
|
+
shown = ahead.length;
|
|
59
|
+
waiting(ahead.length, labelOf(join(dir, ahead[0])));
|
|
60
|
+
}
|
|
61
|
+
await Bun.sleep(POLL_MS);
|
|
62
|
+
}
|
|
63
|
+
return await work();
|
|
64
|
+
} finally {
|
|
65
|
+
release();
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export { queueDir, holders, holding, inLine };
|