@kaynooo/cli-wt 0.1.2 → 0.1.7

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-0gbs87r4.js +313 -0
  3. package/dist/cli-1nyesy1b.js +674 -0
  4. package/dist/cli-4g5ehhgn.js +251 -0
  5. package/dist/cli-6ybxw5sc.js +97 -0
  6. package/dist/cli-dmkfxdbr.js +153 -0
  7. package/dist/cli-dmzvmpge.js +106 -0
  8. package/dist/cli-e2h20nyy.js +36 -0
  9. package/dist/cli-j82fak6j.js +69 -0
  10. package/dist/cli-k4471y24.js +779 -0
  11. package/dist/cli-kek450vq.js +519 -0
  12. package/dist/cli-n5rt07v7.js +105 -0
  13. package/dist/cli-pkvw2k4x.js +37 -0
  14. package/dist/cli-w4w36hng.js +67 -0
  15. package/dist/cli.js +238 -2592
  16. package/dist/commands-jtnbchtb.js +222 -0
  17. package/dist/init-4ynjrztr.js +166 -0
  18. package/dist/list-js6drtvg.js +88 -0
  19. package/dist/print-q6qaqg22.js +77 -0
  20. package/dist/prompt-y71tp3f5.js +436 -0
  21. package/dist/prune-beweag7w.js +17 -0
  22. package/dist/run-7eayrqwy.js +18 -0
  23. package/dist/shell-xrgvqrpp.js +55 -0
  24. package/dist/stack-h3pgyx1e.js +20 -0
  25. package/dist/tools-4j56r47a.js +13 -0
  26. package/package.json +6 -6
  27. package/src/cli.ts +270 -76
  28. package/src/commands.ts +58 -42
  29. package/src/compose.ts +37 -14
  30. package/src/config.ts +8 -1
  31. package/src/errors.ts +31 -5
  32. package/src/files.ts +15 -23
  33. package/src/git.ts +53 -7
  34. package/src/index.ts +3 -2
  35. package/src/init.ts +56 -10
  36. package/src/jobs.ts +60 -19
  37. package/src/list.ts +26 -13
  38. package/src/print.ts +76 -0
  39. package/src/project.ts +134 -23
  40. package/src/proxy.ts +9 -9
  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
package/dist/cli.js CHANGED
@@ -1,2555 +1,67 @@
1
1
  #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
2
  // @bun
3
+ import {
4
+ isInteractive,
5
+ warn,
6
+ jsonOption,
7
+ fail,
8
+ badUsage,
9
+ parse
10
+ } from "./cli-k4471y24.js";
11
+ import {
12
+ printError,
13
+ runCli,
14
+ knownMessage,
15
+ knownHint,
16
+ failureText,
17
+ failKnown
18
+ } from "./cli-1nyesy1b.js";
19
+ import {
20
+ slugOf,
21
+ canNotify,
22
+ notifyRefused,
23
+ wtJobs,
24
+ loadProjects,
25
+ worktreeOf,
26
+ assertWorktreeExists,
27
+ listTasks,
28
+ currentDir,
29
+ locate,
30
+ locateWorktree
31
+ } from "./cli-kek450vq.js";
3
32
 
4
33
  // src/cli.ts
5
- import process11 from "process";
6
- // ../kit/src/args.ts
7
- import process5 from "process";
8
- import { parseArgs } from "util";
9
-
10
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
11
- var ot = /[.*+?^${}()|[\]\\]/g;
12
- function B(t) {
13
- return t.replace(ot, "\\$&");
14
- }
15
- var N = new Map;
16
- var be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
17
- var z = new Map;
18
-
19
- // ../kit/src/mode.ts
20
- import process2 from "process";
21
- var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
22
- var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
23
- function isSet(value) {
24
- return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
25
- }
26
- function outputMode(stream = process2.stdout, env = process2.env) {
27
- const chosen = env.KIT_MODE;
28
- if (chosen !== undefined && MODES.has(chosen))
29
- return chosen;
30
- if (AGENT_VARIABLES.some((name) => isSet(env[name])))
31
- return "agent";
32
- if (stream.isTTY === true)
33
- return "terminal";
34
- return isSet(env.CI) ? "ci" : "pipe";
35
- }
36
-
37
- // ../kit/src/style.ts
38
- import process3 from "process";
39
-
40
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
41
- var G2 = /^[a-f0-9]+$/i;
42
- function b(r) {
43
- let e = r.startsWith("#") ? r.slice(1) : r;
44
- if (!G2.test(e))
45
- return [0, 0, 0];
46
- if (e.length === 3 || e.length === 4)
47
- return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
48
- if (e.length !== 6 && e.length !== 8)
49
- throw Error(`Invalid hex color length: ${e.length}`);
50
- return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
51
- }
52
- var B2 = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
53
- let [l, n, c] = b(r);
54
- return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
55
- }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
56
- var h = new Set(["", "1", "2", "3", "true"]);
57
- function C(r, e = globalThis.process?.env ?? {}) {
58
- if (e.FORCE_COLOR !== undefined)
59
- return h.has(e.FORCE_COLOR);
60
- if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
61
- return false;
62
- return r?.isTTY === true;
63
- }
64
- function f(r, e = []) {
65
- let l = "", n = "";
66
- for (let t = 0, i = e.length;t < i; t++)
67
- l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
68
- let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
69
- return new Proxy(c, { get(t, i) {
70
- let a = B2[i];
71
- if (Array.isArray(a)) {
72
- let s = g.get(i);
73
- if (s === undefined)
74
- s = f(r, [...e, a]), g.set(i, s);
75
- return s;
76
- }
77
- if (typeof a === "function")
78
- return (...s) => {
79
- let y = `${i}:${s.join(",")}`, u = g.get(y);
80
- if (u === undefined) {
81
- if (g.size >= 64)
82
- g.clear();
83
- u = f(r, [...e, a(...s)]), g.set(y, u);
84
- }
85
- return u;
86
- };
87
- throw Error(`Unknown style: ${String(i)}`);
88
- } });
89
- }
90
- function Fe(r = {}) {
91
- return f(r);
92
- }
93
- var o = Fe();
94
-
95
- // ../kit/src/theme.ts
96
- var ENDS = new Map;
97
- var STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
98
- var MAX_FILE_BYTES = 64 * 1024;
99
- var warned = new Set;
100
-
101
- // ../kit/src/style.ts
102
- function takesControlCodes(stream, env = process3.env) {
103
- return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
104
- }
105
- function paint(stream, env = process3.env) {
106
- return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
107
- }
108
- var STATUS_WORDS = {
109
- passed: ["passed", "success", "succeeded", "ok"],
110
- failed: ["failed", "failure", "error", "errored"],
111
- running: ["running", "in_progress", "started", "holding"],
112
- queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
113
- skipped: ["skipped", "cancelled", "canceled", "manual"]
114
- };
115
- var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
116
-
117
- // ../kit/src/format.ts
118
- var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
119
- function formatSeconds(total) {
120
- let rest = Math.max(0, Math.round(total));
121
- const amounts = UNITS.map(([unit, size]) => {
122
- const amount = Math.floor(rest / size);
123
- rest -= amount * size;
124
- return `${amount}${unit}`;
125
- });
126
- const first = amounts.findIndex((amount) => !amount.startsWith("0"));
127
- if (first === -1)
128
- return "0s";
129
- const next = amounts[first + 1];
130
- return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
131
- }
132
- function formatDuration(ms) {
133
- return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
134
- }
135
- function upTo(text, separator) {
136
- const end = text.indexOf(separator);
137
- return end === -1 ? text : text.slice(0, end);
138
- }
139
- var ESCAPE = String.fromCharCode(27);
140
-
141
- // ../kit/src/help.ts
142
- import process4 from "process";
143
- var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
144
- var USAGE_PREFIX = /^usage:\s*/i;
145
- var FULL_STOP = /\.$/;
146
- function usageLine(usage, colors = paint(process4.stdout)) {
147
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
148
- }
149
- function helpText(usage, options, colors = paint(process4.stdout), { examples = [], exits = [] } = {}) {
150
- return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
151
- `);
152
- }
153
- function exitRows(exits, colors = paint(process4.stdout)) {
154
- if (exits.length === 0)
155
- return [];
156
- return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
157
- }
158
- function wantsHelpJson(env = process4.env) {
159
- return env.KIT_HELP === "json";
160
- }
161
- function description(usage, { examples = [], replaces, exits } = {}, options) {
162
- const lines = usage.replace(USAGE_PREFIX, "").split(`
163
- `);
164
- const first = lines[0];
165
- const colon = first.indexOf(": ");
166
- const prose = lines[lines.indexOf("") + 1] ?? "";
167
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
168
- return {
169
- synopsis: colon === -1 ? first : first.slice(0, colon),
170
- summary: colon === -1 ? fallback : first.slice(colon + 2),
171
- ...replaces === undefined ? {} : { replaces },
172
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
173
- ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
174
- ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
175
- };
176
- }
177
- function exampleRows(examples, colors = paint(process4.stdout)) {
178
- if (examples.length === 0 || outputMode() === "agent")
179
- return [];
180
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
181
- }
182
- var MAX_INLINE_CHOICES = 24;
183
- function optionRows(options, colors = paint(process4.stdout)) {
184
- const rows = Object.entries(options).map(([name, option]) => {
185
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
186
- const choices = option.choices?.join("|");
187
- const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
188
- const named = inline ? `<${choices}>` : "<value>";
189
- const placeholder = option.optional === undefined ? named : `[${named}]`;
190
- const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
191
- const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
192
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
193
- });
194
- const width = Math.max(0, ...rows.map((row) => row.width));
195
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
196
- }
197
-
198
- // ../kit/src/text.ts
199
- function distance(a, b) {
200
- const left = [...a];
201
- const right = [...b];
202
- let before = [];
203
- let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
204
- for (const [i, x] of left.entries()) {
205
- const current = [i + 1];
206
- for (const [j, y] of right.entries()) {
207
- let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
208
- if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
209
- cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
210
- current.push(cost);
211
- }
212
- before = previous;
213
- previous = current;
214
- }
215
- return previous[right.length] ?? 0;
216
- }
217
- function closest(name, names) {
218
- const started = names.find((known) => known.startsWith(name));
219
- if (started !== undefined)
220
- return started;
221
- const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
222
- return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
223
- }
224
-
225
- // ../kit/src/args.ts
226
- var DASHES = /^-+/;
227
- class Exit extends Error {
228
- code;
229
- hint;
230
- constructor(message, code, hint) {
231
- super(message);
232
- this.code = code;
233
- this.hint = hint;
234
- }
235
- }
236
- function fail(message, code = 2, hint) {
237
- throw new Exit(message, code, hint);
238
- }
239
-
240
- class UsageError extends Exit {
241
- constructor(message, hint) {
242
- super(message, 2, hint);
243
- }
244
- }
245
- function badUsage(message) {
246
- throw new UsageError(message);
247
- }
248
-
249
- class HelpShown extends Exit {
250
- constructor() {
251
- super("help shown", 0);
252
- }
253
- }
254
-
255
- class Completing {
256
- options;
257
- positionals;
258
- candidates;
259
- constructor(options, positionals = [], candidates = {}) {
260
- this.options = options;
261
- this.positionals = positionals;
262
- this.candidates = candidates;
263
- }
264
- }
265
- var completion = { active: false };
266
- var OUTPUT_OPTIONS = {
267
- color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
268
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
269
- };
270
- function applyOutput(color, plain, env = process5.env) {
271
- const when = plain === true ? "never" : color ?? "auto";
272
- if (when === "auto")
273
- return;
274
- if (when !== "always" && when !== "never")
275
- badUsage(`--color takes auto, always or never, not ${when}`);
276
- if (when === "always") {
277
- env.FORCE_COLOR = "1";
278
- delete env.NO_COLOR;
279
- } else {
280
- env.NO_COLOR = "1";
281
- delete env.FORCE_COLOR;
282
- }
283
- }
284
- function parse(args, usage, options, settings = {}) {
285
- const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
286
- const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
287
- const listing = listed(all, settings.allowNegative === true);
288
- if (completion.active)
289
- throw new Completing(listing, settings.positionals, settings.candidates);
290
- const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
291
- let parsed;
292
- try {
293
- parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
294
- } catch (error) {
295
- const message = parseError(error);
296
- throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
297
- }
298
- const values = parsed.values;
299
- applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
300
- if (values.help === true) {
301
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
302
- throw new HelpShown;
303
- }
304
- checkChoices(parsed.values, all);
305
- checkConflicts(parsed.values, all);
306
- if (settings.positionals !== undefined)
307
- checkPositionals(parsed.positionals, settings.positionals);
308
- return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
309
- }
310
- function splitRest(args, passes) {
311
- const separator = passes ? args.indexOf("--") : -1;
312
- return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
313
- }
314
- function splitTrailing(args, options, count) {
315
- const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
316
- let seen = 0;
317
- if (count === 0)
318
- return { own: args, rest: undefined };
319
- for (let at = 0;at < args.length; at++) {
320
- const word = args[at];
321
- if (word === "--")
322
- break;
323
- if (word.startsWith("-")) {
324
- if (takesValue(word))
325
- at++;
326
- continue;
327
- }
328
- seen++;
329
- if (seen === count)
330
- return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
331
- }
332
- return { own: args, rest: undefined };
333
- }
334
- function listed(options, allowNegative) {
335
- if (!allowNegative)
336
- return options;
337
- return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
338
- if (option.type !== "boolean" || option.negative === undefined)
339
- return [[name, option]];
340
- return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
341
- }));
342
- }
343
- function withAliases(args, options) {
344
- const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
345
- if (named.size === 0)
346
- return args;
347
- const separator = args.indexOf("--");
348
- const own = separator === -1 ? args : args.slice(0, separator);
349
- return [...own.map((arg) => {
350
- const at = arg.indexOf("=");
351
- const current = named.get(at === -1 ? arg : arg.slice(0, at));
352
- return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
353
- }), ...separator === -1 ? [] : args.slice(separator)];
354
- }
355
- function withBare(args, options) {
356
- const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
357
- if (bare.size === 0)
358
- return args;
359
- const separator = args.indexOf("--");
360
- const own = separator === -1 ? args : args.slice(0, separator);
361
- return [...own.flatMap((arg, index) => {
362
- const optional = bare.get(arg);
363
- const next = own[index + 1];
364
- const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
365
- return optional === undefined || value ? [arg] : [arg, optional.bare];
366
- }), ...separator === -1 ? [] : args.slice(separator)];
367
- }
368
- function checkConflicts(values, options) {
369
- const given = (name) => values[name] !== undefined && values[name] !== false;
370
- for (const [name, { conflicts = [] }] of Object.entries(options)) {
371
- const other = given(name) ? conflicts.find(given) : undefined;
372
- if (other !== undefined)
373
- badUsage(`--${name} cannot be used with --${other}`);
374
- }
375
- }
376
- function checkChoices(values, options) {
377
- for (const [name, option] of Object.entries(options)) {
378
- if (option.choices === undefined)
379
- continue;
380
- const given = values[name];
381
- for (const value of Array.isArray(given) ? given : [given]) {
382
- if (typeof value === "string")
383
- oneOf(value, name, option.choices);
384
- }
385
- }
386
- }
387
- function oneOf(value, name, choices) {
388
- if (!choices.includes(value))
389
- badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
390
- return value;
391
- }
392
- function checkPositionals(given, names) {
393
- const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
394
- const required = names.filter((name) => !name.startsWith("[")).length;
395
- if (given.length < required)
396
- badUsage(`missing ${names[given.length]}`);
397
- if (!variadic && given.length > names.length)
398
- badUsage(`unexpected argument ${given[names.length]}`);
399
- }
400
- function joinDashValues(args, options) {
401
- const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
402
- const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
403
- const joined = [];
404
- for (let i = 0;i < args.length; i++) {
405
- const arg = args[i] ?? "";
406
- if (arg === "--")
407
- return [...joined, ...args.slice(i)];
408
- const name = longOf.get(arg);
409
- const next = args[i + 1];
410
- if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
411
- joined.push(`--${name}=${next}`);
412
- i++;
413
- } else {
414
- joined.push(arg);
415
- }
416
- }
417
- return joined;
418
- }
419
- function parseError(error) {
420
- const message = upTo(error instanceof Error ? error.message : String(error), ". ");
421
- return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
422
- }
423
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
424
- function nearestOption(message, options, allowNegative) {
425
- const typed = UNKNOWN_OPTION.exec(message)?.[1];
426
- if (typed === undefined)
427
- return;
428
- const word = typed.replace(DASHES, "");
429
- if (word.length < 2 && !typed.startsWith("--"))
430
- return;
431
- const known = Object.entries(options).flatMap(([name, option]) => [
432
- ...option.short === undefined ? [] : [`-${option.short}`],
433
- `--${name}`,
434
- ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
435
- ]);
436
- const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
437
- return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
438
- }
439
- // ../kit/src/argv.ts
440
- import { readFileSync, realpathSync } from "fs";
441
- import { resolve } from "path";
442
- import process6 from "process";
443
- function commandLine() {
444
- try {
445
- return readFileSync("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
446
- } catch {
447
- return;
448
- }
449
- }
450
- function realPath(word) {
451
- try {
452
- return realpathSync(resolve(word));
453
- } catch {
454
- return;
455
- }
456
- }
457
- function scriptArgs(argv = process6.argv.slice(2), cmdline = commandLine(), script = process6.argv[1]) {
458
- const target = script === undefined ? undefined : realPath(script) ?? script;
459
- const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve(word) === script || realPath(word) === target));
460
- const after = at === -1 ? [] : cmdline.slice(at + 1);
461
- return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
462
- }
463
- // ../kit/src/progress.ts
464
- var ESC = String.fromCharCode(27);
465
- var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
466
- var RESET_STYLE = `${ESC}[0m`;
467
- var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
468
- // ../kit/src/cli.ts
469
- import { readFileSync as readFileSync2, realpathSync as realpathSync2 } from "fs";
470
- import { dirname as dirname2, join as join2 } from "path";
471
- import process9 from "process";
472
-
473
- // ../kit/src/completions.ts
474
- var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
475
- var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
476
- set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
477
- set -l current (commandline -ct)
478
- for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
479
- if test "$line" = __files__
480
- __fish_complete_path $current
481
- else
482
- echo $line
483
- end
484
- end
485
- end`;
486
- var BASH_FUNCTION = `__kaynooo_cli_complete() {
487
- local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
488
- local -a lines
489
- COMPREPLY=()
490
- lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
491
- for line in "\${lines[@]}"; do
492
- if [[ $line == __files__ ]]; then
493
- COMPREPLY+=($(compgen -f -- "$cur"))
494
- else
495
- words+="\${line%%$'\\t'*}"$'\\n'
496
- fi
497
- done
498
- COMPREPLY+=($(compgen -W "$words" -- "$cur"))
499
- }`;
500
- var ZSH_FUNCTION = `__kaynooo_cli_complete() {
501
- local line
502
- local -a described plain
503
- for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
504
- if [[ $line == __files__ ]]; then
505
- _files
506
- elif [[ $line == *$'\\t'* ]]; then
507
- described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
508
- else
509
- plain+=("$line")
510
- fi
511
- done
512
- (( \${#described} )) && _describe -V value described
513
- (( \${#plain} )) && compadd -- "\${plain[@]}"
514
- return 0
515
- }`;
516
- function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
517
- if (shell === "fish")
518
- return `${header}
519
- ${FISH_FUNCTION}
520
- ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
521
- `).join("")}`;
522
- if (shell === "bash")
523
- return `${header}
524
- ${BASH_FUNCTION}
525
- complete -F __kaynooo_cli_complete ${bins.join(" ")}
526
- `;
527
- return `${header}
528
- ${ZSH_FUNCTION}
529
- compdef __kaynooo_cli_complete ${bins.join(" ")}
530
- `;
531
- }
532
-
533
- // ../kit/src/notify.ts
534
- import process7 from "process";
535
- var NOTIFY_AFTER_MS = 1e4;
536
- var CANCELLED = 130;
537
- function base64(text) {
538
- return Buffer.from(text).toString("base64");
539
- }
540
- function notification(title, body, env = process7.env) {
541
- const id = `kit${process7.pid}`;
542
- const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
543
- return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
544
- }
545
- function notifyEnd(command, code, ms, { stream = process7.stderr, env = process7.env } = {}) {
546
- if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
547
- return;
548
- stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
549
- }
550
-
551
- // ../kit/src/usage.ts
552
- import { appendFileSync, mkdirSync } from "fs";
553
- import { homedir } from "os";
554
- import { dirname, isAbsolute, join } from "path";
555
- import process8 from "process";
556
-
557
- // ../kit/src/logs.ts
558
- var DAY_MS = 24 * 60 * 60 * 1000;
559
- var CLI_FOLDER = "kaynooo-cli";
560
-
561
- // ../kit/src/usage.ts
562
- var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
563
- var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
564
- var LONGEST_NAME = 40;
565
- var usageError;
566
- function noteUsageError(message) {
567
- usageError = message;
568
- }
569
- function stateHome(env = process8.env) {
570
- const dir = env.XDG_STATE_HOME;
571
- return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
572
- }
573
- function usagePath(env = process8.env) {
574
- return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
575
- }
576
- function usageRecorded(env = process8.env) {
577
- const off = env.KAYNOOO_CLI_NO_USAGE;
578
- return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
579
- }
580
- function flagNames(argv) {
581
- const end = argv.indexOf("--");
582
- const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
583
- return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
584
- }
585
- function usageEntry(bin, command, argv, code, now = new Date) {
586
- const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
587
- usageError = undefined;
588
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
589
- }
590
- function recordUsage(entry, env = process8.env) {
591
- if (!usageRecorded(env))
592
- return;
593
- try {
594
- const path = usagePath(env);
595
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
596
- appendFileSync(path, `${JSON.stringify(entry)}
597
- `, { mode: 384 });
598
- } catch {}
599
- }
600
-
601
- // ../kit/src/cli.ts
602
- var LEVEL_OPTIONS = {
603
- ...OUTPUT_OPTIONS,
604
- help: { type: "boolean", short: "h", description: "show this help" }
605
- };
606
- var TOP_OPTIONS = {
607
- ...LEVEL_OPTIONS,
608
- version: { type: "boolean", short: "v", description: "print the version" },
609
- completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
610
- };
611
- async function commandRows(all, colors) {
612
- const commands = shown(all);
613
- const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
614
- const groups = new Map([["Commands:", []]]);
615
- const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
616
- for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
617
- const heading = group === undefined ? "Commands:" : `${group}:`;
618
- const rows = groups.get(heading) ?? [];
619
- rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
620
- groups.set(heading, rows);
621
- }
622
- return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
623
- }
624
- function shown(commands) {
625
- return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
626
- }
627
- function takeOutputFlags(argv) {
628
- let index = 0;
629
- for (;index < argv.length; index++) {
630
- const word = argv[index];
631
- if (word === "--plain")
632
- applyOutput(undefined, true);
633
- else if (word.startsWith("--color="))
634
- applyOutput(word.slice("--color=".length), undefined);
635
- else if (word === "--color" && argv[index + 1] !== undefined)
636
- applyOutput(argv[++index], undefined);
637
- else
638
- break;
639
- }
640
- return argv.slice(index);
641
- }
642
- async function resolveSummary(summary) {
643
- return typeof summary === "string" ? summary : summary();
644
- }
645
- function scopeOf(commands, extra, aliases) {
646
- return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
647
- }
648
- async function expand(scope, words) {
649
- if (scope.lazy.length === 0)
650
- return scope;
651
- const commands = { ...scope.commands };
652
- for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
653
- for (const [name, command] of Object.entries(added))
654
- commands[name] ??= command;
655
- }
656
- return { ...scope, commands, lazy: [] };
657
- }
658
- async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
659
- const colors = paint(stream);
660
- const prefix = path.join(" ");
661
- const summary = await resolveSummary(lazySummary);
662
- if (wantsHelpJson())
663
- return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
664
- const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
665
- const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
666
- const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
667
- return [
668
- header(colors, summary),
669
- "",
670
- usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
671
- "",
672
- ...await commandRows(commands, colors),
673
- ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
674
- "",
675
- colors.bold("Options:"),
676
- ...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
677
- ...exampleRows(examples ?? [], colors),
678
- "",
679
- `${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
680
- ].join(`
681
- `);
682
- }
683
- function printError(prefix, message, hint, cause) {
684
- const colors = paint(process9.stderr);
685
- const styled = takesControlCodes(process9.stderr);
686
- const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
687
- const under = (label, text, tint) => text === undefined ? "" : `
688
- ${styled ? tint(label) : `${label}:`} ${text}`;
689
- console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
690
- }
691
- function printJsonError(message, hint, cause) {
692
- console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
693
- }
694
- function wantsJson(argv) {
695
- const end = argv.indexOf("--");
696
- return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
697
- }
698
- function reportThrown(prefix, error, redact = (text) => text, json = false) {
699
- if (error instanceof HelpShown)
700
- return 0;
701
- const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
702
- const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
703
- const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
704
- if (error instanceof Exit && error.code === 2)
705
- noteUsageError(error.message);
706
- const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
707
- report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
708
- return error instanceof Exit ? error.code : 1;
709
- }
710
- async function dispatch(level, typed, { version, redact }) {
711
- const prefix = level.path.join(" ");
712
- let argv;
713
- try {
714
- argv = takeOutputFlags(typed);
715
- } catch (error) {
716
- return reportThrown(prefix, error);
717
- }
718
- const [name, ...args] = argv;
719
- const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
720
- if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
721
- try {
722
- return await fallback.run([]);
723
- } catch (error) {
724
- return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
725
- }
726
- }
727
- if (name === undefined && level.path.length > 1) {
728
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stderr));
729
- return 2;
730
- }
731
- if (name === undefined || name === "help" || name === "--help" || name === "-h") {
732
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stdout));
733
- return 0;
734
- }
735
- if (level.path.length === 1 && (name === "--version" || name === "-v")) {
736
- console.log(version);
737
- return 0;
738
- }
739
- let command = level.commands[level.aliases?.[name] ?? name];
740
- let rest = args;
741
- let ran = name;
742
- if (command === undefined && level.lazy.length > 0) {
743
- level = await expand(level, [...level.path.slice(1), ...argv]);
744
- command = level.commands[level.aliases?.[name] ?? name];
745
- }
746
- if (command === undefined && level.defaultCommand !== undefined) {
747
- command = level.commands[level.defaultCommand];
748
- rest = argv;
749
- ran = level.defaultCommand;
750
- }
751
- if (command === undefined) {
752
- const meant = closest(name, Object.keys(shown(level.commands)));
753
- printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
754
- return 2;
755
- }
756
- if ("commands" in command) {
757
- const { summary } = command;
758
- return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
759
- }
760
- try {
761
- return await command.run(rest);
762
- } catch (error) {
763
- return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
764
- }
765
- }
766
- var COMPLETE = "__complete";
767
- var FILES = "__files__";
768
- async function completingOf(run) {
769
- completion.active = true;
770
- try {
771
- await run([]);
772
- } catch (error) {
773
- if (error instanceof Completing)
774
- return error;
775
- } finally {
776
- completion.active = false;
777
- }
778
- return new Completing({});
779
- }
780
- async function optionsOf(run) {
781
- return (await completingOf(run)).options;
782
- }
783
- function candidateLine(candidate) {
784
- return typeof candidate === "string" ? candidate : candidate.join("\t");
785
- }
786
- function positionalBeingTyped(before, { options, positionals }) {
787
- const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
788
- const typed = [];
789
- let at = 0;
790
- while (at < before.length) {
791
- const word = before[at];
792
- if (word === "--") {
793
- typed.push(...before.slice(at + 1));
794
- break;
795
- }
796
- if (!word.startsWith("-"))
797
- typed.push(word);
798
- else if (takesValue(word))
799
- at++;
800
- at++;
801
- }
802
- const last = positionals.at(-1);
803
- if (typed.length < positionals.length)
804
- return { name: positionals[typed.length], typed };
805
- return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
806
- }
807
- async function leafCandidates(run, words) {
808
- const completing = await completingOf(run);
809
- if ((words.at(-1) ?? "").startsWith("-"))
810
- return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
811
- const flag = words.at(-2);
812
- const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
813
- const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
814
- if (option?.type === "string") {
815
- const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
816
- return values === undefined ? [FILES] : values.map(candidateLine);
817
- }
818
- const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
819
- return values === undefined ? [FILES] : values.map(candidateLine);
820
- }
821
- async function candidates(scope, defaultCommand, words, before = []) {
822
- const [word = "", ...rest] = words;
823
- const listing = rest.length === 0 && !word.startsWith("-");
824
- let { commands, aliases } = scope;
825
- let command = commands[aliases?.[word] ?? word];
826
- if (listing || command === undefined) {
827
- ({ commands, aliases } = await expand(scope, [...before, ...words]));
828
- command = commands[aliases?.[word] ?? word];
829
- }
830
- if (listing) {
831
- const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
832
- const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
833
- const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
834
- const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
835
- return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
836
- }
837
- if (command === undefined) {
838
- const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
839
- return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
840
- }
841
- return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
842
- }
843
- var COMPLETIONS = "--completions";
844
- function flagValue([flag = "", ...rest]) {
845
- return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
846
- }
847
- function printCompletionScript(name, args) {
848
- const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
849
- if (shell === undefined || args.length !== 1) {
850
- printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
851
- return 2;
852
- }
853
- console.log(completionScript(shell, [name]).trimEnd());
854
- return 0;
855
- }
856
- async function printCandidates(found) {
857
- for (const line of await found)
858
- console.log(line);
859
- return 0;
860
- }
861
- function packageVersion(entry = Bun.main) {
862
- let resolved = entry;
863
- try {
864
- resolved = realpathSync2(entry);
865
- } catch {}
866
- for (let dir = dirname2(resolved);; dir = dirname2(dir)) {
867
- try {
868
- const { version } = JSON.parse(readFileSync2(join2(dir, "package.json"), "utf8"));
869
- if (typeof version === "string")
870
- return version;
871
- } catch {}
872
- if (dirname2(dir) === dir)
873
- return "0.0.0";
874
- }
875
- }
876
- async function runCli(cli, argv = scriptArgs()) {
877
- const version = cli.version ?? packageVersion();
878
- if (argv[0] === COMPLETE)
879
- return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
880
- if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
881
- return printCompletionScript(cli.name, flagValue(argv));
882
- const started = performance.now();
883
- const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
884
- const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
885
- notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
886
- if (cli.usage !== false) {
887
- try {
888
- recordUsage(usageEntry(cli.name, command, argv, code));
889
- } catch {}
890
- }
891
- return code;
892
- }
893
- function commandPath(scope, argv) {
894
- const path = [];
895
- let level = scope;
896
- for (const word of argv.filter((each) => !each.startsWith("-"))) {
897
- const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
898
- const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
899
- if (command === undefined)
900
- break;
901
- path.push(word);
902
- if (!("commands" in command))
903
- break;
904
- level = scopeOf(command.commands, command.extraCommands, command.aliases);
905
- }
906
- return path.length === 0 ? undefined : path.join(" ");
907
- }
908
- // ../kit/src/folders.ts
909
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
910
- // ../kit/src/secrets.ts
911
- var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
912
- // ../kit/src/sessions.ts
913
- var {Glob } = globalThis.Bun;
914
- var SESSION_FILES = new Glob("*.json");
915
- var ACCOUNT_DIRS = new Glob("*/sessions");
916
- // src/commands.ts
917
- import { existsSync as existsSync10, rmSync as rmSync4 } from "fs";
918
- var {$: $8 } = globalThis.Bun;
919
-
920
- // src/errors.ts
921
- import { readFileSync as readFileSync3 } from "fs";
922
- class KnownError extends Error {
923
- }
924
- var BOOT_TIME_LINE = /^btime (\d+)$/m;
925
- var bootedAt;
926
- function bootTime() {
927
- bootedAt ??= Number(readFileSync3("/proc/stat", "utf8").match(BOOT_TIME_LINE)?.[1] ?? 0) * 1000;
928
- return bootedAt;
929
- }
930
- function alive(pid) {
931
- try {
932
- process.kill(pid, 0);
933
- return true;
934
- } catch (error) {
935
- return error.code === "EPERM";
936
- }
937
- }
938
- function failKnown(error) {
939
- if (error instanceof KnownError)
940
- fail(error.message, 1);
941
- throw error;
942
- }
943
-
944
- // src/files.ts
945
- import { existsSync as existsSync4, lstatSync, mkdirSync as mkdirSync3, readFileSync as readFileSync6, renameSync, rmSync as rmSync2, statSync, symlinkSync, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
946
- import { constants } from "os";
947
- import { basename as basename2, dirname as dirname4, join as join7 } from "path";
948
- var {$: $2 } = globalThis.Bun;
949
-
950
- // src/compose.ts
951
- import { existsSync as existsSync3, readFileSync as readFileSync4 } from "fs";
952
- import { join as join5 } from "path";
953
- var {$ } = globalThis.Bun;
954
-
955
- // src/project.ts
956
- import { existsSync as existsSync2, readdirSync, realpathSync as realpathSync3 } from "fs";
957
- import { basename, dirname as dirname3, join as join4 } from "path";
958
-
959
- // src/config.ts
960
- import { existsSync } from "fs";
961
- import { homedir as homedir2 } from "os";
962
- import { join as join3 } from "path";
963
- var LEADING_TILDE = /^~(?=\/|$)/;
964
- function expandHome(path) {
965
- return path.replace(LEADING_TILDE, homedir2());
966
- }
967
- var configPath = () => process.env.WT_CONFIG ?? join3((process.env.XDG_CONFIG_HOME ?? "") || join3(homedir2(), ".config"), "wt", "config.ts");
968
- function resolveConfig(config = {}) {
969
- const configDir = join3(configPath(), "..");
970
- const state = expandHome(config.state ?? join3(homedir2(), ".cache", "wt"));
971
- return {
972
- manifests: expandHome(config.manifests ?? join3(configDir, "projects")),
973
- worktrees: expandHome(config.worktrees ?? "{root}/.worktrees/{repo}"),
974
- overrides: expandHome(config.overrides ?? join3(homedir2(), ".local", "share", "wt", "overrides")),
975
- state,
976
- jobs: expandHome(config.jobs ?? join3(state, "jobs")),
977
- proxyNetwork: config.proxyNetwork ?? "proxy",
978
- runner: config.runner ?? {}
979
- };
980
- }
981
- var loaded;
982
- async function wtConfig() {
983
- if (loaded)
984
- return loaded;
985
- const path = configPath();
986
- if (!existsSync(path))
987
- return loaded = resolveConfig();
988
- try {
989
- const { default: config } = await import(path);
990
- return loaded = resolveConfig(config);
991
- } catch (error) {
992
- throw new KnownError(`${path} does not load: ${error instanceof Error ? error.message : String(error)}`);
993
- }
994
- }
995
- function fillTemplate(argv, values) {
996
- return argv.map((arg) => arg.replaceAll(/\{(\w+)\}/g, (match, key) => values[key] ?? match));
997
- }
998
-
999
- // src/port.ts
1000
- function stringToPort(s, min = 1024, max = 65535) {
1001
- let hash = 2166136261;
1002
- for (let i = 0;i < s.length; i++) {
1003
- hash ^= s.charCodeAt(i);
1004
- hash = hash * 16777619 >>> 0;
1005
- }
1006
- return min + hash % (max - min + 1);
1007
- }
1008
-
1009
- // src/project.ts
1010
- class WtError extends KnownError {
1011
- }
1012
- var TASK_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
1013
- var ROUTE_TARGET = /^client$|^[\w.-]+:\d+$/;
1014
- function worktreeFiles(settings, id) {
1015
- return {
1016
- override: join4(settings.overrides, `${id}.override.yml`),
1017
- setupMarker: join4(settings.state, `${id}.setup`),
1018
- clonesPending: join4(settings.state, `${id}.clones-pending`)
1019
- };
1020
- }
1021
- function worktreeHost(host, task) {
1022
- return host.startsWith("*.") ? `*.${task}.${host.slice(2)}` : `${task}.${host}`;
1023
- }
1024
- function assertValid(project) {
1025
- for (const route of project.routes) {
1026
- if (!ROUTE_TARGET.test(route.to))
1027
- throw new WtError(`${project.name}: route ${route.host} goes to "${route.to}", expected "client" or "<service>:<port>"`);
1028
- if (route.passthrough && project.certs === undefined)
1029
- throw new WtError(`${project.name}: passthrough route ${route.host} needs \`certs\``);
1030
- }
1031
- }
1032
- async function loadProjects() {
1033
- const settings = await wtConfig();
1034
- const files = existsSync2(settings.manifests) ? readdirSync(settings.manifests).filter((file) => file.endsWith(".ts")).sort() : [];
1035
- return Promise.all(files.map(async (file) => {
1036
- const { default: config } = await import(join4(settings.manifests, file));
1037
- const project = { ...config, root: expandHome(config.root), name: basename(file, ".ts"), settings };
1038
- assertValid(project);
1039
- return project;
1040
- }));
1041
- }
1042
- async function findProject(name) {
1043
- const project = (await loadProjects()).find((p) => p.name === name);
1044
- if (!project)
1045
- throw new WtError(`no project named ${name} in ${(await wtConfig()).manifests}`);
1046
- return project;
1047
- }
1048
- var tasksDir = (project) => fillTemplate([project.settings.worktrees], { root: dirname3(project.root), repo: basename(project.root) })[0];
1049
- function worktreeOf(project, task) {
1050
- if (task === "main" || !TASK_PATTERN.test(task))
1051
- throw new WtError(`invalid task name "${task}": lowercase letters, digits and inner dashes, at most 63, and not "main"`);
1052
- const mainHosts = new Set(project.routes.map((route) => route.host));
1053
- const taken = project.routes.find((route) => mainHosts.has(worktreeHost(route.host, task)));
1054
- if (taken)
1055
- throw new WtError(`invalid task name "${task}": the worktree's ${worktreeHost(taken.host, task)} would be one of main's hosts`);
1056
- const id = `${basename(project.root)}--${task}`;
1057
- return {
1058
- project,
1059
- task,
1060
- dir: join4(tasksDir(project), task),
1061
- id,
1062
- clientPort: stringToPort(`${project.name}--${task}`),
1063
- files: worktreeFiles(project.settings, id)
1064
- };
1065
- }
1066
- function assertWorktreeExists(worktree) {
1067
- if (!existsSync2(worktree.dir))
1068
- throw new WtError(`no worktree ${worktree.task}, create it with \`wt add ${worktree.task}\``);
1069
- }
1070
- function listTasks(project) {
1071
- const dir = tasksDir(project);
1072
- return existsSync2(dir) ? readdirSync(dir).filter((task) => TASK_PATTERN.test(task)).sort() : [];
1073
- }
1074
- async function locate(cwd, projectName) {
1075
- const here = realpathSync3(cwd);
1076
- const projects = projectName !== undefined ? [await findProject(projectName)] : await loadProjects();
1077
- for (const project of projects) {
1078
- const dir = tasksDir(project);
1079
- if (here.startsWith(`${dir}/`)) {
1080
- const rest = here.slice(dir.length + 1);
1081
- const slash = rest.indexOf("/");
1082
- return { project, task: slash === -1 ? rest : rest.slice(0, slash) };
1083
- }
1084
- if (here === project.root || here.startsWith(`${project.root}/`))
1085
- return { project, task: "main" };
1086
- }
1087
- if (projects.length === 1)
1088
- return { project: projects[0], task: "main" };
1089
- throw new WtError("not inside a known project or worktree (cd into one, or pass --project)");
1090
- }
1091
- async function locateWorktree(cwd, task, projectName) {
1092
- const here = await locate(cwd, projectName);
1093
- const name = task ?? here.task;
1094
- if (name === "main")
1095
- throw new WtError("this is the main checkout, name a task");
1096
- return worktreeOf(here.project, name);
1097
- }
1098
-
1099
- // src/compose.ts
1100
- var COMPOSE_FILES = ["compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml"];
1101
- var SKIP_PROFILE = "wt-skip";
1102
- function composeEnv(overrides = {}) {
1103
- const env = Object.entries(process.env).filter(([key]) => key !== "COMPOSE_FILE" && key !== "COMPOSE_PROJECT_NAME");
1104
- return { ...Object.fromEntries(env), ...overrides };
1105
- }
1106
- async function composeConfig(dir, env = {}) {
1107
- const result = await $`docker compose config --format json`.cwd(dir).env(composeEnv(env)).quiet().nothrow();
1108
- if (result.exitCode !== 0)
1109
- throw new WtError(`docker compose config failed in ${dir}:
1110
- ${result.stderr.toString()}`);
1111
- return JSON.parse(result.stdout.toString());
1112
- }
1113
- var COMPOSE_FILE_LINE = /^COMPOSE_FILE=(.*)$/m;
1114
- var QUOTES_AROUND = /^["']|["']$/g;
1115
- function baseComposeFiles(dir, overrides) {
1116
- const envFile = join5(dir, ".env");
1117
- const line = existsSync3(envFile) ? readFileSync4(envFile, "utf8").match(COMPOSE_FILE_LINE) : null;
1118
- const files = line ? line[1].replace(QUOTES_AROUND, "").split(":").filter(Boolean) : [];
1119
- const base = files.filter((file) => !file.startsWith(`${overrides}/`));
1120
- if (base.length)
1121
- return base;
1122
- const found = COMPOSE_FILES.find((file) => existsSync3(join5(dir, file)));
1123
- if (found === undefined)
1124
- throw new WtError(`no compose file in ${dir}`);
1125
- return [found];
1126
- }
1127
- var q = (value) => JSON.stringify(value);
1128
- var DEVPROXY_HOST_LABEL = /^devproxy\.[\w-]+\.host$/;
1129
- var SERVICE = /^[^:]*/;
1130
- function proxyLabels(worktree, config) {
1131
- const { routes, skip = [] } = worktree.project;
1132
- const labels = new Map;
1133
- const add = (service, ...entries) => labels.set(service, [...labels.get(service) ?? [], ...entries]);
1134
- const routed = routes.find((route) => route.to !== "client")?.to;
1135
- const anchor = routed === undefined ? Object.keys(config.services).find((service) => !skip.includes(service)) : SERVICE.exec(routed)[0];
1136
- for (const [index, route] of routes.entries()) {
1137
- const key = `devproxy.wt${index}`;
1138
- const host = [`${key}.host`, worktreeHost(route.host, worktree.task)];
1139
- if (route.to === "client") {
1140
- if (anchor !== undefined)
1141
- add(anchor, host, [`${key}.to`, `host:${worktree.clientPort}`]);
1142
- continue;
1143
- }
1144
- const [service = "", port = ""] = route.to.split(":");
1145
- add(service, host, [`${key}.port`, port], ...route.passthrough ? [[`${key}.passthrough`, "true"]] : []);
1146
- }
1147
- for (const [service, settings] of Object.entries(config.services)) {
1148
- for (const [key, value] of Object.entries(settings.labels ?? {})) {
1149
- if (DEVPROXY_HOST_LABEL.test(key))
1150
- add(service, [key, value.split(",").map((host) => worktreeHost(host.trim(), worktree.task)).join(",")]);
1151
- }
1152
- }
1153
- return labels;
1154
- }
1155
- function renderOverride(worktree, config) {
1156
- const skip = new Set(worktree.project.skip);
1157
- const routeHosts = new Set(worktree.project.routeHosts);
1158
- const labels = proxyLabels(worktree, config);
1159
- const network = worktree.project.settings.proxyNetwork;
1160
- const extraHosts = worktree.project.routes.filter((route) => !route.host.startsWith("*.")).map((route) => ` - ${q(`${worktreeHost(route.host, worktree.task)}:host-gateway`)}`);
1161
- const lines = [`# Generated by wt for ${worktree.id}, rewritten on every \`wt sync\`.`, "services:"];
1162
- let joined = false;
1163
- for (const [name, service] of Object.entries(config.services)) {
1164
- const body = [];
1165
- if (skip.has(name))
1166
- body.push(` profiles: [${q(SKIP_PROFILE)}]`);
1167
- if (service.container_name !== undefined && service.container_name !== "")
1168
- body.push(" container_name: !reset null");
1169
- if ((service.ports?.length ?? 0) > 0)
1170
- body.push(" ports: !reset []");
1171
- if (routeHosts.has(name) && extraHosts.length)
1172
- body.push(" extra_hosts:", ...extraHosts);
1173
- if (labels.has(name))
1174
- body.push(" labels:", ...labels.get(name).map(([key, value]) => ` ${q(key)}: ${q(value)}`));
1175
- const networks = (service.network_mode ?? "") !== "" ? [] : Object.entries(service.networks ?? {});
1176
- const joins = (service.network_mode ?? "") === "" && !skip.has(name) && !(network in (service.networks ?? {})) && labels.get(name)?.some(([key]) => key.endsWith(".port")) === true;
1177
- const networkLines = networks.flatMap(([own, settings]) => {
1178
- if (own === network)
1179
- return (settings?.aliases?.length ?? 0) > 0 ? [` ${network}:`, " aliases: !reset []"] : [];
1180
- if (service.container_name !== undefined && service.container_name !== "")
1181
- return [` ${q(own)}:`, ` aliases: [${q(service.container_name)}]`];
1182
- return joins ? [` ${q(own)}: {}`] : [];
1183
- });
1184
- if (joins) {
1185
- joined = true;
1186
- networkLines.push(` ${network}: {}`);
1187
- }
1188
- if (networkLines.length)
1189
- body.push(" networks:", ...networkLines);
1190
- if (body.length)
1191
- lines.push(` ${q(name)}:`, ...body);
1192
- }
1193
- if (joined && config.networks?.[network] === undefined)
1194
- lines.push("networks:", ` ${network}:`, ` name: ${network}`, " external: true");
1195
- return `${lines.join(`
1196
- `)}
1197
- `;
1198
- }
1199
- function overrideWarnings(worktree, config) {
1200
- const skip = new Set(worktree.project.skip);
1201
- const network = worktree.project.settings.proxyNetwork;
1202
- const warnings = [];
1203
- for (const [name, service] of Object.entries(config.services)) {
1204
- if (skip.has(name))
1205
- continue;
1206
- if (service.network_mode === "host")
1207
- warnings.push(`service ${name} runs on the host network and may collide with main, consider adding it to skip`);
1208
- if (service.networks && network in service.networks && !service.networks[network]?.aliases?.some((alias) => alias !== name))
1209
- warnings.push(`service ${name} has no alias of its own on the proxy network, so the worktree answers to ${name} there too and the shared proxy round-robins between them, give it one in the project override`);
1210
- }
1211
- for (const [key, volume] of Object.entries(config.volumes ?? {})) {
1212
- if (volume.external || volume.name !== undefined && !volume.name.startsWith(`${config.name}_`))
1213
- warnings.push(`volume ${key} is named ${volume.name ?? key} outside the project, main and the worktree share it`);
1214
- }
1215
- return warnings;
1216
- }
1217
- async function runningProjects() {
1218
- const result = await $`docker compose ls --format json`.quiet().nothrow();
1219
- if (result.exitCode !== 0)
1220
- return new Set;
1221
- return new Set(JSON.parse(result.stdout.toString()).map((stack) => stack.Name));
1222
- }
1223
-
1224
- // src/queue.ts
1225
- import { mkdirSync as mkdirSync2, readdirSync as readdirSync2, readFileSync as readFileSync5, rmSync, writeFileSync } from "fs";
1226
- import { join as join6 } from "path";
1227
- var queueDir = (settings, name) => join6(settings.state, "queues", name);
1228
- var POLL_MS = 1000;
1229
- function liveTickets(dir) {
1230
- const names = readdirSync2(dir).sort();
1231
- return names.filter((name) => {
1232
- const dash = name.indexOf("-");
1233
- if (Number(name.slice(0, dash)) >= bootTime() && alive(Number(name.slice(dash + 1))))
1234
- return true;
1235
- rmSync(join6(dir, name), { force: true });
1236
- return false;
1237
- });
1238
- }
1239
- function labelOf(ticket) {
1240
- try {
1241
- return readFileSync5(ticket, "utf8");
1242
- } catch {
1243
- return "";
1244
- }
1245
- }
1246
- async function inLine(dir, label, waiting, work) {
1247
- mkdirSync2(dir, { recursive: true });
1248
- const name = `${String(Date.now()).padStart(15, "0")}-${process.pid}`;
1249
- const ticket = join6(dir, name);
1250
- const release = () => rmSync(ticket, { force: true });
1251
- writeFileSync(ticket, label);
1252
- process.once("exit", release);
1253
- try {
1254
- let shown = -1;
1255
- for (;; ) {
1256
- const ahead = liveTickets(dir).filter((other) => other < name);
1257
- if (ahead.length === 0)
1258
- break;
1259
- if (ahead.length !== shown) {
1260
- shown = ahead.length;
1261
- waiting(ahead.length, labelOf(join6(dir, ahead[0])));
1262
- }
1263
- await Bun.sleep(POLL_MS);
1264
- }
1265
- return await work();
1266
- } finally {
1267
- release();
1268
- }
1269
- }
1270
-
1271
- // src/files.ts
1272
- var PARTIAL = ".wt-partial";
1273
- var PAUSE_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
1274
- function writeIfChanged(path, content) {
1275
- if (existsSync4(path) && readFileSync6(path, "utf8") === content)
1276
- return false;
1277
- mkdirSync3(dirname4(path), { recursive: true });
1278
- writeFileSync2(path, content);
1279
- return true;
1280
- }
1281
- async function volumeExists(name) {
1282
- return (await $2`docker volume inspect ${name}`.quiet().nothrow()).exitCode === 0;
1283
- }
1284
- async function copyFromMain(worktree) {
1285
- const warnings = [];
1286
- for (const entry of worktree.project.copy ?? []) {
1287
- const source = join7(worktree.project.root, entry);
1288
- const target = join7(worktree.dir, entry);
1289
- if (!existsSync4(source)) {
1290
- warnings.push(`copy: ${entry} does not exist in main`);
1291
- continue;
1292
- }
1293
- if (existsSync4(target))
1294
- continue;
1295
- const partial = `${target}${PARTIAL}`;
1296
- mkdirSync3(dirname4(target), { recursive: true });
1297
- rmSync2(partial, { recursive: true, force: true });
1298
- await $2`cp -a --reflink=auto ${source} ${partial}`.quiet();
1299
- renameSync(partial, target);
1300
- }
1301
- return warnings;
1302
- }
1303
- function linkFromMain(worktree) {
1304
- for (const entry of worktree.project.link ?? []) {
1305
- const source = join7(worktree.project.root, entry);
1306
- const target = join7(worktree.dir, entry);
1307
- if (existsSync4(source) && !existsSync4(target)) {
1308
- mkdirSync3(dirname4(target), { recursive: true });
1309
- symlinkSync(source, target);
1310
- }
1311
- }
1312
- }
1313
- var WILDCARD_LABEL = /^\*\./;
1314
- function rewriteHosts(text, routes, task) {
1315
- const hosts = [...new Set(routes.map((route) => route.host.replace(WILDCARD_LABEL, "")))].sort((a, b) => b.length - a.length);
1316
- const pattern = new RegExp(`(?<![\\w.-])(\\.?)(${hosts.map(B).join("|")})(?![\\w.-])`, "g");
1317
- return text.replace(pattern, (_, dot, host) => `${dot}${worktreeHost(host, task)}`);
1318
- }
1319
- function setEnvValue(text, key, value) {
1320
- const line = `${key}=${value}`;
1321
- const pattern = new RegExp(`^${B(key)}=.*$`, "m");
1322
- if (pattern.test(text))
1323
- return text.replace(pattern, line);
1324
- return `${text}${text === "" || text.endsWith(`
1325
- `) ? "" : `
1326
- `}${line}
1327
- `;
1328
- }
1329
- function expandEnvValue(value, worktree) {
1330
- return value.replaceAll("{task}", worktree.task).replaceAll("{port}", String(worktree.clientPort));
1331
- }
1332
- function writeEnvFiles(worktree) {
1333
- const { project, task, dir } = worktree;
1334
- const envFiles = (project.copy ?? []).filter((entry) => basename2(entry).startsWith(".env") && statSync(join7(dir, entry), { throwIfNoEntry: false })?.isFile());
1335
- for (const entry of new Set([...envFiles, ".env"])) {
1336
- const file = join7(dir, entry);
1337
- let text = existsSync4(file) ? rewriteHosts(readFileSync6(file, "utf8"), project.routes, task) : "";
1338
- for (const [key, value] of Object.entries(project.env?.[entry] ?? {}))
1339
- text = setEnvValue(text, key, expandEnvValue(value, worktree));
1340
- if (entry === ".env") {
1341
- text = setEnvValue(text, "COMPOSE_PROJECT_NAME", worktree.id);
1342
- text = setEnvValue(text, "COMPOSE_FILE", [...baseComposeFiles(dir, worktree.project.settings.overrides), worktree.files.override].join(":"));
1343
- }
1344
- writeIfChanged(file, text);
1345
- }
1346
- }
1347
- function unlinkLegacySymlink(dir, entry) {
1348
- let path = dir;
1349
- for (const part of entry.split("/")) {
1350
- path = join7(path, part);
1351
- const stat = lstatSync(path, { throwIfNoEntry: false });
1352
- if (!stat)
1353
- return;
1354
- if (stat.isSymbolicLink())
1355
- return unlinkSync(path);
1356
- }
1357
- }
1358
- async function mainContainers(main, status) {
1359
- return (await $2`docker ps -q --filter ${`status=${status}`} --filter ${`label=com.docker.compose.project=${main.name}`}`.quiet().text()).split(`
1360
- `).filter(Boolean);
1361
- }
1362
- function unpause(ids) {
1363
- if (ids.length)
1364
- Bun.spawnSync(["docker", "unpause", ...ids], { stdout: "ignore", stderr: "ignore" });
1365
- }
1366
- async function whilePaused(ids, work, abort, record) {
1367
- const release = () => {
1368
- unpause(ids);
1369
- if (record !== undefined)
1370
- rmSync2(record, { force: true });
1371
- };
1372
- const onSignal = (signal) => {
1373
- abort?.();
1374
- release();
1375
- process.exit(128 + constants.signals[signal]);
1376
- };
1377
- for (const signal of PAUSE_SIGNALS)
1378
- process.once(signal, onSignal);
1379
- try {
1380
- if (ids.length) {
1381
- if (record !== undefined) {
1382
- mkdirSync3(dirname4(record), { recursive: true });
1383
- writeFileSync2(record, `${ids.join(`
1384
- `)}
1385
- `);
1386
- }
1387
- await $2`docker pause ${ids}`.quiet();
1388
- }
1389
- return await work();
1390
- } finally {
1391
- for (const signal of PAUSE_SIGNALS)
1392
- process.off(signal, onSignal);
1393
- release();
1394
- }
1395
- }
1396
- async function settle(copies) {
1397
- const results = await Promise.allSettled(copies.map(async (copy) => copy()));
1398
- return results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
1399
- }
1400
- function failureText(error) {
1401
- if (error instanceof $2.ShellError)
1402
- return error.stderr.toString().trim() || error.message;
1403
- return error instanceof Error ? error.message : String(error);
1404
- }
1405
- var pausedRecord = (worktree) => queueDir(worktree.project.settings, `${worktree.project.name}.paused`);
1406
- function readPending(file) {
1407
- return new Set(existsSync4(file) ? readFileSync6(file, "utf8").split(`
1408
- `).filter(Boolean) : []);
1409
- }
1410
- function writePending(file, volumes) {
1411
- const text = [...volumes].join(`
1412
- `);
1413
- if (!text)
1414
- return rmSync2(file, { force: true });
1415
- mkdirSync3(dirname4(file), { recursive: true });
1416
- writeFileSync2(file, `${text}
1417
- `);
1418
- }
1419
- async function cloneData(worktree, main) {
1420
- return inLine(queueDir(worktree.project.settings, `${worktree.project.name}.clone`), `cloning ${worktree.task}`, (_, running) => console.error(`wt: ${worktree.project.name}'s main is busy ${running || "cloning"}, waiting`), async () => {
1421
- const record = pausedRecord(worktree);
1422
- const recorded = readPending(record);
1423
- const leftover = recorded.size ? (await mainContainers(main, "paused")).filter((id) => recorded.has(id)) : [];
1424
- unpause(leftover);
1425
- rmSync2(record, { force: true });
1426
- const warnings = leftover.length ? [`clone: unpaused ${leftover.length} of main's containers a clone cut short had left paused`] : [];
1427
- return [...warnings, ...await cloneInLine(worktree, main)];
1428
- });
1429
- }
1430
- async function cloneInLine(worktree, main) {
1431
- const warnings = [];
1432
- const pending = [];
1433
- const unfinished = readPending(worktree.files.clonesPending);
1434
- const copyLabel = `wt.clone=${worktree.id}`;
1435
- const stopCopies = () => {
1436
- const ids = Bun.spawnSync(["docker", "ps", "-q", "--filter", `label=${copyLabel}`]).stdout.toString().split(`
1437
- `).filter(Boolean);
1438
- if (ids.length)
1439
- Bun.spawnSync(["docker", "rm", "-f", ...ids], { stdout: "ignore", stderr: "ignore" });
1440
- };
1441
- for (const entry of worktree.project.clone ?? []) {
1442
- const source = join7(worktree.project.root, entry);
1443
- if (existsSync4(source)) {
1444
- unlinkLegacySymlink(worktree.dir, entry);
1445
- const target = join7(worktree.dir, entry);
1446
- if (existsSync4(target))
1447
- continue;
1448
- if (!statSync(source).isDirectory())
1449
- throw new WtError(`clone: ${entry} is not a directory`);
1450
- const partial = `/to/${basename2(target)}${PARTIAL}`;
1451
- pending.push({
1452
- copy: async () => {
1453
- mkdirSync3(dirname4(target), { recursive: true });
1454
- await $2`docker run --rm --label ${copyLabel} -v ${`${source}:/from:ro`} -v ${`${dirname4(target)}:/to`} alpine sh -c ${`rm -rf '${partial}' && mkdir '${partial}' && cp -a /from/. '${partial}/' && mv '${partial}' '/to/${basename2(target)}'`}`.quiet();
1455
- }
1456
- });
1457
- continue;
1458
- }
1459
- const volume = main.volumes?.[entry];
1460
- if (!volume) {
1461
- warnings.push(`clone: ${entry} is neither a path in main nor a volume of its stack`);
1462
- continue;
1463
- }
1464
- if (volume.driver_opts?.device !== undefined && volume.driver_opts.device !== "")
1465
- throw new WtError(`clone: volume ${entry} is a bind to ${volume.driver_opts.device}, list that path instead`);
1466
- const sourceVolume = volume.name ?? `${main.name}_${entry}`;
1467
- const targetVolume = `${worktree.id}_${entry}`;
1468
- if (await volumeExists(targetVolume)) {
1469
- if (!unfinished.has(targetVolume))
1470
- continue;
1471
- const removed = await $2`docker volume rm ${targetVolume}`.quiet().nothrow();
1472
- if (removed.exitCode !== 0)
1473
- throw new WtError(`clone: volume ${targetVolume} was cut short mid-copy and cannot be emptied (${removed.stderr.toString().trim()}), \`wt down ${worktree.task}\` then \`wt sync ${worktree.task}\``);
1474
- }
1475
- if (!await volumeExists(sourceVolume)) {
1476
- warnings.push(`clone: main has no volume ${sourceVolume} yet, the worktree starts with an empty one`);
1477
- continue;
1478
- }
1479
- pending.push({
1480
- volume: targetVolume,
1481
- copy: async () => {
1482
- await $2`docker volume create --label ${`com.docker.compose.project=${worktree.id}`} --label ${`com.docker.compose.volume=${entry}`} ${targetVolume}`.quiet();
1483
- await $2`docker run --rm --label ${copyLabel} -v ${`${sourceVolume}:/from:ro`} -v ${`${targetVolume}:/to`} alpine cp -a /from/. /to/`.quiet();
1484
- unfinished.delete(targetVolume);
1485
- }
1486
- });
1487
- }
1488
- if (!pending.length) {
1489
- writePending(worktree.files.clonesPending, unfinished);
1490
- return warnings;
1491
- }
1492
- for (const { volume } of pending) {
1493
- if (volume !== undefined)
1494
- unfinished.add(volume);
1495
- }
1496
- writePending(worktree.files.clonesPending, unfinished);
1497
- const failures = await whilePaused(await mainContainers(main, "running"), async () => settle(pending.map(({ copy }) => copy)), stopCopies, pausedRecord(worktree));
1498
- writePending(worktree.files.clonesPending, unfinished);
1499
- if (failures.length)
1500
- throw new WtError(`clone failed, \`wt sync ${worktree.task}\` starts it again:
1501
- ${failures.map(failureText).join(`
1502
- `)}`);
1503
- return warnings;
1504
- }
1505
-
1506
- // src/git.ts
1507
- import { existsSync as existsSync5, mkdirSync as mkdirSync4, readdirSync as readdirSync3, rmdirSync } from "fs";
1508
- import { basename as basename3, dirname as dirname5, join as join8 } from "path";
1509
- var {$: $3 } = globalThis.Bun;
1510
- async function git2(cwd, ...args) {
1511
- const result = await $3`git -C ${cwd} ${args}`.quiet().nothrow();
1512
- return { ok: result.exitCode === 0, out: `${result.stdout.toString()}${result.stderr.toString()}`.trim() };
1513
- }
1514
- async function branchExists(repo, branch) {
1515
- if ((await git2(repo, "show-ref", "--quiet", "--verify", `refs/heads/${branch}`)).ok)
1516
- return true;
1517
- return (await git2(repo, "for-each-ref", "--format=%(refname)", `refs/remotes/*/${branch}`)).out !== "";
1518
- }
1519
- async function onBranch(repo, dir, branch) {
1520
- return git2(repo, "worktree", "add", ...await branchExists(repo, branch) ? [dir, branch] : ["-b", branch, dir]);
1521
- }
1522
- async function addWorktrees(worktree, branch) {
1523
- const { project, dir } = worktree;
1524
- if (existsSync5(dir))
1525
- throw new WtError(`${dir} already exists: \`wt sync ${worktree.task} -p ${project.name}\` finishes it, \`wt rm ${worktree.task} -p ${project.name}\` removes it`);
1526
- mkdirSync4(dirname5(dir), { recursive: true });
1527
- const root = project.repos.length ? await git2(project.root, "worktree", "add", "--detach", dir) : await onBranch(project.root, dir, branch);
1528
- if (!root.ok)
1529
- throw new WtError(`git worktree add failed for the root:
1530
- ${root.out}`);
1531
- for (const repo of project.repos) {
1532
- const added = await onBranch(join8(project.root, repo), join8(dir, repo), branch);
1533
- if (!added.ok) {
1534
- await removeWorktrees(worktree);
1535
- throw new WtError(`git worktree add failed for ${repo}, rolled back:
1536
- ${added.out}`);
1537
- }
1538
- }
1539
- }
1540
- async function removeWorktrees(worktree) {
1541
- const { project, dir } = worktree;
1542
- await Promise.all(project.repos.map(async (repo) => git2(join8(project.root, repo), "worktree", "remove", "--force", join8(dir, repo))));
1543
- await git2(project.root, "worktree", "remove", "--force", dir);
1544
- if (existsSync5(dir))
1545
- await $3`docker run --rm -v ${`${dirname5(dir)}:/parent`} alpine rm -rf ${`/parent/${basename3(dir)}`}`.quiet();
1546
- await Promise.all([".", ...project.repos].map(async (repo) => git2(join8(project.root, repo), "worktree", "prune")));
1547
- if (existsSync5(dirname5(dir)) && !readdirSync3(dirname5(dir)).length)
1548
- rmdirSync(dirname5(dir));
1549
- }
1550
- async function dirtyRepos(worktree) {
1551
- const repos = [".", ...worktree.project.repos];
1552
- const statuses = await Promise.all(repos.map(async (repo) => git2(join8(worktree.dir, repo), "status", "--porcelain")));
1553
- return repos.filter((_, index) => statuses[index].ok && statuses[index].out !== "").map((repo) => repo === "." ? "root" : repo);
1554
- }
1555
- async function unreachableByRepo(dir, repos) {
1556
- const all = [".", ...repos];
1557
- const counts = await Promise.all(all.map(async (repo) => git2(join8(dir, repo), "rev-list", "--count", "HEAD", "--not", "--branches", "--remotes", "--tags")));
1558
- return all.map((repo, index) => ({ repo: repo === "." ? "root" : repo, count: Number(counts[index].ok ? counts[index].out : 0) })).filter(({ count }) => count > 0);
1559
- }
1560
- async function unreachableCommits(worktree) {
1561
- return (await unreachableByRepo(worktree.dir, worktree.project.repos)).map(({ repo, count }) => `${repo} (${count} commit${count === 1 ? "" : "s"})`);
1562
- }
1563
- async function unreachableCount(dir, repos) {
1564
- return (await unreachableByRepo(dir, repos)).reduce((total, { count }) => total + count, 0);
1565
- }
1566
- async function isRegistered(worktree) {
1567
- const listed = await git2(worktree.project.root, "worktree", "list", "--porcelain");
1568
- return listed.out.split(`
1569
- `).includes(`worktree ${worktree.dir}`);
1570
- }
1571
- async function currentBranch(dir) {
1572
- const result = await git2(dir, "rev-parse", "--abbrev-ref", "HEAD");
1573
- return result.ok ? result.out : "?";
1574
- }
1575
-
1576
- // src/routes.ts
1577
- import { existsSync as existsSync6, mkdirSync as mkdirSync5 } from "fs";
1578
- import { join as join9 } from "path";
1579
- var {$: $4 } = globalThis.Bun;
1580
- var LEADING_STAR = /^\*/;
1581
- async function mkcert(certFile, keyFile, hosts) {
1582
- const result = await $4`mkcert -cert-file ${certFile} -key-file ${keyFile} ${hosts}`.quiet().nothrow();
1583
- if (result.exitCode !== 0)
1584
- throw new WtError(`mkcert failed for ${hosts.join(" ")}:
1585
- ${result.stderr.toString()}`);
1586
- }
1587
- async function writeStackCerts(worktree) {
1588
- const { project } = worktree;
1589
- if (project.certs === undefined)
1590
- return;
1591
- const dir = join9(worktree.dir, project.certs);
1592
- mkdirSync5(dir, { recursive: true });
1593
- await Promise.all(project.routes.map(async (route) => {
1594
- const served = worktreeHost(route.host, worktree.task);
1595
- const name = served.replace(LEADING_STAR, "_wildcard");
1596
- const cert = join9(dir, `${name}.pem`);
1597
- const key = join9(dir, `${name}-key.pem`);
1598
- return existsSync6(cert) && existsSync6(key) ? undefined : mkcert(cert, key, [served]);
1599
- }));
1600
- }
1601
- function urlsOf(worktree) {
1602
- return worktree.project.routes.filter((route) => !route.host.startsWith("*.")).map((route) => `https://${worktreeHost(route.host, worktree.task)}`);
1603
- }
1604
-
1605
- // src/run.ts
1606
- import { existsSync as existsSync8, mkdirSync as mkdirSync6, readdirSync as readdirSync4, rmSync as rmSync3, writeFileSync as writeFileSync3 } from "fs";
1607
- import { userInfo } from "os";
1608
- import { join as join10 } from "path";
1609
- var {$: $5 } = globalThis.Bun;
1610
-
1611
- // src/env_file.ts
1612
- import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
1613
-
1614
- // ../env/src/dotenv.ts
1615
- var ASSIGNMENT = /^\s*(?:export\s+)?([A-Z_][\w.-]*)\s*=(.*)$/i;
1616
- var INLINE_COMMENT = /\s+#.*$/;
1617
- var CARRIAGE_RETURN = /\r$/;
1618
- var ESCAPES = { n: `
1619
- `, r: "\r", t: "\t", '"': '"', "\\": "\\", $: "$" };
1620
- function closingQuote(text, quote) {
1621
- for (let index = 0;index < text.length; index++) {
1622
- if (quote === '"' && text[index] === "\\")
1623
- index++;
1624
- else if (text[index] === quote)
1625
- return index;
1626
- }
1627
- return -1;
1628
- }
1629
- function unescapeDollar(text) {
1630
- return text.replaceAll("\\$", "$");
1631
- }
1632
- function unescapeDouble(text) {
1633
- let out = "";
1634
- for (let index = 0;index < text.length; index++) {
1635
- const next = text[index + 1];
1636
- if (text[index] === "\\" && next !== undefined && next in ESCAPES) {
1637
- out += ESCAPES[next];
1638
- index++;
1639
- } else {
1640
- out += text[index];
1641
- }
1642
- }
1643
- return out;
1644
- }
1645
- function parseDotenv(text) {
1646
- const physical = text.split(`
1647
- `);
1648
- const lines = [];
1649
- for (let index = 0;index < physical.length; index++) {
1650
- const line = physical[index] ?? "";
1651
- const match = ASSIGNMENT.exec(line.replace(CARRIAGE_RETURN, ""));
1652
- if (match === null) {
1653
- lines.push({ raw: line });
1654
- continue;
1655
- }
1656
- const [, key = "", rest = ""] = match;
1657
- const start = rest.trimStart();
1658
- const quote = start[0];
1659
- if (quote !== '"' && quote !== "'" && quote !== "`") {
1660
- lines.push({ raw: line, key, value: unescapeDollar(start.replace(INLINE_COMMENT, "").trim()) });
1661
- continue;
1662
- }
1663
- let body = start.slice(1);
1664
- let raw = line;
1665
- let end = closingQuote(body, quote);
1666
- const first = index;
1667
- while (end === -1 && index + 1 < physical.length && !ASSIGNMENT.test(physical[index + 1] ?? "")) {
1668
- index++;
1669
- body += `
1670
- ${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
1671
- raw += `
1672
- ${physical[index] ?? ""}`;
1673
- end = closingQuote(body, quote);
1674
- }
1675
- if (end === -1 && index + 1 < physical.length) {
1676
- index = first;
1677
- lines.push({ raw: line, key, value: unescapeDollar(start.replace(INLINE_COMMENT, "").trim()), unterminated: true });
1678
- continue;
1679
- }
1680
- const inner = end === -1 ? body : body.slice(0, end);
1681
- lines.push({ raw, key, value: quote === '"' ? unescapeDouble(inner) : unescapeDollar(inner) });
1682
- }
1683
- return { lines };
1684
- }
1685
- function entries(file) {
1686
- const map = new Map;
1687
- for (const line of file.lines) {
1688
- if (line.key !== undefined)
1689
- map.set(line.key, line.value ?? "");
1690
- }
1691
- return map;
1692
- }
1693
-
1694
- // src/env_file.ts
1695
- function readEnvFile(path) {
1696
- return existsSync7(path) ? Object.fromEntries(entries(parseDotenv(readFileSync7(path, "utf8")))) : {};
1697
- }
1698
-
1699
- // src/run.ts
1700
- var POSTGRES = /^postgres(?:ql)?:$/;
1701
- var DEFAULT_PORT = 5432;
1702
- var READY_TRIES = 60;
1703
- var testContainer = (worktree) => `wt-${worktree.project.name}-test-db`;
1704
- function testDatabase(dir) {
1705
- const base = existsSync8(join10(dir, ".env")) ? ".env" : ".env.dist";
1706
- const env = Object.assign({}, ...[base, ".env.test", ".env.test.local"].map((file) => readEnvFile(join10(dir, file))));
1707
- if (env.DATABASE_URL === undefined || env.DATABASE_URL === "")
1708
- throw new WtError(`no DATABASE_URL in the test env files of ${dir}`);
1709
- const url = new URL(env.DATABASE_URL);
1710
- if (!POSTGRES.test(url.protocol))
1711
- throw new WtError(`wt run only starts Postgres, and ${dir} tests against ${url.protocol.slice(0, -1)}`);
1712
- return { host: url.hostname, port: Number(url.port || DEFAULT_PORT), user: decodeURIComponent(url.username), password: decodeURIComponent(url.password) };
1713
- }
1714
- function testToken(task) {
1715
- return task.replaceAll("-", "_");
1716
- }
1717
- function databaseImage(config, host) {
1718
- const service = config.services[host] ?? Object.values(config.services).find((each) => Object.values(each.networks ?? {}).some((network) => network?.aliases?.includes(host)));
1719
- if (service?.image === undefined || service.image === "")
1720
- throw new WtError(`no service of ${config.name} answers to ${host}, the test database host, with an image to start`);
1721
- return service.image;
1722
- }
1723
- function runPlan(worktree, run, config, database, ids = userInfo(), tty = false) {
1724
- const service = config.services[run.service];
1725
- if (!service)
1726
- throw new WtError(`${config.name} has no service ${run.service}`);
1727
- const source = join10(worktree.project.root, run.dir);
1728
- const target = service.volumes?.find((volume) => volume.type === "bind" && volume.source === source)?.target;
1729
- if (target === undefined)
1730
- throw new WtError(`${run.service} does not bind-mount ${source}, so wt cannot tell where the worktree's copy goes`);
1731
- const network = `wt-${worktree.project.name}-test`;
1732
- const container = testContainer(worktree);
1733
- return {
1734
- network,
1735
- container,
1736
- database: [
1737
- "run",
1738
- "-d",
1739
- "--name",
1740
- container,
1741
- "--network",
1742
- network,
1743
- "--network-alias",
1744
- database.host,
1745
- "--tmpfs",
1746
- "/var/lib/postgresql/data",
1747
- "-e",
1748
- `POSTGRES_USER=${database.user}`,
1749
- "-e",
1750
- "POSTGRES_PASSWORD",
1751
- "-e",
1752
- `PGPORT=${database.port}`,
1753
- databaseImage(config, database.host)
1754
- ],
1755
- runner: (command) => [
1756
- "run",
1757
- "--rm",
1758
- "-i",
1759
- ...tty ? ["-t"] : [],
1760
- "--pull",
1761
- "never",
1762
- "--network",
1763
- network,
1764
- ...run.dns !== undefined ? ["--dns", run.dns] : [],
1765
- "-u",
1766
- `${ids.uid}:${ids.gid}`,
1767
- "-e",
1768
- "HOME=/tmp",
1769
- ...Object.entries(run.env ?? {}).flatMap(([key, value]) => ["-e", `${key}=${value}`]),
1770
- "-e",
1771
- `TEST_TOKEN=${testToken(worktree.task)}`,
1772
- "-v",
1773
- `${join10(worktree.dir, run.dir)}:${target}`,
1774
- "-w",
1775
- target,
1776
- service.image ?? `${config.name}-${run.service}`,
1777
- ...command
1778
- ]
1779
- };
1780
- }
1781
- async function runningId(container) {
1782
- const result = await $5`docker inspect --format ${"{{if .State.Running}}{{.Id}}{{end}}"} ${container}`.quiet().nothrow();
1783
- return result.text().trim() || undefined;
1784
- }
1785
- async function ensureDatabase(plan, database) {
1786
- if ((await $5`docker network inspect ${plan.network}`.quiet().nothrow()).exitCode !== 0)
1787
- await $5`docker network create ${plan.network}`.quiet().nothrow();
1788
- let id = await runningId(plan.container);
1789
- if (id === undefined) {
1790
- await $5`docker rm -f ${plan.container}`.quiet().nothrow();
1791
- const started = await $5`docker ${plan.database}`.env({ ...process.env, POSTGRES_PASSWORD: database.password }).quiet().nothrow();
1792
- id = await runningId(plan.container);
1793
- if (id === undefined)
1794
- throw new WtError(`${plan.container} did not start:
1795
- ${started.stderr.toString().trim()}`);
1796
- }
1797
- for (let tries = 0;tries < READY_TRIES; tries++) {
1798
- if ((await $5`docker exec ${plan.container} pg_isready -q -h 127.0.0.1 -U ${database.user}`.quiet().nothrow()).exitCode === 0)
1799
- return id;
1800
- await Bun.sleep(1000);
1801
- }
1802
- throw new WtError(`${plan.container} is not accepting connections after ${READY_TRIES} s: docker logs ${plan.container}`);
1803
- }
1804
- async function runInherit(command) {
1805
- const child = Bun.spawn(command, { stdio: ["inherit", "inherit", "inherit"] });
1806
- const forward = (signal) => child.kill(signal);
1807
- process.on("SIGINT", forward);
1808
- process.on("SIGTERM", forward);
1809
- try {
1810
- return await child.exited;
1811
- } finally {
1812
- process.off("SIGINT", forward);
1813
- process.off("SIGTERM", forward);
1814
- }
1815
- }
1816
- async function forgetTestDatabases(worktree) {
1817
- const container = testContainer(worktree);
1818
- if (await runningId(container) !== undefined) {
1819
- const listed = await $5`docker exec ${container} sh -c ${'psql -U "$POSTGRES_USER" -d postgres -Atc "select datname from pg_database"'}`.quiet().nothrow();
1820
- const ours = listed.text().split(`
1821
- `).filter((name) => name.endsWith(`_test${testToken(worktree.task)}`));
1822
- for (const name of ours)
1823
- await $5`docker exec ${container} sh -c ${'dropdb -U "$POSTGRES_USER" --force "$0"'} ${name}`.quiet().nothrow();
1824
- }
1825
- const markers = worktree.project.settings.state;
1826
- if (!existsSync8(markers))
1827
- return;
1828
- for (const file of readdirSync4(markers).filter((name) => name.startsWith(`${worktree.id}.test-`)))
1829
- rmSync3(join10(markers, file), { force: true });
1830
- }
1831
- async function provision(worktree, run, plan, databaseId) {
1832
- const markers = worktree.project.settings.state;
1833
- const marker = join10(markers, `${worktree.id}.test-${databaseId.slice(0, 12)}`);
1834
- if (existsSync8(marker))
1835
- return;
1836
- 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 () => {
1837
- if (existsSync8(marker))
1838
- return;
1839
- console.error(`wt run: provisioning ${worktree.task}'s test database`);
1840
- for (const step of run.provision) {
1841
- if (await runInherit(["docker", ...plan.runner(["sh", "-c", step])]) !== 0)
1842
- throw new WtError(`provisioning failed on \`${step}\`, run it again with \`wt run ${worktree.task} -- sh -c '${step}'\``);
1843
- }
1844
- mkdirSync6(markers, { recursive: true });
1845
- writeFileSync3(marker, "");
1846
- });
1847
- }
1848
- async function runTask(task, command, project) {
1849
- const worktree = await locateWorktree(process.cwd(), task, project);
1850
- const { run, name, root } = worktree.project;
1851
- assertWorktreeExists(worktree);
1852
- if (!run)
1853
- throw new WtError(`${name} has no \`run\` in its manifest, so wt cannot tell which service runs its tests`);
1854
- const database = testDatabase(join10(worktree.dir, run.dir));
1855
- const plan = runPlan(worktree, run, await composeConfig(root), database, userInfo(), Boolean(process.stdin.isTTY && process.stdout.isTTY));
1856
- await provision(worktree, run, plan, await ensureDatabase(plan, database));
1857
- return runInherit(["docker", ...plan.runner(command)]);
1858
- }
1859
- async function runHeavy(command) {
1860
- const label = `${command.join(" ")} (in ${process.cwd()})`;
1861
- return inLine(queueDir(await wtConfig(), "heavy"), label, (ahead, running) => console.error(`wt heavy: ${ahead} ahead, running ${running}`), async () => runInherit(command));
1862
- }
1863
-
1864
- // src/stack.ts
1865
- import { existsSync as existsSync9, mkdirSync as mkdirSync7, writeFileSync as writeFileSync4 } from "fs";
1866
- import { homedir as homedir3 } from "os";
1867
- import { dirname as dirname7 } from "path";
1868
- var {$: $7 } = globalThis.Bun;
1869
-
1870
- // src/proxy.ts
1871
- import { dirname as dirname6, join as join11 } from "path";
1872
- var {$: $6 } = globalThis.Bun;
1873
- function devproxyArgv() {
1874
- const onPath = Bun.which("devproxy");
1875
- if (onPath !== null)
1876
- return [onPath];
1877
- try {
1878
- return [process.execPath, join11(dirname6(Bun.resolveSync("@kaynooo/devproxy", import.meta.dir)), "..", "dist", "cli.js")];
1879
- } catch {
1880
- return [];
1881
- }
1882
- }
1883
- async function hasDevproxy() {
1884
- const argv = devproxyArgv();
1885
- return argv.length > 0 && (await $6`${argv} hosts --json`.quiet().nothrow()).exitCode === 0;
1886
- }
1887
- async function proxyHostList() {
1888
- const argv = devproxyArgv();
1889
- const result = argv.length ? await $6`${argv} hosts --json`.quiet().nothrow() : undefined;
1890
- return result?.exitCode === 0 ? JSON.parse(result.stdout.toString()) : [];
1891
- }
1892
- async function devproxyUp() {
1893
- const argv = devproxyArgv();
1894
- if (!argv.length || (await $6`${argv} up`.nothrow()).exitCode !== 0)
1895
- throw new WtError("the shared proxy did not come up: `devproxy status` says why");
1896
- }
1897
-
1898
- // src/stack.ts
1899
- var LEADING_ROOT = /^[/~]+/;
1900
- var UNSAFE_IN_FILE_NAME = /[^\w.-]+/g;
1901
- function slugOf(ref) {
1902
- return ref.replace(LEADING_ROOT, "").replace(UNSAFE_IN_FILE_NAME, "--");
1903
- }
1904
- async function spawnInherit(argv, cwd, env = process.env) {
1905
- return Bun.spawn(argv, { cwd, env, stdio: ["inherit", "inherit", "inherit"] }).exited;
1906
- }
1907
- async function spawnRunner(role, argv, cwd) {
1908
- try {
1909
- return await spawnInherit(argv, cwd);
1910
- } catch (error) {
1911
- if (error.code === "ENOENT")
1912
- throw new WtError(`\`${argv[0]}\` is not on PATH: fix runner.${role} in ${configPath()}`);
1913
- throw error;
1914
- }
1915
- }
1916
- var argvOf = (template, worktree) => fillTemplate(template, { project: worktree.project.name, task: worktree.task, dir: worktree.dir, id: worktree.id });
1917
- async function runTemplate(role, template, worktree) {
1918
- const argv = argvOf(template, worktree);
1919
- if (await spawnRunner(role, argv, worktree.dir) !== 0)
1920
- throw new WtError(`\`${argv.join(" ")}\` failed`);
1921
- }
1922
- async function runSetup(worktree, env = composeEnv()) {
1923
- const setup = worktree.project.setup ?? [];
1924
- const marker = worktree.files.setupMarker;
1925
- if (!setup.length || existsSync9(marker))
1926
- return;
1927
- for (const command of setup) {
1928
- if (await spawnInherit(["sh", "-c", command], worktree.dir, env) !== 0)
1929
- throw new WtError(`the worktree setup failed on \`${command}\``);
1930
- }
1931
- mkdirSync7(dirname7(marker), { recursive: true });
1932
- writeFileSync4(marker, "");
1933
- }
1934
- async function stackUp(worktree) {
1935
- const { up } = worktree.project.settings.runner;
1936
- if (up)
1937
- return runTemplate("up", up, worktree);
1938
- if (await hasDevproxy())
1939
- await devproxyUp();
1940
- const network = worktree.project.settings.proxyNetwork;
1941
- if (worktree.project.routes.length > 0 && (await $7`docker network inspect ${network}`.quiet().nothrow()).exitCode !== 0)
1942
- 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`);
1943
- if (await spawnInherit(["docker", "compose", "up", "-d", "--build"], worktree.dir, composeEnv()) !== 0)
1944
- throw new WtError(`docker compose up failed in ${worktree.dir}`);
1945
- await runSetup(worktree);
1946
- }
1947
- async function stackDown(worktree) {
1948
- const { down } = worktree.project.settings.runner;
1949
- if (down && existsSync9(worktree.dir))
1950
- return runTemplate("down", down, worktree);
1951
- const here = existsSync9(worktree.dir);
1952
- const argv = here ? ["docker", "compose", "down", "--remove-orphans"] : ["docker", "compose", "-p", worktree.id, "down", "--remove-orphans"];
1953
- if (await spawnInherit(argv, here ? worktree.dir : homedir3(), composeEnv()) !== 0)
1954
- throw new WtError(`docker compose down failed for ${worktree.id}`);
1955
- }
1956
- async function afterRemove(worktree) {
1957
- const { removed } = worktree.project.settings.runner;
1958
- if (!removed)
1959
- return;
1960
- const argv = argvOf(removed, worktree);
1961
- try {
1962
- if (await spawnRunner("removed", argv, worktree.project.root) !== 0)
1963
- console.warn(`wt: \`${argv.join(" ")}\` failed after removing ${worktree.id}`);
1964
- } catch (error) {
1965
- if (!(error instanceof WtError))
1966
- throw error;
1967
- console.warn(`wt: ${error.message}, after removing ${worktree.id}`);
1968
- }
1969
- }
1970
- async function hasContainers(composeName) {
1971
- const found = await $7`docker ps -aq --filter ${`label=com.docker.compose.project=${composeName}`}`.quiet().nothrow();
1972
- return found.stdout.toString().trim() !== "";
1973
- }
1974
-
1975
- // src/sync.ts
1976
- async function syncWorktree(worktree) {
1977
- assertWorktreeExists(worktree);
1978
- const [warnings, main] = await Promise.all([copyFromMain(worktree), composeConfig(worktree.project.root)]);
1979
- linkFromMain(worktree);
1980
- writeEnvFiles(worktree);
1981
- warnings.push(...await cloneData(worktree, main));
1982
- const config = await composeConfig(worktree.dir, { COMPOSE_FILE: baseComposeFiles(worktree.dir, worktree.project.settings.overrides).join(":"), COMPOSE_PROJECT_NAME: worktree.id });
1983
- writeIfChanged(worktree.files.override, renderOverride(worktree, config));
1984
- warnings.push(...overrideWarnings(worktree, config));
1985
- await composeConfig(worktree.dir);
1986
- await writeStackCerts(worktree);
1987
- for (const warning of warnings)
1988
- console.warn(`wt: ${warning}`);
1989
- }
1990
-
1991
- // src/commands.ts
1992
- var ANONYMOUS_VOLUME = /^[0-9a-f]{64}$/;
1993
- var WHITESPACE = /\s+/;
1994
- async function anonymousVolumes(worktree) {
1995
- const containers = (await $8`docker ps -aq --filter ${`label=com.docker.compose.project=${worktree.id}`}`.quiet().text()).split(`
1996
- `).filter(Boolean);
1997
- if (!containers.length)
1998
- return [];
1999
- const mounts = await $8`docker inspect --format ${'{{range .Mounts}}{{if eq .Type "volume"}}{{.Name}} {{end}}{{end}}'} ${containers}`.quiet().nothrow();
2000
- return mounts.text().split(WHITESPACE).filter((name) => ANONYMOUS_VOLUME.test(name));
2001
- }
2002
- async function removeVolumes(worktree, anonymous) {
2003
- const named = (await $8`docker volume ls -q --filter ${`label=com.docker.compose.project=${worktree.id}`}`.quiet().text()).split(`
2004
- `).filter((volume) => volume.startsWith(`${worktree.id}_`));
2005
- const volumes = [...new Set([...named, ...anonymous])];
2006
- if (!volumes.length)
2007
- return;
2008
- const removed = await $8`docker volume rm ${volumes}`.quiet().nothrow();
2009
- if (removed.exitCode !== 0)
2010
- throw new WtError(`could not remove the volumes of ${worktree.id}:
2011
- ${removed.stderr.toString().trim()}`);
2012
- }
2013
- async function addTask(task, branch, options) {
2014
- const { project } = await locate(process.cwd(), options.project);
2015
- const worktree = worktreeOf(project, task);
2016
- const checkout = branch ?? `wt/${task}`;
2017
- await addWorktrees(worktree, checkout);
2018
- try {
2019
- await syncWorktree(worktree);
2020
- } catch (error) {
2021
- const way = `the worktree is checked out but not ready: \`wt sync ${task} -p ${project.name}\` resumes it, \`wt rm ${task} -p ${project.name}\` removes it`;
2022
- if (error instanceof KnownError || error instanceof $8.ShellError)
2023
- throw new WtError(`${failureText(error)}
2024
- ${way}`);
2025
- console.error(`wt: ${way}`);
2026
- throw error;
2027
- }
2028
- console.log(`wt: created ${worktree.dir} on ${checkout}`);
2029
- for (const url of urlsOf(worktree))
2030
- console.log(` ${url}`);
2031
- console.log(` wt up ${task}`);
2032
- }
2033
- async function syncTask(task, options) {
2034
- const worktree = await locateWorktree(process.cwd(), task, options.project);
2035
- await syncWorktree(worktree);
2036
- console.log(`wt: synced ${worktree.id}`);
2037
- }
2038
- async function refuseLosingWork(worktree, force) {
2039
- if (force || !existsSync10(worktree.dir))
2040
- return;
2041
- const dirty = await dirtyRepos(worktree);
2042
- if (dirty.length)
2043
- throw new WtError(`uncommitted changes in ${dirty.join(", ")}, commit them or pass --force`);
2044
- const unreachable = await unreachableCommits(worktree);
2045
- if (unreachable.length)
2046
- throw new WtError(`commits on no branch in ${unreachable.join(", ")} would be lost, \`git switch -c <branch>\` there or pass --force`);
2047
- }
2048
- async function assertRemovable(task, options) {
2049
- const worktree = await locateWorktree(process.cwd(), task, options.project);
2050
- if (!existsSync10(worktree.dir) && !Object.values(worktree.files).some((file) => existsSync10(file)) && !await isRegistered(worktree))
2051
- throw new WtError(`no worktree ${worktree.task} of ${worktree.project.name}, nothing removed`);
2052
- await refuseLosingWork(worktree, options.force === true);
2053
- }
2054
- async function removeTask(task, options) {
2055
- const worktree = await locateWorktree(process.cwd(), task, options.project);
2056
- process.chdir(worktree.project.root);
2057
- const anonymous = await anonymousVolumes(worktree);
2058
- await refuseLosingWork(worktree, options.force === true);
2059
- if (existsSync10(worktree.dir) || await hasContainers(worktree.id))
2060
- await stackDown(worktree);
2061
- await removeVolumes(worktree, anonymous);
2062
- for (const file of Object.values(worktree.files))
2063
- rmSync4(file, { force: true });
2064
- await forgetTestDatabases(worktree);
2065
- await removeWorktrees(worktree);
2066
- await afterRemove(worktree);
2067
- console.log(`wt: removed ${worktree.id}, its branches are kept`);
2068
- }
2069
- async function printUrls(task, options) {
2070
- for (const url of urlsOf(await locateWorktree(process.cwd(), task, options.project)))
2071
- console.log(url);
2072
- }
2073
- async function upTask(worktree) {
2074
- assertWorktreeExists(worktree);
2075
- await stackUp(worktree);
2076
- }
2077
- async function downTask(worktree) {
2078
- assertWorktreeExists(worktree);
2079
- await stackDown(worktree);
2080
- }
2081
- async function printPath(task, options) {
2082
- const { project } = await locate(process.cwd(), options.project);
2083
- if (task === undefined || task === "main")
2084
- return console.log(project.root);
2085
- const worktree = worktreeOf(project, task);
2086
- assertWorktreeExists(worktree);
2087
- console.log(worktree.dir);
2088
- }
2089
- async function printTasks(options) {
2090
- try {
2091
- console.log(listTasks((await locate(process.cwd(), options.project)).project).join(`
2092
- `));
2093
- } catch {}
2094
- }
2095
-
2096
- // src/init.ts
2097
- import { existsSync as existsSync11, mkdirSync as mkdirSync8, readdirSync as readdirSync5, statSync as statSync2, writeFileSync as writeFileSync5 } from "fs";
2098
- import { homedir as homedir4 } from "os";
2099
- import { basename as basename4, join as join12, relative } from "path";
2100
- var CERT_PATH = /cert/i;
2101
- var HTTP_TARGET = /^(?:https?:\/\/)?([\w.-]+):(\d+)$/;
2102
- var PASSTHROUGH_TARGET = /^([\w.-]+):(\d+)$/;
2103
- async function ignoredPaths(repo, paths) {
2104
- if (!paths.length)
2105
- return [];
2106
- const matched = new Set((await git2(repo, "check-ignore", ...paths)).out.split(`
2107
- `));
2108
- return paths.filter((path) => matched.has(path));
2109
- }
2110
- function mountedPaths(config) {
2111
- const binds = Object.values(config.services).flatMap((service) => (service.volumes ?? []).filter((v) => v.type === "bind").map((v) => v.source));
2112
- const devices = Object.values(config.volumes ?? {}).flatMap((volume) => volume.driver_opts?.device ?? []);
2113
- return [...new Set([...binds, ...devices])];
2114
- }
2115
- async function findRoutes(config, name, network) {
2116
- const serviceOf = (target) => Object.entries(config.services).find(([service, settings]) => settings.container_name === target || `${config.name}-${service}-1` === target || settings.networks?.[network]?.aliases?.includes(target))?.[0];
2117
- const routes = [];
2118
- for (const { host, to, passthrough } of await proxyHostList()) {
2119
- const [, target = "", port = ""] = (passthrough ? PASSTHROUGH_TARGET : HTTP_TARGET).exec(to) ?? [];
2120
- const service = serviceOf(target);
2121
- if (target === "host" && Number(port) === stringToPort(name))
2122
- routes.push({ host, to: "client" });
2123
- else if (service !== undefined)
2124
- routes.push({ host, to: `${service}:${Number(port)}`, ...passthrough ? { passthrough } : {} });
2125
- }
2126
- return routes;
2127
- }
2128
- async function secretsToCopy(root, repos) {
2129
- const perBase = await Promise.all([".", ...repos].map(async (base) => {
2130
- const envFiles = readdirSync5(join12(root, base)).filter((entry) => (entry.startsWith(".env") || entry === ".nuxtrc") && statSync2(join12(root, base, entry)).isFile());
2131
- const jwt = base !== "." && existsSync11(join12(root, base, "config", "jwt")) ? [join12(base, "config", "jwt")] : [];
2132
- return [...(await ignoredPaths(join12(root, base), envFiles)).map((entry) => join12(base, entry)), ...jwt];
2133
- }));
2134
- return perBase.flat();
2135
- }
2136
- async function draftFor(dir, given) {
2137
- const top = await git2(dir, "rev-parse", "--show-toplevel");
2138
- if (!top.ok)
2139
- throw new WtError(`${dir} is not inside a git repository`);
2140
- const root = top.out;
2141
- const config = await composeConfig(root);
2142
- const name = given ?? basename4(root);
2143
- const mounted = mountedPaths(config).filter((path) => path.startsWith(`${root}/`)).map((path) => relative(root, path));
2144
- const repos = readdirSync5(root).filter((entry) => existsSync11(join12(root, entry, ".git")) && mounted.some((path) => path === entry || path.startsWith(`${entry}/`)));
2145
- const inRepo = (path) => repos.some((repo) => path === repo || path.startsWith(`${repo}/`));
2146
- const volumes = Object.entries(config.volumes ?? {}).filter(([, volume]) => (volume.driver_opts?.device ?? "") === "");
2147
- const [secrets, ignoredMounts, volumesExist] = await Promise.all([
2148
- secretsToCopy(root, repos),
2149
- ignoredPaths(root, mounted.filter((path) => !inRepo(path) && existsSync11(join12(root, path)))),
2150
- Promise.all(volumes.map(async ([key, volume]) => volumeExists(volume.name ?? `${config.name}_${key}`)))
2151
- ]);
2152
- const routes = await findRoutes(config, name, (await wtConfig()).proxyNetwork);
2153
- const certs = routes.some((route) => route.passthrough) ? mounted.find((path) => CERT_PATH.test(path)) : undefined;
2154
- return {
2155
- name,
2156
- root: root.replace(homedir4(), "~"),
2157
- repos,
2158
- copy: [...secrets, ...ignoredMounts.filter((path) => CERT_PATH.test(path))],
2159
- clone: [...ignoredMounts.filter((path) => !CERT_PATH.test(path)), ...volumes.filter((_, index) => volumesExist[index]).map(([key]) => key)],
2160
- skip: Object.entries(config.services).filter(([, service]) => service.network_mode === "host").map(([service]) => service),
2161
- ...certs !== undefined && { certs },
2162
- routes
2163
- };
2164
- }
2165
- var list = (values) => `[${values.map((value) => `'${value}'`).join(", ")}]`;
2166
- function render(draft) {
2167
- const routes = draft.routes.map((route) => ` { host: '${route.host}', to: '${route.to}'${route.passthrough ? ", passthrough: true" : ""} },`);
2168
- return [
2169
- `import type { ProjectConfig } from '@kaynooo/cli-wt'`,
2170
- "",
2171
- "// Drafted by `wt init`: check every list against the stack before the first `wt add`.",
2172
- "export default {",
2173
- ` root: '${draft.root}',`,
2174
- ` repos: ${list(draft.repos)},`,
2175
- ` copy: ${list(draft.copy)},`,
2176
- ` clone: ${list(draft.clone)},`,
2177
- ...draft.skip.length ? [` skip: ${list(draft.skip)},`] : [],
2178
- ...draft.certs !== undefined ? [` certs: '${draft.certs}',`] : [],
2179
- " setup: [],",
2180
- " routes: [",
2181
- ...routes,
2182
- " ],",
2183
- "} satisfies ProjectConfig",
2184
- ""
2185
- ].join(`
2186
- `);
2187
- }
2188
- async function initProject(dir, options) {
2189
- const draft = await draftFor(dir, options.name);
2190
- const content = render(draft);
2191
- if (options.print)
2192
- return console.log(content);
2193
- const { manifests } = await wtConfig();
2194
- const file = join12(manifests, `${draft.name}.ts`);
2195
- mkdirSync8(manifests, { recursive: true });
2196
- if (existsSync11(file))
2197
- throw new WtError(`${file} already exists, compare with \`wt init --print\``);
2198
- writeFileSync5(file, content);
2199
- console.log(`wt: drafted ${file}, review it before \`wt add\``);
2200
- }
2201
-
2202
- // src/jobs.ts
2203
- import { closeSync, fstatSync, mkdirSync as mkdirSync9, openSync, readdirSync as readdirSync6, readFileSync as readFileSync8, readSync, renameSync as renameSync2, rmSync as rmSync5, statSync as statSync3, writeFileSync as writeFileSync6 } from "fs";
2204
- import { join as join13 } from "path";
2205
- var {$: $9 } = globalThis.Bun;
2206
- var HELD_ENV = "WT_JOBS_HELD";
2207
- var STARTING_MS = 30000;
2208
- var TAKEOVER_MS = 5000;
2209
- var TAIL_BYTES = 4096;
2210
- var DOING = { up: "coming up", down: "stopping", add: "being made", sync: "syncing", rm: "being removed" };
2211
- var DONE = { up: ["is up", "Its stack came up"], add: ["is ready", "The worktree is made, its stack still down"] };
2212
- function writeJob(file, job) {
2213
- const partial = `${file}.${process.pid}.tmp`;
2214
- writeFileSync6(partial, JSON.stringify(job));
2215
- renameSync2(partial, file);
2216
- }
2217
- function readJob(file) {
2218
- try {
2219
- return JSON.parse(readFileSync8(file, "utf8"));
2220
- } catch {
2221
- return;
2222
- }
2223
- }
2224
- function doing(table, job) {
2225
- const words = job === undefined ? "busy" : table[job.verb] ?? `busy with ${job.verb}`;
2226
- return job?.service !== undefined ? `${words} ${job.service}` : words;
2227
- }
2228
- function held(lock, now = Date.now()) {
2229
- try {
2230
- const pid = Number(readFileSync8(lock, "utf8").trim());
2231
- const writtenAt = statSync3(lock, { throwIfNoEntry: false })?.mtimeMs ?? 0;
2232
- if (writtenAt < bootTime())
2233
- return false;
2234
- return pid ? alive(pid) : now - writtenAt < STARTING_MS;
2235
- } catch {
2236
- return false;
2237
- }
2238
- }
2239
- function takeOver(lock) {
2240
- const guard = `${lock}.takeover`;
34
+ import process from "process";
35
+ var commands = async () => import("./commands-jtnbchtb.js");
36
+ var printing = async () => import("./print-q6qaqg22.js");
37
+ var APP = "wt";
38
+ var jobs = wtJobs;
39
+ async function guarded(action, bg) {
40
+ let built;
2241
41
  try {
2242
- writeFileSync6(guard, "", { flag: "wx" });
42
+ built = await jobs();
2243
43
  } catch (error) {
2244
- if (error.code !== "EEXIST")
2245
- throw error;
2246
- if (Date.now() - (statSync3(guard, { throwIfNoEntry: false })?.mtimeMs ?? 0) < TAKEOVER_MS)
2247
- return false;
2248
- rmSync5(guard, { force: true });
2249
- return takeOver(lock);
2250
- }
2251
- try {
2252
- if (!held(lock))
2253
- rmSync5(lock, { force: true });
2254
- return true;
2255
- } finally {
2256
- rmSync5(guard, { force: true });
44
+ if (bg !== undefined)
45
+ await notifyRefused(APP, bg, failureText(error));
46
+ return failKnown(error);
2257
47
  }
48
+ return built.guarded(action, bg);
2258
49
  }
2259
- var heldHere = () => (process.env[HELD_ENV] ?? "").split(`
2260
- `).filter(Boolean);
2261
- var heldEntry = (lock) => `${process.pid} ${lock}`;
2262
- function stillHeldBy(entry) {
2263
- const space = entry.indexOf(" ");
2264
- const lock = entry.slice(space + 1);
2265
- try {
2266
- return readFileSync8(lock, "utf8").trim() === entry.slice(0, space) && held(lock);
2267
- } catch {
2268
- return false;
2269
- }
50
+ function bgName(values, ...words) {
51
+ return values.bg ? [APP, ...words.filter((word) => word !== undefined)].join(" ") : undefined;
2270
52
  }
2271
- function logTail(file, lines = 5) {
53
+ async function projectNames() {
2272
54
  try {
2273
- const fd = openSync(file, "r");
2274
- try {
2275
- const size = fstatSync(fd).size;
2276
- const buffer = Buffer.alloc(Math.min(size, TAIL_BYTES));
2277
- readSync(fd, buffer, 0, buffer.length, size - buffer.length);
2278
- return buffer.toString("utf8").trim().split(`
2279
- `).slice(-lines).join(`
2280
- `);
2281
- } finally {
2282
- closeSync(fd);
2283
- }
2284
- } catch {
2285
- return "";
2286
- }
2287
- }
2288
- async function notify(app, title, body, critical = false) {
2289
- if (Bun.which("notify-send") !== null)
2290
- await $9`notify-send -a ${app} ${critical ? ["-u", "critical"] : []} ${title} ${body}`.quiet().nothrow();
2291
- }
2292
-
2293
- class Jobs {
2294
- dir;
2295
- app;
2296
- env;
2297
- doing;
2298
- done;
2299
- constructor({ dir, app, words = {} }) {
2300
- this.dir = dir;
2301
- this.app = app;
2302
- this.env = `${app.toUpperCase()}_JOB`;
2303
- this.doing = { ...DOING, ...words.doing };
2304
- this.done = { ...DONE, ...words.done };
2305
- }
2306
- paths(slug) {
2307
- return { job: join13(this.dir, `${slug}.json`), lock: join13(this.dir, `${slug}.lock`), log: join13(this.dir, `${slug}.log`) };
2308
- }
2309
- holds(stack) {
2310
- const { lock } = this.paths(stack.slug);
2311
- return heldHere().some((entry) => entry.endsWith(` ${lock}`) && stillHeldBy(entry));
2312
- }
2313
- claim(stack, verb, detached, service) {
2314
- const { job: jobFile, lock, log } = this.paths(stack.slug);
2315
- mkdirSync9(this.dir, { recursive: true });
2316
- for (let attempt = 0;; attempt++) {
2317
- try {
2318
- writeFileSync6(lock, detached ? "" : String(process.pid), { flag: "wx" });
2319
- break;
2320
- } catch (error) {
2321
- if (error.code !== "EEXIST")
2322
- throw error;
2323
- if (attempt > 0 || held(lock) || !takeOver(lock)) {
2324
- const running = readJob(jobFile);
2325
- throw new KnownError(`${stack.ref} is already ${doing(this.doing, running)}${running !== undefined && running.log !== "" ? `, see ${running.log}` : ""}`);
2326
- }
2327
- }
2328
- }
2329
- const job = { ref: stack.ref, verb, ...service !== undefined && { service }, pid: detached ? null : process.pid, startedAt: Date.now(), log: detached ? log : "" };
2330
- writeJob(jobFile, job);
2331
- return job;
2332
- }
2333
- adopt(stack) {
2334
- const { job: jobFile, lock } = this.paths(stack.slug);
2335
- const job = readJob(jobFile);
2336
- if (!job)
2337
- throw new KnownError(`no job claimed for ${stack.slug}`);
2338
- job.pid = process.pid;
2339
- writeFileSync6(lock, String(process.pid));
2340
- writeJob(jobFile, job);
2341
- return job;
2342
- }
2343
- finish(stack, job, code) {
2344
- const { job: jobFile, lock } = this.paths(stack.slug);
2345
- writeJob(jobFile, { ...job, endedAt: Date.now(), code });
2346
- rmSync5(lock, { force: true });
2347
- }
2348
- states() {
2349
- const states = new Map;
2350
- let files;
2351
- try {
2352
- files = readdirSync6(this.dir).filter((file) => file.endsWith(".json"));
2353
- } catch {
2354
- return states;
2355
- }
2356
- for (const file of files) {
2357
- const slug = file.slice(0, -".json".length);
2358
- const job = readJob(join13(this.dir, file));
2359
- if (!job)
2360
- continue;
2361
- if (job.endedAt !== undefined)
2362
- states.set(slug, { last: job });
2363
- else if (held(this.paths(slug).lock))
2364
- states.set(slug, { running: job });
2365
- else
2366
- states.set(slug, { last: { ...job, code: null, endedAt: statSync3(join13(this.dir, file), { throwIfNoEntry: false })?.mtimeMs ?? job.startedAt } });
2367
- }
2368
- return states;
2369
- }
2370
- forget(stack) {
2371
- for (const file of Object.values(this.paths(stack.slug)))
2372
- rmSync5(file, { force: true });
2373
- }
2374
- async run(stack, verb, work, service) {
2375
- if (this.holds(stack))
2376
- return attempt(async () => work(false));
2377
- const detached = process.env[this.env] === stack.slug;
2378
- const job = detached ? this.adopt(stack) : this.claim(stack, verb, false, service);
2379
- const before = process.env[HELD_ENV];
2380
- delete process.env[this.env];
2381
- process.env[HELD_ENV] = [...heldHere(), heldEntry(this.paths(stack.slug).lock)].join(`
2382
- `);
2383
- let code = 1;
2384
- try {
2385
- code = await attempt(async () => work(detached));
2386
- } finally {
2387
- if (before === undefined)
2388
- delete process.env[HELD_ENV];
2389
- else
2390
- process.env[HELD_ENV] = before;
2391
- this.finish(stack, job, code);
2392
- }
2393
- if (detached)
2394
- await this.notifyEnd(stack, job, code);
2395
- return code;
2396
- }
2397
- async failDetached(message) {
2398
- const slug = process.env[this.env];
2399
- if (slug === undefined || slug === "")
55
+ return (await loadProjects(() => {
2400
56
  return;
2401
- delete process.env[this.env];
2402
- const job = readJob(this.paths(slug).job);
2403
- if (!job || job.endedAt !== undefined)
2404
- return;
2405
- this.finish({ slug }, job, 1);
2406
- await notify(this.app, `${this.what(job)} failed`, message, true);
2407
- }
2408
- async guarded(action, bg) {
2409
- try {
2410
- return await action() ?? 0;
2411
- } catch (error) {
2412
- const message = error instanceof Error ? error.message : String(error);
2413
- await this.failDetached(message);
2414
- if (bg !== undefined)
2415
- await this.notifyRefused(bg, message);
2416
- return failKnown(error);
2417
- }
2418
- }
2419
- async notifyRefused(what, message) {
2420
- await notify(this.app, `${what} not started`, message, true);
2421
- }
2422
- detach(stack, verb, argv, service) {
2423
- const job = this.claim(stack, verb, true, service);
2424
- const out = openSync(job.log, "w");
2425
- try {
2426
- Bun.spawn([process.execPath, "--no-env-file", ...argv], { stdio: ["ignore", out, out], env: { ...process.env, [this.env]: stack.slug }, detached: true }).unref();
2427
- } catch (error) {
2428
- this.finish(stack, job, 1);
2429
- throw error;
2430
- } finally {
2431
- closeSync(out);
2432
- }
2433
- return job;
2434
- }
2435
- what(job) {
2436
- return [this.app, job.verb, job.ref, ...job.service !== undefined ? [job.service] : []].join(" ");
2437
- }
2438
- async notifyEnd(stack, job, code) {
2439
- const done = job.service !== undefined ? undefined : this.done[job.verb];
2440
- if (code === 0) {
2441
- if (done)
2442
- await notify(this.app, `${stack.ref} ${done[0]}`, done[1]);
2443
- return;
2444
- }
2445
- await notify(this.app, `${this.what(job)} failed`, logTail(job.log) || `see ${job.log}`, true);
2446
- }
2447
- }
2448
- async function attempt(work) {
2449
- try {
2450
- await work();
2451
- return 0;
2452
- } catch (error) {
2453
- console.error(error instanceof KnownError ? `error: ${error.message}` : error);
2454
- return 1;
2455
- }
2456
- }
2457
-
2458
- // src/list.ts
2459
- import { basename as basename5, join as join14 } from "path";
2460
- var UNSAFE_IN_SESSION = /[.:\s/]/g;
2461
- var sessionOf = (name) => name.replace(UNSAFE_IN_SESSION, "-");
2462
- async function projectsToList(options) {
2463
- let here = null;
2464
- try {
2465
- here = (await locate(process.cwd(), options.project)).project;
2466
- } catch {}
2467
- const everywhere = options.all === true || !here && !options.json;
2468
- return { here, projects: everywhere ? await loadProjects() : [here].filter((project) => project !== null) };
2469
- }
2470
- function changedFiles(outputs) {
2471
- return outputs.flatMap((out) => out.split(`
2472
- `)).filter((line) => line.trim() !== "").length;
2473
- }
2474
- async function dirtyCount(dir, repos) {
2475
- const statuses = await Promise.all([".", ...repos].map(async (repo) => git2(join14(dir, repo), "--no-optional-locks", "status", "--porcelain")));
2476
- return changedFiles(statuses.filter((status) => status.ok).map((status) => status.out));
2477
- }
2478
- async function checkoutsOf(project, running) {
2479
- const branchDir = project.repos[0] ?? ".";
2480
- const mainHost = project.routes.find((route) => !route.host.startsWith("*."))?.host;
2481
- const main = { id: basename5(project.root), task: "main", dir: project.root, url: mainHost !== undefined ? `https://${mainHost}` : "" };
2482
- const worktrees = listTasks(project).map((task) => {
2483
- const worktree = worktreeOf(project, task);
2484
- return { id: worktree.id, task, dir: worktree.dir, url: urlsOf(worktree)[0] ?? "" };
2485
- });
2486
- return Promise.all([main, ...worktrees].map(async ({ id, task, dir, url }) => ({
2487
- project: project.name,
2488
- task,
2489
- dir,
2490
- branch: await currentBranch(join14(dir, branchDir)),
2491
- url,
2492
- running: running.has(id),
2493
- dirty: await dirtyCount(dir, project.repos),
2494
- unbranched: task === "main" ? 0 : await unreachableCount(dir, project.repos),
2495
- session: sessionOf(task === "main" ? basename5(dir) : id)
2496
- })));
2497
- }
2498
- async function listWorktrees(options) {
2499
- const [running, { here, projects }] = await Promise.all([runningProjects(), projectsToList(options)]);
2500
- const checkouts = (await Promise.all(projects.map(async (project) => checkoutsOf(project, running)))).flat();
2501
- if (options.json) {
2502
- console.log(JSON.stringify({ project: here?.name ?? null, checkouts }));
2503
- return;
2504
- }
2505
- const rows = checkouts.map((checkout) => [checkout.running ? "*" : " ", checkout.project, checkout.task, checkout.branch, checkout.url, [checkout.dirty ? `${checkout.dirty} changed` : "", checkout.unbranched ? `${checkout.unbranched} on no branch` : ""].filter(Boolean).join(", ")]);
2506
- const widths = rows[0]?.map((_, column) => Math.max(...rows.map((row) => row[column].length))) ?? [];
2507
- for (const row of rows)
2508
- console.log(row.map((cell, column) => cell.padEnd(widths[column])).join(" ").trimEnd());
2509
- }
2510
-
2511
- // src/shell.ts
2512
- var FISH = `function wt --description 'git worktrees of a compose project, each with its own stack'
2513
- switch "$argv[1]"
2514
- case cd
2515
- set -l dir (command wt path $argv[2..-1]); or return
2516
- builtin cd $dir
2517
- case rm
2518
- set -l main (command wt path 2>/dev/null)
2519
- command wt $argv
2520
- set -l code $status
2521
- test -d $PWD; or builtin cd $main
2522
- return $code
2523
- case '*'
2524
- command wt $argv
2525
- end
2526
- end
2527
- command wt --completions fish | source
2528
- complete -c wt -n __fish_use_subcommand -a cd -d 'go to a worktree, or main'
2529
- complete -c wt -n '__fish_seen_subcommand_from cd' -f -a '(command wt tasks) main'`;
2530
- function shellWrapper(shell) {
2531
- if (shell !== "fish")
2532
- throw new KnownError(`no wrapper for ${shell ?? "that shell"} yet, only fish`);
2533
- return FISH;
2534
- }
2535
-
2536
- // src/cli.ts
2537
- async function jobs() {
2538
- return new Jobs({ dir: (await wtConfig()).jobs, app: "wt" });
2539
- }
2540
- async function guarded(action) {
2541
- try {
2542
- return await (await jobs()).guarded(action);
2543
- } catch (error) {
2544
- return failKnown(error);
57
+ })).map((project) => project.name);
58
+ } catch {
59
+ return [];
2545
60
  }
2546
61
  }
2547
- async function projectNames() {
2548
- return (await loadProjects()).map((project) => project.name);
2549
- }
2550
62
  async function taskNames() {
2551
63
  try {
2552
- return listTasks((await locate(process11.cwd())).project);
64
+ return listTasks((await locate(currentDir())).project);
2553
65
  } catch {
2554
66
  return [];
2555
67
  }
@@ -2557,8 +69,7 @@ async function taskNames() {
2557
69
  var TASK = { "[task]": taskNames, "<task>": taskNames };
2558
70
  var PROJECT_OPTION = { type: "string", short: "p", candidates: projectNames, description: "manifest to use instead of the one the current directory belongs to" };
2559
71
  var BG_OPTION = { type: "boolean", description: "run it away from any terminal, its output in the worktree's job log, a notification saying how it went" };
2560
- async function asWorktreeJob(verb, task, options, argv, work) {
2561
- const { project } = await locate(process11.cwd(), options.project);
72
+ async function asWorktreeJob(verb, { project, task }, options, argv, work) {
2562
73
  const ref = `${project.name}/${task}`;
2563
74
  const stack = { ref, slug: slugOf(ref) };
2564
75
  const queue = await jobs();
@@ -2568,20 +79,62 @@ async function asWorktreeJob(verb, task, options, argv, work) {
2568
79
  queue.forget(stack);
2569
80
  return code;
2570
81
  }
2571
- try {
2572
- const job = queue.detach(stack, verb, [import.meta.path, ...argv, "-p", project.name]);
2573
- console.log(`wt: ${verb} ${ref} runs out of sight, its output in ${job.log}`);
2574
- } catch (error) {
2575
- await queue.notifyRefused(`wt ${verb} ${ref}`, error instanceof Error ? error.message : String(error));
2576
- throw error;
2577
- }
82
+ const job = queue.detach(stack, verb, [import.meta.path, ...argv, "-p", project.name]);
83
+ console.log(`wt: ${verb} ${ref} runs out of sight, its output in ${job.log}${canNotify() ? "" : `; nothing here notifies its end, \`wt ls\` shows how it went`}`);
2578
84
  return 0;
2579
85
  }
2580
- var ADD_USAGE = `wt add <task> [branch] [-p <name>] [--bg]
86
+ async function inTurn(command, worktrees, act) {
87
+ let code = 0;
88
+ for (const worktree of worktrees) {
89
+ try {
90
+ code = Math.max(code, await act(worktree));
91
+ } catch (error) {
92
+ const message = knownMessage(error);
93
+ if (message === undefined)
94
+ throw error;
95
+ printError(`${APP} ${command}`, message, knownHint(error));
96
+ code = 1;
97
+ }
98
+ }
99
+ return code;
100
+ }
101
+ async function eachWorktree(command, projectName, act) {
102
+ const { project } = await locate(currentDir(), projectName);
103
+ const tasks = listTasks(project);
104
+ if (!tasks.length)
105
+ console.log(`wt: ${project.name} has no worktree`);
106
+ return inTurn(command, tasks.map((task) => worktreeOf(project, task)), act);
107
+ }
108
+ async function prune(options) {
109
+ const { describeLeftBehind, leftBehind, pruneRegistrations } = await import("./prune-beweag7w.js");
110
+ const found = await leftBehind(options);
111
+ if (!found.length) {
112
+ console.log("wt: nothing left behind");
113
+ return 0;
114
+ }
115
+ console.log(describeLeftBehind(found).join(`
116
+ `));
117
+ if (!options.yes) {
118
+ if (!isInteractive()) {
119
+ warn("nothing removed, `wt prune -y` removes it");
120
+ return 0;
121
+ }
122
+ const { confirm } = await import("./prompt-y71tp3f5.js");
123
+ if (await confirm("Remove it all?", { default: false }) !== true)
124
+ return 1;
125
+ }
126
+ const { removeTask } = await commands();
127
+ const code = await inTurn("prune", found.flatMap((each) => each.orphans.map((orphan) => orphan.worktree)), async (worktree) => asWorktreeJob("rm", worktree, { project: worktree.project.name }, [], async () => removeTask(worktree.task, { project: worktree.project.name, force: true })));
128
+ for (const { project } of found)
129
+ await pruneRegistrations(project);
130
+ return code;
131
+ }
132
+ var ALL_OPTION = { type: "boolean", description: "every worktree of the project, one after the other" };
133
+ var ADD_USAGE = `wt add <task> [branch] [--from <ref>] [--up] [-p <name>] [--bg]
2581
134
 
2582
- Creates a worktree, copies its files and data from main, and routes its subdomains. The task is a lowercase name, also the subdomain label; the branch defaults to wt/<task>.
135
+ Creates a worktree, copies its files and data from main, and routes its subdomains; --up starts its stack too. The task is a lowercase name, also the subdomain label; the branch defaults to wt/<task>. A branch that does not exist yet forks from main's current commit, or from --from, and the output says which.
2583
136
 
2584
- Exits 0 once the worktree is ready, 1 when it cannot be made or provisioned, 2 on a usage error.`;
137
+ Exits 0 once the worktree is ready (and up), 1 when it cannot be made, provisioned or started, 2 on a usage error.`;
2585
138
  var SYNC_USAGE = `wt sync [task] [-p <name>]
2586
139
 
2587
140
  Provisions a worktree again after a manifest change: missing copies and clones, compose override, certificates and routes. The task defaults to the worktree the current directory is in.
@@ -2589,24 +142,53 @@ Provisions a worktree again after a manifest change: missing copies and clones,
2589
142
  Exits 0 once it is provisioned, 1 when a step fails, 2 on a usage error.`;
2590
143
  var RM_USAGE = `wt rm <task> [-f] [-p <name>] [--bg]
2591
144
 
2592
- Stops a worktree stack and deletes its checkouts, volumes, certificates and routes, keeping its branches.
145
+ Stops a worktree stack and deletes its checkouts, volumes, certificates and routes, keeping its branches. Gitignored files go with the folder unchecked: edits to a copied .env.local, uploads and the like are lost, so save them first.
2593
146
 
2594
147
  Exits 0 once it is gone, 1 when uncommitted changes or lost commits refuse it (unless --force) or a step fails, 2 on a usage error.`;
2595
- var UP_USAGE = `wt up [task] [-p <name>] [--bg]
148
+ var UP_USAGE = `wt up [task | --all] [-p <name>] [--bg]
2596
149
 
2597
- Starts a worktree stack: \`docker compose up -d --build\` in the worktree then the manifest's setup the first time, or the config's runner.up. The task defaults to the worktree the current directory is in.
150
+ Starts a worktree stack: \`docker compose up -d --build\` in the worktree then the manifest's setup the first time, or the config's runner.up. The task defaults to the worktree the current directory is in; --all starts every worktree of the project in turn.
2598
151
 
2599
- Exits 0 once the stack is up, 1 when a command fails, 2 on a usage error.`;
2600
- var DOWN_USAGE = `wt down [task] [-p <name>] [--bg]
152
+ Exits 0 once the stacks are up, 1 when a command fails, 2 on a usage error.`;
153
+ var DOWN_USAGE = `wt down [task | --all] [-p <name>] [--bg]
2601
154
 
2602
- Stops a worktree stack: \`docker compose down\` in the worktree, or the config's runner.down. The task defaults to the worktree the current directory is in.
155
+ Stops a worktree stack: \`docker compose down\` in the worktree, or the config's runner.down. A stack whose folder is gone is stopped by its compose project name, runner.down skipped. The task defaults to the worktree the current directory is in; --all stops every worktree of the project in turn.
2603
156
 
2604
- Exits 0 once the stack is down, 1 when a command fails, 2 on a usage error.`;
157
+ Exits 0 once the stacks are down, 1 when a command fails, 2 on a usage error.`;
158
+ var LOGS_USAGE = `wt logs [task] [-f] [-p <name>]
159
+
160
+ Prints the log of the worktree's last --bg job, a job run in a terminal having printed there; -f follows its stack's compose logs instead, from their last 100 lines. The task defaults to the worktree the current directory is in.
161
+
162
+ Exits 0 once printed, 1 when no --bg job left a log, compose's code with -f, 2 on a usage error.`;
163
+ var PRUNE_USAGE = `wt prune [-a] [-y] [-p <name>]
164
+
165
+ Lists what worktrees removed by hand, or an add that crashed, left behind: wt's files, job records, queues, containers and volumes, and git's registrations of folders gone. Once confirmed, removes each as \`wt rm --force\` would. The current project, or every project with -a.
166
+
167
+ Exits 0 once removed, or when nothing is left or nothing could be asked, 1 when a removal fails or is declined, 2 on a usage error.`;
168
+ async function startOrStop(verb, args) {
169
+ const { values, positionals: [task] } = parse(args, verb === "up" ? UP_USAGE : DOWN_USAGE, { project: PROJECT_OPTION, all: ALL_OPTION, bg: BG_OPTION }, { positionals: ["[task]"], candidates: TASK });
170
+ const act = async (worktree) => asWorktreeJob(verb, worktree, values, [verb, worktree.task], async () => {
171
+ const { downTask, upTask } = await commands();
172
+ return verb === "up" ? upTask(worktree) : downTask(worktree);
173
+ });
174
+ if (values.all && task !== undefined)
175
+ badUsage(`wt ${verb} takes a task or --all, not both`);
176
+ return guarded(async () => {
177
+ if (values.all)
178
+ return eachWorktree(verb, values.project, act);
179
+ const worktree = await locateWorktree(currentDir(), task, values.project);
180
+ if (verb === "up")
181
+ assertWorktreeExists(worktree);
182
+ else
183
+ await (await commands()).assertStoppable(worktree);
184
+ return act(worktree);
185
+ }, bgName(values, verb, values.all ? "--all" : task));
186
+ }
2605
187
  var SHELL_USAGE = `wt shell <shell>
2606
188
 
2607
- Prints the shell function that lets \`wt cd\` change directory and \`wt rm\` leave the folder it removes: \`wt shell fish | source\` in config.fish.
189
+ Prints the shell function that lets \`wt cd\` change directory and \`wt rm\` leave the folder it removes, with wt's completion. Save it where the shell reads it at start, so no process runs then, and again after upgrading wt: \`wt shell fish > ~/.config/fish/conf.d/wt.fish\`; for bash or zsh, a file sourced from ~/.bashrc, or from ~/.zshrc after compinit.
2608
190
 
2609
- Exits 0 when it printed the wrapper, 1 for a shell it has none for, 2 on a usage error.`;
191
+ Exits 0 when it printed the wrapper, 1 for a shell it has none for (fish, bash and zsh have one), 2 on a usage error.`;
2610
192
  var LS_USAGE = `wt ls [-a] [-p <name>] [--json]
2611
193
 
2612
194
  Lists main and the worktrees of the current project, or of every project, with their changed files.
@@ -2622,6 +204,11 @@ var INIT_USAGE = `wt init [dir] [--name <name>] [--print]
2622
204
  Drafts a manifest for the project checked out in a directory, the current one by default, into the config's manifests folder.
2623
205
 
2624
206
  Exits 0 once it is written or printed, 1 when the folder holds no compose project, 2 on a usage error.`;
207
+ var DOCTOR_USAGE = `wt doctor
208
+
209
+ Lists each program wt runs: where it is on PATH, or how to get it, and what wt needs it for.
210
+
211
+ Exits 0 when every program the projects need is there, 1 when one is missing, 2 on a usage error.`;
2625
212
  var RUN_USAGE = `wt run <task> [-p <name>] -- <command>...
2626
213
 
2627
214
  Runs a command of a worktree in a throwaway container of its run service, against a test database of its own, provisioned on first use.
@@ -2632,6 +219,16 @@ var HEAVY_USAGE = `wt heavy -- <command>...
2632
219
  Runs a heavy command (a full suite, e2e) once those queued before it, from any session, are done.
2633
220
 
2634
221
  Exits with the command's code, 2 on a usage error.`;
222
+ var OPEN_USAGE = `wt open [task] [-p <name>]
223
+
224
+ Opens the worktree's main URL in the browser ($BROWSER, else the system's opener). The task defaults to the checkout the current directory is in, \`main\` naming main's.
225
+
226
+ Exits 0 once the browser is started, 1 when there is no such worktree, no URL or no browser, 2 on a usage error.`;
227
+ var CD_USAGE = `wt cd [task] [-p <name>]
228
+
229
+ Goes to a worktree's directory, or main's when no task is given. A program cannot change its shell's directory, so this runs in the shell function \`wt shell\` prints; run as a program, it says so.
230
+
231
+ Exits 0 once there, 1 when there is no such worktree or the shell function is missing, 2 on a usage error.`;
2635
232
  var URL_USAGE = `wt url [task] [-p <name>]
2636
233
 
2637
234
  Prints the URLs of a worktree.
@@ -2639,11 +236,11 @@ Prints the URLs of a worktree.
2639
236
  Exits 0 when it printed it, 1 when there is no such worktree or project, 2 on a usage error.`;
2640
237
  var TASKS_USAGE = `wt tasks [-p <name>]
2641
238
 
2642
- Prints the worktree names of the project, one per line.
239
+ Prints the worktree names of the project, one per line, nothing when it has none.
2643
240
 
2644
- Exits 0 when it printed them, 1 when there is no such project, 2 on a usage error.`;
2645
- process11.exitCode = await runCli({
2646
- name: "wt",
241
+ Exits 0 when it printed them, 1 when there is no such project or its manifest does not load, 2 on a usage error.`;
242
+ process.exitCode = await runCli({
243
+ name: APP,
2647
244
  about: "git worktrees of a compose project, each with its own stack, data and <task>.<host> subdomains beside main",
2648
245
  replaces: "a second clone, port juggling and a shared database to try a branch",
2649
246
  examples: [["wt add planning", "a worktree on wt/planning with its own stack"], ["wt up planning", "start it"], ["wt rm planning", "stop and delete it, keeping its branches"]],
@@ -2651,8 +248,16 @@ process11.exitCode = await runCli({
2651
248
  add: {
2652
249
  summary: "create a worktree, copy its files and data from main, and route its subdomains",
2653
250
  run: async (args) => {
2654
- const { values, positionals: [task, branch] } = parse(args, ADD_USAGE, { project: PROJECT_OPTION, bg: BG_OPTION }, { positionals: ["<task>", "[branch]"] });
2655
- return guarded(async () => asWorktreeJob("add", task, values, ["add", task, ...branch === undefined ? [] : [branch]], async () => addTask(task, branch, values)));
251
+ const { values, positionals: [task, branch] } = parse(args, ADD_USAGE, {
252
+ project: PROJECT_OPTION,
253
+ up: { type: "boolean", description: "start its stack once it is ready, as `wt up` does" },
254
+ from: { type: "string", description: "the commit, branch or tag a new branch forks from, main's current commit by default" },
255
+ bg: BG_OPTION
256
+ }, { positionals: ["<task>", "[branch]"] });
257
+ return guarded(async () => {
258
+ const worktree = worktreeOf((await locate(currentDir(), values.project)).project, task);
259
+ return asWorktreeJob(values.up ? "add --up" : "add", worktree, values, ["add", task, ...branch === undefined ? [] : [branch], ...values.from === undefined ? [] : ["--from", values.from], ...values.up ? ["--up"] : []], async () => (await commands()).addTask(task, branch, values));
260
+ }, bgName(values, values.up ? "add --up" : "add", task));
2656
261
  }
2657
262
  },
2658
263
  sync: {
@@ -2660,8 +265,9 @@ process11.exitCode = await runCli({
2660
265
  run: async (args) => {
2661
266
  const { values, positionals: [task] } = parse(args, SYNC_USAGE, { project: PROJECT_OPTION }, { positionals: ["[task]"], candidates: TASK });
2662
267
  return guarded(async () => {
2663
- const { task: name } = await locateWorktree(process11.cwd(), task, values.project);
2664
- return asWorktreeJob("sync", name, values, ["sync", name], async () => syncTask(name, values));
268
+ const worktree = await locateWorktree(currentDir(), task, values.project);
269
+ assertWorktreeExists(worktree);
270
+ return asWorktreeJob("sync", worktree, values, ["sync", worktree.task], async () => (await commands()).syncTask(worktree.task, values));
2665
271
  });
2666
272
  }
2667
273
  },
@@ -2674,47 +280,76 @@ process11.exitCode = await runCli({
2674
280
  bg: BG_OPTION
2675
281
  }, { positionals: ["<task>"], candidates: TASK });
2676
282
  return guarded(async () => {
2677
- await assertRemovable(task, values);
2678
- return asWorktreeJob("rm", task, values, ["rm", task, ...values.force ? ["--force"] : []], async () => removeTask(task, values));
2679
- });
283
+ const { assertRemovable, removeTask } = await commands();
284
+ const worktree = await assertRemovable(task, values);
285
+ return asWorktreeJob("rm", worktree, values, ["rm", task, ...values.force ? ["--force"] : []], async () => removeTask(task, values));
286
+ }, bgName(values, "rm", task));
2680
287
  }
2681
288
  },
2682
289
  up: {
2683
290
  summary: "start a worktree stack",
2684
- run: async (args) => {
2685
- const { values, positionals: [task] } = parse(args, UP_USAGE, { project: PROJECT_OPTION, bg: BG_OPTION }, { positionals: ["[task]"], candidates: TASK });
2686
- return guarded(async () => {
2687
- const worktree = await locateWorktree(process11.cwd(), task, values.project);
2688
- return asWorktreeJob("up", worktree.task, values, ["up", worktree.task], async () => upTask(worktree));
2689
- });
2690
- }
291
+ run: async (args) => startOrStop("up", args)
2691
292
  },
2692
293
  down: {
2693
294
  summary: "stop a worktree stack",
295
+ run: async (args) => startOrStop("down", args)
296
+ },
297
+ logs: {
298
+ summary: "print the log of a worktree's last --bg job, or follow its stack's compose logs",
2694
299
  run: async (args) => {
2695
- const { values, positionals: [task] } = parse(args, DOWN_USAGE, { project: PROJECT_OPTION, bg: BG_OPTION }, { positionals: ["[task]"], candidates: TASK });
300
+ const { values, positionals: [task] } = parse(args, LOGS_USAGE, {
301
+ project: PROJECT_OPTION,
302
+ follow: { type: "boolean", short: "f", description: "follow the stack's compose logs instead, from their last 100 lines" }
303
+ }, { positionals: ["[task]"], candidates: TASK });
2696
304
  return guarded(async () => {
2697
- const worktree = await locateWorktree(process11.cwd(), task, values.project);
2698
- return asWorktreeJob("down", worktree.task, values, ["down", worktree.task], async () => downTask(worktree));
305
+ const worktree = await locateWorktree(currentDir(), task, values.project);
306
+ assertWorktreeExists(worktree);
307
+ if (values.follow)
308
+ return (await import("./stack-h3pgyx1e.js")).followLogs(worktree);
309
+ const { printJobLog } = await printing();
310
+ await printJobLog(worktree, await jobs());
311
+ return 0;
2699
312
  });
2700
313
  }
2701
314
  },
315
+ prune: {
316
+ summary: "remove what worktrees removed by hand left behind",
317
+ run: async (args) => {
318
+ const { values } = parse(args, PRUNE_USAGE, {
319
+ project: PROJECT_OPTION,
320
+ all: { type: "boolean", short: "a", description: "every project, even from inside one" },
321
+ yes: { type: "boolean", short: "y", description: "remove without asking" }
322
+ }, { positionals: [] });
323
+ return guarded(async () => prune(values));
324
+ }
325
+ },
2702
326
  ls: {
2703
327
  summary: "list main and the worktrees of the current project, or of every project",
2704
328
  run: async (args) => {
2705
329
  const { values } = parse(args, LS_USAGE, {
2706
330
  project: PROJECT_OPTION,
2707
331
  all: { type: "boolean", short: "a", description: "every project, even from inside one" },
2708
- json: { type: "boolean", description: "print { project, checkouts }, project being the one the directory is in, null outside every one" }
332
+ json: jsonOption("{ project, checkouts }, project being the one the directory is in, null outside every one")
2709
333
  }, { positionals: [] });
2710
- return guarded(async () => listWorktrees(values));
334
+ return guarded(async () => (await import("./list-js6drtvg.js")).listWorktrees(values));
335
+ }
336
+ },
337
+ cd: {
338
+ summary: "go to a worktree, or main (through the shell function of `wt shell`)",
339
+ run: async (args) => {
340
+ const { values, positionals: [task] } = parse(args, CD_USAGE, { project: PROJECT_OPTION }, { positionals: ["[task]"], candidates: { "[task]": async () => [...await taskNames(), "main"] } });
341
+ return guarded(async () => {
342
+ const { printPath } = await printing();
343
+ await printPath(task, values);
344
+ fail("cd needs the shell function `wt shell <shell>` prints, as a program cannot change its shell's directory", 1, "cd to the path above");
345
+ });
2711
346
  }
2712
347
  },
2713
348
  path: {
2714
349
  summary: "print the directory of a worktree, or of main",
2715
350
  run: async (args) => {
2716
351
  const { values, positionals: [task] } = parse(args, PATH_USAGE, { project: PROJECT_OPTION }, { positionals: ["[task]"], candidates: TASK });
2717
- return guarded(async () => printPath(task, values));
352
+ return guarded(async () => (await printing()).printPath(task, values));
2718
353
  }
2719
354
  },
2720
355
  init: {
@@ -2724,7 +359,14 @@ process11.exitCode = await runCli({
2724
359
  name: { type: "string", description: "the manifest's name, also hashed into the dev server port (the checkout's folder name)" },
2725
360
  print: { type: "boolean", description: "print the draft instead of writing it" }
2726
361
  }, { positionals: ["[dir]"] });
2727
- return guarded(async () => initProject(dir ?? process11.cwd(), values));
362
+ return guarded(async () => (await import("./init-4ynjrztr.js")).initProject(dir ?? currentDir(), values));
363
+ }
364
+ },
365
+ doctor: {
366
+ summary: "list the programs wt runs, where each is or how to get it",
367
+ run: async (args) => {
368
+ parse(args, DOCTOR_USAGE, {});
369
+ return guarded(async () => (await import("./tools-4j56r47a.js")).doctor(await loadProjects()));
2728
370
  }
2729
371
  },
2730
372
  run: {
@@ -2738,7 +380,7 @@ process11.exitCode = await runCli({
2738
380
  });
2739
381
  if (rest === undefined || rest.length === 0)
2740
382
  badUsage("give the command after --");
2741
- return guarded(async () => runTask(task, rest, values.project));
383
+ return guarded(async () => (await import("./run-7eayrqwy.js")).runTask(task, rest, values.project));
2742
384
  }
2743
385
  },
2744
386
  heavy: {
@@ -2751,33 +393,37 @@ process11.exitCode = await runCli({
2751
393
  });
2752
394
  if (rest === undefined || rest.length === 0)
2753
395
  badUsage("give the command after --");
2754
- return guarded(async () => runHeavy(rest));
396
+ return guarded(async () => (await import("./run-7eayrqwy.js")).runHeavy(rest));
2755
397
  }
2756
398
  },
2757
399
  shell: {
2758
400
  summary: "print the shell function letting `wt cd` change directory",
2759
401
  run: async (args) => {
2760
- const { positionals: [shell] } = parse(args, SHELL_USAGE, {}, { positionals: ["<shell>"], candidates: { "<shell>": async () => Promise.resolve(["fish"]) } });
402
+ const { positionals: [shell] } = parse(args, SHELL_USAGE, {}, { positionals: ["<shell>"], candidates: { "<shell>": async () => Promise.resolve(["fish", "bash", "zsh"]) } });
2761
403
  return guarded(async () => {
2762
- console.log(shellWrapper(shell));
2763
- await Promise.resolve();
404
+ console.log((await import("./shell-xrgvqrpp.js")).shellWrapper(shell));
2764
405
  });
2765
406
  }
2766
407
  },
408
+ open: {
409
+ summary: "open a worktree's main URL in the browser",
410
+ run: async (args) => {
411
+ const { values, positionals: [task] } = parse(args, OPEN_USAGE, { project: PROJECT_OPTION }, { positionals: ["[task]"], candidates: TASK });
412
+ return guarded(async () => (await printing()).openTask(task, values));
413
+ }
414
+ },
2767
415
  url: {
2768
416
  summary: "print the URLs of a worktree",
2769
- hidden: true,
2770
417
  run: async (args) => {
2771
418
  const { values, positionals: [task] } = parse(args, URL_USAGE, { project: PROJECT_OPTION }, { positionals: ["[task]"], candidates: TASK });
2772
- return guarded(async () => printUrls(task, values));
419
+ return guarded(async () => (await printing()).printUrls(task, values));
2773
420
  }
2774
421
  },
2775
422
  tasks: {
2776
423
  summary: "print the worktree names of the project",
2777
- hidden: true,
2778
424
  run: async (args) => {
2779
425
  const { values } = parse(args, TASKS_USAGE, { project: PROJECT_OPTION }, { positionals: [] });
2780
- return guarded(async () => printTasks(values));
426
+ return guarded(async () => (await printing()).printTasks(values));
2781
427
  }
2782
428
  }
2783
429
  }