@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/gc.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/gc.ts
5
- import process18 from "process";
5
+ import process19 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process9 from "process";
8
8
  import { parseArgs } from "util";
@@ -493,7 +493,7 @@ function printJson(value) {
493
493
 
494
494
  // ../kit/src/help.ts
495
495
  import process8 from "process";
496
- var OPTIONAL = /\[[^\]]+\]/g;
496
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
497
497
  var USAGE_PREFIX = /^usage:\s*/i;
498
498
  var FULL_STOP = /\.$/;
499
499
  function usageLine(usage, colors = paint(process8.stdout)) {
@@ -532,29 +532,41 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
532
532
  return [];
533
533
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
534
534
  }
535
+ var MAX_INLINE_CHOICES = 24;
535
536
  function optionRows(options, colors = paint(process8.stdout)) {
536
537
  const rows = Object.entries(options).map(([name, option]) => {
537
538
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
538
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
539
+ const choices = option.choices?.join("|");
540
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
541
+ const named = inline ? `<${choices}>` : "<value>";
539
542
  const placeholder = option.optional === undefined ? named : `[${named}]`;
540
543
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
541
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
544
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
545
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
542
546
  });
543
547
  const width = Math.max(0, ...rows.map((row) => row.width));
544
548
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
545
549
  }
546
550
 
547
551
  // ../kit/src/text.ts
548
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
552
+ var ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
549
553
  function distance(a, b) {
550
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
551
- for (const [i, left] of [...a].entries()) {
554
+ const left = [...a];
555
+ const right = [...b];
556
+ let before = [];
557
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
558
+ for (const [i, x] of left.entries()) {
552
559
  const current = [i + 1];
553
- for (const [j, right] of [...b].entries())
554
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
560
+ for (const [j, y] of right.entries()) {
561
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
562
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
563
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
564
+ current.push(cost);
565
+ }
566
+ before = previous;
555
567
  previous = current;
556
568
  }
557
- return previous[b.length] ?? 0;
569
+ return previous[right.length] ?? 0;
558
570
  }
559
571
  function closest(name, names) {
560
572
  const started = names.find((known) => known.startsWith(name));
@@ -630,7 +642,7 @@ class Completing {
630
642
  }
631
643
  var completion = { active: false };
632
644
  var OUTPUT_OPTIONS = {
633
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
645
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
634
646
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
635
647
  };
636
648
  function applyOutput(color, plain, env = process9.env) {
@@ -1138,13 +1150,91 @@ function interceptOutput(clear) {
1138
1150
  // ../kit/src/cli.ts
1139
1151
  import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
1140
1152
  import { dirname as dirname3, join as join5 } from "path";
1141
- import process14 from "process";
1153
+ import process15 from "process";
1154
+
1155
+ // ../kit/src/completions.ts
1156
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
1157
+ 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'
1158
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
1159
+ set -l current (commandline -ct)
1160
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
1161
+ if test "$line" = __files__
1162
+ __fish_complete_path $current
1163
+ else
1164
+ echo $line
1165
+ end
1166
+ end
1167
+ end`;
1168
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
1169
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
1170
+ local -a lines
1171
+ COMPREPLY=()
1172
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
1173
+ for line in "\${lines[@]}"; do
1174
+ if [[ $line == __files__ ]]; then
1175
+ COMPREPLY+=($(compgen -f -- "$cur"))
1176
+ else
1177
+ words+="\${line%%$'\\t'*}"$'\\n'
1178
+ fi
1179
+ done
1180
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
1181
+ }`;
1182
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
1183
+ local line
1184
+ local -a described plain
1185
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
1186
+ if [[ $line == __files__ ]]; then
1187
+ _files
1188
+ elif [[ $line == *$'\\t'* ]]; then
1189
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
1190
+ else
1191
+ plain+=("$line")
1192
+ fi
1193
+ done
1194
+ (( \${#described} )) && _describe -V value described
1195
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
1196
+ return 0
1197
+ }`;
1198
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
1199
+ if (shell === "fish")
1200
+ return `${header}
1201
+ ${FISH_FUNCTION}
1202
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
1203
+ `).join("")}`;
1204
+ if (shell === "bash")
1205
+ return `${header}
1206
+ ${BASH_FUNCTION}
1207
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
1208
+ `;
1209
+ return `${header}
1210
+ ${ZSH_FUNCTION}
1211
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
1212
+ `;
1213
+ }
1214
+
1215
+ // ../kit/src/notify.ts
1216
+ import process13 from "process";
1217
+ var NOTIFY_AFTER_MS = 1e4;
1218
+ var CANCELLED = 130;
1219
+ function base64(text) {
1220
+ return Buffer.from(text).toString("base64");
1221
+ }
1222
+ function notification(title, body, env = process13.env) {
1223
+ const id = `kit${process13.pid}`;
1224
+ 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\\`];
1225
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1226
+ }
1227
+ function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
1228
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1229
+ return;
1230
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1231
+ }
1142
1232
 
1143
1233
  // ../kit/src/usage.ts
1144
1234
  import { appendFileSync, mkdirSync } from "fs";
1145
1235
  import { homedir as homedir3 } from "os";
1146
1236
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
1147
- import process13 from "process";
1237
+ import process14 from "process";
1148
1238
 
1149
1239
  // ../kit/src/logs.ts
1150
1240
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -1158,14 +1248,14 @@ var usageError;
1158
1248
  function noteUsageError(message) {
1159
1249
  usageError = message;
1160
1250
  }
1161
- function stateHome(env = process13.env) {
1251
+ function stateHome(env = process14.env) {
1162
1252
  const dir = env.XDG_STATE_HOME;
1163
1253
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1164
1254
  }
1165
- function usagePath(env = process13.env) {
1255
+ function usagePath(env = process14.env) {
1166
1256
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
1167
1257
  }
1168
- function usageRecorded(env = process13.env) {
1258
+ function usageRecorded(env = process14.env) {
1169
1259
  const off = env.KAYNOOO_CLI_NO_USAGE;
1170
1260
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1171
1261
  }
@@ -1179,7 +1269,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
1179
1269
  usageError = undefined;
1180
1270
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1181
1271
  }
1182
- function recordUsage(entry, env = process13.env) {
1272
+ function recordUsage(entry, env = process14.env) {
1183
1273
  if (!usageRecorded(env))
1184
1274
  return;
1185
1275
  try {
@@ -1195,10 +1285,14 @@ var LEVEL_OPTIONS = {
1195
1285
  ...OUTPUT_OPTIONS,
1196
1286
  help: { type: "boolean", short: "h", description: "show this help" }
1197
1287
  };
1198
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
1288
+ var TOP_OPTIONS = {
1289
+ ...LEVEL_OPTIONS,
1290
+ version: { type: "boolean", short: "v", description: "print the version" },
1291
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1292
+ };
1199
1293
  function printError(prefix, message, hint, cause) {
1200
- const colors = paint(process14.stderr);
1201
- const styled = takesControlCodes(process14.stderr);
1294
+ const colors = paint(process15.stderr);
1295
+ const styled = takesControlCodes(process15.stderr);
1202
1296
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1203
1297
  const under = (label, text, tint) => text === undefined ? "" : `
1204
1298
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1278,6 +1372,19 @@ async function leafCandidates(run, words) {
1278
1372
  const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1279
1373
  return values === undefined ? [FILES] : values.map(candidateLine);
1280
1374
  }
1375
+ var COMPLETIONS = "--completions";
1376
+ function flagValue([flag = "", ...rest]) {
1377
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1378
+ }
1379
+ function printCompletionScript(name, args) {
1380
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1381
+ if (shell === undefined || args.length !== 1) {
1382
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1383
+ return 2;
1384
+ }
1385
+ console.log(completionScript(shell, [name]).trimEnd());
1386
+ return 0;
1387
+ }
1281
1388
  async function printCandidates(found) {
1282
1389
  for (const line of await found)
1283
1390
  console.log(line);
@@ -1301,16 +1408,20 @@ function packageVersion(entry = Bun.main) {
1301
1408
  async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1302
1409
  if (argv[0] === COMPLETE)
1303
1410
  return printCandidates(leafCandidates(run, argv.slice(1)));
1411
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1412
+ return printCompletionScript(name, flagValue(argv));
1304
1413
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1305
1414
  console.log(version ?? packageVersion());
1306
1415
  return 0;
1307
1416
  }
1308
1417
  let code;
1418
+ const started = performance.now();
1309
1419
  try {
1310
1420
  code = await run(argv);
1311
1421
  } catch (error) {
1312
1422
  code = reportThrown(name, error, redact, wantsJson(argv));
1313
1423
  }
1424
+ notifyEnd(name, code, performance.now() - started);
1314
1425
  if (usage !== false) {
1315
1426
  try {
1316
1427
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1327,7 +1438,7 @@ var {Glob } = globalThis.Bun;
1327
1438
  var SESSION_FILES = new Glob("*.json");
1328
1439
  var ACCOUNT_DIRS = new Glob("*/sessions");
1329
1440
  // ../kit/src/watch.ts
1330
- import process15 from "process";
1441
+ import process16 from "process";
1331
1442
  import { format } from "util";
1332
1443
  var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1333
1444
  var DEFAULT_SECONDS = 2;
@@ -1349,7 +1460,7 @@ function withoutWatch(args) {
1349
1460
  }
1350
1461
  return rest;
1351
1462
  }
1352
- async function watching(value, step, stream = process15.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1463
+ async function watching(value, step, stream = process16.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1353
1464
  const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1354
1465
  if (!takesControlCodes(stream))
1355
1466
  badUsage("--watch redraws the screen, so it needs a terminal");
@@ -1357,12 +1468,12 @@ async function watching(value, step, stream = process15.stdout, sleep = Bun.slee
1357
1468
  for (let round = 0;round < rounds; round++) {
1358
1469
  const held = [];
1359
1470
  const { log, info } = console;
1360
- const write = process15.stdout.write.bind(process15.stdout);
1471
+ const write = process16.stdout.write.bind(process16.stdout);
1361
1472
  const hold = (...parts) => void held.push(`${format(...parts)}
1362
1473
  `);
1363
1474
  console.log = hold;
1364
1475
  console.info = hold;
1365
- process15.stdout.write = (text) => {
1476
+ process16.stdout.write = (text) => {
1366
1477
  held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1367
1478
  return true;
1368
1479
  };
@@ -1371,7 +1482,7 @@ async function watching(value, step, stream = process15.stdout, sleep = Bun.slee
1371
1482
  } finally {
1372
1483
  console.log = log;
1373
1484
  console.info = info;
1374
- process15.stdout.write = write;
1485
+ process16.stdout.write = write;
1375
1486
  }
1376
1487
  stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1377
1488
  await sleep(interval);
@@ -1381,7 +1492,7 @@ async function watching(value, step, stream = process15.stdout, sleep = Bun.slee
1381
1492
  // ../kit/src/workspace-root.ts
1382
1493
  import { homedir as homedir4 } from "os";
1383
1494
  import { dirname as dirname4, join as join6, resolve as resolve4 } from "path";
1384
- import process16 from "process";
1495
+ import process17 from "process";
1385
1496
  function expandHome(path, home) {
1386
1497
  if (path === "~")
1387
1498
  return home;
@@ -1391,7 +1502,7 @@ function configured(env, home) {
1391
1502
  const folder = readUserConfig("config", { home, xdg: env.XDG_CONFIG_HOME }).workspace;
1392
1503
  return typeof folder === "string" && folder !== "" ? folder : undefined;
1393
1504
  }
1394
- function workspaceRoot({ given, env = process16.env, home = homedir4() } = {}) {
1505
+ function workspaceRoot({ given, env = process17.env, home = homedir4() } = {}) {
1395
1506
  const fromEnv = env.KAYNOOO_WORKSPACE === "" ? undefined : env.KAYNOOO_WORKSPACE;
1396
1507
  return resolve4(expandHome(given ?? fromEnv ?? configured(env, home) ?? join6(home, "Workspace"), home));
1397
1508
  }
@@ -1467,7 +1578,7 @@ var OPTIONS = {
1467
1578
  };
1468
1579
  var RENAME = /^[RC]\d*$/;
1469
1580
  var NOT_A_REPOSITORY = /not a git repository/i;
1470
- var LITERAL = { ...process18.env, GIT_LITERAL_PATHSPECS: "1" };
1581
+ var LITERAL = { ...process19.env, GIT_LITERAL_PATHSPECS: "1" };
1471
1582
  function messageOf(title, lines, tickets) {
1472
1583
  return [title, lines.join(`
1473
1584
  `), tickets.join(`
@@ -1487,6 +1598,20 @@ async function stagedElsewhere(paths) {
1487
1598
  const ours = new Set(given.split("\x00"));
1488
1599
  return all.split("\x00").filter((path) => path !== "" && !ours.has(path));
1489
1600
  }
1601
+ async function renameSources(paths) {
1602
+ const fields = (await checked(["diff", "--cached", "-M", "--name-status", "-z"])).split("\x00");
1603
+ const sources = [];
1604
+ for (let i = 0;i < fields.length; i++) {
1605
+ if (!RENAME.test(fields[i] ?? ""))
1606
+ continue;
1607
+ const from = fields[i + 1] ?? "";
1608
+ const to = fields[i + 2] ?? "";
1609
+ if (paths.includes(to) && !paths.includes(from))
1610
+ sources.push(from);
1611
+ i += 2;
1612
+ }
1613
+ return sources;
1614
+ }
1490
1615
  async function unstage(paths) {
1491
1616
  const hasHead = (await git2(["rev-parse", "--verify", "-q", "HEAD"], LITERAL)).code === 0;
1492
1617
  await git2(hasHead ? ["reset", "-q", "--", ...paths] : ["rm", "-r", "-q", "--cached", "--", ...paths], LITERAL);
@@ -1498,12 +1623,12 @@ function fileLine(line) {
1498
1623
  async function main(argv) {
1499
1624
  const parsed = parse(argv, USAGE, OPTIONS, { rest: true, replaces: "git add, git status and git commit chained", examples: ['gc "fix(api): retry a timed-out fetch" -- src/api.ts', ['gc "feat(ui): a dark theme" -m "The toggle sits in the header." --ticket "#12 - Dark theme" -- src/theme.ts src/header.ts', "a body line and a ticket"]] });
1500
1625
  const { values, positionals, rest = [] } = parsed;
1501
- const paths = [...new Set(rest)];
1626
+ const given = [...new Set(rest)];
1502
1627
  if (positionals.length !== 1)
1503
1628
  fail(`give the title as one quoted argument and the paths after --
1504
1629
 
1505
1630
  ${USAGE}`);
1506
- if (paths.length === 0)
1631
+ if (given.length === 0)
1507
1632
  fail(`give the paths to commit after --
1508
1633
 
1509
1634
  ${USAGE}`);
@@ -1520,12 +1645,14 @@ ${USAGE}`);
1520
1645
  const violation = commitMessageViolation(message);
1521
1646
  if (violation !== null)
1522
1647
  fail(`nothing staged: ${violation}`, 1);
1523
- const statuses = await Promise.all(paths.map(async (path) => checked(["status", "--porcelain", "--untracked-files=all", "--", path])));
1524
- const unchanged = paths.filter((_, i) => statuses[i] === "");
1525
- const addable = paths.filter((_, i) => !(statuses[i] ?? "").trimEnd().split(`
1648
+ const statuses = await Promise.all(given.map(async (path) => checked(["status", "--porcelain", "--untracked-files=all", "--", path])));
1649
+ const unchanged = given.filter((_, i) => statuses[i] === "");
1650
+ const addable = given.filter((_, i) => !(statuses[i] ?? "").trimEnd().split(`
1526
1651
  `).every((line) => line.startsWith("D ")));
1527
1652
  if (unchanged.length > 0)
1528
1653
  fail(`nothing staged: no change to commit in ${unchanged.join(", ")} (unchanged, ignored or missing)`, 1, runHint("gst", "see what changed"));
1654
+ const sources = await renameSources(given);
1655
+ const paths = [...given, ...sources];
1529
1656
  const others = await stagedElsewhere(paths);
1530
1657
  if (others.length > 0)
1531
1658
  fail(`nothing staged: the index already holds ${others.join(", ")}, which this commit would carry along`, 1, runHint(`git restore --staged -- ${others.join(" ")}`, "unstage them, or name them in the paths too"));
@@ -1557,7 +1684,7 @@ ${(commit.stderr + commit.stdout).trim()}`;
1557
1684
  });
1558
1685
  printJson({ sha: (await checked(["rev-parse", "HEAD"])).trim(), subject: head.slice(head.indexOf(" ") + 1), files: changes });
1559
1686
  } else if (values.quiet !== true) {
1560
- console.log([head, ...lines.filter(Boolean).map(fileLine)].join(`
1687
+ console.log([head, ...lines.filter(Boolean).map(fileLine), ...sources.map((from) => `also committed ${from}, the other side of a staged rename`)].join(`
1561
1688
  `));
1562
1689
  }
1563
1690
  return signals.signal === undefined ? 0 : exitCodeOf(null, signals.signal);
@@ -1565,4 +1692,4 @@ ${(commit.stderr + commit.stdout).trim()}`;
1565
1692
  signals.release();
1566
1693
  }
1567
1694
  }
1568
- process18.exitCode = await runMain({ name: "gc", run: main });
1695
+ process19.exitCode = await runMain({ name: "gc", run: main });