@kaynooo/cli-git 0.13.1 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/gp.js ADDED
@@ -0,0 +1,1369 @@
1
+ #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
+ // @bun
3
+
4
+ // src/gp.ts
5
+ import process17 from "process";
6
+ // ../kit/src/args.ts
7
+ import process9 from "process";
8
+ import { parseArgs } from "util";
9
+
10
+ // ../kit/src/format.ts
11
+ import process7 from "process";
12
+
13
+ // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
14
+ var N = new Map;
15
+ var Nt = /\s+\S*$/;
16
+ var Y = /\s/;
17
+ function ko(t, e, r = "...") {
18
+ let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
19
+ if (t.length <= e)
20
+ return t;
21
+ let l = Math.max(0, e), c = t.substring(0, Math.max(0, s ? l - n.length : l));
22
+ if (o && !Y.test(t[c.length] ?? " "))
23
+ c = c.replace(Nt, "") || c;
24
+ if (o)
25
+ c = c.trimEnd();
26
+ return s ? (c + n).slice(0, l) : c + n;
27
+ }
28
+ 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));
29
+ var z = new Map;
30
+
31
+ // ../kit/src/mode.ts
32
+ import process2 from "process";
33
+ var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
34
+ var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
35
+ function isSet(value) {
36
+ return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
37
+ }
38
+ function outputMode(stream = process2.stdout, env = process2.env) {
39
+ const chosen = env.KIT_MODE;
40
+ if (chosen !== undefined && MODES.has(chosen))
41
+ return chosen;
42
+ if (AGENT_VARIABLES.some((name) => isSet(env[name])))
43
+ return "agent";
44
+ if (stream.isTTY === true)
45
+ return "terminal";
46
+ return isSet(env.CI) ? "ci" : "pipe";
47
+ }
48
+ function isInteractive(streams = process2) {
49
+ return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
50
+ }
51
+
52
+ // ../kit/src/style.ts
53
+ import process6 from "process";
54
+
55
+ // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
56
+ var G2 = /^[a-f0-9]+$/i;
57
+ function b(r) {
58
+ let e = r.startsWith("#") ? r.slice(1) : r;
59
+ if (!G2.test(e))
60
+ return [0, 0, 0];
61
+ if (e.length === 3 || e.length === 4)
62
+ return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
63
+ if (e.length !== 6 && e.length !== 8)
64
+ throw Error(`Invalid hex color length: ${e.length}`);
65
+ return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
66
+ }
67
+ 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") => {
68
+ let [l, n, c] = b(r);
69
+ return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
70
+ }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
71
+ var h = new Set(["", "1", "2", "3", "true"]);
72
+ function C(r, e = globalThis.process?.env ?? {}) {
73
+ if (e.FORCE_COLOR !== undefined)
74
+ return h.has(e.FORCE_COLOR);
75
+ if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
76
+ return false;
77
+ return r?.isTTY === true;
78
+ }
79
+ function f(r, e = []) {
80
+ let l = "", n = "";
81
+ for (let t = 0, i = e.length;t < i; t++)
82
+ l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
83
+ let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
84
+ return new Proxy(c, { get(t, i) {
85
+ let a = B2[i];
86
+ if (Array.isArray(a)) {
87
+ let s = g.get(i);
88
+ if (s === undefined)
89
+ s = f(r, [...e, a]), g.set(i, s);
90
+ return s;
91
+ }
92
+ if (typeof a === "function")
93
+ return (...s) => {
94
+ let y = `${i}:${s.join(",")}`, u = g.get(y);
95
+ if (u === undefined) {
96
+ if (g.size >= 64)
97
+ g.clear();
98
+ u = f(r, [...e, a(...s)]), g.set(y, u);
99
+ }
100
+ return u;
101
+ };
102
+ throw Error(`Unknown style: ${String(i)}`);
103
+ } });
104
+ }
105
+ function Fe(r = {}) {
106
+ return f(r);
107
+ }
108
+ var o = Fe();
109
+
110
+ // ../kit/src/theme.ts
111
+ import { existsSync as existsSync2, readFileSync, statSync } from "fs";
112
+ import { homedir as homedir2 } from "os";
113
+ import { join as join3, resolve as resolve2 } from "path";
114
+ import process5 from "process";
115
+
116
+ // ../kit/src/config.ts
117
+ import { existsSync } from "fs";
118
+ import { dirname, join, resolve } from "path";
119
+ import process3 from "process";
120
+ function findUp(names, from = process3.cwd(), stop = () => false) {
121
+ const wanted = typeof names === "string" ? [names] : names;
122
+ for (let dir = resolve(from);; dir = dirname(dir)) {
123
+ const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
124
+ if (found !== undefined)
125
+ return found;
126
+ if (stop(dir) || dirname(dir) === dir)
127
+ return;
128
+ }
129
+ }
130
+
131
+ // ../kit/src/user-config.ts
132
+ import { homedir } from "os";
133
+ import { join as join2 } from "path";
134
+ import process4 from "process";
135
+ function configBase(where = {}) {
136
+ const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
137
+ return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
138
+ }
139
+ function userConfigPath(bin, where = {}) {
140
+ return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
141
+ }
142
+
143
+ // ../kit/src/theme.ts
144
+ var ENDS = new Map;
145
+ var DEFAULT = {
146
+ colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", plan: "magenta", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
147
+ glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", plan: "\u25C7", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D", open: "\u2022", leaf: "\xB7", guide: "\u2502" },
148
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
149
+ bins: {},
150
+ gradient: ["#c084fc", "#67e8f9"]
151
+ };
152
+ var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
153
+ var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
154
+ var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
155
+ var PRESETS = {
156
+ default: {},
157
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
158
+ mono: { colors: MONO, accents: ["bold"], gradient: undefined },
159
+ ascii: { glyphs: ASCII }
160
+ };
161
+ 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"]);
162
+ var HEX = /^#[0-9a-f]{6}$/i;
163
+ var CONTROL = /\p{Cc}/u;
164
+ var MAX_FILE_BYTES = 64 * 1024;
165
+ var SPACES = /\s+/;
166
+ function isColorSpec(spec) {
167
+ if (typeof spec === "number")
168
+ return Number.isInteger(spec) && spec >= 0 && spec <= 255;
169
+ return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
170
+ }
171
+ var CUBE = [0, 95, 135, 175, 215, 255];
172
+ function cubeLevel(channel) {
173
+ return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
174
+ }
175
+ function nearest256(hex) {
176
+ const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
177
+ const levels = rgb.map(cubeLevel);
178
+ const cube = levels.map((level) => CUBE[level]);
179
+ const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
180
+ const greyValue = 8 + grey * 10;
181
+ const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
182
+ return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
183
+ }
184
+ function hasTrueColor(env) {
185
+ return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
186
+ }
187
+ function tinted(colors, spec, env = process5.env) {
188
+ if (typeof spec === "number")
189
+ return colors.ansi256(spec);
190
+ return spec.trim().split(SPACES).reduce((chain, token) => {
191
+ if (HEX.test(token))
192
+ return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
193
+ return chain[token] ?? chain;
194
+ }, colors);
195
+ }
196
+ function isRecord(value) {
197
+ return typeof value === "object" && value !== null && !Array.isArray(value);
198
+ }
199
+ function readThemeFile(path, warn) {
200
+ try {
201
+ const stat = statSync(path, { throwIfNoEntry: false });
202
+ if (stat === undefined)
203
+ return;
204
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
205
+ warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
206
+ return;
207
+ }
208
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
209
+ if (isRecord(parsed))
210
+ return parsed;
211
+ warn(`${path} is not a JSON object, theme ignored`);
212
+ } catch (error) {
213
+ warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
214
+ }
215
+ return;
216
+ }
217
+ function applyPreset(theme, name, warn, where) {
218
+ if (name === undefined)
219
+ return;
220
+ if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
221
+ warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
222
+ return;
223
+ }
224
+ const preset = PRESETS[name];
225
+ Object.assign(theme.colors, preset.colors);
226
+ Object.assign(theme.glyphs, preset.glyphs);
227
+ if (preset.accents !== undefined)
228
+ theme.accents = [...preset.accents];
229
+ if (Object.hasOwn(preset, "gradient"))
230
+ theme.gradient = preset.gradient;
231
+ return name;
232
+ }
233
+ function applyFile(theme, file, where, warn) {
234
+ if (isRecord(file.colors)) {
235
+ for (const [key, value] of Object.entries(file.colors)) {
236
+ if (!Object.hasOwn(DEFAULT.colors, key))
237
+ warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
238
+ else if (!isColorSpec(value))
239
+ warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
240
+ else
241
+ theme.colors[key] = value;
242
+ }
243
+ }
244
+ if (isRecord(file.glyphs)) {
245
+ for (const [key, value] of Object.entries(file.glyphs)) {
246
+ if (!Object.hasOwn(DEFAULT.glyphs, key))
247
+ warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
248
+ else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
249
+ warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
250
+ else
251
+ theme.glyphs[key] = value;
252
+ }
253
+ }
254
+ if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
255
+ theme.accents = [...file.accents];
256
+ else if (file.accents !== undefined)
257
+ warn(`${where}: accents must be a non-empty list of colours`);
258
+ if (file.gradient === null)
259
+ theme.gradient = undefined;
260
+ else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
261
+ theme.gradient = [file.gradient[0], file.gradient[1]];
262
+ else if (file.gradient !== undefined)
263
+ warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
264
+ if (isRecord(file.bins)) {
265
+ for (const [bin, value] of Object.entries(file.bins)) {
266
+ if (isColorSpec(value))
267
+ theme.bins[bin] = value;
268
+ else
269
+ warn(`${where}: bin ${bin} has no valid colour`);
270
+ }
271
+ }
272
+ }
273
+ function endsWalk(home) {
274
+ return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
275
+ }
276
+ var warned = new Set;
277
+ function warnOnce(message) {
278
+ if (warned.has(message))
279
+ return;
280
+ warned.add(message);
281
+ console.error(`warning: theme ${message}`);
282
+ }
283
+ function isPath(chosen) {
284
+ return chosen.includes("/") || chosen.endsWith(".json");
285
+ }
286
+ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
287
+ const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
288
+ const sources = [];
289
+ const chosen = env.KIT_THEME ?? "";
290
+ const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
291
+ if (isPath(chosen))
292
+ wanted.push(resolve2(from, chosen));
293
+ const files = [];
294
+ for (const path of wanted) {
295
+ const file = path === undefined ? undefined : readThemeFile(path, warn);
296
+ if (path !== undefined && file !== undefined)
297
+ files.push({ path, file });
298
+ }
299
+ let preset = "default";
300
+ if (chosen !== "" && !isPath(chosen)) {
301
+ preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
302
+ } else {
303
+ const named = files.findLast(({ file }) => file.preset !== undefined);
304
+ if (named !== undefined)
305
+ preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
306
+ }
307
+ for (const { path, file } of files) {
308
+ applyFile(theme, file, path, warn);
309
+ sources.push(path);
310
+ }
311
+ return { theme, sources, preset };
312
+ }
313
+ var current;
314
+ var currentKey = "";
315
+ function activeTheme() {
316
+ const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
317
+ if (current === undefined || key !== currentKey) {
318
+ current = loadTheme();
319
+ currentKey = key;
320
+ }
321
+ return current;
322
+ }
323
+
324
+ // ../kit/src/style.ts
325
+ var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
326
+ function takesControlCodes(stream, env = process6.env) {
327
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
328
+ }
329
+ function paint(stream, env = process6.env) {
330
+ return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
331
+ }
332
+ function marked(mark, text, stream, detail, env = process6.env) {
333
+ const colors = paint(stream, env);
334
+ let head = MARK_WORDS[mark];
335
+ if (takesControlCodes(stream, env)) {
336
+ const { theme } = activeTheme();
337
+ head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
338
+ }
339
+ return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
340
+ }
341
+ function role(name, stream, env = process6.env) {
342
+ const colors = paint(stream, env);
343
+ return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
344
+ }
345
+ var STATUS_WORDS = {
346
+ passed: ["passed", "success", "succeeded", "ok"],
347
+ failed: ["failed", "failure", "error", "errored"],
348
+ running: ["running", "in_progress", "started", "holding"],
349
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
350
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
351
+ };
352
+ var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
353
+
354
+ // ../kit/src/format.ts
355
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
356
+ function formatSeconds(total) {
357
+ let rest = Math.max(0, Math.round(total));
358
+ const amounts = UNITS.map(([unit, size]) => {
359
+ const amount = Math.floor(rest / size);
360
+ rest -= amount * size;
361
+ return `${amount}${unit}`;
362
+ });
363
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
364
+ if (first === -1)
365
+ return "0s";
366
+ const next = amounts[first + 1];
367
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
368
+ }
369
+ function upTo(text, separator) {
370
+ const end = text.indexOf(separator);
371
+ return end === -1 ? text : text.slice(0, end);
372
+ }
373
+ function formatAge(date, now = Date.now()) {
374
+ const at = typeof date === "number" ? date : Date.parse(date);
375
+ if (Number.isNaN(at))
376
+ return "-";
377
+ const seconds = (now - at) / 1000;
378
+ return seconds < 60 ? "just now" : `${upTo(formatSeconds(seconds), " ")} ago`;
379
+ }
380
+ function truncate(text, width) {
381
+ return ko(text, width, { suffix: "\u2026", includeSuffix: true });
382
+ }
383
+ var LINE_BREAKS = /\s*\n\s*/g;
384
+ var ESCAPE = String.fromCharCode(27);
385
+ function textWidth(text) {
386
+ return Bun.stringWidth(text);
387
+ }
388
+ function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
389
+ const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
390
+ if (outputMode(stream, env) === "agent")
391
+ return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
392
+ `);
393
+ const widths = [];
394
+ for (const row of cells) {
395
+ for (const [index, cell] of row.entries())
396
+ widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
397
+ }
398
+ const shown = fit === undefined ? cells : narrow(cells, widths, fit);
399
+ const colors = paint(stream);
400
+ const lines = shown.map((row) => row.map((cell, index) => {
401
+ const width = widths[index] ?? 0;
402
+ const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
403
+ if (align[index] === "right")
404
+ return `${gap}${cell}`;
405
+ return index === row.length - 1 ? cell : `${cell}${gap}`;
406
+ }).join(" ").trimEnd());
407
+ const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
408
+ return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
409
+ `);
410
+ }
411
+ function narrow(rows, widths, limit) {
412
+ const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
413
+ const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
414
+ const floor = 8;
415
+ while (used() > limit) {
416
+ let widest = -1;
417
+ for (const [index, width] of widths.entries()) {
418
+ if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
419
+ widest = index;
420
+ }
421
+ if (widest === -1)
422
+ break;
423
+ widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
424
+ }
425
+ return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
426
+ }
427
+ function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
428
+ return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
429
+ }
430
+ function printJson(value) {
431
+ console.log(jsonText(value));
432
+ }
433
+
434
+ // ../kit/src/help.ts
435
+ import process8 from "process";
436
+ var OPTIONAL = /\[[^\]]+\]/g;
437
+ var USAGE_PREFIX = /^usage:\s*/i;
438
+ var FULL_STOP = /\.$/;
439
+ function usageLine(usage, colors = paint(process8.stdout)) {
440
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
441
+ }
442
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
443
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
444
+ `);
445
+ }
446
+ function exitRows(exits, colors = paint(process8.stdout)) {
447
+ if (exits.length === 0)
448
+ return [];
449
+ const width = Math.max(...exits.map(([code]) => String(code).length));
450
+ return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
451
+ }
452
+ function replacesRows(replaces, colors = paint(process8.stdout)) {
453
+ return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
454
+ }
455
+ function wantsHelpJson(env = process8.env) {
456
+ return env.KIT_HELP === "json";
457
+ }
458
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
459
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
460
+ `);
461
+ const first = lines[0];
462
+ const colon = first.indexOf(": ");
463
+ const prose = lines[lines.indexOf("") + 1] ?? "";
464
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
465
+ return {
466
+ synopsis: colon === -1 ? first : first.slice(0, colon),
467
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
468
+ ...replaces === undefined ? {} : { replaces },
469
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
470
+ ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
471
+ ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
472
+ };
473
+ }
474
+ function exampleRows(examples, colors = paint(process8.stdout)) {
475
+ if (examples.length === 0 || outputMode() === "agent")
476
+ return [];
477
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
478
+ }
479
+ function optionRows(options, colors = paint(process8.stdout)) {
480
+ const rows = Object.entries(options).map(([name, option]) => {
481
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
482
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
483
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
484
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
485
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
486
+ });
487
+ const width = Math.max(0, ...rows.map((row) => row.width));
488
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
489
+ }
490
+
491
+ // ../kit/src/text.ts
492
+ var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
493
+ function distance(a, b) {
494
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
495
+ for (const [i, left] of [...a].entries()) {
496
+ const current = [i + 1];
497
+ for (const [j, right] of [...b].entries())
498
+ current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
499
+ previous = current;
500
+ }
501
+ return previous[b.length] ?? 0;
502
+ }
503
+ function closest(name, names) {
504
+ const started = names.find((known) => known.startsWith(name));
505
+ if (started !== undefined)
506
+ return started;
507
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
508
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
509
+ }
510
+ // ../kit/src/input.ts
511
+ var WHOLE = /^\d+$/;
512
+ function wholeNumber(value, name, fallback, min = 1) {
513
+ if (value === undefined)
514
+ return fallback;
515
+ const number = Number(value);
516
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
517
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
518
+ return number;
519
+ }
520
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
521
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
522
+ function duration(value, name, fallback, unit = "s") {
523
+ if (value === undefined)
524
+ return fallback;
525
+ const match = DURATION.exec(value.trim());
526
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
527
+ if (ms < 1)
528
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
529
+ return ms;
530
+ }
531
+
532
+ // ../kit/src/args.ts
533
+ var DASHES = /^-+/;
534
+ function jsonOption(holds) {
535
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
536
+ }
537
+ class Exit extends Error {
538
+ code;
539
+ hint;
540
+ constructor(message, code, hint) {
541
+ super(message);
542
+ this.code = code;
543
+ this.hint = hint;
544
+ }
545
+ }
546
+ function fail(message, code = 2, hint) {
547
+ throw new Exit(message, code, hint);
548
+ }
549
+
550
+ class UsageError extends Exit {
551
+ constructor(message, hint) {
552
+ super(message, 2, hint);
553
+ }
554
+ }
555
+ function badUsage(message) {
556
+ throw new UsageError(message);
557
+ }
558
+
559
+ class HelpShown extends Exit {
560
+ constructor() {
561
+ super("help shown", 0);
562
+ }
563
+ }
564
+
565
+ class Completing {
566
+ options;
567
+ positionals;
568
+ candidates;
569
+ constructor(options, positionals = [], candidates = {}) {
570
+ this.options = options;
571
+ this.positionals = positionals;
572
+ this.candidates = candidates;
573
+ }
574
+ }
575
+ var completion = { active: false };
576
+ var OUTPUT_OPTIONS = {
577
+ color: { type: "string", description: "auto (on a terminal alone), always or never" },
578
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
579
+ };
580
+ function applyOutput(color, plain, env = process9.env) {
581
+ const when = plain === true ? "never" : color ?? "auto";
582
+ if (when === "auto")
583
+ return;
584
+ if (when !== "always" && when !== "never")
585
+ badUsage(`--color takes auto, always or never, not ${when}`);
586
+ if (when === "always") {
587
+ env.FORCE_COLOR = "1";
588
+ delete env.NO_COLOR;
589
+ } else {
590
+ env.NO_COLOR = "1";
591
+ delete env.FORCE_COLOR;
592
+ }
593
+ }
594
+ function parse(args, usage, options, settings = {}) {
595
+ const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
596
+ const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
597
+ const listing = listed(all, settings.allowNegative === true);
598
+ if (completion.active)
599
+ throw new Completing(listing, settings.positionals, settings.candidates);
600
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
601
+ let parsed;
602
+ try {
603
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
604
+ } catch (error) {
605
+ const message = parseError(error);
606
+ throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
607
+ }
608
+ const values = parsed.values;
609
+ applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
610
+ if (values.help === true) {
611
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
612
+ throw new HelpShown;
613
+ }
614
+ checkChoices(parsed.values, all);
615
+ checkConflicts(parsed.values, all);
616
+ if (settings.positionals !== undefined)
617
+ checkPositionals(parsed.positionals, settings.positionals);
618
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
619
+ }
620
+ function splitRest(args, passes) {
621
+ const separator = passes ? args.indexOf("--") : -1;
622
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
623
+ }
624
+ function splitTrailing(args, options, count) {
625
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
626
+ let seen = 0;
627
+ if (count === 0)
628
+ return { own: args, rest: undefined };
629
+ for (let at = 0;at < args.length; at++) {
630
+ const word = args[at];
631
+ if (word === "--")
632
+ break;
633
+ if (word.startsWith("-")) {
634
+ if (takesValue(word))
635
+ at++;
636
+ continue;
637
+ }
638
+ seen++;
639
+ if (seen === count)
640
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
641
+ }
642
+ return { own: args, rest: undefined };
643
+ }
644
+ function listed(options, allowNegative) {
645
+ if (!allowNegative)
646
+ return options;
647
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
648
+ if (option.type !== "boolean" || option.negative === undefined)
649
+ return [[name, option]];
650
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
651
+ }));
652
+ }
653
+ function withAliases(args, options) {
654
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
655
+ if (named.size === 0)
656
+ return args;
657
+ const separator = args.indexOf("--");
658
+ const own = separator === -1 ? args : args.slice(0, separator);
659
+ return [...own.map((arg) => {
660
+ const at = arg.indexOf("=");
661
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
662
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
663
+ }), ...separator === -1 ? [] : args.slice(separator)];
664
+ }
665
+ function withBare(args, options) {
666
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
667
+ if (bare.size === 0)
668
+ return args;
669
+ const separator = args.indexOf("--");
670
+ const own = separator === -1 ? args : args.slice(0, separator);
671
+ return [...own.flatMap((arg, index) => {
672
+ const optional = bare.get(arg);
673
+ const next = own[index + 1];
674
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
675
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
676
+ }), ...separator === -1 ? [] : args.slice(separator)];
677
+ }
678
+ function checkConflicts(values, options) {
679
+ const given = (name) => values[name] !== undefined && values[name] !== false;
680
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
681
+ const other = given(name) ? conflicts.find(given) : undefined;
682
+ if (other !== undefined)
683
+ badUsage(`--${name} cannot be used with --${other}`);
684
+ }
685
+ }
686
+ function checkChoices(values, options) {
687
+ for (const [name, option] of Object.entries(options)) {
688
+ if (option.choices === undefined)
689
+ continue;
690
+ const given = values[name];
691
+ for (const value of Array.isArray(given) ? given : [given]) {
692
+ if (typeof value === "string")
693
+ oneOf(value, name, option.choices);
694
+ }
695
+ }
696
+ }
697
+ function oneOf(value, name, choices) {
698
+ if (!choices.includes(value))
699
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
700
+ return value;
701
+ }
702
+ function checkPositionals(given, names) {
703
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
704
+ const required = names.filter((name) => !name.startsWith("[")).length;
705
+ if (given.length < required)
706
+ badUsage(`missing ${names[given.length]}`);
707
+ if (!variadic && given.length > names.length)
708
+ badUsage(`unexpected argument ${given[names.length]}`);
709
+ }
710
+ function joinDashValues(args, options) {
711
+ const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
712
+ const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
713
+ const joined = [];
714
+ for (let i = 0;i < args.length; i++) {
715
+ const arg = args[i] ?? "";
716
+ if (arg === "--")
717
+ return [...joined, ...args.slice(i)];
718
+ const name = longOf.get(arg);
719
+ const next = args[i + 1];
720
+ if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
721
+ joined.push(`--${name}=${next}`);
722
+ i++;
723
+ } else {
724
+ joined.push(arg);
725
+ }
726
+ }
727
+ return joined;
728
+ }
729
+ function parseError(error) {
730
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
731
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
732
+ }
733
+ var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
734
+ function nearestOption(message, options, allowNegative) {
735
+ const typed = UNKNOWN_OPTION.exec(message)?.[1];
736
+ if (typed === undefined)
737
+ return;
738
+ const word = typed.replace(DASHES, "");
739
+ if (word.length < 2 && !typed.startsWith("--"))
740
+ return;
741
+ const known = Object.entries(options).flatMap(([name, option]) => [
742
+ ...option.short === undefined ? [] : [`-${option.short}`],
743
+ `--${name}`,
744
+ ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
745
+ ]);
746
+ const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
747
+ return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
748
+ }
749
+ // ../kit/src/argv.ts
750
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
751
+ import { resolve as resolve3 } from "path";
752
+ import process10 from "process";
753
+ function commandLine() {
754
+ try {
755
+ return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
756
+ } catch {
757
+ return;
758
+ }
759
+ }
760
+ function realPath(word) {
761
+ try {
762
+ return realpathSync(resolve3(word));
763
+ } catch {
764
+ return;
765
+ }
766
+ }
767
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
768
+ const target = script === undefined ? undefined : realPath(script) ?? script;
769
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
770
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
771
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
772
+ }
773
+ // ../kit/src/process.ts
774
+ import { constants } from "os";
775
+ import process11 from "process";
776
+ var KILL_GRACE_MS = 2000;
777
+ var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
778
+ function exitCodeOf(code, signal) {
779
+ if (code !== null)
780
+ return code;
781
+ if (typeof signal === "number")
782
+ return 128 + signal;
783
+ return signal === null ? 129 : 128 + constants.signals[signal];
784
+ }
785
+ function holdSignals(cleanup) {
786
+ let received;
787
+ let child;
788
+ const held = {
789
+ get signal() {
790
+ return received;
791
+ },
792
+ forward: (to) => {
793
+ child = to;
794
+ },
795
+ release: () => {
796
+ for (const signal of SIGNALS)
797
+ process11.off(signal, onSignal);
798
+ }
799
+ };
800
+ function onSignal(signal) {
801
+ received = signal;
802
+ if (child !== undefined) {
803
+ child.kill(signal);
804
+ return;
805
+ }
806
+ if (cleanup === undefined)
807
+ return;
808
+ held.release();
809
+ cleanup(signal);
810
+ process11.kill(process11.pid, signal);
811
+ }
812
+ for (const signal of SIGNALS)
813
+ process11.on(signal, onSignal);
814
+ return held;
815
+ }
816
+ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
817
+ const chunks = [];
818
+ const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
819
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
820
+ const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
821
+ const timers = [];
822
+ const killGroup = (killing) => {
823
+ if (state.done)
824
+ return;
825
+ try {
826
+ if (grouped)
827
+ process11.kill(-proc.pid, killing);
828
+ else
829
+ proc.kill(killing);
830
+ } catch {}
831
+ };
832
+ const stop = () => {
833
+ killGroup("SIGTERM");
834
+ timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
835
+ };
836
+ const onAbort = () => stop();
837
+ if (timeoutMs !== undefined) {
838
+ timers.push(setTimeout(() => {
839
+ state.timedOut = true;
840
+ stop();
841
+ }, timeoutMs));
842
+ }
843
+ if (signal?.aborted === true)
844
+ onAbort();
845
+ else
846
+ signal?.addEventListener("abort", onAbort, { once: true });
847
+ onStart?.({ kill: (killing) => killGroup(killing) });
848
+ const drain = async (stream, name) => {
849
+ for await (const data of stream) {
850
+ if (state.failure !== undefined)
851
+ continue;
852
+ try {
853
+ onChunk?.({ stream: name, data });
854
+ } catch (error) {
855
+ state.failure = error;
856
+ stop();
857
+ continue;
858
+ }
859
+ if (state.kept + data.length > maxBytes) {
860
+ state.truncated = true;
861
+ continue;
862
+ }
863
+ state.kept += data.length;
864
+ chunks.push({ stream: name, data });
865
+ }
866
+ };
867
+ try {
868
+ await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
869
+ await proc.exited;
870
+ } finally {
871
+ state.done = true;
872
+ for (const timer of timers)
873
+ clearTimeout(timer);
874
+ signal?.removeEventListener("abort", onAbort);
875
+ }
876
+ if (state.failure !== undefined)
877
+ throw state.failure;
878
+ const joined = () => Buffer.concat(chunks.map(({ data }) => data));
879
+ let output;
880
+ let text;
881
+ return {
882
+ code: exitCodeOf(proc.exitCode, proc.signalCode),
883
+ chunks,
884
+ timedOut: state.timedOut,
885
+ truncated: state.truncated,
886
+ get output() {
887
+ return output ??= joined();
888
+ },
889
+ get text() {
890
+ return text ??= (output ??= joined()).toString();
891
+ }
892
+ };
893
+ }
894
+
895
+ // ../kit/src/progress.ts
896
+ var ESC = String.fromCharCode(27);
897
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
898
+ var RESET_STYLE = `${ESC}[0m`;
899
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
900
+ // ../kit/src/cli.ts
901
+ import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
902
+ import { dirname as dirname3, join as join5 } from "path";
903
+ import process13 from "process";
904
+
905
+ // ../kit/src/usage.ts
906
+ import { appendFileSync, mkdirSync } from "fs";
907
+ import { homedir as homedir3 } from "os";
908
+ import { dirname as dirname2, isAbsolute, join as join4 } from "path";
909
+ import process12 from "process";
910
+
911
+ // ../kit/src/logs.ts
912
+ var DAY_MS = 24 * 60 * 60 * 1000;
913
+ var CLI_FOLDER = "kaynooo-cli";
914
+
915
+ // ../kit/src/usage.ts
916
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
917
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
918
+ var LONGEST_NAME = 40;
919
+ var usageError;
920
+ function noteUsageError(message) {
921
+ usageError = message;
922
+ }
923
+ function stateHome(env = process12.env) {
924
+ const dir = env.XDG_STATE_HOME;
925
+ return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
926
+ }
927
+ function usagePath(env = process12.env) {
928
+ return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
929
+ }
930
+ function usageRecorded(env = process12.env) {
931
+ const off = env.KAYNOOO_CLI_NO_USAGE;
932
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
933
+ }
934
+ function flagNames(argv) {
935
+ const end = argv.indexOf("--");
936
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
937
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
938
+ }
939
+ function usageEntry(bin, command, argv, code, now = new Date) {
940
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
941
+ usageError = undefined;
942
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
943
+ }
944
+ function recordUsage(entry, env = process12.env) {
945
+ if (!usageRecorded(env))
946
+ return;
947
+ try {
948
+ const path = usagePath(env);
949
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
950
+ appendFileSync(path, `${JSON.stringify(entry)}
951
+ `, { mode: 384 });
952
+ } catch {}
953
+ }
954
+
955
+ // ../kit/src/cli.ts
956
+ var LEVEL_OPTIONS = {
957
+ ...OUTPUT_OPTIONS,
958
+ help: { type: "boolean", short: "h", description: "show this help" }
959
+ };
960
+ var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
961
+ function printError(prefix, message, hint, cause) {
962
+ const colors = paint(process13.stderr);
963
+ const styled = takesControlCodes(process13.stderr);
964
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
965
+ const under = (label, text, tint) => text === undefined ? "" : `
966
+ ${styled ? tint(label) : `${label}:`} ${text}`;
967
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
968
+ }
969
+ function runHint(command, effect) {
970
+ return `run \`${command}\`${effect === undefined ? "" : ` to ${effect}`}`;
971
+ }
972
+ function printJsonError(message, hint, cause) {
973
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
974
+ }
975
+ function wantsJson(argv) {
976
+ const end = argv.indexOf("--");
977
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
978
+ }
979
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
980
+ if (error instanceof HelpShown)
981
+ return 0;
982
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
983
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
984
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
985
+ if (error instanceof Exit && error.code === 2)
986
+ noteUsageError(error.message);
987
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
988
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
989
+ return error instanceof Exit ? error.code : 1;
990
+ }
991
+ var COMPLETE = "__complete";
992
+ var FILES = "__files__";
993
+ async function completingOf(run) {
994
+ completion.active = true;
995
+ try {
996
+ await run([]);
997
+ } catch (error) {
998
+ if (error instanceof Completing)
999
+ return error;
1000
+ } finally {
1001
+ completion.active = false;
1002
+ }
1003
+ return new Completing({});
1004
+ }
1005
+ function candidateLine(candidate) {
1006
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
1007
+ }
1008
+ function positionalBeingTyped(before, { options, positionals }) {
1009
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1010
+ const typed = [];
1011
+ let at = 0;
1012
+ while (at < before.length) {
1013
+ const word = before[at];
1014
+ if (word === "--") {
1015
+ typed.push(...before.slice(at + 1));
1016
+ break;
1017
+ }
1018
+ if (!word.startsWith("-"))
1019
+ typed.push(word);
1020
+ else if (takesValue(word))
1021
+ at++;
1022
+ at++;
1023
+ }
1024
+ const last = positionals.at(-1);
1025
+ if (typed.length < positionals.length)
1026
+ return { name: positionals[typed.length], typed };
1027
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1028
+ }
1029
+ async function leafCandidates(run, words) {
1030
+ const completing = await completingOf(run);
1031
+ if ((words.at(-1) ?? "").startsWith("-"))
1032
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1033
+ const flag = words.at(-2);
1034
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1035
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1036
+ if (option?.type === "string") {
1037
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1038
+ return values === undefined ? [FILES] : values.map(candidateLine);
1039
+ }
1040
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1041
+ return values === undefined ? [FILES] : values.map(candidateLine);
1042
+ }
1043
+ async function printCandidates(found) {
1044
+ for (const line of await found)
1045
+ console.log(line);
1046
+ return 0;
1047
+ }
1048
+ function packageVersion(entry = Bun.main) {
1049
+ for (let dir = dirname3(realpathSync2(entry));; dir = dirname3(dir)) {
1050
+ try {
1051
+ const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
1052
+ if (typeof version === "string")
1053
+ return version;
1054
+ } catch {}
1055
+ if (dirname3(dir) === dir)
1056
+ return "0.0.0";
1057
+ }
1058
+ }
1059
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1060
+ if (argv[0] === COMPLETE)
1061
+ return printCandidates(leafCandidates(run, argv.slice(1)));
1062
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1063
+ console.log(version ?? packageVersion());
1064
+ return 0;
1065
+ }
1066
+ let code;
1067
+ try {
1068
+ code = await run(argv);
1069
+ } catch (error) {
1070
+ code = reportThrown(name, error, redact, wantsJson(argv));
1071
+ }
1072
+ if (usage !== false) {
1073
+ try {
1074
+ recordUsage(usageEntry(name, undefined, argv, code));
1075
+ } catch {}
1076
+ }
1077
+ return code;
1078
+ }
1079
+ // ../kit/src/folders.ts
1080
+ var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1081
+ // ../kit/src/secrets.ts
1082
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1083
+ // ../kit/src/sessions.ts
1084
+ var {Glob } = globalThis.Bun;
1085
+ var SESSION_FILES = new Glob("*.json");
1086
+ var ACCOUNT_DIRS = new Glob("*/sessions");
1087
+ // ../kit/src/watch.ts
1088
+ import process14 from "process";
1089
+ import { format } from "util";
1090
+ var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1091
+ var DEFAULT_SECONDS = 2;
1092
+ var ATTACHED_SHORT = /^-w./;
1093
+ var INTERVAL = /^\d+(?:\.\d+)?(?:ms|[smh])?$/;
1094
+ function watchOption(what) {
1095
+ return { type: "string", short: "w", optional: { bare: "", accepts: INTERVAL }, description: `redraw ${what} every 2s, or every interval given (500ms, 5s), until ctrl-c` };
1096
+ }
1097
+ function withoutWatch(args) {
1098
+ const rest = [];
1099
+ for (let at = 0;at < args.length; at++) {
1100
+ const arg = args[at];
1101
+ if (arg === "--watch" || arg === "-w") {
1102
+ if (args[at + 1] !== undefined && INTERVAL.test(args[at + 1]))
1103
+ at++;
1104
+ } else if (!arg.startsWith("--watch=") && !ATTACHED_SHORT.test(arg)) {
1105
+ rest.push(arg);
1106
+ }
1107
+ }
1108
+ return rest;
1109
+ }
1110
+ async function watching(value, step, stream = process14.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1111
+ const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1112
+ if (!takesControlCodes(stream))
1113
+ badUsage("--watch redraws the screen, so it needs a terminal");
1114
+ let code = 0;
1115
+ for (let round = 0;round < rounds; round++) {
1116
+ const held = [];
1117
+ const { log, info } = console;
1118
+ const write = process14.stdout.write.bind(process14.stdout);
1119
+ const hold = (...parts) => void held.push(`${format(...parts)}
1120
+ `);
1121
+ console.log = hold;
1122
+ console.info = hold;
1123
+ process14.stdout.write = (text) => {
1124
+ held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1125
+ return true;
1126
+ };
1127
+ try {
1128
+ code = await step();
1129
+ } finally {
1130
+ console.log = log;
1131
+ console.info = info;
1132
+ process14.stdout.write = write;
1133
+ }
1134
+ stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1135
+ await sleep(interval);
1136
+ }
1137
+ return code;
1138
+ }
1139
+ // src/git.ts
1140
+ async function git2(args, env) {
1141
+ const ran = await runCommand(["git", "--no-optional-locks", "-c", "core.quotePath=false", ...args], env === undefined ? {} : { env });
1142
+ const text = (stream) => Buffer.concat(ran.chunks.filter((chunk) => chunk.stream === stream).map((chunk) => chunk.data)).toString();
1143
+ return { code: ran.code, stdout: text("stdout"), stderr: text("stderr") };
1144
+ }
1145
+
1146
+ // src/repos.ts
1147
+ import { readdir } from "fs/promises";
1148
+ import { join as join6, relative, resolve as resolve4 } from "path";
1149
+ import process16 from "process";
1150
+
1151
+ // src/status.ts
1152
+ var AHEAD_BEHIND = /\+(\d+) -(\d+)/;
1153
+ var OCTAL = /[0-7]/;
1154
+ var ESCAPES = { a: 7, b: 8, t: 9, n: 10, v: 11, f: 12, r: 13 };
1155
+ var ENCODER = new TextEncoder;
1156
+ var DECODER = new TextDecoder;
1157
+ function unquote(path) {
1158
+ if (!path.startsWith('"') || !path.endsWith('"'))
1159
+ return path;
1160
+ const bytes = [];
1161
+ const text = [...path.slice(1, -1)];
1162
+ for (let i = 0;i < text.length; i++) {
1163
+ const char = text[i] ?? "";
1164
+ const next = text[i + 1] ?? "";
1165
+ if (char !== "\\") {
1166
+ bytes.push(...ENCODER.encode(char));
1167
+ } else if (OCTAL.test(next)) {
1168
+ bytes.push(Number.parseInt(text.slice(i + 1, i + 4).join(""), 8));
1169
+ i += 3;
1170
+ } else {
1171
+ bytes.push(ESCAPES[next] ?? next.charCodeAt(0));
1172
+ i++;
1173
+ }
1174
+ }
1175
+ return DECODER.decode(new Uint8Array(bytes));
1176
+ }
1177
+ function after(line, count) {
1178
+ let index = 0;
1179
+ for (let field = 0;field < count; field++)
1180
+ index = line.indexOf(" ", index) + 1;
1181
+ return line.slice(index);
1182
+ }
1183
+ function parseStatus(text) {
1184
+ const status = { branch: "", oid: "", upstream: null, aheadBehind: null, changes: [], conflicted: [], untracked: [] };
1185
+ let hasBranch = false;
1186
+ for (const line of text.split(`
1187
+ `)) {
1188
+ if (line.startsWith("# branch.oid ")) {
1189
+ status.oid = line.slice("# branch.oid ".length);
1190
+ } else if (line.startsWith("# branch.head ")) {
1191
+ status.branch = line.slice("# branch.head ".length);
1192
+ hasBranch = true;
1193
+ } else if (line.startsWith("# branch.upstream ")) {
1194
+ status.upstream = line.slice("# branch.upstream ".length);
1195
+ } else if (line.startsWith("# branch.ab ")) {
1196
+ const [, ahead = "0", behind = "0"] = AHEAD_BEHIND.exec(line) ?? [];
1197
+ status.aheadBehind = { ahead: Number(ahead), behind: Number(behind) };
1198
+ } else if (line.startsWith("1 ")) {
1199
+ status.changes.push({ path: unquote(after(line, 8)), index: line[2] ?? ".", worktree: line[3] ?? "." });
1200
+ } else if (line.startsWith("2 ")) {
1201
+ const [path = "", from = ""] = after(line, 9).split("\t");
1202
+ status.changes.push({ path: unquote(path), from: unquote(from), index: line[2] ?? ".", worktree: line[3] ?? "." });
1203
+ } else if (line.startsWith("u ")) {
1204
+ status.conflicted.push(unquote(after(line, 10)));
1205
+ } else if (line.startsWith("? ")) {
1206
+ status.untracked.push(unquote(line.slice(2)));
1207
+ }
1208
+ }
1209
+ return hasBranch ? status : null;
1210
+ }
1211
+ function summary(status, head) {
1212
+ const { branch, oid, upstream, aheadBehind, changes, conflicted, untracked } = status;
1213
+ const on = branch === "(detached)" ? `detached at ${oid.slice(0, 7)}` : `branch \`${branch}\``;
1214
+ let tracking = "no upstream";
1215
+ if (upstream !== null)
1216
+ tracking = aheadBehind === null ? `upstream \`${upstream}\` gone or never fetched` : `${aheadBehind.ahead} ahead and ${aheadBehind.behind} behind \`${upstream}\` as of the last fetch`;
1217
+ const files = [`${changes.length} changed`, untracked.length > 0 ? `${untracked.length} untracked` : "", conflicted.length > 0 ? `${conflicted.length} conflicted` : ""].filter(Boolean).join(", ");
1218
+ const [sha, title] = head.trim().split("\x00");
1219
+ const last = sha === undefined || sha === "" ? "; no commit yet" : `; HEAD ${sha} ${title ?? ""}`.trimEnd();
1220
+ return `${on}, ${tracking}; ${files} files${last}`;
1221
+ }
1222
+
1223
+ // src/repos.ts
1224
+ var SKIPPED = new Set(["node_modules", "vendor", "dist"]);
1225
+ var DEPTH = 4;
1226
+ async function reposUnder(root, depth = DEPTH) {
1227
+ const found = [];
1228
+ async function walk(dir, left) {
1229
+ let entries;
1230
+ try {
1231
+ entries = await readdir(dir, { withFileTypes: true });
1232
+ } catch {
1233
+ return;
1234
+ }
1235
+ if (entries.some((entry) => entry.name === ".git"))
1236
+ found.push(dir);
1237
+ if (left === 0)
1238
+ return;
1239
+ await Promise.all(entries.filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && !SKIPPED.has(entry.name)).map(async (entry) => walk(join6(dir, entry.name), left - 1)));
1240
+ }
1241
+ await walk(resolve4(root), depth);
1242
+ return found.sort();
1243
+ }
1244
+ async function toplevelOf(dir) {
1245
+ const read = await git2(["-C", dir, "rev-parse", "--show-toplevel"]);
1246
+ return read.code === 0 ? read.stdout.trim() : undefined;
1247
+ }
1248
+ async function reposOf(roots) {
1249
+ const starts = roots.length > 0 ? roots : [await toplevelOf(".") ?? process16.cwd()];
1250
+ const found = await Promise.all(starts.map(async (root) => reposUnder(root)));
1251
+ return [...new Set(found.flat())].sort();
1252
+ }
1253
+ async function repoState(dir) {
1254
+ const [read, log] = await Promise.all([git2(["-C", dir, "status", "--porcelain=v2", "--branch"]), git2(["-C", dir, "log", "-1", "--format=%h%x00%s"])]);
1255
+ const [sha, title = ""] = log.code === 0 && log.stdout.trim() !== "" ? log.stdout.trim().split("\x00") : [];
1256
+ return { path: relative(process16.cwd(), dir) || ".", dir, status: read.code === 0 ? parseStatus(read.stdout) : null, head: sha === undefined ? null : { sha, title } };
1257
+ }
1258
+ function trackingOf(status) {
1259
+ if (status.upstream === null)
1260
+ return "no upstream";
1261
+ if (status.aheadBehind === null)
1262
+ return "upstream gone";
1263
+ const { ahead, behind } = status.aheadBehind;
1264
+ const parts = [ahead > 0 ? `${ahead} ahead` : "", behind > 0 ? `${behind} behind` : ""].filter(Boolean);
1265
+ return parts.length === 0 ? "up to date" : parts.join(", ");
1266
+ }
1267
+ function changesOf(status) {
1268
+ const { changes, untracked, conflicted } = status;
1269
+ const parts = [changes.length > 0 ? `${changes.length} changed` : "", untracked.length > 0 ? `${untracked.length} untracked` : "", conflicted.length > 0 ? `${conflicted.length} conflicted` : ""].filter(Boolean);
1270
+ return parts.length === 0 ? "clean" : parts.join(", ");
1271
+ }
1272
+ function branchOf(status) {
1273
+ return status.branch === "(detached)" ? `detached at ${status.oid.slice(0, 7)}` : status.branch;
1274
+ }
1275
+
1276
+ // src/gp.ts
1277
+ var USAGE = `gp [dir]...: pushes the current branch of the repository, or of each dir's, when it is ahead of its upstream as of the last fetch or has none yet, the latter with -u to origin (the only remote when there is no origin)
1278
+
1279
+ --repos pushes every repository at and below the current one's toplevel, or below each dir given, the way gst --repos lists them. A detached HEAD, a branch with nothing to push and a repository with no remote are skipped, saying so; the pushes run one after another.
1280
+ What follows -- goes to every git push as is (gp -- --tags, gp -- --force-with-lease), and a branch with nothing ahead is then pushed too.`;
1281
+ var EXITS = [[0, "every push went through, or there was nothing to push"], [1, "a push was refused or a repository could not be read"], [2, "outside a git repository or a usage error"]];
1282
+ var OPTIONS = {
1283
+ repos: { type: "boolean", short: "r", description: "every repository nested below too" },
1284
+ "dry-run": { type: "boolean", description: "say what would be pushed, pushing nothing" },
1285
+ json: jsonOption("one {path, branch, remote, commits, outcome, reason?} per repository, outcome being pushed, would-push, skipped or refused")
1286
+ };
1287
+ var GIT_FAILURE = /^(?: ! |error: |fatal: )/;
1288
+ function whyRefused(stderr) {
1289
+ const lines = stderr.split(`
1290
+ `).map((line) => line.trimEnd()).filter(Boolean);
1291
+ return (lines.find((line) => GIT_FAILURE.test(line)) ?? lines.at(-1) ?? "git push failed").trim();
1292
+ }
1293
+ async function remoteFor(dir) {
1294
+ const remotes = (await git2(["-C", dir, "remote"])).stdout.split(`
1295
+ `).filter(Boolean);
1296
+ if (remotes.includes("origin"))
1297
+ return "origin";
1298
+ return remotes.length === 1 ? remotes[0] : undefined;
1299
+ }
1300
+ async function unpushed(dir, branch) {
1301
+ const count = await git2(["-C", dir, "rev-list", "--count", branch, "--not", "--remotes"]);
1302
+ return count.code === 0 ? Number(count.stdout.trim()) : null;
1303
+ }
1304
+ async function push(repo, { dryRun, extra }) {
1305
+ const { path, dir, status } = repo;
1306
+ const skipped = (reason, branch = null) => ({ path, branch, remote: null, commits: null, outcome: "skipped", reason });
1307
+ if (status === null)
1308
+ return { path, branch: null, remote: null, commits: null, outcome: "refused", reason: "git could not read it" };
1309
+ const { branch, upstream, aheadBehind } = status;
1310
+ if (branch === "(detached)")
1311
+ return skipped("detached HEAD");
1312
+ let args;
1313
+ let remote;
1314
+ let commits;
1315
+ if (upstream === null) {
1316
+ const name = await remoteFor(dir);
1317
+ if (name === undefined)
1318
+ return skipped("no upstream, and no origin remote to push to", branch);
1319
+ args = ["push", "-u", ...extra, name, branch];
1320
+ remote = `${name}/${branch}`;
1321
+ commits = await unpushed(dir, branch);
1322
+ } else {
1323
+ if (aheadBehind !== null && aheadBehind.ahead === 0 && extra.length === 0)
1324
+ return skipped("nothing to push", branch);
1325
+ args = ["push", ...extra];
1326
+ remote = upstream;
1327
+ commits = aheadBehind?.ahead ?? await unpushed(dir, branch);
1328
+ }
1329
+ if (dryRun)
1330
+ return { path, branch, remote, commits, outcome: "would-push" };
1331
+ const pushed = await git2(["-C", dir, ...args]);
1332
+ return pushed.code === 0 ? { path, branch, remote, commits, outcome: "pushed" } : { path, branch, remote, commits, outcome: "refused", reason: whyRefused(pushed.stderr) };
1333
+ }
1334
+ function line(result) {
1335
+ const { dim } = paint(process17.stdout);
1336
+ const sent = result.commits === null ? "" : `, ${result.commits} ${result.commits === 1 ? "commit" : "commits"}`;
1337
+ const what = `${result.branch} -> ${result.remote}${sent}`;
1338
+ const said = {
1339
+ pushed: () => marked("ok", `pushed ${what}`, process17.stdout),
1340
+ "would-push": () => `would push ${what}`,
1341
+ skipped: () => dim(result.reason ?? "skipped"),
1342
+ refused: () => marked("problem", `${result.branch === null ? "" : `${result.branch}: `}${result.reason ?? "refused"}`, process17.stdout)
1343
+ }[result.outcome];
1344
+ return [role("path", process17.stdout)(result.path), said()];
1345
+ }
1346
+ async function main(argv) {
1347
+ const { values, positionals, rest = [] } = parse(argv, USAGE, OPTIONS, { positionals: ["[dir]..."], rest: true, exits: EXITS, replaces: "git push, git push -u origin <branch> and a git -C <repo> push per nested repository", examples: ["gp", ["gp --repos", "every repository nested in this one"], ["gp --repos --dry-run", "what would go out"], ["gp . ../other", "this repository and a sibling"], ["gp -- --force-with-lease", "flags for git push"]] });
1348
+ let dirs;
1349
+ if (values.repos === true) {
1350
+ dirs = await reposOf(positionals);
1351
+ } else {
1352
+ const found = await Promise.all((positionals.length > 0 ? positionals : ["."]).map(async (dir) => toplevelOf(dir)));
1353
+ if (found.includes(undefined))
1354
+ fail(`not inside a git repository: ${(positionals.length > 0 ? positionals : ["."]).filter((_, at) => found[at] === undefined).join(", ")}`);
1355
+ dirs = [...new Set(found)];
1356
+ }
1357
+ if (dirs.length === 0)
1358
+ fail(`no git repository at or below ${positionals.length === 0 ? "the current directory" : positionals.join(", ")}`);
1359
+ const repos = await Promise.all(dirs.map(repoState));
1360
+ const results = [];
1361
+ for (const repo of repos)
1362
+ results.push(await push(repo, { dryRun: values["dry-run"] === true, extra: rest }));
1363
+ if (values.json === true)
1364
+ printJson(results);
1365
+ else
1366
+ console.log(table(results.map(line)));
1367
+ return results.some((result) => result.outcome === "refused") ? 1 : 0;
1368
+ }
1369
+ process17.exitCode = await runMain({ name: "gp", run: main });