@kaynooo/cli-git 0.5.2 → 0.6.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/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # gst and gc
1
+ # gst, gc and gb
2
2
 
3
3
  Git for Claude Code, where a session would otherwise chain `git status --short` and `git log --oneline` to read the state, or `git add <paths> && git status && git commit -m ...` to commit and have the commit bounced over its message.
4
4
 
@@ -22,6 +22,15 @@ Prints one line with the branch, its upstream and how far ahead and behind it is
22
22
  - A path may be a directory or a deleted file. When git refuses the commit (a hook), the paths are unstaged again and git's output is shown.
23
23
  - Exit codes: 0 committed, 1 refused, 2 a usage error.
24
24
 
25
+ ## gb
26
+
27
+ `gb [branch]` picks a git branch with fzf and switches to it: the branches last checked out first (from the reflog), then the other local ones, then the remote ones with no local branch yet. The header says where HEAD stands, each row how its branch stands against its upstream and whether it is merged into the base. Keys: enter switches (a remote branch gets its tracking branch), ctrl-n creates a branch named after the query, ctrl-d deletes the highlighted local branch with `git branch -d`, ctrl-r fetches and prunes. Without fzf or a terminal it lists the branches, as JSON with `--json`.
28
+
29
+ - `gb <branch>` switches without the picker, a bare name finding the remote branch it would create; `gb -` goes back, `gb -c <name>` creates a branch, `gb -d <branch>` deletes a local one.
30
+ - A branch checked out in another worktree needs a `cd`, which a command cannot do for its shell: `gb` prints the worktree's path on stdout and a hint on stderr.
31
+ - Hidden flags for wrappers: `--emit` (with any of the above) prints the command as lines for a shell function to run, `--list` the rows as JSON for term, `--names` the branches with their last commit for shell completions, `--show <branch>` the preview and `--rows`, `--fetch` what ctrl-r reloads.
32
+ - Exit codes: the git command's, 1 when no branch is picked or found, 2 outside a repository.
33
+
25
34
  ## Library
26
35
 
27
36
  `@kaynooo/cli-git/message` exports `commitMessageViolation(message)`, the rule a message breaks as the sentence to show or null, and the rule sentences, for the guard that checks a `git commit` typed by hand.
package/dist/gb.js ADDED
@@ -0,0 +1,1234 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // src/gb.ts
5
+ import process9 from "process";
6
+
7
+ // ../kit/src/args.ts
8
+ import process3 from "process";
9
+ import { parseArgs } from "util";
10
+
11
+ // ../kit/src/style.ts
12
+ import process from "process";
13
+
14
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
15
+ function x(s) {
16
+ let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
17
+ if (!/^[a-f0-9]+$/.test(r))
18
+ return [0, 0, 0];
19
+ let t = r.length, n = (c) => Number.parseInt(c, 16);
20
+ if (t === 3 || t === 4) {
21
+ let c = n(r[0] + r[0]), u = n(r[1] + r[1]), h = n(r[2] + r[2]), g = t === 4 ? n(r[3] + r[3]) : undefined;
22
+ return g !== undefined ? [c, u, h, g] : [c, u, h];
23
+ }
24
+ if (t !== 6 && t !== 8)
25
+ throw Error(`Invalid hex color length: ${t}`);
26
+ let a = n(r.slice(0, 2)), b = n(r.slice(2, 4)), o = n(r.slice(4, 6)), y = t === 8 ? n(r.slice(6, 8)) : undefined;
27
+ if ([a, b, o].some(Number.isNaN) || y !== undefined && Number.isNaN(y))
28
+ throw Error(`Invalid hex color value: ${s}`);
29
+ return y !== undefined ? [a, b, o, y] : [a, b, o];
30
+ }
31
+ function A(s) {
32
+ let [r, t, n, a] = s;
33
+ if (a)
34
+ return `#${(r << 24 | t << 16 | n << 8 | Math.round((a ?? 1) * 255)).toString(16).padStart(8, "0").toUpperCase()}`;
35
+ return `#${(r << 16 | t << 8 | n).toString(16).padStart(6, "0").toUpperCase()}`;
36
+ }
37
+ function R(s, r, t) {
38
+ s = (s % 360 + 360) % 360, t /= 100;
39
+ let n = r * Math.min(t, 1 - t) / 100, a = (b) => {
40
+ let o = (b + s / 30) % 12, y = t - n * Math.max(Math.min(o - 3, 9 - o, 1), -1);
41
+ return Math.round(255 * y);
42
+ };
43
+ return [a(0), a(8), a(4)];
44
+ }
45
+ function k(s) {
46
+ let [r, t, n] = s;
47
+ r /= 255, t /= 255, n /= 255;
48
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = 0, y = 0, c = (a + b) / 2;
49
+ if (a !== b) {
50
+ let u = a - b;
51
+ if (y = c > 0 && c < 1 ? u / (1 - Math.abs(2 * c - 1)) : 0, a === r)
52
+ o = (t - n) / u + (t < n ? 6 : 0);
53
+ else if (a === t)
54
+ o = (n - r) / u + 2;
55
+ else
56
+ o = (r - t) / u + 4;
57
+ o /= 6;
58
+ }
59
+ return [Math.round(o * 360), Math.round(y * 100), Math.round(c * 100)];
60
+ }
61
+ function H(s, r, t) {
62
+ s = (s % 360 + 360) % 360, r /= 100, t /= 100;
63
+ let n = (a) => {
64
+ let b = (a + s / 60) % 6, o = t - t * r * Math.max(Math.min(b, 4 - b, 1), 0);
65
+ return Math.round(255 * o);
66
+ };
67
+ return [n(5), n(3), n(1)];
68
+ }
69
+ function f(s) {
70
+ let [r, t, n] = s;
71
+ r /= 255, t /= 255, n /= 255;
72
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = a - b, y = 0, c = a === 0 ? 0 : o / a, u = a;
73
+ if (o !== 0) {
74
+ if (a === r)
75
+ y = (t - n) / o + (t < n ? 6 : 0);
76
+ else if (a === t)
77
+ y = (n - r) / o + 2;
78
+ else
79
+ y = (r - t) / o + 4;
80
+ y /= 6;
81
+ }
82
+ return [Math.round(y * 360), Math.round(c * 100), Math.round(u * 100)];
83
+ }
84
+ function O(s) {
85
+ let r = s[0] / 255, t = s[1] / 255, n = s[2] / 255, a = 1 - Math.max(r, t, n);
86
+ if (a === 1)
87
+ return [0, 0, 0, 100];
88
+ let b = (1 - r - a) / (1 - a), o = (1 - t - a) / (1 - a), y = (1 - n - a) / (1 - a);
89
+ return [Math.round(b * 100), Math.round(o * 100), Math.round(y * 100), Math.round(a * 100)];
90
+ }
91
+ function v(s, r, t, n) {
92
+ return s /= 100, r /= 100, t /= 100, n /= 100, [Math.round(255 * (1 - s) * (1 - n)), Math.round(255 * (1 - r) * (1 - n)), Math.round(255 * (1 - t) * (1 - n))];
93
+ }
94
+ var m = (s) => s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
95
+ var p = (s) => s <= 0.0031308 ? 12.92 * s : 1.055 * s ** 0.4166666666666667 - 0.055;
96
+ var i = (s, r) => Math.round(s * 10 ** r) / 10 ** r;
97
+ function T(s) {
98
+ let r = m(s[0] / 255), t = m(s[1] / 255), n = m(s[2] / 255), a = Math.cbrt(0.4122214708 * r + 0.5363325363 * t + 0.0514459929 * n), b = Math.cbrt(0.2119034982 * r + 0.6806995451 * t + 0.1073969566 * n), o = Math.cbrt(0.0883024619 * r + 0.2817188376 * t + 0.6299787005 * n);
99
+ return [i(0.2104542553 * a + 0.793617785 * b - 0.0040720468 * o, 4), i(1.9779984951 * a - 2.428592205 * b + 0.4505937099 * o, 4), i(0.0259040371 * a + 0.7827717662 * b - 0.808675766 * o, 4)];
100
+ }
101
+ function M(s, r, t) {
102
+ let n = (s + 0.3963377774 * r + 0.2158037573 * t) ** 3, a = (s - 0.1055613458 * r - 0.0638541728 * t) ** 3, b = (s - 0.0894841775 * r - 1.291485548 * t) ** 3, o = p(4.0767416621 * n - 3.3077115913 * a + 0.2309699292 * b), y = p(-1.2684380046 * n + 2.6097574011 * a - 0.3413193965 * b), c = p(-0.0041960863 * n - 0.7034186147 * a + 1.707614701 * b), u = (h) => Math.min(255, Math.max(0, Math.round(h * 255)));
103
+ return [u(o), u(y), u(c)];
104
+ }
105
+ function d(s) {
106
+ let [r, t, n] = T(s), a = Math.sqrt(t * t + n * n), b = (Math.atan2(n, t) * 180 / Math.PI + 360) % 360;
107
+ return [i(r, 4), i(a, 4), i(b, 2)];
108
+ }
109
+ function C(s, r, t) {
110
+ let n = t * Math.PI / 180;
111
+ return M(s, r * Math.cos(n), r * Math.sin(n));
112
+ }
113
+ function l(s) {
114
+ let r = s / 255;
115
+ return r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
116
+ }
117
+
118
+ class e {
119
+ r;
120
+ g;
121
+ b;
122
+ a;
123
+ constructor(s, r, t, n = 1) {
124
+ this.r = s, this.g = r, this.b = t, this.a = n;
125
+ }
126
+ static from(s, r) {
127
+ if (s === "hex") {
128
+ let [t, n, a, b] = x(r);
129
+ return new e(t, n, a, b);
130
+ }
131
+ if (s === "rgb") {
132
+ if (Array.isArray(r)) {
133
+ let [o, y, c, u] = r;
134
+ return new e(o, y, c, u);
135
+ }
136
+ let { r: t, g: n, b: a, a: b } = r;
137
+ return new e(t, n, a, b);
138
+ }
139
+ if (s === "hsl") {
140
+ let t, n, a, b;
141
+ if (Array.isArray(r))
142
+ [t, n, a, b] = r;
143
+ else
144
+ ({ h: t, s: n, l: a, a: b } = r);
145
+ let [o, y, c] = R(t, n, a);
146
+ return new e(o, y, c, b);
147
+ }
148
+ if (s === "hsv") {
149
+ let t, n, a, b;
150
+ if (Array.isArray(r))
151
+ [t, n, a, b] = r;
152
+ else
153
+ ({ h: t, s: n, v: a, a: b } = r);
154
+ let [o, y, c] = H(t, n, a);
155
+ return new e(o, y, c, b);
156
+ }
157
+ if (s === "cmyk") {
158
+ let t, n, a, b, o;
159
+ if (Array.isArray(r))
160
+ [t, n, a, b, o] = r;
161
+ else
162
+ ({ c: t, m: n, y: a, k: b, a: o } = r);
163
+ let [y, c, u] = v(t, n, a, b);
164
+ return new e(y, c, u, o);
165
+ }
166
+ if (s === "oklch") {
167
+ let t, n, a, b;
168
+ if (Array.isArray(r))
169
+ [t, n, a, b] = r;
170
+ else
171
+ ({ l: t, c: n, h: a, a: b } = r);
172
+ let [o, y, c] = C(t, n, a);
173
+ return new e(o, y, c, b);
174
+ }
175
+ if (s === "oklab") {
176
+ let t, n, a, b;
177
+ if (Array.isArray(r))
178
+ [t, n, a, b] = r;
179
+ else
180
+ ({ l: t, a: n, b: a, alpha: b } = r);
181
+ let [o, y, c] = M(t, n, a);
182
+ return new e(o, y, c, b);
183
+ }
184
+ throw Error("Invalid input");
185
+ }
186
+ to(s) {
187
+ switch (s) {
188
+ case "rgb":
189
+ return [this.r, this.g, this.b];
190
+ case "rgba":
191
+ return [this.r, this.g, this.b, this.a];
192
+ case "hex":
193
+ return A([this.r, this.g, this.b]);
194
+ case "hexa":
195
+ return A([this.r, this.g, this.b, this.a]);
196
+ case "hsl":
197
+ return k([this.r, this.g, this.b]);
198
+ case "hsla":
199
+ return [...k([this.r, this.g, this.b]), this.a];
200
+ case "hsv":
201
+ return f([this.r, this.g, this.b]);
202
+ case "hsva":
203
+ return [...f([this.r, this.g, this.b]), this.a];
204
+ case "cmyk":
205
+ return O([this.r, this.g, this.b]);
206
+ case "cmyka":
207
+ return [...O([this.r, this.g, this.b]), this.a];
208
+ case "oklch":
209
+ return d([this.r, this.g, this.b]);
210
+ case "oklcha":
211
+ return [...d([this.r, this.g, this.b]), this.a];
212
+ case "oklab":
213
+ return T([this.r, this.g, this.b]);
214
+ case "oklaba":
215
+ return [...T([this.r, this.g, this.b]), this.a];
216
+ default:
217
+ return [this.r, this.g, this.b];
218
+ }
219
+ }
220
+ getLuminance() {
221
+ let s = l(this.r), r = l(this.g), t = l(this.b);
222
+ return 0.2126 * s + 0.7152 * r + 0.0722 * t;
223
+ }
224
+ contrastRatio(s) {
225
+ let r = this.getLuminance(), t = s.getLuminance(), [n, a] = r >= t ? [r, t] : [t, r];
226
+ return (n + 0.05) / (a + 0.05);
227
+ }
228
+ bestContrastForeground() {
229
+ let s = new e(255, 255, 255, 1), r = new e(0, 0, 0, 1), t = this.contrastRatio(s), n = this.contrastRatio(r);
230
+ return t >= n ? s : r;
231
+ }
232
+ }
233
+
234
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
235
+ var r = 39;
236
+ var o = 49;
237
+ var f2 = "\x1B[";
238
+ var C2 = { 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, r], red: [31, r], green: [32, r], yellow: [33, r], blue: [34, r], magenta: [35, r], cyan: [36, r], white: [37, r], gray: [90, r], grey: [90, r], blackBright: [90, r], redBright: [91, r], greenBright: [92, r], yellowBright: [93, r], blueBright: [94, r], magentaBright: [95, r], cyanBright: [96, r], whiteBright: [97, r], bgBlack: [40, o], bgRed: [41, o], bgGreen: [42, o], bgYellow: [43, o], bgBlue: [44, o], bgMagenta: [45, o], bgCyan: [46, o], bgWhite: [47, o], bgBlackBright: [100, o], bgRedBright: [101, o], bgGreenBright: [102, o], bgYellowBright: [103, o], bgBlueBright: [104, o], bgMagentaBright: [105, o], bgCyanBright: [106, o], bgWhiteBright: [107, o], rgb: (i, n, a, l = "fg") => [`${l === "fg" ? 38 : 48};2;${i};${n};${a}`, l === "fg" ? r : o], hex: (i, n = "fg") => {
239
+ let [a, l, s] = e.from("hex", i).to("rgb");
240
+ return [`${n === "fg" ? 38 : 48};2;${a};${l};${s}`, n === "fg" ? r : o];
241
+ }, ansi256: (i, n = "fg") => [`${n === "fg" ? 38 : 48};5;${i}`, n === "fg" ? r : o] };
242
+ var b = new Set(["", "1", "2", "3", "true"]);
243
+ function h(i, n = globalThis.process?.env ?? {}) {
244
+ if (n.FORCE_COLOR !== undefined)
245
+ return b.has(n.FORCE_COLOR);
246
+ if (n.NO_COLOR !== undefined || n.NODE_DISABLE_COLORS !== undefined || n.TERM === "dumb")
247
+ return false;
248
+ return i?.isTTY === true;
249
+ }
250
+ function d2(i, n, a) {
251
+ if (!h(a.stream ?? globalThis.process?.stdout, a.env))
252
+ return n;
253
+ let l = "", s = "";
254
+ for (let g = 0, y = i.length;g < y; g++) {
255
+ let [c, p] = i[g];
256
+ l += `${f2}${c}m`, s = `${f2}${p}m${s}`;
257
+ }
258
+ return l + n + s;
259
+ }
260
+ function u(i, n = []) {
261
+ return new Proxy((l) => d2(n, l, i), { get(l, s) {
262
+ let g = C2[s];
263
+ if (Array.isArray(g))
264
+ return u(i, [...n, g]);
265
+ if (typeof g === "function")
266
+ return (...y) => u(i, [...n, g(...y)]);
267
+ throw Error(`Unknown style: ${String(s)}`);
268
+ } });
269
+ }
270
+ function le(i = {}) {
271
+ return u(i);
272
+ }
273
+ var t = le();
274
+
275
+ // ../kit/src/style.ts
276
+ function takesControlCodes(stream, env = process.env) {
277
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
278
+ }
279
+ function paint(stream, env = process.env) {
280
+ return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
281
+ }
282
+ var STATUSES = {
283
+ passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
284
+ failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
285
+ running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
286
+ queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
287
+ skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
288
+ };
289
+ var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
290
+
291
+ // ../kit/src/format.ts
292
+ function upTo(text, separator) {
293
+ const end = text.indexOf(separator);
294
+ return end === -1 ? text : text.slice(0, end);
295
+ }
296
+ var ESCAPE = String.fromCharCode(27);
297
+ function printJson(value) {
298
+ console.log(JSON.stringify(value, undefined, 2));
299
+ }
300
+
301
+ // ../kit/src/help.ts
302
+ import process2 from "process";
303
+ var OPTIONAL = /\[[^\]]+\]/g;
304
+ var USAGE_PREFIX = /^usage:\s*/i;
305
+ var FULL_STOP = /\.$/;
306
+ function usageLine(usage, colors = paint(process2.stdout)) {
307
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
308
+ }
309
+ function helpText(usage, options, colors = paint(process2.stdout), { examples = [], replaces } = {}) {
310
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
311
+ `);
312
+ }
313
+ function replacesRows(replaces, colors = paint(process2.stdout)) {
314
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
315
+ }
316
+ function wantsHelpJson(env = process2.env) {
317
+ return env.KIT_HELP === "json";
318
+ }
319
+ function description(usage, { examples = [], replaces } = {}) {
320
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
321
+ `);
322
+ const first = lines[0];
323
+ const colon = first.indexOf(": ");
324
+ const prose = lines[lines.indexOf("") + 1] ?? "";
325
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
326
+ return {
327
+ synopsis: colon === -1 ? first : first.slice(0, colon),
328
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
329
+ ...replaces === undefined ? {} : { replaces },
330
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
331
+ };
332
+ }
333
+ function exampleRows(examples, colors = paint(process2.stdout)) {
334
+ if (examples.length === 0)
335
+ return [];
336
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
337
+ }
338
+ function optionRows(options, colors = paint(process2.stdout)) {
339
+ const rows = Object.entries(options).map(([name, option]) => {
340
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
341
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
342
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
343
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
344
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
345
+ });
346
+ const width = Math.max(0, ...rows.map((row) => row.width));
347
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
348
+ }
349
+
350
+ // ../kit/src/text.ts
351
+ var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
352
+ function distance(a, b) {
353
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
354
+ for (const [i, left] of [...a].entries()) {
355
+ const current = [i + 1];
356
+ for (const [j, right] of [...b].entries())
357
+ current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
358
+ previous = current;
359
+ }
360
+ return previous[b.length] ?? 0;
361
+ }
362
+ function closest(name, names) {
363
+ const started = names.find((known) => known.startsWith(name));
364
+ if (started !== undefined)
365
+ return started;
366
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
367
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
368
+ }
369
+ // ../kit/src/input.ts
370
+ var WHOLE = /^\d+$/;
371
+ function wholeNumber(value, name, fallback, min = 1) {
372
+ if (value === undefined)
373
+ return fallback;
374
+ const number = Number(value);
375
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
376
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
377
+ return number;
378
+ }
379
+
380
+ // ../kit/src/args.ts
381
+ var DASHES = /^-+/;
382
+ function jsonOption(holds) {
383
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
384
+ }
385
+
386
+ class Exit extends Error {
387
+ code;
388
+ hint;
389
+ constructor(message, code, hint) {
390
+ super(message);
391
+ this.code = code;
392
+ this.hint = hint;
393
+ }
394
+ }
395
+ function fail(message, code = 2, hint) {
396
+ throw new Exit(message, code, hint);
397
+ }
398
+
399
+ class UsageError extends Exit {
400
+ constructor(message, hint) {
401
+ super(message, 2, hint);
402
+ }
403
+ }
404
+ function badUsage(message) {
405
+ throw new UsageError(message);
406
+ }
407
+
408
+ class HelpShown extends Exit {
409
+ constructor() {
410
+ super("help shown", 0);
411
+ }
412
+ }
413
+
414
+ class Completing {
415
+ options;
416
+ positionals;
417
+ candidates;
418
+ constructor(options, positionals = [], candidates = {}) {
419
+ this.options = options;
420
+ this.positionals = positionals;
421
+ this.candidates = candidates;
422
+ }
423
+ }
424
+ var completion = { active: false };
425
+ var OUTPUT_OPTIONS = {
426
+ color: { type: "string", description: "auto (on a terminal alone), always or never" },
427
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
428
+ };
429
+ function applyOutput(color, plain, env = process3.env) {
430
+ const when = plain === true ? "never" : color ?? "auto";
431
+ if (when === "auto")
432
+ return;
433
+ if (when !== "always" && when !== "never")
434
+ badUsage(`--color takes auto, always or never, not ${when}`);
435
+ if (when === "always") {
436
+ env.FORCE_COLOR = "1";
437
+ delete env.NO_COLOR;
438
+ } else {
439
+ env.NO_COLOR = "1";
440
+ delete env.FORCE_COLOR;
441
+ }
442
+ }
443
+ function parse(args, usage, options, settings = {}) {
444
+ const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
445
+ const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
446
+ const listing = listed(all, settings.allowNegative === true);
447
+ if (completion.active)
448
+ throw new Completing(listing, settings.positionals, settings.candidates);
449
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
450
+ let parsed;
451
+ try {
452
+ parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
453
+ } catch (error) {
454
+ const message = parseError(error);
455
+ throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
456
+ }
457
+ const values = parsed.values;
458
+ applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
459
+ if (values.help === true) {
460
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
461
+ throw new HelpShown;
462
+ }
463
+ checkChoices(parsed.values, all);
464
+ checkConflicts(parsed.values, all);
465
+ if (settings.positionals !== undefined)
466
+ checkPositionals(parsed.positionals, settings.positionals);
467
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
468
+ }
469
+ function splitRest(args, passes) {
470
+ const separator = passes ? args.indexOf("--") : -1;
471
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
472
+ }
473
+ function splitTrailing(args, options, count) {
474
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
475
+ let seen = 0;
476
+ if (count === 0)
477
+ return { own: args, rest: undefined };
478
+ for (let at = 0;at < args.length; at++) {
479
+ const word = args[at];
480
+ if (word === "--")
481
+ break;
482
+ if (word.startsWith("-")) {
483
+ if (takesValue(word))
484
+ at++;
485
+ continue;
486
+ }
487
+ seen++;
488
+ if (seen === count)
489
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
490
+ }
491
+ return { own: args, rest: undefined };
492
+ }
493
+ function listed(options, allowNegative) {
494
+ if (!allowNegative)
495
+ return options;
496
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
497
+ if (option.type !== "boolean" || option.negative === undefined)
498
+ return [[name, option]];
499
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
500
+ }));
501
+ }
502
+ function withBare(args, options) {
503
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
504
+ if (bare.size === 0)
505
+ return args;
506
+ const separator = args.indexOf("--");
507
+ const own = separator === -1 ? args : args.slice(0, separator);
508
+ return [...own.flatMap((arg, index) => {
509
+ const optional = bare.get(arg);
510
+ const next = own[index + 1];
511
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
512
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
513
+ }), ...separator === -1 ? [] : args.slice(separator)];
514
+ }
515
+ function checkConflicts(values, options) {
516
+ const given = (name) => values[name] !== undefined && values[name] !== false;
517
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
518
+ const other = given(name) ? conflicts.find(given) : undefined;
519
+ if (other !== undefined)
520
+ badUsage(`--${name} cannot be used with --${other}`);
521
+ }
522
+ }
523
+ function checkChoices(values, options) {
524
+ for (const [name, option] of Object.entries(options)) {
525
+ if (option.choices === undefined)
526
+ continue;
527
+ const given = values[name];
528
+ for (const value of Array.isArray(given) ? given : [given]) {
529
+ if (typeof value === "string")
530
+ oneOf(value, name, option.choices);
531
+ }
532
+ }
533
+ }
534
+ function oneOf(value, name, choices) {
535
+ if (!choices.includes(value))
536
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
537
+ return value;
538
+ }
539
+ function checkPositionals(given, names) {
540
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
541
+ const required = names.filter((name) => !name.startsWith("[")).length;
542
+ if (given.length < required)
543
+ badUsage(`missing ${names[given.length]}`);
544
+ if (!variadic && given.length > names.length)
545
+ badUsage(`unexpected argument ${given[names.length]}`);
546
+ }
547
+ function joinDashValues(args, options) {
548
+ const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
549
+ const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
550
+ const joined = [];
551
+ for (let i = 0;i < args.length; i++) {
552
+ const arg = args[i] ?? "";
553
+ if (arg === "--")
554
+ return [...joined, ...args.slice(i)];
555
+ const name = longOf.get(arg);
556
+ const next = args[i + 1];
557
+ if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
558
+ joined.push(`--${name}=${next}`);
559
+ i++;
560
+ } else {
561
+ joined.push(arg);
562
+ }
563
+ }
564
+ return joined;
565
+ }
566
+ function parseError(error) {
567
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
568
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
569
+ }
570
+ var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
571
+ function nearestOption(message, options, allowNegative) {
572
+ const typed = UNKNOWN_OPTION.exec(message)?.[1];
573
+ if (typed === undefined)
574
+ return;
575
+ const word = typed.replace(DASHES, "");
576
+ if (word.length < 2 && !typed.startsWith("--"))
577
+ return;
578
+ const known = Object.entries(options).flatMap(([name, option]) => [
579
+ ...option.short === undefined ? [] : [`-${option.short}`],
580
+ `--${name}`,
581
+ ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
582
+ ]);
583
+ const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
584
+ return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
585
+ }
586
+ // ../kit/src/process.ts
587
+ import { constants } from "os";
588
+ import process4 from "process";
589
+ var KILL_GRACE_MS = 2000;
590
+ var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
591
+ function exitCodeOf(code, signal) {
592
+ if (code !== null)
593
+ return code;
594
+ if (typeof signal === "number")
595
+ return 128 + signal;
596
+ return signal === null ? 129 : 128 + constants.signals[signal];
597
+ }
598
+ function holdSignals(cleanup) {
599
+ let received;
600
+ let child;
601
+ const held = {
602
+ get signal() {
603
+ return received;
604
+ },
605
+ forward: (to) => {
606
+ child = to;
607
+ },
608
+ release: () => {
609
+ for (const signal of SIGNALS)
610
+ process4.off(signal, onSignal);
611
+ }
612
+ };
613
+ function onSignal(signal) {
614
+ received = signal;
615
+ if (child !== undefined) {
616
+ child.kill(signal);
617
+ return;
618
+ }
619
+ if (cleanup === undefined)
620
+ return;
621
+ held.release();
622
+ cleanup(signal);
623
+ process4.kill(process4.pid, signal);
624
+ }
625
+ for (const signal of SIGNALS)
626
+ process4.on(signal, onSignal);
627
+ return held;
628
+ }
629
+ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
630
+ const chunks = [];
631
+ const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
632
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
633
+ const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
634
+ const timers = [];
635
+ const killGroup = (killing) => {
636
+ if (state.done)
637
+ return;
638
+ try {
639
+ if (grouped)
640
+ process4.kill(-proc.pid, killing);
641
+ else
642
+ proc.kill(killing);
643
+ } catch {}
644
+ };
645
+ const stop = () => {
646
+ killGroup("SIGTERM");
647
+ timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
648
+ };
649
+ const onAbort = () => stop();
650
+ if (timeoutMs !== undefined) {
651
+ timers.push(setTimeout(() => {
652
+ state.timedOut = true;
653
+ stop();
654
+ }, timeoutMs));
655
+ }
656
+ if (signal?.aborted === true)
657
+ onAbort();
658
+ else
659
+ signal?.addEventListener("abort", onAbort, { once: true });
660
+ onStart?.({ kill: (killing) => killGroup(killing) });
661
+ const drain = async (stream, name) => {
662
+ for await (const data of stream) {
663
+ if (state.failure !== undefined)
664
+ continue;
665
+ try {
666
+ onChunk?.({ stream: name, data });
667
+ } catch (error) {
668
+ state.failure = error;
669
+ stop();
670
+ continue;
671
+ }
672
+ if (state.kept + data.length > maxBytes) {
673
+ state.truncated = true;
674
+ continue;
675
+ }
676
+ state.kept += data.length;
677
+ chunks.push({ stream: name, data });
678
+ }
679
+ };
680
+ try {
681
+ await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
682
+ await proc.exited;
683
+ } finally {
684
+ state.done = true;
685
+ for (const timer of timers)
686
+ clearTimeout(timer);
687
+ signal?.removeEventListener("abort", onAbort);
688
+ }
689
+ if (state.failure !== undefined)
690
+ throw state.failure;
691
+ const joined = () => Buffer.concat(chunks.map(({ data }) => data));
692
+ let output;
693
+ let text;
694
+ return {
695
+ code: exitCodeOf(proc.exitCode, proc.signalCode),
696
+ chunks,
697
+ timedOut: state.timedOut,
698
+ truncated: state.truncated,
699
+ get output() {
700
+ return output ??= joined();
701
+ },
702
+ get text() {
703
+ return text ??= (output ??= joined()).toString();
704
+ }
705
+ };
706
+ }
707
+
708
+ // ../kit/src/progress.ts
709
+ var ESC = String.fromCharCode(27);
710
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
711
+ var RESET_STYLE = `${ESC}[0m`;
712
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
713
+ // ../kit/src/cli.ts
714
+ import process6 from "process";
715
+
716
+ // ../kit/src/usage.ts
717
+ import { appendFileSync, mkdirSync } from "fs";
718
+ import { homedir } from "os";
719
+ import { dirname, isAbsolute, join } from "path";
720
+ import process5 from "process";
721
+
722
+ // ../kit/src/logs.ts
723
+ var DAY_MS = 24 * 60 * 60 * 1000;
724
+ var CLI_FOLDER = "kaynooo-cli";
725
+
726
+ // ../kit/src/usage.ts
727
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
728
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
729
+ var LONGEST_NAME = 40;
730
+ var usageError;
731
+ function noteUsageError(message) {
732
+ usageError = message;
733
+ }
734
+ function stateHome(env = process5.env) {
735
+ const dir = env.XDG_STATE_HOME;
736
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
737
+ }
738
+ function usagePath(env = process5.env) {
739
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
740
+ }
741
+ function usageRecorded(env = process5.env) {
742
+ const off = env.KAYNOOO_CLI_NO_USAGE;
743
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
744
+ }
745
+ function flagNames(argv) {
746
+ const end = argv.indexOf("--");
747
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
748
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
749
+ }
750
+ function usageEntry(bin, command, argv, code, now = new Date) {
751
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
752
+ usageError = undefined;
753
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
754
+ }
755
+ function recordUsage(entry, env = process5.env) {
756
+ if (!usageRecorded(env))
757
+ return;
758
+ try {
759
+ const path = usagePath(env);
760
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
761
+ appendFileSync(path, `${JSON.stringify(entry)}
762
+ `, { mode: 384 });
763
+ } catch {}
764
+ }
765
+
766
+ // ../kit/src/cli.ts
767
+ var LEVEL_OPTIONS = {
768
+ ...OUTPUT_OPTIONS,
769
+ help: { type: "boolean", short: "h", description: "show this help" }
770
+ };
771
+ var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
772
+ function printError(prefix, message, hint, cause) {
773
+ const colors = paint(process6.stderr);
774
+ const styled = takesControlCodes(process6.stderr);
775
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
776
+ const under = (label, text, tint) => text === undefined ? "" : `
777
+ ${styled ? tint(label) : `${label}:`} ${text}`;
778
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
779
+ }
780
+ function runHint(command, effect) {
781
+ return `run \`${command}\`${effect === undefined ? "" : ` to ${effect}`}`;
782
+ }
783
+ function printJsonError(message, hint, cause) {
784
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
785
+ }
786
+ function wantsJson(argv) {
787
+ const end = argv.indexOf("--");
788
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
789
+ }
790
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
791
+ if (error instanceof HelpShown)
792
+ return 0;
793
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
794
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
795
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
796
+ if (error instanceof UsageError)
797
+ noteUsageError(error.message);
798
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
799
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
800
+ return error instanceof Exit ? error.code : 1;
801
+ }
802
+ var COMPLETE = "__complete";
803
+ var FILES = "__files__";
804
+ async function completingOf(run) {
805
+ completion.active = true;
806
+ try {
807
+ await run([]);
808
+ } catch (error) {
809
+ if (error instanceof Completing)
810
+ return error;
811
+ } finally {
812
+ completion.active = false;
813
+ }
814
+ return new Completing({});
815
+ }
816
+ function candidateLine(candidate) {
817
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
818
+ }
819
+ function positionalBeingTyped(before, { options, positionals }) {
820
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
821
+ let index = 0;
822
+ let at = 0;
823
+ while (at < before.length) {
824
+ const word = before[at];
825
+ if (word === "--") {
826
+ index += before.length - at - 1;
827
+ break;
828
+ }
829
+ if (!word.startsWith("-"))
830
+ index++;
831
+ else if (takesValue(word))
832
+ at++;
833
+ at++;
834
+ }
835
+ const last = positionals.at(-1);
836
+ if (index < positionals.length)
837
+ return positionals[index];
838
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
839
+ }
840
+ async function leafCandidates(run, words) {
841
+ const completing = await completingOf(run);
842
+ if ((words.at(-1) ?? "").startsWith("-"))
843
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
844
+ const flag = words.at(-2);
845
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
846
+ if (option?.type === "string") {
847
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
848
+ return values === undefined ? [FILES] : values.map(candidateLine);
849
+ }
850
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
851
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
852
+ return values === undefined ? [FILES] : values.map(candidateLine);
853
+ }
854
+ async function printCandidates(found) {
855
+ for (const line of await found)
856
+ console.log(line);
857
+ return 0;
858
+ }
859
+ async function runMain({ name, version, run, redact, usage }, argv = process6.argv.slice(2)) {
860
+ if (argv[0] === COMPLETE)
861
+ return printCandidates(leafCandidates(run, argv.slice(1)));
862
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
863
+ console.log(version);
864
+ return 0;
865
+ }
866
+ let code;
867
+ try {
868
+ code = await run(argv);
869
+ } catch (error) {
870
+ code = reportThrown(name, error, redact, wantsJson(argv));
871
+ }
872
+ if (usage !== false)
873
+ recordUsage(usageEntry(name, undefined, argv, code));
874
+ return code;
875
+ }
876
+ // ../kit/src/secrets.ts
877
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
878
+ // ../kit/src/sessions.ts
879
+ var {Glob } = globalThis.Bun;
880
+ var SESSION_FILES = new Glob("*.json");
881
+ var ACCOUNT_DIRS = new Glob("*/sessions");
882
+ // package.json
883
+ var version = "0.6.0";
884
+
885
+ // src/branch.ts
886
+ import { basename } from "path";
887
+ import process8 from "process";
888
+
889
+ // ../kit/src/fzf.ts
890
+ function table(rows) {
891
+ const widths = rows[0]?.cells.map((_, index) => Math.max(...rows.map((row) => Bun.stringWidth(row.cells[index])))) ?? [];
892
+ return rows.map((row) => [
893
+ ...row.hidden,
894
+ ...row.cells.map((cell, index) => index === row.cells.length - 1 ? cell.trimEnd() : `${cell}${" ".repeat(widths[index] + 1 - Bun.stringWidth(cell))}`)
895
+ ].join("\t"));
896
+ }
897
+ function fzf(rows, options) {
898
+ const hidden = options.hidden ?? rows[0]?.hidden.length ?? 0;
899
+ const proc = Bun.spawnSync([
900
+ "fzf",
901
+ "--prompt",
902
+ options.prompt,
903
+ ...options.header === undefined ? [] : ["--header", options.header],
904
+ ...(options.expect ?? []).length > 0 ? ["--expect", (options.expect ?? []).join(",")] : [],
905
+ "--ansi",
906
+ "--reverse",
907
+ "--height",
908
+ options.height ?? "100%",
909
+ "--delimiter",
910
+ "\t",
911
+ "--with-nth",
912
+ `${hidden + 1}..`,
913
+ "--nth",
914
+ `1..${options.searched}`,
915
+ "--tabstop",
916
+ "1",
917
+ "--tiebreak",
918
+ "chunk,index",
919
+ ...options.preview === undefined ? [] : ["--preview", options.preview, "--preview-window", "down,40%"],
920
+ ...(options.bind ?? []).flatMap((bind) => ["--bind", bind]),
921
+ ...options.query === true ? ["--print-query"] : []
922
+ ], {
923
+ stdin: new TextEncoder().encode(table(rows).join(`
924
+ `)),
925
+ stdout: "pipe",
926
+ stderr: "inherit"
927
+ });
928
+ return picked(proc.stdout.toString(), hidden, options);
929
+ }
930
+ function picked(output, hidden, options) {
931
+ const lines = output.split(`
932
+ `);
933
+ const query = options.query === true ? lines.shift() : "";
934
+ const [key, line] = (options.expect ?? []).length > 0 ? [lines[0], lines[1]] : ["", lines[0]];
935
+ if (line !== undefined && line !== "")
936
+ return { key, hidden: line.split("\t").slice(0, hidden), query };
937
+ return options.query === true && key !== "" ? { key, hidden: [], query } : undefined;
938
+ }
939
+ function word(arg) {
940
+ if (typeof arg === "string")
941
+ return `=${arg}`;
942
+ return "given" in arg ? `+${arg.given}` : `?${arg.ask}`;
943
+ }
944
+ function emit(mode, typed, recorded, command) {
945
+ const words = command.map(word);
946
+ console.log([mode, typed, recorded, ...words].join(`
947
+ `));
948
+ }
949
+ function list(rows) {
950
+ console.log(JSON.stringify(rows));
951
+ }
952
+
953
+ // src/branch.ts
954
+ var usage2 = `gb [branch]
955
+ gb -
956
+ gb -c <name>
957
+ gb -d <branch>
958
+
959
+ Without a branch, picks one with fzf when it is installed and a terminal is attached: the branches last checked out first, as the reflog has them, then the other local ones, then the remote ones with no local branch yet. The header says where HEAD stands, each row how its branch stands against its upstream and whether it is merged into the base. enter switches to it (a remote one gets its local tracking branch), ctrl-n creates a branch named after the query, ctrl-d deletes the highlighted local branch with \`git branch -d\`, which refuses one not merged yet, and ctrl-r fetches, prunes and lists again. Without fzf or a terminal it lists the branches instead.
960
+ \`gb <branch>\` switches without the picker, a bare name finding the remote branch it would create. \`gb -\` goes back to the previous branch, \`gb -c <name>\` creates one and switches to it, \`gb -d <branch>\` deletes a local one.
961
+ A branch checked out in another worktree cannot be switched to: gb prints that worktree's path on stdout and a hint on stderr, since a command cannot change its parent shell's folder.
962
+
963
+ Exits with the code of the git command it ran, 1 when there is no branch by that name or nothing was picked, 2 outside a git repository.`;
964
+ var options = {
965
+ create: { type: "boolean", short: "c", description: "create the branch named by the rest of the line and switch to it" },
966
+ delete: { type: "boolean", short: "d", description: "delete the local branch with git branch -d" },
967
+ json: jsonOption("[{ name, remote, worktree, when, subject, date, upstream, track, merged }]")
968
+ };
969
+ var FIELDS = ["%(refname)", "%(refname:short)", "%(committerdate:unix)", "%(committerdate:relative)", "%(subject)", "%(worktreepath)", "%(upstream:short)", "%(upstream:track,nobracket)"];
970
+ var CHECKOUT = /^checkout: moving from (\S+) to (\S+)$/;
971
+ var KEYS = "enter go, ctrl-n new from query, ctrl-d delete if merged, ctrl-r fetch";
972
+ var TRACK_TINTS = { ahead: "green", behind: "red", gone: "yellow" };
973
+ var TRACK_WORD = /^\w+/;
974
+ var WHITESPACE = /\s+/;
975
+ var colors = paint({ isTTY: true });
976
+ function read(args) {
977
+ const proc = Bun.spawnSync(["git", ...args], { stderr: "pipe" });
978
+ return proc.success ? proc.stdout.toString().trim() : "";
979
+ }
980
+ function visited(reflog) {
981
+ const order = new Set;
982
+ for (const line of reflog) {
983
+ const move = CHECKOUT.exec(line);
984
+ if (move) {
985
+ order.add(move[2]);
986
+ order.add(move[1]);
987
+ }
988
+ }
989
+ return [...order];
990
+ }
991
+ function ordered(branches, recent, current) {
992
+ const rank = new Map(recent.map((name, index) => [name, index]));
993
+ const locals = branches.filter((branch) => !branch.remote && branch.name !== current);
994
+ const names = new Set(branches.filter((branch) => !branch.remote).map((branch) => branch.name));
995
+ const remotes = branches.filter((branch) => branch.remote && !names.has(localName(branch.name)));
996
+ const byDate = (a, b) => b.date - a.date;
997
+ return [
998
+ ...locals.filter((branch) => rank.has(branch.name)).sort((a, b) => rank.get(a.name) - rank.get(b.name)),
999
+ ...locals.filter((branch) => !rank.has(branch.name)).sort(byDate),
1000
+ ...remotes.sort(byDate)
1001
+ ];
1002
+ }
1003
+ function localName(remote) {
1004
+ return remote.slice(remote.indexOf("/") + 1);
1005
+ }
1006
+ function branches(against) {
1007
+ const here = read(["rev-parse", "--show-toplevel"]);
1008
+ const lines = read(["for-each-ref", `--format=${FIELDS.join("%00")}`, "refs/heads", "refs/remotes"]).split(`
1009
+ `).filter(Boolean);
1010
+ const merged = new Set(against !== undefined ? read(["branch", "--merged", against, "--format=%(refname:short)"]).split(`
1011
+ `) : []);
1012
+ return lines.map((line) => line.split("\x00")).filter(([ref = ""]) => !ref.endsWith("/HEAD")).map(([ref = "", name = "", date = "0", when = "", subject = "", worktree = "", upstream = "", track = ""]) => {
1013
+ const remote = ref.startsWith("refs/remotes/");
1014
+ return {
1015
+ name,
1016
+ remote,
1017
+ worktree: worktree === here ? "" : worktree,
1018
+ when,
1019
+ subject,
1020
+ date: Number(date),
1021
+ upstream,
1022
+ track,
1023
+ merged: !remote && merged.has(name) && name !== against && name !== localName(against ?? "")
1024
+ };
1025
+ });
1026
+ }
1027
+ function base() {
1028
+ const remote = read(["symbolic-ref", "--short", "-q", "refs/remotes/origin/HEAD"]);
1029
+ if (remote)
1030
+ return remote;
1031
+ return ["main", "master"].find((name) => read(["rev-parse", "--verify", "-q", `refs/heads/${name}`]) !== "");
1032
+ }
1033
+ function goTo(branch) {
1034
+ if (branch.worktree)
1035
+ return ["cd", branch.worktree];
1036
+ return branch.remote ? ["git", "switch", "--track", branch.name] : ["git", "switch", branch.name];
1037
+ }
1038
+ function remove(branch) {
1039
+ if (branch.remote)
1040
+ fail(`${branch.name} is a remote branch, deleting it is left to git push --delete`, 1);
1041
+ return ["git", "branch", "-d", branch.name];
1042
+ }
1043
+ function invalid(name) {
1044
+ if (!name)
1045
+ return "Type the name of the new branch first";
1046
+ return Bun.spawnSync(["git", "check-ref-format", "--branch", name], { stdout: "ignore", stderr: "ignore" }).success ? "" : `${name} is not a valid branch name`;
1047
+ }
1048
+ function track(text, tint = colors) {
1049
+ return text.split(", ").filter(Boolean).map((part) => tint[TRACK_TINTS[TRACK_WORD.exec(part)?.[0] ?? ""] ?? "dim"](part)).join(" ");
1050
+ }
1051
+ function tags(branch, tint = colors) {
1052
+ const away = branch.remote ? tint.magenta("remote") : "";
1053
+ const where = branch.worktree === "" ? away : tint.green(`wt ${basename(branch.worktree)}`);
1054
+ return [where, track(branch.track, tint), branch.merged ? tint.cyan("merged") : ""].filter(Boolean).join(" ");
1055
+ }
1056
+ function status(current, head, changed) {
1057
+ const parts = [current ? `on ${colors.bold(current.name)}` : `${colors.bold("HEAD")} detached at ${head}`];
1058
+ if (current?.upstream !== undefined && current.upstream !== "")
1059
+ parts.push(`${colors.dim(current.upstream)} ${track(current.track) || "up to date"}`);
1060
+ if (changed)
1061
+ parts.push(colors.yellow(`${changed} uncommitted`));
1062
+ return parts.join(colors.dim(" | "));
1063
+ }
1064
+ function row(branch) {
1065
+ const name = branch.remote ? `${colors.dim(branch.name.slice(0, branch.name.indexOf("/") + 1))}${colors.magenta(localName(branch.name))}` : branch.name;
1066
+ return { hidden: [branch.name], cells: [name, colors.dim(branch.when), tags(branch), colors.dim(branch.subject)] };
1067
+ }
1068
+ function preview(name) {
1069
+ const against = base();
1070
+ const lines = [];
1071
+ const compared = against !== undefined && against !== name;
1072
+ if (compared) {
1073
+ const [behind = "0", ahead = "0"] = read(["rev-list", "--left-right", "--count", `${against}...${name}`]).split(WHITESPACE);
1074
+ lines.push(`${colors.green(`${ahead} ahead`)}, ${colors.red(`${behind} behind`)} ${colors.dim(against)}
1075
+ `);
1076
+ }
1077
+ const own = compared ? [`${against}..${name}`] : [name];
1078
+ const log = ["log", "--color=always", "--format=%C(auto)%h %s %C(dim)%cr, %an", "-30"];
1079
+ lines.push(read([...log, ...own]) || read([...log, name]));
1080
+ return lines.join(`
1081
+ `);
1082
+ }
1083
+ function load() {
1084
+ const found = branches(base());
1085
+ const current = read(["branch", "--show-current"]);
1086
+ return { found, current, all: ordered(found, visited(read(["reflog", "-n", "2000", "--format=%gs"]).split(`
1087
+ `)), current) };
1088
+ }
1089
+ function header(found, current, failure = "") {
1090
+ const changed = read(["status", "--porcelain", "--untracked-files=no"]).split(`
1091
+ `).filter(Boolean).length;
1092
+ const here = found.find((branch) => !branch.remote && branch.name === current) ?? (current ? { name: current, upstream: "", track: "" } : undefined);
1093
+ const line = status(here, here ? "" : read(["rev-parse", "--short", "HEAD"]), changed);
1094
+ return `${line}${failure ? colors.dim(" | ") + colors.red(failure) : ""}
1095
+ ${KEYS}`;
1096
+ }
1097
+ function listed2(all) {
1098
+ list([
1099
+ ...all.map((branch) => ({
1100
+ label: branch.name,
1101
+ hint: [branch.track, branch.when, branch.subject].filter(Boolean).join(" \xB7 "),
1102
+ typed: branch.name,
1103
+ preview: ["--show", branch.name],
1104
+ actions: [
1105
+ ...branch.remote ? [] : [{ label: "Delete", key: "ctrl-d", typed: `-d ${branch.name}` }],
1106
+ { label: "Fetch", key: "ctrl-r", reload: ["--fetch"] }
1107
+ ]
1108
+ })),
1109
+ { label: "New branch", hint: "git switch -c", typed: "-c", asks: "" }
1110
+ ]);
1111
+ }
1112
+ function hidden(flag, rest) {
1113
+ if (flag === "--show") {
1114
+ console.log(preview(rest[0] ?? ""));
1115
+ return 0;
1116
+ }
1117
+ if (read(["rev-parse", "--git-dir"]) === "")
1118
+ fail("not a git repository", 2);
1119
+ if (flag === "--fetch") {
1120
+ const fetched = Bun.spawnSync(["git", "fetch", "--all", "--prune", "--quiet"], { stdout: "ignore", stderr: "ignore" }).success;
1121
+ console.log(header(branches(base()), read(["branch", "--show-current"]), fetched ? "" : "fetch failed"));
1122
+ return 0;
1123
+ }
1124
+ if (flag === "--list") {
1125
+ listed2(load().all);
1126
+ return 0;
1127
+ }
1128
+ if (flag === "--rows") {
1129
+ console.log(table(load().all.map(row)).join(`
1130
+ `));
1131
+ return 0;
1132
+ }
1133
+ if (flag === "--names") {
1134
+ console.log(load().all.map((branch) => `${branch.name} ${branch.when}, ${branch.subject}`).join(`
1135
+ `));
1136
+ return 0;
1137
+ }
1138
+ return;
1139
+ }
1140
+ function create(name) {
1141
+ const problem = invalid(name);
1142
+ if (problem)
1143
+ fail(problem, 1);
1144
+ return ["git", "switch", "-c", name];
1145
+ }
1146
+ async function gb(args) {
1147
+ const [flag = ""] = args;
1148
+ if (["--show", "--fetch", "--list", "--rows", "--names"].includes(flag))
1149
+ return hidden(flag, args.slice(1)) ?? 0;
1150
+ const emitting = flag === "--emit";
1151
+ const parsed = parse(emitting ? args.slice(1) : args, usage2, options, { replaces: "git switch, git branch -d and git checkout typed per branch", examples: ["gb", ["gb feature", "switch to feature, or create it from origin/feature"], ["gb -", "back to the previous branch"], ["gb -c fix/login", "create a branch and switch to it"], ["gb -d old", "delete a merged local branch"]] });
1152
+ const [named] = parsed.positionals;
1153
+ if (read(["rev-parse", "--git-dir"]) === "")
1154
+ fail("not a git repository", 2);
1155
+ let typed;
1156
+ let command;
1157
+ if (parsed.values.create === true) {
1158
+ const name = parsed.positionals.join(" ");
1159
+ command = create(name);
1160
+ typed = `-c ${name}`;
1161
+ } else if (named === "-") {
1162
+ command = ["git", "switch", "-"];
1163
+ typed = "-";
1164
+ } else {
1165
+ const { found, current, all } = load();
1166
+ const deleting = parsed.values.delete === true;
1167
+ let branch;
1168
+ let key = "";
1169
+ if (named === undefined) {
1170
+ const interactive = process8.stdin.isTTY && process8.stderr.isTTY && parsed.values.json !== true;
1171
+ if (!interactive || Bun.which("fzf") === null) {
1172
+ if (emitting)
1173
+ fail("the picker needs a terminal and fzf", 1);
1174
+ if (interactive)
1175
+ console.error("fzf is not installed, listing the branches instead");
1176
+ if (parsed.values.json === true)
1177
+ printJson(all);
1178
+ else
1179
+ console.log(table(all.map(row)).map((line) => process8.stdout.isTTY ? line : Bun.stripANSI(line)).join(`
1180
+ `));
1181
+ return 0;
1182
+ }
1183
+ const self = `${process8.execPath} ${process8.argv[1]}`;
1184
+ const picked = fzf(all.map(row), {
1185
+ prompt: "gb> ",
1186
+ header: header(found, current),
1187
+ expect: ["ctrl-d", "ctrl-n"],
1188
+ searched: 1,
1189
+ preview: `${self} --show {1}`,
1190
+ bind: [`ctrl-r:transform-header(${self} --fetch)+reload(${self} --rows)`],
1191
+ query: true,
1192
+ hidden: 1
1193
+ });
1194
+ if (picked?.key === "ctrl-n") {
1195
+ const name = picked.query.trim();
1196
+ return finish(create(name), `-c ${name}`, emitting);
1197
+ }
1198
+ branch = picked && load().all.find((candidate) => candidate.name === picked.hidden[0]);
1199
+ if (!branch)
1200
+ return 1;
1201
+ key = picked.key;
1202
+ } else {
1203
+ branch = all.find((candidate) => candidate.name === named) ?? all.find((candidate) => candidate.remote && localName(candidate.name) === named);
1204
+ if (!branch) {
1205
+ const nearest = closest(named, all.map((candidate) => candidate.name));
1206
+ return fail(`no branch named ${named}${nearest === undefined ? "" : `, did you mean ${nearest}?`}`, 1);
1207
+ }
1208
+ }
1209
+ if (deleting || key === "ctrl-d") {
1210
+ command = remove(branch);
1211
+ typed = `-d ${branch.name}`;
1212
+ } else {
1213
+ command = goTo(branch);
1214
+ typed = branch.name;
1215
+ }
1216
+ }
1217
+ return finish(command, typed, emitting);
1218
+ }
1219
+ async function finish(command, typed, emitting) {
1220
+ if (emitting) {
1221
+ emit("run", typed, "", command);
1222
+ return 0;
1223
+ }
1224
+ const words = command;
1225
+ if (words[0] === "cd") {
1226
+ console.log(words[1]);
1227
+ console.error(`checked out in another worktree: cd ${words[1]}`);
1228
+ return 0;
1229
+ }
1230
+ return Bun.spawn(words, { stdio: ["inherit", "inherit", "inherit"] }).exited;
1231
+ }
1232
+
1233
+ // src/gb.ts
1234
+ process9.exitCode = await runMain({ name: "gb", version, run: gb });
package/dist/gc.js CHANGED
@@ -880,7 +880,7 @@ var {Glob } = globalThis.Bun;
880
880
  var SESSION_FILES = new Glob("*.json");
881
881
  var ACCOUNT_DIRS = new Glob("*/sessions");
882
882
  // package.json
883
- var version = "0.5.2";
883
+ var version = "0.6.0";
884
884
 
885
885
  // src/git.ts
886
886
  async function git2(args, env) {
package/dist/gst.js CHANGED
@@ -880,7 +880,7 @@ var {Glob } = globalThis.Bun;
880
880
  var SESSION_FILES = new Glob("*.json");
881
881
  var ACCOUNT_DIRS = new Glob("*/sessions");
882
882
  // package.json
883
- var version = "0.5.2";
883
+ var version = "0.6.0";
884
884
 
885
885
  // src/git.ts
886
886
  async function git2(args, env) {
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-git",
3
3
  "type": "module",
4
- "version": "0.5.2",
5
- "description": "gst and gc: a repository's state in one call, and a commit of exactly the paths given, its message checked before anything is staged.",
4
+ "version": "0.6.0",
5
+ "description": "gst, gc and gb: a repository's state in one call, a commit of exactly the paths given, its message checked before anything is staged, and a branch picked with fzf.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
8
8
  "homepage": "https://git.kaynooo.fr/kaynooo/cli/src/branch/main/packages/git#readme",
@@ -24,7 +24,8 @@
24
24
  },
25
25
  "bin": {
26
26
  "gst": "./dist/gst.js",
27
- "gc": "./dist/gc.js"
27
+ "gc": "./dist/gc.js",
28
+ "gb": "./dist/gb.js"
28
29
  },
29
30
  "files": [
30
31
  "dist",
@@ -37,9 +38,10 @@
37
38
  "registry": "https://git.kaynooo.fr/api/packages/kaynooo/npm/"
38
39
  },
39
40
  "scripts": {
40
- "build": "$npm_execpath build src/gst.ts src/gc.ts --target bun --outdir dist",
41
+ "build": "$npm_execpath build src/gst.ts src/gc.ts src/gb.ts --target bun --outdir dist",
41
42
  "gst": "$npm_execpath src/gst.ts",
42
- "gc": "$npm_execpath src/gc.ts"
43
+ "gc": "$npm_execpath src/gc.ts",
44
+ "gb": "$npm_execpath src/gb.ts"
43
45
  },
44
46
  "devDependencies": {
45
47
  "@kaynooo/cli-kit": "0.20.0"