@kaynooo/cli-git 0.7.1 → 0.9.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 +2 -2
- package/dist/gb.js +934 -119
- package/dist/gc.js +287 -52
- package/dist/gst.js +300 -57
- package/package.json +3 -3
package/dist/gb.js
CHANGED
|
@@ -2,13 +2,37 @@
|
|
|
2
2
|
// @bun
|
|
3
3
|
|
|
4
4
|
// src/gb.ts
|
|
5
|
-
import
|
|
5
|
+
import process17 from "process";
|
|
6
6
|
// ../kit/src/args.ts
|
|
7
|
-
import
|
|
7
|
+
import process9 from "process";
|
|
8
8
|
import { parseArgs } from "util";
|
|
9
9
|
|
|
10
|
-
// ../kit/src/
|
|
10
|
+
// ../kit/src/format.ts
|
|
11
|
+
import process7 from "process";
|
|
12
|
+
|
|
13
|
+
// ../kit/src/mode.ts
|
|
11
14
|
import process2 from "process";
|
|
15
|
+
var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
16
|
+
var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
|
|
17
|
+
function isSet(value) {
|
|
18
|
+
return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
19
|
+
}
|
|
20
|
+
function outputMode(stream = process2.stdout, env = process2.env) {
|
|
21
|
+
const chosen = env.KIT_MODE;
|
|
22
|
+
if (chosen !== undefined && MODES.has(chosen))
|
|
23
|
+
return chosen;
|
|
24
|
+
if (AGENT_VARIABLES.some((name) => isSet(env[name])))
|
|
25
|
+
return "agent";
|
|
26
|
+
if (stream.isTTY === true)
|
|
27
|
+
return "terminal";
|
|
28
|
+
return isSet(env.CI) ? "ci" : "pipe";
|
|
29
|
+
}
|
|
30
|
+
function isInteractive(streams = process2) {
|
|
31
|
+
return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// ../kit/src/style.ts
|
|
35
|
+
import process6 from "process";
|
|
12
36
|
|
|
13
37
|
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
|
|
14
38
|
function x(s) {
|
|
@@ -271,21 +295,229 @@ function le(i = {}) {
|
|
|
271
295
|
}
|
|
272
296
|
var t = le();
|
|
273
297
|
|
|
298
|
+
// ../kit/src/theme.ts
|
|
299
|
+
import { existsSync as existsSync2, readFileSync, statSync } from "fs";
|
|
300
|
+
import { homedir as homedir2 } from "os";
|
|
301
|
+
import { join as join3, resolve as resolve2 } from "path";
|
|
302
|
+
import process5 from "process";
|
|
303
|
+
|
|
304
|
+
// ../kit/src/config.ts
|
|
305
|
+
import { existsSync } from "fs";
|
|
306
|
+
import { dirname, join, resolve } from "path";
|
|
307
|
+
import process3 from "process";
|
|
308
|
+
function findUp(names, from = process3.cwd(), stop = () => false) {
|
|
309
|
+
const wanted = typeof names === "string" ? [names] : names;
|
|
310
|
+
for (let dir = resolve(from);; dir = dirname(dir)) {
|
|
311
|
+
const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
|
|
312
|
+
if (found !== undefined)
|
|
313
|
+
return found;
|
|
314
|
+
if (stop(dir) || dirname(dir) === dir)
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// ../kit/src/user-config.ts
|
|
320
|
+
import { homedir } from "os";
|
|
321
|
+
import { join as join2 } from "path";
|
|
322
|
+
import process4 from "process";
|
|
323
|
+
function configBase(where = {}) {
|
|
324
|
+
const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
|
|
325
|
+
return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
|
|
326
|
+
}
|
|
327
|
+
function userConfigPath(bin, where = {}) {
|
|
328
|
+
return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// ../kit/src/theme.ts
|
|
332
|
+
var DEFAULT = {
|
|
333
|
+
colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
|
|
334
|
+
glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501" },
|
|
335
|
+
accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
|
|
336
|
+
bins: {}
|
|
337
|
+
};
|
|
338
|
+
var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
|
|
339
|
+
var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
|
|
340
|
+
var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#" };
|
|
341
|
+
var PRESETS = {
|
|
342
|
+
default: {},
|
|
343
|
+
"high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"] },
|
|
344
|
+
mono: { colors: MONO, accents: ["bold"] },
|
|
345
|
+
ascii: { glyphs: ASCII }
|
|
346
|
+
};
|
|
347
|
+
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"]);
|
|
348
|
+
var HEX = /^#[0-9a-f]{6}$/i;
|
|
349
|
+
var CONTROL = /\p{Cc}/u;
|
|
350
|
+
var MAX_FILE_BYTES = 64 * 1024;
|
|
351
|
+
var SPACES = /\s+/;
|
|
352
|
+
function isColorSpec(spec) {
|
|
353
|
+
if (typeof spec === "number")
|
|
354
|
+
return Number.isInteger(spec) && spec >= 0 && spec <= 255;
|
|
355
|
+
return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
|
|
356
|
+
}
|
|
357
|
+
var CUBE = [0, 95, 135, 175, 215, 255];
|
|
358
|
+
function cubeLevel(channel) {
|
|
359
|
+
return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
|
|
360
|
+
}
|
|
361
|
+
function nearest256(hex) {
|
|
362
|
+
const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
|
|
363
|
+
const levels = rgb.map(cubeLevel);
|
|
364
|
+
const cube = levels.map((level) => CUBE[level]);
|
|
365
|
+
const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
|
|
366
|
+
const greyValue = 8 + grey * 10;
|
|
367
|
+
const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
|
|
368
|
+
return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
|
|
369
|
+
}
|
|
370
|
+
function hasTrueColor(env) {
|
|
371
|
+
return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
|
|
372
|
+
}
|
|
373
|
+
function tinted(colors, spec, env = process5.env) {
|
|
374
|
+
if (typeof spec === "number")
|
|
375
|
+
return colors.ansi256(spec);
|
|
376
|
+
return spec.trim().split(SPACES).reduce((chain, token) => {
|
|
377
|
+
if (HEX.test(token))
|
|
378
|
+
return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
|
|
379
|
+
return chain[token] ?? chain;
|
|
380
|
+
}, colors);
|
|
381
|
+
}
|
|
382
|
+
function isRecord(value) {
|
|
383
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
384
|
+
}
|
|
385
|
+
function readThemeFile(path, warn) {
|
|
386
|
+
try {
|
|
387
|
+
const stat = statSync(path, { throwIfNoEntry: false });
|
|
388
|
+
if (stat === undefined)
|
|
389
|
+
return;
|
|
390
|
+
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
|
|
391
|
+
warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
395
|
+
if (isRecord(parsed))
|
|
396
|
+
return parsed;
|
|
397
|
+
warn(`${path} is not a JSON object, theme ignored`);
|
|
398
|
+
} catch (error) {
|
|
399
|
+
warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
|
|
400
|
+
}
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
function applyPreset(theme, name, warn, where) {
|
|
404
|
+
if (name === undefined)
|
|
405
|
+
return;
|
|
406
|
+
if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
|
|
407
|
+
warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
const preset = PRESETS[name];
|
|
411
|
+
Object.assign(theme.colors, preset.colors);
|
|
412
|
+
Object.assign(theme.glyphs, preset.glyphs);
|
|
413
|
+
if (preset.accents !== undefined)
|
|
414
|
+
theme.accents = [...preset.accents];
|
|
415
|
+
return name;
|
|
416
|
+
}
|
|
417
|
+
function applyFile(theme, file, where, warn) {
|
|
418
|
+
if (isRecord(file.colors)) {
|
|
419
|
+
for (const [key, value] of Object.entries(file.colors)) {
|
|
420
|
+
if (!Object.hasOwn(DEFAULT.colors, key))
|
|
421
|
+
warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
|
|
422
|
+
else if (!isColorSpec(value))
|
|
423
|
+
warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
|
|
424
|
+
else
|
|
425
|
+
theme.colors[key] = value;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
if (isRecord(file.glyphs)) {
|
|
429
|
+
for (const [key, value] of Object.entries(file.glyphs)) {
|
|
430
|
+
if (!Object.hasOwn(DEFAULT.glyphs, key))
|
|
431
|
+
warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
|
|
432
|
+
else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
|
|
433
|
+
warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
|
|
434
|
+
else
|
|
435
|
+
theme.glyphs[key] = value;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
|
|
439
|
+
theme.accents = [...file.accents];
|
|
440
|
+
else if (file.accents !== undefined)
|
|
441
|
+
warn(`${where}: accents must be a non-empty list of colours`);
|
|
442
|
+
if (isRecord(file.bins)) {
|
|
443
|
+
for (const [bin, value] of Object.entries(file.bins)) {
|
|
444
|
+
if (isColorSpec(value))
|
|
445
|
+
theme.bins[bin] = value;
|
|
446
|
+
else
|
|
447
|
+
warn(`${where}: bin ${bin} has no valid colour`);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
function endsWalk(home) {
|
|
452
|
+
return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
|
|
453
|
+
}
|
|
454
|
+
var warned = new Set;
|
|
455
|
+
function warnOnce(message) {
|
|
456
|
+
if (warned.has(message))
|
|
457
|
+
return;
|
|
458
|
+
warned.add(message);
|
|
459
|
+
console.error(`warning: theme ${message}`);
|
|
460
|
+
}
|
|
461
|
+
function isPath(chosen) {
|
|
462
|
+
return chosen.includes("/") || chosen.endsWith(".json");
|
|
463
|
+
}
|
|
464
|
+
function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
|
|
465
|
+
const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null) };
|
|
466
|
+
const sources = [];
|
|
467
|
+
const chosen = env.KIT_THEME ?? "";
|
|
468
|
+
const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
|
|
469
|
+
if (isPath(chosen))
|
|
470
|
+
wanted.push(resolve2(from, chosen));
|
|
471
|
+
const files = [];
|
|
472
|
+
for (const path of wanted) {
|
|
473
|
+
const file = path === undefined ? undefined : readThemeFile(path, warn);
|
|
474
|
+
if (path !== undefined && file !== undefined)
|
|
475
|
+
files.push({ path, file });
|
|
476
|
+
}
|
|
477
|
+
let preset = "default";
|
|
478
|
+
if (chosen !== "" && !isPath(chosen)) {
|
|
479
|
+
preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
|
|
480
|
+
} else {
|
|
481
|
+
const named = files.findLast(({ file }) => file.preset !== undefined);
|
|
482
|
+
if (named !== undefined)
|
|
483
|
+
preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
|
|
484
|
+
}
|
|
485
|
+
for (const { path, file } of files) {
|
|
486
|
+
applyFile(theme, file, path, warn);
|
|
487
|
+
sources.push(path);
|
|
488
|
+
}
|
|
489
|
+
return { theme, sources, preset };
|
|
490
|
+
}
|
|
491
|
+
var current;
|
|
492
|
+
var currentKey = "";
|
|
493
|
+
function activeTheme() {
|
|
494
|
+
const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
|
|
495
|
+
if (current === undefined || key !== currentKey) {
|
|
496
|
+
current = loadTheme();
|
|
497
|
+
currentKey = key;
|
|
498
|
+
}
|
|
499
|
+
return current;
|
|
500
|
+
}
|
|
501
|
+
|
|
274
502
|
// ../kit/src/style.ts
|
|
275
|
-
function takesControlCodes(stream, env =
|
|
276
|
-
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
|
|
503
|
+
function takesControlCodes(stream, env = process6.env) {
|
|
504
|
+
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
|
|
277
505
|
}
|
|
278
|
-
function paint(stream, env =
|
|
506
|
+
function paint(stream, env = process6.env) {
|
|
279
507
|
return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
280
508
|
}
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
509
|
+
function role(name, stream, env = process6.env) {
|
|
510
|
+
const colors = paint(stream, env);
|
|
511
|
+
return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
|
|
512
|
+
}
|
|
513
|
+
var STATUS_WORDS = {
|
|
514
|
+
passed: ["passed", "success", "succeeded", "ok"],
|
|
515
|
+
failed: ["failed", "failure", "error", "errored"],
|
|
516
|
+
running: ["running", "in_progress", "started", "holding"],
|
|
517
|
+
queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
|
|
518
|
+
skipped: ["skipped", "cancelled", "canceled", "manual"]
|
|
287
519
|
};
|
|
288
|
-
var STATUS_OF = new Map(Object.entries(
|
|
520
|
+
var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
289
521
|
|
|
290
522
|
// ../kit/src/format.ts
|
|
291
523
|
function upTo(text, separator) {
|
|
@@ -293,32 +525,35 @@ function upTo(text, separator) {
|
|
|
293
525
|
return end === -1 ? text : text.slice(0, end);
|
|
294
526
|
}
|
|
295
527
|
var ESCAPE = String.fromCharCode(27);
|
|
528
|
+
function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
|
|
529
|
+
return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
|
|
530
|
+
}
|
|
296
531
|
function printJson(value) {
|
|
297
|
-
console.log(
|
|
532
|
+
console.log(jsonText(value));
|
|
298
533
|
}
|
|
299
534
|
|
|
300
535
|
// ../kit/src/help.ts
|
|
301
|
-
import
|
|
536
|
+
import process8 from "process";
|
|
302
537
|
var OPTIONAL = /\[[^\]]+\]/g;
|
|
303
538
|
var USAGE_PREFIX = /^usage:\s*/i;
|
|
304
539
|
var FULL_STOP = /\.$/;
|
|
305
|
-
function usageLine(usage, colors = paint(
|
|
540
|
+
function usageLine(usage, colors = paint(process8.stdout)) {
|
|
306
541
|
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
307
542
|
}
|
|
308
|
-
function helpText(usage, options, colors = paint(
|
|
543
|
+
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
|
|
309
544
|
return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
310
545
|
`);
|
|
311
546
|
}
|
|
312
|
-
function exitRows(exits, colors = paint(
|
|
547
|
+
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
313
548
|
if (exits.length === 0)
|
|
314
549
|
return [];
|
|
315
550
|
const width = Math.max(...exits.map(([code]) => String(code).length));
|
|
316
551
|
return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
|
|
317
552
|
}
|
|
318
|
-
function replacesRows(replaces, colors = paint(
|
|
319
|
-
return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
553
|
+
function replacesRows(replaces, colors = paint(process8.stdout)) {
|
|
554
|
+
return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
320
555
|
}
|
|
321
|
-
function wantsHelpJson(env =
|
|
556
|
+
function wantsHelpJson(env = process8.env) {
|
|
322
557
|
return env.KIT_HELP === "json";
|
|
323
558
|
}
|
|
324
559
|
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
@@ -337,12 +572,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
|
337
572
|
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
338
573
|
};
|
|
339
574
|
}
|
|
340
|
-
function exampleRows(examples, colors = paint(
|
|
341
|
-
if (examples.length === 0)
|
|
575
|
+
function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
576
|
+
if (examples.length === 0 || outputMode() === "agent")
|
|
342
577
|
return [];
|
|
343
578
|
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
344
579
|
}
|
|
345
|
-
function optionRows(options, colors = paint(
|
|
580
|
+
function optionRows(options, colors = paint(process8.stdout)) {
|
|
346
581
|
const rows = Object.entries(options).map(([name, option]) => {
|
|
347
582
|
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
348
583
|
const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
|
|
@@ -433,7 +668,7 @@ var OUTPUT_OPTIONS = {
|
|
|
433
668
|
color: { type: "string", description: "auto (on a terminal alone), always or never" },
|
|
434
669
|
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
435
670
|
};
|
|
436
|
-
function applyOutput(color, plain, env =
|
|
671
|
+
function applyOutput(color, plain, env = process9.env) {
|
|
437
672
|
const when = plain === true ? "never" : color ?? "auto";
|
|
438
673
|
if (when === "auto")
|
|
439
674
|
return;
|
|
@@ -604,7 +839,7 @@ function nearestOption(message, options, allowNegative) {
|
|
|
604
839
|
}
|
|
605
840
|
// ../kit/src/process.ts
|
|
606
841
|
import { constants } from "os";
|
|
607
|
-
import
|
|
842
|
+
import process10 from "process";
|
|
608
843
|
var KILL_GRACE_MS = 2000;
|
|
609
844
|
var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
610
845
|
function exitCodeOf(code, signal) {
|
|
@@ -626,7 +861,7 @@ function holdSignals(cleanup) {
|
|
|
626
861
|
},
|
|
627
862
|
release: () => {
|
|
628
863
|
for (const signal of SIGNALS)
|
|
629
|
-
|
|
864
|
+
process10.off(signal, onSignal);
|
|
630
865
|
}
|
|
631
866
|
};
|
|
632
867
|
function onSignal(signal) {
|
|
@@ -639,10 +874,10 @@ function holdSignals(cleanup) {
|
|
|
639
874
|
return;
|
|
640
875
|
held.release();
|
|
641
876
|
cleanup(signal);
|
|
642
|
-
|
|
877
|
+
process10.kill(process10.pid, signal);
|
|
643
878
|
}
|
|
644
879
|
for (const signal of SIGNALS)
|
|
645
|
-
|
|
880
|
+
process10.on(signal, onSignal);
|
|
646
881
|
return held;
|
|
647
882
|
}
|
|
648
883
|
async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
|
|
@@ -656,7 +891,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
|
|
|
656
891
|
return;
|
|
657
892
|
try {
|
|
658
893
|
if (grouped)
|
|
659
|
-
|
|
894
|
+
process10.kill(-proc.pid, killing);
|
|
660
895
|
else
|
|
661
896
|
proc.kill(killing);
|
|
662
897
|
} catch {}
|
|
@@ -730,15 +965,15 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
|
|
|
730
965
|
var RESET_STYLE = `${ESC}[0m`;
|
|
731
966
|
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
732
967
|
// ../kit/src/cli.ts
|
|
733
|
-
import { readFileSync, realpathSync } from "fs";
|
|
734
|
-
import { dirname as
|
|
735
|
-
import
|
|
968
|
+
import { readFileSync as readFileSync2, realpathSync } from "fs";
|
|
969
|
+
import { dirname as dirname3, join as join5 } from "path";
|
|
970
|
+
import process12 from "process";
|
|
736
971
|
|
|
737
972
|
// ../kit/src/usage.ts
|
|
738
973
|
import { appendFileSync, mkdirSync } from "fs";
|
|
739
|
-
import { homedir } from "os";
|
|
740
|
-
import { dirname, isAbsolute, join } from "path";
|
|
741
|
-
import
|
|
974
|
+
import { homedir as homedir3 } from "os";
|
|
975
|
+
import { dirname as dirname2, isAbsolute, join as join4 } from "path";
|
|
976
|
+
import process11 from "process";
|
|
742
977
|
|
|
743
978
|
// ../kit/src/logs.ts
|
|
744
979
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
@@ -752,14 +987,14 @@ var usageError;
|
|
|
752
987
|
function noteUsageError(message) {
|
|
753
988
|
usageError = message;
|
|
754
989
|
}
|
|
755
|
-
function stateHome(env =
|
|
990
|
+
function stateHome(env = process11.env) {
|
|
756
991
|
const dir = env.XDG_STATE_HOME;
|
|
757
|
-
return dir !== undefined && isAbsolute(dir) ? dir :
|
|
992
|
+
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
758
993
|
}
|
|
759
|
-
function usagePath(env =
|
|
760
|
-
return
|
|
994
|
+
function usagePath(env = process11.env) {
|
|
995
|
+
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
761
996
|
}
|
|
762
|
-
function usageRecorded(env =
|
|
997
|
+
function usageRecorded(env = process11.env) {
|
|
763
998
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
764
999
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
765
1000
|
}
|
|
@@ -773,12 +1008,12 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
773
1008
|
usageError = undefined;
|
|
774
1009
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
775
1010
|
}
|
|
776
|
-
function recordUsage(entry, env =
|
|
1011
|
+
function recordUsage(entry, env = process11.env) {
|
|
777
1012
|
if (!usageRecorded(env))
|
|
778
1013
|
return;
|
|
779
1014
|
try {
|
|
780
1015
|
const path = usagePath(env);
|
|
781
|
-
mkdirSync(
|
|
1016
|
+
mkdirSync(dirname2(path), { recursive: true, mode: 448 });
|
|
782
1017
|
appendFileSync(path, `${JSON.stringify(entry)}
|
|
783
1018
|
`, { mode: 384 });
|
|
784
1019
|
} catch {}
|
|
@@ -791,8 +1026,8 @@ var LEVEL_OPTIONS = {
|
|
|
791
1026
|
};
|
|
792
1027
|
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
793
1028
|
function printError(prefix, message, hint, cause) {
|
|
794
|
-
const colors = paint(
|
|
795
|
-
const styled = takesControlCodes(
|
|
1029
|
+
const colors = paint(process12.stderr);
|
|
1030
|
+
const styled = takesControlCodes(process12.stderr);
|
|
796
1031
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
797
1032
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
798
1033
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -814,7 +1049,7 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
|
814
1049
|
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
815
1050
|
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
816
1051
|
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
817
|
-
if (error instanceof
|
|
1052
|
+
if (error instanceof Exit && error.code === 2)
|
|
818
1053
|
noteUsageError(error.message);
|
|
819
1054
|
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
820
1055
|
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
@@ -878,17 +1113,17 @@ async function printCandidates(found) {
|
|
|
878
1113
|
return 0;
|
|
879
1114
|
}
|
|
880
1115
|
function packageVersion(entry = Bun.main) {
|
|
881
|
-
for (let dir =
|
|
1116
|
+
for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
|
|
882
1117
|
try {
|
|
883
|
-
const { version } = JSON.parse(
|
|
1118
|
+
const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
|
|
884
1119
|
if (typeof version === "string")
|
|
885
1120
|
return version;
|
|
886
1121
|
} catch {}
|
|
887
|
-
if (
|
|
1122
|
+
if (dirname3(dir) === dir)
|
|
888
1123
|
return "0.0.0";
|
|
889
1124
|
}
|
|
890
1125
|
}
|
|
891
|
-
async function runMain({ name, version, run, redact, usage }, argv =
|
|
1126
|
+
async function runMain({ name, version, run, redact, usage }, argv = process12.argv.slice(2)) {
|
|
892
1127
|
if (argv[0] === COMPLETE)
|
|
893
1128
|
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
894
1129
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
@@ -916,9 +1151,625 @@ var SESSION_FILES = new Glob("*.json");
|
|
|
916
1151
|
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
917
1152
|
// src/branch.ts
|
|
918
1153
|
import { basename } from "path";
|
|
919
|
-
import
|
|
1154
|
+
import process16 from "process";
|
|
1155
|
+
|
|
1156
|
+
// ../kit/src/picker/score.ts
|
|
1157
|
+
var MATCH = 16;
|
|
1158
|
+
var CONSECUTIVE = 12;
|
|
1159
|
+
var BOUNDARY = 10;
|
|
1160
|
+
var PREFIX = 8;
|
|
1161
|
+
var GAP = 1;
|
|
1162
|
+
var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
|
|
1163
|
+
var UPPER = /\p{Lu}/u;
|
|
1164
|
+
var LOWER = /\p{Ll}/u;
|
|
1165
|
+
var NONE = Number.NEGATIVE_INFINITY;
|
|
1166
|
+
function startsWord(text, index) {
|
|
1167
|
+
if (index === 0)
|
|
1168
|
+
return true;
|
|
1169
|
+
const before = text[index - 1];
|
|
1170
|
+
return BOUNDARY_AFTER.has(before) || LOWER.test(before) && UPPER.test(text[index]);
|
|
1171
|
+
}
|
|
1172
|
+
function fuzzy(query, text) {
|
|
1173
|
+
if (query === "")
|
|
1174
|
+
return { score: 0, positions: [] };
|
|
1175
|
+
const exact = query !== query.toLowerCase();
|
|
1176
|
+
const needle = exact ? query : query.toLowerCase();
|
|
1177
|
+
const haystack = exact ? text : text.toLowerCase();
|
|
1178
|
+
if (haystack.length !== text.length || needle.length > haystack.length)
|
|
1179
|
+
return;
|
|
1180
|
+
const width = haystack.length;
|
|
1181
|
+
const best = Array.from({ length: needle.length }, () => new Array(width).fill(NONE));
|
|
1182
|
+
const from = Array.from({ length: needle.length }, () => new Array(width).fill(-1));
|
|
1183
|
+
for (let j = 0;j < needle.length; j++) {
|
|
1184
|
+
let run = NONE;
|
|
1185
|
+
let runAt = -1;
|
|
1186
|
+
for (let i = j;i < width; i++) {
|
|
1187
|
+
if (j > 0 && i - 2 >= j - 1) {
|
|
1188
|
+
const candidate = best[j - 1][i - 2] + (i - 2) * GAP;
|
|
1189
|
+
if (candidate > run) {
|
|
1190
|
+
run = candidate;
|
|
1191
|
+
runAt = i - 2;
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
if (haystack[i] !== needle[j])
|
|
1195
|
+
continue;
|
|
1196
|
+
const here = MATCH + (startsWord(text, i) ? BOUNDARY : 0) + (i === 0 ? PREFIX : 0);
|
|
1197
|
+
if (j === 0) {
|
|
1198
|
+
best[0][i] = here - i * GAP;
|
|
1199
|
+
continue;
|
|
1200
|
+
}
|
|
1201
|
+
const joined = best[j - 1][i - 1] + CONSECUTIVE;
|
|
1202
|
+
const skipped = run - (i - 1) * GAP;
|
|
1203
|
+
if (joined > NONE && joined >= skipped) {
|
|
1204
|
+
best[j][i] = joined + here;
|
|
1205
|
+
from[j][i] = i - 1;
|
|
1206
|
+
} else if (skipped > NONE) {
|
|
1207
|
+
best[j][i] = skipped + here;
|
|
1208
|
+
from[j][i] = runAt;
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
const last = best[needle.length - 1];
|
|
1213
|
+
let end = -1;
|
|
1214
|
+
for (let i = 0;i < width; i++) {
|
|
1215
|
+
if (last[i] > NONE && (end === -1 || last[i] > last[end]))
|
|
1216
|
+
end = i;
|
|
1217
|
+
}
|
|
1218
|
+
if (end === -1)
|
|
1219
|
+
return;
|
|
1220
|
+
const positions = [];
|
|
1221
|
+
for (let j = needle.length - 1, i = end;j >= 0; j--) {
|
|
1222
|
+
positions.unshift(i);
|
|
1223
|
+
i = from[j][i];
|
|
1224
|
+
}
|
|
1225
|
+
return { score: last[end], positions };
|
|
1226
|
+
}
|
|
1227
|
+
function rank(query, lines) {
|
|
1228
|
+
if (query === "")
|
|
1229
|
+
return lines.map((_, index) => ({ index, positions: [] }));
|
|
1230
|
+
const found = [];
|
|
1231
|
+
for (const [index, line] of lines.entries()) {
|
|
1232
|
+
const match = fuzzy(query, line);
|
|
1233
|
+
if (match !== undefined)
|
|
1234
|
+
found.push({ index, positions: match.positions, score: match.score });
|
|
1235
|
+
}
|
|
1236
|
+
return found.sort((a, b) => b.score - a.score || lines[a.index].length - lines[b.index].length || a.index - b.index);
|
|
1237
|
+
}
|
|
920
1238
|
|
|
921
|
-
// ../kit/src/
|
|
1239
|
+
// ../kit/src/picker/state.ts
|
|
1240
|
+
var ANSI2 = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
|
|
1241
|
+
var CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
|
|
1242
|
+
var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
|
|
1243
|
+
var SGR = /^\x1B\[[0-9;]*m$/;
|
|
1244
|
+
var RESET = /^\x1B\[0?m$/;
|
|
1245
|
+
var COLUMN_GAP = 2;
|
|
1246
|
+
var PASTE_START = "\x1B[200~";
|
|
1247
|
+
var PASTE_END = "\x1B[201~";
|
|
1248
|
+
var LAST_WORD = /\S*\s*$/;
|
|
1249
|
+
var KEY_SEQUENCES = /\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
|
|
1250
|
+
var KEYS = {
|
|
1251
|
+
"\x1B[A": "up",
|
|
1252
|
+
"\x1BOA": "up",
|
|
1253
|
+
"\x10": "up",
|
|
1254
|
+
"\x1B[B": "down",
|
|
1255
|
+
"\x1BOB": "down",
|
|
1256
|
+
"\x0E": "down",
|
|
1257
|
+
"\r": "enter",
|
|
1258
|
+
"\n": "enter",
|
|
1259
|
+
"\x03": "cancel",
|
|
1260
|
+
"\x1B": "cancel",
|
|
1261
|
+
"\x7F": "erase",
|
|
1262
|
+
"\b": "erase",
|
|
1263
|
+
"\x15": "clear",
|
|
1264
|
+
"\x17": "word",
|
|
1265
|
+
"\t": "tab"
|
|
1266
|
+
};
|
|
1267
|
+
var CTRL_KEY = /^ctrl-[abd-gkln-z]$/;
|
|
1268
|
+
function repeat(value, count) {
|
|
1269
|
+
return Array.from({ length: count }).fill(value);
|
|
1270
|
+
}
|
|
1271
|
+
function styled(line) {
|
|
1272
|
+
let text = "";
|
|
1273
|
+
const styles = [];
|
|
1274
|
+
let active = "";
|
|
1275
|
+
let colored = false;
|
|
1276
|
+
let last = 0;
|
|
1277
|
+
function add(chunk) {
|
|
1278
|
+
const flat = chunk.replace(CONTROL2, " ");
|
|
1279
|
+
text += flat;
|
|
1280
|
+
colored ||= active !== "" && flat !== "";
|
|
1281
|
+
styles.push(...repeat(active, flat.length));
|
|
1282
|
+
}
|
|
1283
|
+
for (const found of line.matchAll(ANSI2)) {
|
|
1284
|
+
add(line.slice(last, found.index));
|
|
1285
|
+
last = found.index + found[0].length;
|
|
1286
|
+
if (SGR.test(found[0]))
|
|
1287
|
+
active = RESET.test(found[0]) ? "" : active + found[0];
|
|
1288
|
+
}
|
|
1289
|
+
add(line.slice(last));
|
|
1290
|
+
return { text, styles: colored ? styles : undefined };
|
|
1291
|
+
}
|
|
1292
|
+
function lay(rows, searched) {
|
|
1293
|
+
const parsed = rows.map((row) => row.cells.map(styled));
|
|
1294
|
+
const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
|
|
1295
|
+
return parsed.map((cells) => {
|
|
1296
|
+
let text = "";
|
|
1297
|
+
const styles = [];
|
|
1298
|
+
let colored = false;
|
|
1299
|
+
let searchEnd = 0;
|
|
1300
|
+
for (const [column, cell] of cells.entries()) {
|
|
1301
|
+
const last = column === cells.length - 1;
|
|
1302
|
+
const shown = cells.length > 1 && last ? cell.text.trimEnd() : cell.text;
|
|
1303
|
+
text += shown;
|
|
1304
|
+
colored ||= cell.styles !== undefined;
|
|
1305
|
+
styles.push(...cell.styles?.slice(0, shown.length) ?? repeat("", shown.length));
|
|
1306
|
+
if (column < searched)
|
|
1307
|
+
searchEnd = cells.length > 1 ? text.trimEnd().length : text.length;
|
|
1308
|
+
if (!last) {
|
|
1309
|
+
const pad = widths[column] - Bun.stringWidth(cell.text) + COLUMN_GAP;
|
|
1310
|
+
text += " ".repeat(pad);
|
|
1311
|
+
styles.push(...repeat("", pad));
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
return { text, styles: colored ? styles : undefined, searchable: text.slice(0, searchEnd) };
|
|
1315
|
+
});
|
|
1316
|
+
}
|
|
1317
|
+
function parseKeys(input, paste = { active: false }, ctrls = []) {
|
|
1318
|
+
const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
|
|
1319
|
+
return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
|
|
1320
|
+
const named = codes.get(sequence);
|
|
1321
|
+
const key = named === undefined ? KEYS[sequence] : { ctrl: named };
|
|
1322
|
+
if (sequence === PASTE_START || sequence === PASTE_END) {
|
|
1323
|
+
paste.active = sequence === PASTE_START;
|
|
1324
|
+
return [];
|
|
1325
|
+
}
|
|
1326
|
+
if (paste.active && (sequence === "\r" || sequence === `
|
|
1327
|
+
`))
|
|
1328
|
+
return [];
|
|
1329
|
+
if (key !== undefined)
|
|
1330
|
+
return [key];
|
|
1331
|
+
return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
|
|
1332
|
+
});
|
|
1333
|
+
}
|
|
1334
|
+
function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
|
|
1335
|
+
const state = { rows: [], items: [], styles: [], searchable: [], searched, header, expect, key: "", status: "", query, matches: [], cursor: 0, marked: new Set, multi, prompt, done: undefined };
|
|
1336
|
+
return withRows(state, rows);
|
|
1337
|
+
}
|
|
1338
|
+
function withRows(state, rows, header = state.header) {
|
|
1339
|
+
const cells = rows.map((row) => typeof row === "string" ? { hidden: [], cells: [row] } : row);
|
|
1340
|
+
const laid = lay(cells, state.searched);
|
|
1341
|
+
const searchable = laid.map((row) => row.searchable);
|
|
1342
|
+
const matches = rank(state.query, searchable);
|
|
1343
|
+
return { ...state, rows: cells, items: laid.map((row) => row.text), styles: laid.map((row) => row.styles), searchable, header, matches, cursor: Math.max(0, Math.min(matches.length - 1, state.cursor)), marked: new Set };
|
|
1344
|
+
}
|
|
1345
|
+
function withQuery(state, query) {
|
|
1346
|
+
return { ...state, query, matches: rank(query, state.searchable), cursor: 0 };
|
|
1347
|
+
}
|
|
1348
|
+
function move(state, by) {
|
|
1349
|
+
return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
|
|
1350
|
+
}
|
|
1351
|
+
function highlighted(state) {
|
|
1352
|
+
return state.matches[state.cursor]?.index;
|
|
1353
|
+
}
|
|
1354
|
+
function press(state, key) {
|
|
1355
|
+
if (state.done !== undefined)
|
|
1356
|
+
return state;
|
|
1357
|
+
if (typeof key === "object") {
|
|
1358
|
+
if ("text" in key)
|
|
1359
|
+
return withQuery(state, state.query + key.text);
|
|
1360
|
+
return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
|
|
1361
|
+
}
|
|
1362
|
+
switch (key) {
|
|
1363
|
+
case "up":
|
|
1364
|
+
return move(state, -1);
|
|
1365
|
+
case "down":
|
|
1366
|
+
return move(state, 1);
|
|
1367
|
+
case "cancel":
|
|
1368
|
+
return { ...state, done: "cancel" };
|
|
1369
|
+
case "erase":
|
|
1370
|
+
return withQuery(state, [...state.query].slice(0, -1).join(""));
|
|
1371
|
+
case "clear":
|
|
1372
|
+
return withQuery(state, "");
|
|
1373
|
+
case "word":
|
|
1374
|
+
return withQuery(state, state.query.replace(LAST_WORD, ""));
|
|
1375
|
+
case "enter":
|
|
1376
|
+
return state.matches.length === 0 && state.marked.size === 0 ? state : { ...state, done: "accept" };
|
|
1377
|
+
case "tab": {
|
|
1378
|
+
const at = highlighted(state);
|
|
1379
|
+
if (!state.multi || at === undefined)
|
|
1380
|
+
return state;
|
|
1381
|
+
const marked = new Set(state.marked);
|
|
1382
|
+
if (!marked.delete(at))
|
|
1383
|
+
marked.add(at);
|
|
1384
|
+
return move({ ...state, marked }, 1);
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
function chosen(state) {
|
|
1389
|
+
if (state.marked.size > 0)
|
|
1390
|
+
return state.rows.filter((_, index) => state.marked.has(index));
|
|
1391
|
+
const at = highlighted(state);
|
|
1392
|
+
return at === undefined ? [] : [state.rows[at]];
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
// ../kit/src/picker/terminal.ts
|
|
1396
|
+
import { openSync } from "fs";
|
|
1397
|
+
import process15 from "process";
|
|
1398
|
+
import tty from "tty";
|
|
1399
|
+
|
|
1400
|
+
// ../kit/src/picker/preview.ts
|
|
1401
|
+
import process14 from "process";
|
|
1402
|
+
|
|
1403
|
+
// ../kit/src/shell.ts
|
|
1404
|
+
var SEPARATORS = new Set([`
|
|
1405
|
+
`, ";", "|"]);
|
|
1406
|
+
var PLAIN_BREAKERS = new Set(["<", ">", "(", ")", "&", "|"]);
|
|
1407
|
+
var GLOB_CHARS = new Set(["*", "?", "["]);
|
|
1408
|
+
var COMMENT_PREFIXES = new Set([";", "&", "|", "(", ")"]);
|
|
1409
|
+
var SAFE_WORD = /^[\w@%+=:,./-]+$/;
|
|
1410
|
+
var DOUBLE_QUOTED_ESCAPES = new Set(["$", "`", '"', "\\"]);
|
|
1411
|
+
var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
|
|
1412
|
+
var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish", "csh", "tcsh", "nu", "xonsh", "elvish", "pwsh", "powershell"]);
|
|
1413
|
+
var SCANNED_PROGRAMS = new Set(["su", "runuser", "flock"]);
|
|
1414
|
+
var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, ...SCANNED_PROGRAMS]);
|
|
1415
|
+
var POWERSHELL = new Set(["pwsh", "powershell"]);
|
|
1416
|
+
var SHELL_VALUE_OPTIONS = new Set(["-o", "-O", "--rcfile", "--init-file"]);
|
|
1417
|
+
var FISH_VALUE_OPTIONS = new Set(["-C", "--init-command"]);
|
|
1418
|
+
var PRINTERS = new Set(["echo", "printf"]);
|
|
1419
|
+
var FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
|
|
1420
|
+
function wrapper(short = "", long = [], operands = 0, runsString = false) {
|
|
1421
|
+
return { short, long, operands, runsString };
|
|
1422
|
+
}
|
|
1423
|
+
var WRAPPERS = new Map([
|
|
1424
|
+
["command", wrapper()],
|
|
1425
|
+
["builtin", wrapper()],
|
|
1426
|
+
["nohup", wrapper()],
|
|
1427
|
+
["setsid", wrapper()],
|
|
1428
|
+
["busybox", wrapper()],
|
|
1429
|
+
["exec", wrapper("a")],
|
|
1430
|
+
["time", wrapper("fo", ["--format", "--output"])],
|
|
1431
|
+
["env", wrapper("uCS", ["--unset", "--chdir", "--split-string", "--argv0"])],
|
|
1432
|
+
["sudo", wrapper("ughpCTrtUDR", ["--user", "--group", "--host", "--prompt", "--close-from", "--command-timeout", "--role", "--type", "--other-user", "--chdir", "--chroot"])],
|
|
1433
|
+
["doas", wrapper("uC")],
|
|
1434
|
+
["timeout", wrapper("sk", ["--signal", "--kill-after"], 1)],
|
|
1435
|
+
["nice", wrapper("n", ["--adjustment"])],
|
|
1436
|
+
["ionice", wrapper("cnpPu", ["--class", "--classdata", "--pid", "--pgid", "--uid"])],
|
|
1437
|
+
["stdbuf", wrapper("ioe", ["--input", "--output", "--error"])],
|
|
1438
|
+
["chroot", wrapper("", ["--userspec", "--groups"], 1)],
|
|
1439
|
+
["watch", wrapper("n", ["--interval"], 0, true)],
|
|
1440
|
+
["flock", wrapper("wE", ["--timeout", "--conflict-exit-code"], 1)],
|
|
1441
|
+
["parallel", wrapper("jnNSaIPlLdTsC", ["--jobs", "--max-args", "--max-replace-args", "--sshlogin", "--arg-file", "--delimiter", "--colsep"], 0, true)],
|
|
1442
|
+
["unbuffer", wrapper()],
|
|
1443
|
+
["systemd-run", wrapper("puEMH", ["--property", "--unit", "--description", "--slice", "--setenv", "--machine", "--host", "--uid", "--gid", "--working-directory", "--nice", "--service-type"])],
|
|
1444
|
+
["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])]
|
|
1445
|
+
]);
|
|
1446
|
+
function shellQuote(word) {
|
|
1447
|
+
return SAFE_WORD.test(word) && !word.startsWith("=") ? word : `'${word.replaceAll("'", "'\\''")}'`;
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
// ../kit/src/picker/preview.ts
|
|
1451
|
+
var PREVIEW_BYTES = 64 * 1024;
|
|
1452
|
+
var PREVIEW_LINES = 200;
|
|
1453
|
+
var PREVIEW_TIMEOUT_MS = 3000;
|
|
1454
|
+
var PLACEHOLDER = /\{([1-9]\d*)?\}/g;
|
|
1455
|
+
function previewCommand(template, line, hidden = []) {
|
|
1456
|
+
return template.replace(PLACEHOLDER, (_, field) => shellQuote(field === undefined ? line : hidden[Number(field) - 1] ?? ""));
|
|
1457
|
+
}
|
|
1458
|
+
function previewLines(output) {
|
|
1459
|
+
const lines = output.split(`
|
|
1460
|
+
`);
|
|
1461
|
+
if (lines.at(-1) === "")
|
|
1462
|
+
lines.pop();
|
|
1463
|
+
return lines.slice(0, PREVIEW_LINES);
|
|
1464
|
+
}
|
|
1465
|
+
async function runPreview(template, line, signal, hidden = []) {
|
|
1466
|
+
const proc = Bun.spawn(["sh", "-c", `exec 2>&1
|
|
1467
|
+
${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
|
|
1468
|
+
const stop = () => {
|
|
1469
|
+
try {
|
|
1470
|
+
process14.kill(-proc.pid, "SIGKILL");
|
|
1471
|
+
} catch {
|
|
1472
|
+
proc.kill();
|
|
1473
|
+
}
|
|
1474
|
+
};
|
|
1475
|
+
const timer = setTimeout(stop, PREVIEW_TIMEOUT_MS);
|
|
1476
|
+
const chunks = [];
|
|
1477
|
+
let size = 0;
|
|
1478
|
+
signal.addEventListener("abort", stop);
|
|
1479
|
+
try {
|
|
1480
|
+
for await (const chunk of proc.stdout) {
|
|
1481
|
+
chunks.push(chunk);
|
|
1482
|
+
size += chunk.length;
|
|
1483
|
+
if (size >= PREVIEW_BYTES) {
|
|
1484
|
+
stop();
|
|
1485
|
+
break;
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
} finally {
|
|
1489
|
+
clearTimeout(timer);
|
|
1490
|
+
signal.removeEventListener("abort", stop);
|
|
1491
|
+
}
|
|
1492
|
+
return signal.aborted ? [] : previewLines(Buffer.concat(chunks).subarray(0, PREVIEW_BYTES).toString());
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
// ../kit/src/picker/view.ts
|
|
1496
|
+
var MIN_HEIGHT = 4;
|
|
1497
|
+
var PREVIEW_MIN_COLUMNS = 80;
|
|
1498
|
+
var PREVIEW_MIN_ROWS = 10;
|
|
1499
|
+
var PREVIEW_SHARE = 0.4;
|
|
1500
|
+
var RESET2 = "\x1B[0m";
|
|
1501
|
+
var SEPARATOR = " \u2502 ";
|
|
1502
|
+
var HEIGHT = /^(\d+)(%?)$/;
|
|
1503
|
+
function parseHeight(text) {
|
|
1504
|
+
const found = HEIGHT.exec(text);
|
|
1505
|
+
if (found === null || Number(found[1]) < 1)
|
|
1506
|
+
return;
|
|
1507
|
+
return found[2] === "%" ? { percent: Math.min(100, Number(found[1])) } : { lines: Number(found[1]) };
|
|
1508
|
+
}
|
|
1509
|
+
function layoutFor(size, height, previewing, position = "right") {
|
|
1510
|
+
const wanted = "lines" in height ? height.lines : Math.round(size.rows * height.percent / 100);
|
|
1511
|
+
const rows = Math.min(size.rows, Math.max(MIN_HEIGHT, wanted));
|
|
1512
|
+
if (position === "down") {
|
|
1513
|
+
const previewHeight = previewing && rows >= PREVIEW_MIN_ROWS ? Math.round(rows * PREVIEW_SHARE) : 0;
|
|
1514
|
+
return { height: rows, listHeight: rows - previewHeight, listWidth: size.columns, previewWidth: 0, previewHeight };
|
|
1515
|
+
}
|
|
1516
|
+
const split = previewing && size.columns >= PREVIEW_MIN_COLUMNS;
|
|
1517
|
+
const listWidth = split ? Math.floor(size.columns / 2) : size.columns;
|
|
1518
|
+
return { height: rows, listHeight: rows, listWidth, previewWidth: split ? size.columns - listWidth - SEPARATOR.length : 0, previewHeight: 0 };
|
|
1519
|
+
}
|
|
1520
|
+
function fit(text, width, plain, mark = plain, marked = new Set, styles) {
|
|
1521
|
+
const room = Bun.stringWidth(text) > width ? width - 1 : width;
|
|
1522
|
+
let out = "";
|
|
1523
|
+
let used = 0;
|
|
1524
|
+
let at = 0;
|
|
1525
|
+
for (const char of text) {
|
|
1526
|
+
const size = Bun.stringWidth(char);
|
|
1527
|
+
if (used + size > room)
|
|
1528
|
+
break;
|
|
1529
|
+
const style = marked.has(at) ? "" : styles?.[at] ?? "";
|
|
1530
|
+
out += style === "" ? (marked.has(at) ? mark : plain)(char) : `${style}${char}${RESET2}`;
|
|
1531
|
+
used += size;
|
|
1532
|
+
at += char.length;
|
|
1533
|
+
}
|
|
1534
|
+
if (room < width) {
|
|
1535
|
+
out += plain("\u2026");
|
|
1536
|
+
used += 1;
|
|
1537
|
+
}
|
|
1538
|
+
return { text: out, width: used };
|
|
1539
|
+
}
|
|
1540
|
+
var identity = (text) => text;
|
|
1541
|
+
function fitStyled(line, width, plain = identity) {
|
|
1542
|
+
const { text, styles } = styled(line);
|
|
1543
|
+
return fit(text, width, plain, plain, new Set, styles);
|
|
1544
|
+
}
|
|
1545
|
+
function caretColumn(state, layout) {
|
|
1546
|
+
return Math.min(layout.listWidth, Bun.stringWidth(state.prompt) + Bun.stringWidth(state.query) + 1);
|
|
1547
|
+
}
|
|
1548
|
+
function listLines(state, layout, theme) {
|
|
1549
|
+
const header = state.header === "" ? [] : state.header.split(`
|
|
1550
|
+
`).map((line) => fitStyled(line, layout.listWidth, theme.label));
|
|
1551
|
+
const rows = Math.max(1, layout.listHeight - 2 - header.length);
|
|
1552
|
+
const prefixWidth = state.multi ? 4 : 2;
|
|
1553
|
+
const top = Math.max(0, Math.min(state.cursor - Math.floor(rows / 2), state.matches.length - rows));
|
|
1554
|
+
const marks = (state.marked.size > 0 ? ` (${state.marked.size} marked)` : "") + (state.status === "" ? "" : ` ${state.status}`);
|
|
1555
|
+
const promptWidth = Bun.stringWidth(state.prompt);
|
|
1556
|
+
const query = fit(state.query, Math.max(1, layout.listWidth - promptWidth), identity);
|
|
1557
|
+
const count = fit(` ${state.matches.length}/${state.items.length}${marks}`, layout.listWidth, theme.label);
|
|
1558
|
+
const lines = [{ text: theme.accent(state.prompt) + query.text, width: promptWidth + query.width }, count, ...header];
|
|
1559
|
+
if (state.matches.length === 0)
|
|
1560
|
+
lines.push(fit(" no match", layout.listWidth, theme.label));
|
|
1561
|
+
for (const [offset, match] of state.matches.slice(top, top + rows).entries()) {
|
|
1562
|
+
const current = top + offset === state.cursor;
|
|
1563
|
+
const pointer = current ? theme.accent("\u276F") : " ";
|
|
1564
|
+
const mark = state.multi ? `${state.marked.has(match.index) ? theme.id("\u25CF") : " "} ` : "";
|
|
1565
|
+
const text = fit(state.items[match.index], layout.listWidth - prefixWidth, current ? theme.value : identity, theme.accent, new Set(match.positions), state.styles[match.index]);
|
|
1566
|
+
lines.push({ text: `${pointer} ${mark}${text.text}`, width: prefixWidth + text.width });
|
|
1567
|
+
}
|
|
1568
|
+
return lines;
|
|
1569
|
+
}
|
|
1570
|
+
function render(state, layout, theme, preview = []) {
|
|
1571
|
+
const left = listLines(state, layout, theme);
|
|
1572
|
+
return Array.from({ length: layout.height }, (_, row) => {
|
|
1573
|
+
if (row >= layout.listHeight)
|
|
1574
|
+
return row === layout.listHeight ? theme.label("\u2500".repeat(layout.listWidth)) : fitStyled(preview[row - layout.listHeight - 1] ?? "", layout.listWidth).text;
|
|
1575
|
+
const list = left[row] ?? { text: "", width: 0 };
|
|
1576
|
+
if (layout.previewWidth === 0)
|
|
1577
|
+
return list.text;
|
|
1578
|
+
return `${list.text}${" ".repeat(Math.max(0, layout.listWidth - list.width))}${theme.label(SEPARATOR)}${fitStyled(preview[row] ?? "", layout.previewWidth).text}`;
|
|
1579
|
+
});
|
|
1580
|
+
}
|
|
1581
|
+
|
|
1582
|
+
// ../kit/src/picker/terminal.ts
|
|
1583
|
+
var PREVIEW_DELAY_MS = 120;
|
|
1584
|
+
var OPEN = { ctrl: "open" };
|
|
1585
|
+
var HIDE_CURSOR = "\x1B[?25l";
|
|
1586
|
+
var SHOW_CURSOR = "\x1B[?25h";
|
|
1587
|
+
var PASTE_ON = "\x1B[?2004h";
|
|
1588
|
+
var PASTE_OFF = "\x1B[?2004l";
|
|
1589
|
+
var CLEAR_BELOW = "\r\x1B[J";
|
|
1590
|
+
var SIGNALS2 = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
1591
|
+
function up(lines) {
|
|
1592
|
+
return lines > 0 ? `\x1B[${lines}A` : "";
|
|
1593
|
+
}
|
|
1594
|
+
function openTerminal() {
|
|
1595
|
+
let input;
|
|
1596
|
+
try {
|
|
1597
|
+
input = new tty.ReadStream(openSync("/dev/tty", "r"));
|
|
1598
|
+
} catch {
|
|
1599
|
+
return fail("no terminal to read keys from (/dev/tty)");
|
|
1600
|
+
}
|
|
1601
|
+
const out = process15.stderr;
|
|
1602
|
+
let resize;
|
|
1603
|
+
return {
|
|
1604
|
+
get columns() {
|
|
1605
|
+
return out.columns || 80;
|
|
1606
|
+
},
|
|
1607
|
+
get rows() {
|
|
1608
|
+
return out.rows || 24;
|
|
1609
|
+
},
|
|
1610
|
+
theme: { accent: role("accent", out), label: role("label", out), value: role("value", out), id: role("id", out) },
|
|
1611
|
+
write: (text) => void out.write(text),
|
|
1612
|
+
listen(onChunk, onResize) {
|
|
1613
|
+
resize = onResize;
|
|
1614
|
+
input.setRawMode(true);
|
|
1615
|
+
out.on("resize", onResize);
|
|
1616
|
+
input.on("data", (chunk) => onChunk(chunk.toString()));
|
|
1617
|
+
},
|
|
1618
|
+
close() {
|
|
1619
|
+
if (resize !== undefined)
|
|
1620
|
+
out.off("resize", resize);
|
|
1621
|
+
try {
|
|
1622
|
+
input.setRawMode(false);
|
|
1623
|
+
} finally {
|
|
1624
|
+
input.destroy();
|
|
1625
|
+
}
|
|
1626
|
+
}
|
|
1627
|
+
};
|
|
1628
|
+
}
|
|
1629
|
+
async function select(rows, settings, terminal = openTerminal()) {
|
|
1630
|
+
const { theme } = terminal;
|
|
1631
|
+
let state = createState(rows, settings);
|
|
1632
|
+
let preview = [];
|
|
1633
|
+
let reserved = 0;
|
|
1634
|
+
let previewTimer;
|
|
1635
|
+
let previewing = new AbortController;
|
|
1636
|
+
let shownLine;
|
|
1637
|
+
let finish;
|
|
1638
|
+
let restored = false;
|
|
1639
|
+
function draw(clear = false) {
|
|
1640
|
+
if (restored)
|
|
1641
|
+
return;
|
|
1642
|
+
const layout = layoutFor({ columns: terminal.columns, rows: terminal.rows }, settings.height, settings.preview !== undefined, settings.previewPosition);
|
|
1643
|
+
let frame = HIDE_CURSOR;
|
|
1644
|
+
if (reserved !== layout.height || clear) {
|
|
1645
|
+
frame += CLEAR_BELOW + `
|
|
1646
|
+
`.repeat(layout.height - 1) + up(layout.height - 1);
|
|
1647
|
+
reserved = layout.height;
|
|
1648
|
+
}
|
|
1649
|
+
frame += `\r${render(state, layout, theme, preview).map((line) => `\x1B[2K${line}`).join(`
|
|
1650
|
+
`)}${up(layout.height - 1)}\r\x1B[${caretColumn(state, layout)}G${SHOW_CURSOR}`;
|
|
1651
|
+
terminal.write(frame);
|
|
1652
|
+
}
|
|
1653
|
+
function refreshPreview() {
|
|
1654
|
+
const at = highlighted(state);
|
|
1655
|
+
if (settings.preview === undefined || at === shownLine)
|
|
1656
|
+
return;
|
|
1657
|
+
shownLine = at;
|
|
1658
|
+
clearTimeout(previewTimer);
|
|
1659
|
+
previewing.abort();
|
|
1660
|
+
previewing = new AbortController;
|
|
1661
|
+
if (at === undefined) {
|
|
1662
|
+
preview = [];
|
|
1663
|
+
return;
|
|
1664
|
+
}
|
|
1665
|
+
const { signal } = previewing;
|
|
1666
|
+
const template = settings.preview;
|
|
1667
|
+
const row = state.rows[at];
|
|
1668
|
+
async function show() {
|
|
1669
|
+
const shown = typeof template === "string" ? await runPreview(template, row.cells.join(" "), signal, row.hidden) : await previewOf(template, row.hidden, signal);
|
|
1670
|
+
if (!signal.aborted) {
|
|
1671
|
+
preview = shown;
|
|
1672
|
+
draw();
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
previewTimer = setTimeout(() => void show(), PREVIEW_DELAY_MS);
|
|
1676
|
+
}
|
|
1677
|
+
function restore() {
|
|
1678
|
+
if (restored)
|
|
1679
|
+
return;
|
|
1680
|
+
restored = true;
|
|
1681
|
+
clearTimeout(previewTimer);
|
|
1682
|
+
previewing.abort();
|
|
1683
|
+
terminal.write(`${CLEAR_BELOW}${PASTE_OFF}${SHOW_CURSOR}`);
|
|
1684
|
+
terminal.close();
|
|
1685
|
+
}
|
|
1686
|
+
const stop = () => {
|
|
1687
|
+
state = { ...state, done: "cancel" };
|
|
1688
|
+
finish?.();
|
|
1689
|
+
};
|
|
1690
|
+
const paste = { active: false };
|
|
1691
|
+
const { reload } = settings;
|
|
1692
|
+
const pending = [];
|
|
1693
|
+
let busy = false;
|
|
1694
|
+
let draining = false;
|
|
1695
|
+
async function reloadRows() {
|
|
1696
|
+
if (reload === undefined)
|
|
1697
|
+
return;
|
|
1698
|
+
busy = true;
|
|
1699
|
+
state = { ...state, status: "reloading" };
|
|
1700
|
+
draw();
|
|
1701
|
+
try {
|
|
1702
|
+
const next = await reload.run();
|
|
1703
|
+
state = { ...withRows(state, next.rows, next.header), status: "" };
|
|
1704
|
+
shownLine = undefined;
|
|
1705
|
+
} catch (error) {
|
|
1706
|
+
state = { ...state, status: `reload failed: ${error instanceof Error ? error.message : String(error)}` };
|
|
1707
|
+
} finally {
|
|
1708
|
+
busy = false;
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
async function drain() {
|
|
1712
|
+
if (draining)
|
|
1713
|
+
return;
|
|
1714
|
+
draining = true;
|
|
1715
|
+
try {
|
|
1716
|
+
for (let key = pending.shift();key !== undefined && state.done === undefined; key = pending.shift()) {
|
|
1717
|
+
if (key === OPEN || typeof key === "object" && "ctrl" in key && key.ctrl === reload?.key)
|
|
1718
|
+
await reloadRows();
|
|
1719
|
+
else
|
|
1720
|
+
state = press(state, key);
|
|
1721
|
+
}
|
|
1722
|
+
} finally {
|
|
1723
|
+
draining = false;
|
|
1724
|
+
}
|
|
1725
|
+
if (state.done !== undefined) {
|
|
1726
|
+
finish?.();
|
|
1727
|
+
return;
|
|
1728
|
+
}
|
|
1729
|
+
refreshPreview();
|
|
1730
|
+
draw();
|
|
1731
|
+
}
|
|
1732
|
+
function onChunk(chunk) {
|
|
1733
|
+
const keys = parseKeys(chunk, paste, [...settings.expect ?? [], ...reload?.key === undefined ? [] : [reload.key]]);
|
|
1734
|
+
if (busy && keys.includes("cancel")) {
|
|
1735
|
+
stop();
|
|
1736
|
+
return;
|
|
1737
|
+
}
|
|
1738
|
+
pending.push(...keys);
|
|
1739
|
+
drain();
|
|
1740
|
+
}
|
|
1741
|
+
const ended = new Promise((resolve) => {
|
|
1742
|
+
finish = resolve;
|
|
1743
|
+
});
|
|
1744
|
+
process15.once("exit", restore);
|
|
1745
|
+
for (const signal of SIGNALS2)
|
|
1746
|
+
process15.once(signal, stop);
|
|
1747
|
+
try {
|
|
1748
|
+
terminal.write(PASTE_ON);
|
|
1749
|
+
terminal.listen(onChunk, () => draw(true));
|
|
1750
|
+
refreshPreview();
|
|
1751
|
+
draw(true);
|
|
1752
|
+
if (reload?.onOpen === true) {
|
|
1753
|
+
pending.push(OPEN);
|
|
1754
|
+
drain();
|
|
1755
|
+
}
|
|
1756
|
+
await ended;
|
|
1757
|
+
} finally {
|
|
1758
|
+
for (const signal of SIGNALS2)
|
|
1759
|
+
process15.off(signal, stop);
|
|
1760
|
+
process15.off("exit", restore);
|
|
1761
|
+
restore();
|
|
1762
|
+
}
|
|
1763
|
+
return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
|
|
1764
|
+
}
|
|
1765
|
+
async function previewOf(preview, hidden, signal) {
|
|
1766
|
+
try {
|
|
1767
|
+
return previewLines(await preview(hidden, signal));
|
|
1768
|
+
} catch (error) {
|
|
1769
|
+
return [error instanceof Error ? error.message : String(error)];
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
// ../kit/src/picker.ts
|
|
922
1773
|
function table(rows) {
|
|
923
1774
|
const widths = rows[0]?.cells.map((_, index) => Math.max(...rows.map((row) => Bun.stringWidth(row.cells[index])))) ?? [];
|
|
924
1775
|
return rows.map((row) => [
|
|
@@ -926,47 +1777,17 @@ function table(rows) {
|
|
|
926
1777
|
...row.cells.map((cell, index) => index === row.cells.length - 1 ? cell.trimEnd() : `${cell}${" ".repeat(widths[index] + 1 - Bun.stringWidth(cell))}`)
|
|
927
1778
|
].join("\t"));
|
|
928
1779
|
}
|
|
929
|
-
function
|
|
930
|
-
const
|
|
931
|
-
const
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
options.height ?? "100%",
|
|
941
|
-
"--delimiter",
|
|
942
|
-
"\t",
|
|
943
|
-
"--with-nth",
|
|
944
|
-
`${hidden + 1}..`,
|
|
945
|
-
"--nth",
|
|
946
|
-
`1..${options.searched}`,
|
|
947
|
-
"--tabstop",
|
|
948
|
-
"1",
|
|
949
|
-
"--tiebreak",
|
|
950
|
-
"chunk,index",
|
|
951
|
-
...options.preview === undefined ? [] : ["--preview", options.preview, "--preview-window", "down,40%"],
|
|
952
|
-
...(options.bind ?? []).flatMap((bind) => ["--bind", bind]),
|
|
953
|
-
...options.query === true ? ["--print-query"] : []
|
|
954
|
-
], {
|
|
955
|
-
stdin: new TextEncoder().encode(table(rows).join(`
|
|
956
|
-
`)),
|
|
957
|
-
stdout: "pipe",
|
|
958
|
-
stderr: "inherit"
|
|
959
|
-
});
|
|
960
|
-
return picked(proc.stdout.toString(), hidden, options);
|
|
961
|
-
}
|
|
962
|
-
function picked(output, hidden, options) {
|
|
963
|
-
const lines = output.split(`
|
|
964
|
-
`);
|
|
965
|
-
const query = options.query === true ? lines.shift() : "";
|
|
966
|
-
const [key, line] = (options.expect ?? []).length > 0 ? [lines[0], lines[1]] : ["", lines[0]];
|
|
967
|
-
if (line !== undefined && line !== "")
|
|
968
|
-
return { key, hidden: line.split("\t").slice(0, hidden), query };
|
|
969
|
-
return options.query === true && key !== "" ? { key, hidden: [], query } : undefined;
|
|
1780
|
+
async function pick(rows, options) {
|
|
1781
|
+
const height = parseHeight(options.height ?? "100%");
|
|
1782
|
+
const keys = [...options.expect ?? [], ...options.reload?.key === undefined ? [] : [options.reload.key]];
|
|
1783
|
+
if (height === undefined)
|
|
1784
|
+
throw new Error(`pick: the height is lines or a percentage, not ${options.height}`);
|
|
1785
|
+
for (const key of keys) {
|
|
1786
|
+
if (!CTRL_KEY.test(key))
|
|
1787
|
+
throw new Error(`pick: ${key} is not a key it can report, one of ctrl-a to ctrl-z but ctrl-c, h, i, j and m`);
|
|
1788
|
+
}
|
|
1789
|
+
const found = await select(rows, { multi: false, prompt: options.prompt, query: "", height, preview: options.preview, previewPosition: "down", header: options.header, expect: options.expect, searched: options.searched, reload: options.reload });
|
|
1790
|
+
return found === undefined ? undefined : { key: found.key, hidden: found.rows[0]?.hidden ?? [], query: found.query };
|
|
970
1791
|
}
|
|
971
1792
|
function word(arg) {
|
|
972
1793
|
if (typeof arg === "string")
|
|
@@ -988,7 +1809,7 @@ gb -
|
|
|
988
1809
|
gb -c <name>
|
|
989
1810
|
gb -d <branch>
|
|
990
1811
|
|
|
991
|
-
Without a branch, picks one
|
|
1812
|
+
Without a branch, picks one when 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 a terminal it lists the branches instead.
|
|
992
1813
|
\`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.
|
|
993
1814
|
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.`;
|
|
994
1815
|
var EXITS = [[0, "it switched, created, deleted or listed"], ["git", "the code of the git command it ran, when that failed"], [1, "there is no branch by that name or nothing was picked"], [2, "outside a git repository or a usage error"]];
|
|
@@ -999,7 +1820,7 @@ var options = {
|
|
|
999
1820
|
};
|
|
1000
1821
|
var FIELDS = ["%(refname)", "%(refname:short)", "%(committerdate:unix)", "%(committerdate:relative)", "%(subject)", "%(worktreepath)", "%(upstream:short)", "%(upstream:track,nobracket)"];
|
|
1001
1822
|
var CHECKOUT = /^checkout: moving from (\S+) to (\S+)$/;
|
|
1002
|
-
var
|
|
1823
|
+
var KEYS2 = "enter go, ctrl-n new from query, ctrl-d delete if merged, ctrl-r fetch";
|
|
1003
1824
|
var TRACK_TINTS = { ahead: "green", behind: "red", gone: "yellow" };
|
|
1004
1825
|
var TRACK_WORD = /^\w+/;
|
|
1005
1826
|
var WHITESPACE = /\s+/;
|
|
@@ -1126,7 +1947,12 @@ function header(found, current, failure = "") {
|
|
|
1126
1947
|
const here = found.find((branch) => !branch.remote && branch.name === current) ?? (current ? { name: current, upstream: "", track: "" } : undefined);
|
|
1127
1948
|
const line = status(here, here ? "" : read(["rev-parse", "--short", "HEAD"]), changed);
|
|
1128
1949
|
return `${line}${failure ? colors.dim(" | ") + colors.red(failure) : ""}
|
|
1129
|
-
${
|
|
1950
|
+
${KEYS2}`;
|
|
1951
|
+
}
|
|
1952
|
+
async function fetched() {
|
|
1953
|
+
const proc = Bun.spawn(["git", "fetch", "--all", "--prune", "--quiet"], { stdout: "ignore", stderr: "ignore" });
|
|
1954
|
+
const success = await proc.exited === 0;
|
|
1955
|
+
return header(branches(base()), read(["branch", "--show-current"]), success ? "" : "fetch failed");
|
|
1130
1956
|
}
|
|
1131
1957
|
function listed2(all) {
|
|
1132
1958
|
list([
|
|
@@ -1143,7 +1969,7 @@ function listed2(all) {
|
|
|
1143
1969
|
{ label: "New branch", hint: "git switch -c", typed: "-c", asks: "" }
|
|
1144
1970
|
]);
|
|
1145
1971
|
}
|
|
1146
|
-
function hidden(flag, rest) {
|
|
1972
|
+
async function hidden(flag, rest) {
|
|
1147
1973
|
if (flag === "--show") {
|
|
1148
1974
|
console.log(preview(rest[0] ?? ""));
|
|
1149
1975
|
return 0;
|
|
@@ -1151,19 +1977,13 @@ function hidden(flag, rest) {
|
|
|
1151
1977
|
if (read(["rev-parse", "--git-dir"]) === "")
|
|
1152
1978
|
fail("not a git repository", 2);
|
|
1153
1979
|
if (flag === "--fetch") {
|
|
1154
|
-
|
|
1155
|
-
console.log(header(branches(base()), read(["branch", "--show-current"]), fetched ? "" : "fetch failed"));
|
|
1980
|
+
console.log(await fetched());
|
|
1156
1981
|
return 0;
|
|
1157
1982
|
}
|
|
1158
1983
|
if (flag === "--list") {
|
|
1159
1984
|
listed2(load().all);
|
|
1160
1985
|
return 0;
|
|
1161
1986
|
}
|
|
1162
|
-
if (flag === "--rows") {
|
|
1163
|
-
console.log(table(load().all.map(row)).join(`
|
|
1164
|
-
`));
|
|
1165
|
-
return 0;
|
|
1166
|
-
}
|
|
1167
1987
|
if (flag === "--names") {
|
|
1168
1988
|
console.log(load().all.map((branch) => `${branch.name} ${branch.when}, ${branch.subject}`).join(`
|
|
1169
1989
|
`));
|
|
@@ -1179,8 +1999,8 @@ function create(name) {
|
|
|
1179
1999
|
}
|
|
1180
2000
|
async function gb(args) {
|
|
1181
2001
|
const [flag = ""] = args;
|
|
1182
|
-
if (["--show", "--fetch", "--list", "--
|
|
1183
|
-
return hidden(flag, args.slice(1)) ?? 0;
|
|
2002
|
+
if (["--show", "--fetch", "--list", "--names"].includes(flag))
|
|
2003
|
+
return await hidden(flag, args.slice(1)) ?? 0;
|
|
1184
2004
|
const emitting = flag === "--emit";
|
|
1185
2005
|
const parsed = parse(emitting ? args.slice(1) : args, usage2, options, { exits: EXITS, 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"]] });
|
|
1186
2006
|
const [named] = parsed.positionals;
|
|
@@ -1201,29 +2021,24 @@ async function gb(args) {
|
|
|
1201
2021
|
let branch;
|
|
1202
2022
|
let key = "";
|
|
1203
2023
|
if (named === undefined) {
|
|
1204
|
-
const interactive =
|
|
1205
|
-
if (!interactive
|
|
2024
|
+
const interactive = isInteractive() && parsed.values.json !== true;
|
|
2025
|
+
if (!interactive) {
|
|
1206
2026
|
if (emitting)
|
|
1207
|
-
fail("the picker needs a terminal
|
|
1208
|
-
if (interactive)
|
|
1209
|
-
console.error("fzf is not installed, listing the branches instead");
|
|
2027
|
+
fail("the picker needs a terminal", 1);
|
|
1210
2028
|
if (parsed.values.json === true)
|
|
1211
2029
|
printJson(all);
|
|
1212
2030
|
else
|
|
1213
|
-
console.log(table(all.map(row)).map((line) =>
|
|
2031
|
+
console.log(table(all.map(row)).map((line) => takesControlCodes(process16.stdout) ? line : Bun.stripANSI(line)).join(`
|
|
1214
2032
|
`));
|
|
1215
2033
|
return 0;
|
|
1216
2034
|
}
|
|
1217
|
-
const
|
|
1218
|
-
const picked = fzf(all.map(row), {
|
|
2035
|
+
const picked = await pick(all.map(row), {
|
|
1219
2036
|
prompt: "gb> ",
|
|
1220
2037
|
header: header(found, current),
|
|
1221
2038
|
expect: ["ctrl-d", "ctrl-n"],
|
|
1222
2039
|
searched: 1,
|
|
1223
|
-
preview:
|
|
1224
|
-
|
|
1225
|
-
query: true,
|
|
1226
|
-
hidden: 1
|
|
2040
|
+
preview: (fields) => preview(fields[0]),
|
|
2041
|
+
reload: { key: "ctrl-r", run: async () => ({ header: await fetched(), rows: load().all.map(row) }) }
|
|
1227
2042
|
});
|
|
1228
2043
|
if (picked?.key === "ctrl-n") {
|
|
1229
2044
|
const name = picked.query.trim();
|
|
@@ -1270,4 +2085,4 @@ async function finish(command, typed, emitting) {
|
|
|
1270
2085
|
}
|
|
1271
2086
|
|
|
1272
2087
|
// src/gb.ts
|
|
1273
|
-
|
|
2088
|
+
process17.exitCode = await runMain({ name: "gb", run: gb });
|