@kaynooo/cli-git 0.15.1 → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/gcl.js CHANGED
@@ -5,7 +5,7 @@
5
5
  import { existsSync as existsSync4, readdirSync, realpathSync as realpathSync3, statSync as statSync2 } from "fs";
6
6
  import { homedir as homedir5 } from "os";
7
7
  import { basename, join as join8, resolve as resolve6 } from "path";
8
- import process19 from "process";
8
+ import process20 from "process";
9
9
  // ../kit/src/args.ts
10
10
  import process9 from "process";
11
11
  import { parseArgs } from "util";
@@ -496,7 +496,7 @@ function printJson(value) {
496
496
 
497
497
  // ../kit/src/help.ts
498
498
  import process8 from "process";
499
- var OPTIONAL = /\[[^\]]+\]/g;
499
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
500
500
  var USAGE_PREFIX = /^usage:\s*/i;
501
501
  var FULL_STOP = /\.$/;
502
502
  function usageLine(usage, colors = paint(process8.stdout)) {
@@ -535,29 +535,41 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
535
535
  return [];
536
536
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
537
537
  }
538
+ var MAX_INLINE_CHOICES = 24;
538
539
  function optionRows(options, colors = paint(process8.stdout)) {
539
540
  const rows = Object.entries(options).map(([name, option]) => {
540
541
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
541
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
542
+ const choices = option.choices?.join("|");
543
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
544
+ const named = inline ? `<${choices}>` : "<value>";
542
545
  const placeholder = option.optional === undefined ? named : `[${named}]`;
543
546
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
544
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
547
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
548
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
545
549
  });
546
550
  const width = Math.max(0, ...rows.map((row) => row.width));
547
551
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
548
552
  }
549
553
 
550
554
  // ../kit/src/text.ts
551
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
555
+ var ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
552
556
  function distance(a, b) {
553
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
554
- for (const [i, left] of [...a].entries()) {
557
+ const left = [...a];
558
+ const right = [...b];
559
+ let before = [];
560
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
561
+ for (const [i, x] of left.entries()) {
555
562
  const current = [i + 1];
556
- for (const [j, right] of [...b].entries())
557
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
563
+ for (const [j, y] of right.entries()) {
564
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
565
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
566
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
567
+ current.push(cost);
568
+ }
569
+ before = previous;
558
570
  previous = current;
559
571
  }
560
- return previous[b.length] ?? 0;
572
+ return previous[right.length] ?? 0;
561
573
  }
562
574
  function closest(name, names) {
563
575
  const started = names.find((known) => known.startsWith(name));
@@ -633,7 +645,7 @@ class Completing {
633
645
  }
634
646
  var completion = { active: false };
635
647
  var OUTPUT_OPTIONS = {
636
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
648
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
637
649
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
638
650
  };
639
651
  function applyOutput(color, plain, env = process9.env) {
@@ -1141,13 +1153,91 @@ function interceptOutput(clear) {
1141
1153
  // ../kit/src/cli.ts
1142
1154
  import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
1143
1155
  import { dirname as dirname3, join as join5 } from "path";
1144
- import process14 from "process";
1156
+ import process15 from "process";
1157
+
1158
+ // ../kit/src/completions.ts
1159
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
1160
+ var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
1161
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
1162
+ set -l current (commandline -ct)
1163
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
1164
+ if test "$line" = __files__
1165
+ __fish_complete_path $current
1166
+ else
1167
+ echo $line
1168
+ end
1169
+ end
1170
+ end`;
1171
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
1172
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
1173
+ local -a lines
1174
+ COMPREPLY=()
1175
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
1176
+ for line in "\${lines[@]}"; do
1177
+ if [[ $line == __files__ ]]; then
1178
+ COMPREPLY+=($(compgen -f -- "$cur"))
1179
+ else
1180
+ words+="\${line%%$'\\t'*}"$'\\n'
1181
+ fi
1182
+ done
1183
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
1184
+ }`;
1185
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
1186
+ local line
1187
+ local -a described plain
1188
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
1189
+ if [[ $line == __files__ ]]; then
1190
+ _files
1191
+ elif [[ $line == *$'\\t'* ]]; then
1192
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
1193
+ else
1194
+ plain+=("$line")
1195
+ fi
1196
+ done
1197
+ (( \${#described} )) && _describe -V value described
1198
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
1199
+ return 0
1200
+ }`;
1201
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
1202
+ if (shell === "fish")
1203
+ return `${header}
1204
+ ${FISH_FUNCTION}
1205
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
1206
+ `).join("")}`;
1207
+ if (shell === "bash")
1208
+ return `${header}
1209
+ ${BASH_FUNCTION}
1210
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
1211
+ `;
1212
+ return `${header}
1213
+ ${ZSH_FUNCTION}
1214
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
1215
+ `;
1216
+ }
1217
+
1218
+ // ../kit/src/notify.ts
1219
+ import process13 from "process";
1220
+ var NOTIFY_AFTER_MS = 1e4;
1221
+ var CANCELLED = 130;
1222
+ function base64(text) {
1223
+ return Buffer.from(text).toString("base64");
1224
+ }
1225
+ function notification(title, body, env = process13.env) {
1226
+ const id = `kit${process13.pid}`;
1227
+ const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
1228
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1229
+ }
1230
+ function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
1231
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1232
+ return;
1233
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1234
+ }
1145
1235
 
1146
1236
  // ../kit/src/usage.ts
1147
1237
  import { appendFileSync, mkdirSync } from "fs";
1148
1238
  import { homedir as homedir3 } from "os";
1149
1239
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
1150
- import process13 from "process";
1240
+ import process14 from "process";
1151
1241
 
1152
1242
  // ../kit/src/logs.ts
1153
1243
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -1161,14 +1251,14 @@ var usageError;
1161
1251
  function noteUsageError(message) {
1162
1252
  usageError = message;
1163
1253
  }
1164
- function stateHome(env = process13.env) {
1254
+ function stateHome(env = process14.env) {
1165
1255
  const dir = env.XDG_STATE_HOME;
1166
1256
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1167
1257
  }
1168
- function usagePath(env = process13.env) {
1258
+ function usagePath(env = process14.env) {
1169
1259
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
1170
1260
  }
1171
- function usageRecorded(env = process13.env) {
1261
+ function usageRecorded(env = process14.env) {
1172
1262
  const off = env.KAYNOOO_CLI_NO_USAGE;
1173
1263
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1174
1264
  }
@@ -1182,7 +1272,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
1182
1272
  usageError = undefined;
1183
1273
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1184
1274
  }
1185
- function recordUsage(entry, env = process13.env) {
1275
+ function recordUsage(entry, env = process14.env) {
1186
1276
  if (!usageRecorded(env))
1187
1277
  return;
1188
1278
  try {
@@ -1198,10 +1288,14 @@ var LEVEL_OPTIONS = {
1198
1288
  ...OUTPUT_OPTIONS,
1199
1289
  help: { type: "boolean", short: "h", description: "show this help" }
1200
1290
  };
1201
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
1291
+ var TOP_OPTIONS = {
1292
+ ...LEVEL_OPTIONS,
1293
+ version: { type: "boolean", short: "v", description: "print the version" },
1294
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1295
+ };
1202
1296
  function printError(prefix, message, hint, cause) {
1203
- const colors = paint(process14.stderr);
1204
- const styled = takesControlCodes(process14.stderr);
1297
+ const colors = paint(process15.stderr);
1298
+ const styled = takesControlCodes(process15.stderr);
1205
1299
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1206
1300
  const under = (label, text, tint) => text === undefined ? "" : `
1207
1301
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1281,6 +1375,19 @@ async function leafCandidates(run, words) {
1281
1375
  const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1282
1376
  return values === undefined ? [FILES] : values.map(candidateLine);
1283
1377
  }
1378
+ var COMPLETIONS = "--completions";
1379
+ function flagValue([flag = "", ...rest]) {
1380
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1381
+ }
1382
+ function printCompletionScript(name, args) {
1383
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1384
+ if (shell === undefined || args.length !== 1) {
1385
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1386
+ return 2;
1387
+ }
1388
+ console.log(completionScript(shell, [name]).trimEnd());
1389
+ return 0;
1390
+ }
1284
1391
  async function printCandidates(found) {
1285
1392
  for (const line of await found)
1286
1393
  console.log(line);
@@ -1304,16 +1411,20 @@ function packageVersion(entry = Bun.main) {
1304
1411
  async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1305
1412
  if (argv[0] === COMPLETE)
1306
1413
  return printCandidates(leafCandidates(run, argv.slice(1)));
1414
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1415
+ return printCompletionScript(name, flagValue(argv));
1307
1416
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1308
1417
  console.log(version ?? packageVersion());
1309
1418
  return 0;
1310
1419
  }
1311
1420
  let code;
1421
+ const started = performance.now();
1312
1422
  try {
1313
1423
  code = await run(argv);
1314
1424
  } catch (error) {
1315
1425
  code = reportThrown(name, error, redact, wantsJson(argv));
1316
1426
  }
1427
+ notifyEnd(name, code, performance.now() - started);
1317
1428
  if (usage !== false) {
1318
1429
  try {
1319
1430
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1330,7 +1441,7 @@ var {Glob } = globalThis.Bun;
1330
1441
  var SESSION_FILES = new Glob("*.json");
1331
1442
  var ACCOUNT_DIRS = new Glob("*/sessions");
1332
1443
  // ../kit/src/watch.ts
1333
- import process15 from "process";
1444
+ import process16 from "process";
1334
1445
  import { format } from "util";
1335
1446
  var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1336
1447
  var DEFAULT_SECONDS = 2;
@@ -1352,7 +1463,7 @@ function withoutWatch(args) {
1352
1463
  }
1353
1464
  return rest;
1354
1465
  }
1355
- async function watching(value, step, stream = process15.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1466
+ async function watching(value, step, stream = process16.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1356
1467
  const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1357
1468
  if (!takesControlCodes(stream))
1358
1469
  badUsage("--watch redraws the screen, so it needs a terminal");
@@ -1360,12 +1471,12 @@ async function watching(value, step, stream = process15.stdout, sleep = Bun.slee
1360
1471
  for (let round = 0;round < rounds; round++) {
1361
1472
  const held = [];
1362
1473
  const { log, info } = console;
1363
- const write = process15.stdout.write.bind(process15.stdout);
1474
+ const write = process16.stdout.write.bind(process16.stdout);
1364
1475
  const hold = (...parts) => void held.push(`${format(...parts)}
1365
1476
  `);
1366
1477
  console.log = hold;
1367
1478
  console.info = hold;
1368
- process15.stdout.write = (text) => {
1479
+ process16.stdout.write = (text) => {
1369
1480
  held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1370
1481
  return true;
1371
1482
  };
@@ -1374,7 +1485,7 @@ async function watching(value, step, stream = process15.stdout, sleep = Bun.slee
1374
1485
  } finally {
1375
1486
  console.log = log;
1376
1487
  console.info = info;
1377
- process15.stdout.write = write;
1488
+ process16.stdout.write = write;
1378
1489
  }
1379
1490
  stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1380
1491
  await sleep(interval);
@@ -1384,7 +1495,7 @@ async function watching(value, step, stream = process15.stdout, sleep = Bun.slee
1384
1495
  // ../kit/src/workspace-root.ts
1385
1496
  import { homedir as homedir4 } from "os";
1386
1497
  import { dirname as dirname4, join as join6, resolve as resolve4 } from "path";
1387
- import process16 from "process";
1498
+ import process17 from "process";
1388
1499
  function expandHome(path, home) {
1389
1500
  if (path === "~")
1390
1501
  return home;
@@ -1394,7 +1505,7 @@ function configured(env, home) {
1394
1505
  const folder = readUserConfig("config", { home, xdg: env.XDG_CONFIG_HOME }).workspace;
1395
1506
  return typeof folder === "string" && folder !== "" ? folder : undefined;
1396
1507
  }
1397
- function workspaceRoot({ given, env = process16.env, home = homedir4() } = {}) {
1508
+ function workspaceRoot({ given, env = process17.env, home = homedir4() } = {}) {
1398
1509
  const fromEnv = env.KAYNOOO_WORKSPACE === "" ? undefined : env.KAYNOOO_WORKSPACE;
1399
1510
  return resolve4(expandHome(given ?? fromEnv ?? configured(env, home) ?? join6(home, "Workspace"), home));
1400
1511
  }
@@ -1408,14 +1519,18 @@ async function git2(args, env) {
1408
1519
  // src/repos.ts
1409
1520
  import { readdir } from "fs/promises";
1410
1521
  import { join as join7, relative, resolve as resolve5 } from "path";
1411
- import process18 from "process";
1522
+ import process19 from "process";
1412
1523
 
1413
1524
  // src/status.ts
1414
1525
  var AHEAD_BEHIND = /\+(\d+) -(\d+)/;
1526
+ var STASH = /^# stash (\d+)$/m;
1415
1527
  var OCTAL = /[0-7]/;
1416
1528
  var ESCAPES = { a: 7, b: 8, t: 9, n: 10, v: 11, f: 12, r: 13 };
1417
1529
  var ENCODER = new TextEncoder;
1418
1530
  var DECODER = new TextDecoder;
1531
+ function stashOf(text) {
1532
+ return Number(STASH.exec(text)?.[1] ?? 0);
1533
+ }
1419
1534
  function unquote(path) {
1420
1535
  if (!path.startsWith('"') || !path.endsWith('"'))
1421
1536
  return path;
@@ -1470,16 +1585,18 @@ function parseStatus(text) {
1470
1585
  }
1471
1586
  return hasBranch ? status : null;
1472
1587
  }
1473
- function summary(status, head) {
1588
+ function summary(status, head, { operation = null, stash = 0 } = {}) {
1474
1589
  const { branch, oid, upstream, aheadBehind, changes, conflicted, untracked } = status;
1475
- const on = branch === "(detached)" ? `detached at ${oid.slice(0, 7)}` : `branch \`${branch}\``;
1590
+ const steps = operation?.step !== undefined && operation.total !== undefined ? ` ${operation.step}/${operation.total}` : "";
1591
+ const during = operation === null ? "" : ` (${operation.kind}${steps} in progress)`;
1592
+ const on = (branch === "(detached)" ? `detached at ${oid.slice(0, 7)}` : `branch \`${branch}\``) + during;
1476
1593
  let tracking = "no upstream";
1477
1594
  if (upstream !== null)
1478
1595
  tracking = aheadBehind === null ? `upstream \`${upstream}\` gone or never fetched` : `${aheadBehind.ahead} ahead and ${aheadBehind.behind} behind \`${upstream}\` as of the last fetch`;
1479
1596
  const files = [`${changes.length} changed`, untracked.length > 0 ? `${untracked.length} untracked` : "", conflicted.length > 0 ? `${conflicted.length} conflicted` : ""].filter(Boolean).join(", ");
1480
1597
  const [sha, title] = head.trim().split("\x00");
1481
1598
  const last = sha === undefined || sha === "" ? "; no commit yet" : `; HEAD ${sha} ${title ?? ""}`.trimEnd();
1482
- return `${on}, ${tracking}; ${files} files${last}`;
1599
+ return `${on}, ${tracking}; ${files} files${stash > 0 ? `; ${stash} stashed` : ""}${last}`;
1483
1600
  }
1484
1601
 
1485
1602
  // src/repos.ts
@@ -1508,14 +1625,14 @@ async function toplevelOf(dir) {
1508
1625
  return read.code === 0 ? read.stdout.trim() : undefined;
1509
1626
  }
1510
1627
  async function reposOf(roots) {
1511
- const starts = roots.length > 0 ? roots : [await toplevelOf(".") ?? process18.cwd()];
1628
+ const starts = roots.length > 0 ? roots : [await toplevelOf(".") ?? process19.cwd()];
1512
1629
  const found = await Promise.all(starts.map(async (root) => reposUnder(root)));
1513
1630
  return [...new Set(found.flat())].sort();
1514
1631
  }
1515
1632
  async function repoState(dir) {
1516
1633
  const [read, log] = await Promise.all([git2(["-C", dir, "status", "--porcelain=v2", "--branch"]), git2(["-C", dir, "log", "-1", "--format=%h%x00%s"])]);
1517
1634
  const [sha, title = ""] = log.code === 0 && log.stdout.trim() !== "" ? log.stdout.trim().split("\x00") : [];
1518
- return { path: relative(process18.cwd(), dir) || ".", dir, status: read.code === 0 ? parseStatus(read.stdout) : null, head: sha === undefined ? null : { sha, title } };
1635
+ return { path: relative(process19.cwd(), dir) || ".", dir, status: read.code === 0 ? parseStatus(read.stdout) : null, head: sha === undefined ? null : { sha, title } };
1519
1636
  }
1520
1637
  function trackingOf(status) {
1521
1638
  if (status.upstream === null)
@@ -1655,7 +1772,7 @@ ${cloned.stderr.trim()}`, 1);
1655
1772
  return 0;
1656
1773
  }
1657
1774
  if (import.meta.main)
1658
- process19.exitCode = await runMain({ name: "gcl", run: main });
1775
+ process20.exitCode = await runMain({ name: "gcl", run: main });
1659
1776
  export {
1660
1777
  nameOf,
1661
1778
  urlOf