@kaynooo/cli-git 0.15.1 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/gst.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/gst.ts
5
- import process20 from "process";
5
+ import process21 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));
@@ -1138,13 +1150,31 @@ 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/notify.ts
1156
+ import process13 from "process";
1157
+ var NOTIFY_AFTER_MS = 1e4;
1158
+ var CANCELLED = 130;
1159
+ function base64(text) {
1160
+ return Buffer.from(text).toString("base64");
1161
+ }
1162
+ function notification(title, body, env = process13.env) {
1163
+ const id = `kit${process13.pid}`;
1164
+ 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\\`];
1165
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1166
+ }
1167
+ function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
1168
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1169
+ return;
1170
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1171
+ }
1142
1172
 
1143
1173
  // ../kit/src/usage.ts
1144
1174
  import { appendFileSync, mkdirSync } from "fs";
1145
1175
  import { homedir as homedir3 } from "os";
1146
1176
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
1147
- import process13 from "process";
1177
+ import process14 from "process";
1148
1178
 
1149
1179
  // ../kit/src/logs.ts
1150
1180
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -1158,14 +1188,14 @@ var usageError;
1158
1188
  function noteUsageError(message) {
1159
1189
  usageError = message;
1160
1190
  }
1161
- function stateHome(env = process13.env) {
1191
+ function stateHome(env = process14.env) {
1162
1192
  const dir = env.XDG_STATE_HOME;
1163
1193
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1164
1194
  }
1165
- function usagePath(env = process13.env) {
1195
+ function usagePath(env = process14.env) {
1166
1196
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
1167
1197
  }
1168
- function usageRecorded(env = process13.env) {
1198
+ function usageRecorded(env = process14.env) {
1169
1199
  const off = env.KAYNOOO_CLI_NO_USAGE;
1170
1200
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1171
1201
  }
@@ -1179,7 +1209,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
1179
1209
  usageError = undefined;
1180
1210
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1181
1211
  }
1182
- function recordUsage(entry, env = process13.env) {
1212
+ function recordUsage(entry, env = process14.env) {
1183
1213
  if (!usageRecorded(env))
1184
1214
  return;
1185
1215
  try {
@@ -1197,8 +1227,8 @@ var LEVEL_OPTIONS = {
1197
1227
  };
1198
1228
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
1199
1229
  function printError(prefix, message, hint, cause) {
1200
- const colors = paint(process14.stderr);
1201
- const styled = takesControlCodes(process14.stderr);
1230
+ const colors = paint(process15.stderr);
1231
+ const styled = takesControlCodes(process15.stderr);
1202
1232
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1203
1233
  const under = (label, text, tint) => text === undefined ? "" : `
1204
1234
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1306,11 +1336,13 @@ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs(
1306
1336
  return 0;
1307
1337
  }
1308
1338
  let code;
1339
+ const started = performance.now();
1309
1340
  try {
1310
1341
  code = await run(argv);
1311
1342
  } catch (error) {
1312
1343
  code = reportThrown(name, error, redact, wantsJson(argv));
1313
1344
  }
1345
+ notifyEnd(name, code, performance.now() - started);
1314
1346
  if (usage !== false) {
1315
1347
  try {
1316
1348
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1327,7 +1359,7 @@ var {Glob } = globalThis.Bun;
1327
1359
  var SESSION_FILES = new Glob("*.json");
1328
1360
  var ACCOUNT_DIRS = new Glob("*/sessions");
1329
1361
  // ../kit/src/watch.ts
1330
- import process15 from "process";
1362
+ import process16 from "process";
1331
1363
  import { format } from "util";
1332
1364
  var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1333
1365
  var DEFAULT_SECONDS = 2;
@@ -1349,7 +1381,7 @@ function withoutWatch(args) {
1349
1381
  }
1350
1382
  return rest;
1351
1383
  }
1352
- async function watching(value, step, stream = process15.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1384
+ async function watching(value, step, stream = process16.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1353
1385
  const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1354
1386
  if (!takesControlCodes(stream))
1355
1387
  badUsage("--watch redraws the screen, so it needs a terminal");
@@ -1357,12 +1389,12 @@ async function watching(value, step, stream = process15.stdout, sleep = Bun.slee
1357
1389
  for (let round = 0;round < rounds; round++) {
1358
1390
  const held = [];
1359
1391
  const { log, info } = console;
1360
- const write = process15.stdout.write.bind(process15.stdout);
1392
+ const write = process16.stdout.write.bind(process16.stdout);
1361
1393
  const hold = (...parts) => void held.push(`${format(...parts)}
1362
1394
  `);
1363
1395
  console.log = hold;
1364
1396
  console.info = hold;
1365
- process15.stdout.write = (text) => {
1397
+ process16.stdout.write = (text) => {
1366
1398
  held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1367
1399
  return true;
1368
1400
  };
@@ -1371,7 +1403,7 @@ async function watching(value, step, stream = process15.stdout, sleep = Bun.slee
1371
1403
  } finally {
1372
1404
  console.log = log;
1373
1405
  console.info = info;
1374
- process15.stdout.write = write;
1406
+ process16.stdout.write = write;
1375
1407
  }
1376
1408
  stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1377
1409
  await sleep(interval);
@@ -1381,7 +1413,7 @@ async function watching(value, step, stream = process15.stdout, sleep = Bun.slee
1381
1413
  // ../kit/src/workspace-root.ts
1382
1414
  import { homedir as homedir4 } from "os";
1383
1415
  import { dirname as dirname4, join as join6, resolve as resolve4 } from "path";
1384
- import process16 from "process";
1416
+ import process17 from "process";
1385
1417
  function expandHome(path, home) {
1386
1418
  if (path === "~")
1387
1419
  return home;
@@ -1391,13 +1423,13 @@ function configured(env, home) {
1391
1423
  const folder = readUserConfig("config", { home, xdg: env.XDG_CONFIG_HOME }).workspace;
1392
1424
  return typeof folder === "string" && folder !== "" ? folder : undefined;
1393
1425
  }
1394
- function workspaceRoot({ given, env = process16.env, home = homedir4() } = {}) {
1426
+ function workspaceRoot({ given, env = process17.env, home = homedir4() } = {}) {
1395
1427
  const fromEnv = env.KAYNOOO_WORKSPACE === "" ? undefined : env.KAYNOOO_WORKSPACE;
1396
1428
  return resolve4(expandHome(given ?? fromEnv ?? configured(env, home) ?? join6(home, "Workspace"), home));
1397
1429
  }
1398
1430
  // src/colour.ts
1399
- import process18 from "process";
1400
- function letter(status, stream = process18.stdout) {
1431
+ import process19 from "process";
1432
+ function letter(status, stream = process19.stdout) {
1401
1433
  const colors = paint(stream);
1402
1434
  const tint = { A: colors.green, M: colors.yellow, D: colors.red, U: colors.red, R: colors.cyan, C: colors.cyan }[status] ?? colors.dim;
1403
1435
  return tint(status);
@@ -1410,17 +1442,45 @@ async function git2(args, env) {
1410
1442
  return { code: ran.code, stdout: text("stdout"), stderr: text("stderr") };
1411
1443
  }
1412
1444
 
1445
+ // src/operation.ts
1446
+ import { existsSync as existsSync4, readFileSync as readFileSync5 } from "fs";
1447
+ import { join as join7 } from "path";
1448
+ function numberIn(path) {
1449
+ try {
1450
+ const value = Number.parseInt(readFileSync5(path, "utf8"), 10);
1451
+ return Number.isNaN(value) ? undefined : value;
1452
+ } catch {
1453
+ return;
1454
+ }
1455
+ }
1456
+ function operationOf(gitDir) {
1457
+ const has = (name) => existsSync4(join7(gitDir, name));
1458
+ if (has("rebase-merge"))
1459
+ return { kind: "rebase", step: numberIn(join7(gitDir, "rebase-merge/msgnum")), total: numberIn(join7(gitDir, "rebase-merge/end")) };
1460
+ if (has("rebase-apply"))
1461
+ return { kind: "rebase", step: numberIn(join7(gitDir, "rebase-apply/next")), total: numberIn(join7(gitDir, "rebase-apply/last")) };
1462
+ for (const [file, kind] of [["MERGE_HEAD", "merge"], ["CHERRY_PICK_HEAD", "cherry-pick"], ["REVERT_HEAD", "revert"], ["BISECT_LOG", "bisect"]]) {
1463
+ if (has(file))
1464
+ return { kind };
1465
+ }
1466
+ return null;
1467
+ }
1468
+
1413
1469
  // src/repos.ts
1414
1470
  import { readdir } from "fs/promises";
1415
- import { join as join7, relative, resolve as resolve5 } from "path";
1416
- import process19 from "process";
1471
+ import { join as join8, relative, resolve as resolve5 } from "path";
1472
+ import process20 from "process";
1417
1473
 
1418
1474
  // src/status.ts
1419
1475
  var AHEAD_BEHIND = /\+(\d+) -(\d+)/;
1476
+ var STASH = /^# stash (\d+)$/m;
1420
1477
  var OCTAL = /[0-7]/;
1421
1478
  var ESCAPES = { a: 7, b: 8, t: 9, n: 10, v: 11, f: 12, r: 13 };
1422
1479
  var ENCODER = new TextEncoder;
1423
1480
  var DECODER = new TextDecoder;
1481
+ function stashOf(text) {
1482
+ return Number(STASH.exec(text)?.[1] ?? 0);
1483
+ }
1424
1484
  function unquote(path) {
1425
1485
  if (!path.startsWith('"') || !path.endsWith('"'))
1426
1486
  return path;
@@ -1475,16 +1535,18 @@ function parseStatus(text) {
1475
1535
  }
1476
1536
  return hasBranch ? status : null;
1477
1537
  }
1478
- function summary(status, head) {
1538
+ function summary(status, head, { operation = null, stash = 0 } = {}) {
1479
1539
  const { branch, oid, upstream, aheadBehind, changes, conflicted, untracked } = status;
1480
- const on = branch === "(detached)" ? `detached at ${oid.slice(0, 7)}` : `branch \`${branch}\``;
1540
+ const steps = operation?.step !== undefined && operation.total !== undefined ? ` ${operation.step}/${operation.total}` : "";
1541
+ const during = operation === null ? "" : ` (${operation.kind}${steps} in progress)`;
1542
+ const on = (branch === "(detached)" ? `detached at ${oid.slice(0, 7)}` : `branch \`${branch}\``) + during;
1481
1543
  let tracking = "no upstream";
1482
1544
  if (upstream !== null)
1483
1545
  tracking = aheadBehind === null ? `upstream \`${upstream}\` gone or never fetched` : `${aheadBehind.ahead} ahead and ${aheadBehind.behind} behind \`${upstream}\` as of the last fetch`;
1484
1546
  const files = [`${changes.length} changed`, untracked.length > 0 ? `${untracked.length} untracked` : "", conflicted.length > 0 ? `${conflicted.length} conflicted` : ""].filter(Boolean).join(", ");
1485
1547
  const [sha, title] = head.trim().split("\x00");
1486
1548
  const last = sha === undefined || sha === "" ? "; no commit yet" : `; HEAD ${sha} ${title ?? ""}`.trimEnd();
1487
- return `${on}, ${tracking}; ${files} files${last}`;
1549
+ return `${on}, ${tracking}; ${files} files${stash > 0 ? `; ${stash} stashed` : ""}${last}`;
1488
1550
  }
1489
1551
 
1490
1552
  // src/repos.ts
@@ -1503,7 +1565,7 @@ async function reposUnder(root, depth = DEPTH) {
1503
1565
  found.push(dir);
1504
1566
  if (left === 0)
1505
1567
  return;
1506
- await Promise.all(entries.filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && !SKIPPED.has(entry.name)).map(async (entry) => walk(join7(dir, entry.name), left - 1)));
1568
+ await Promise.all(entries.filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && !SKIPPED.has(entry.name)).map(async (entry) => walk(join8(dir, entry.name), left - 1)));
1507
1569
  }
1508
1570
  await walk(resolve5(root), depth);
1509
1571
  return found.sort();
@@ -1513,14 +1575,14 @@ async function toplevelOf(dir) {
1513
1575
  return read.code === 0 ? read.stdout.trim() : undefined;
1514
1576
  }
1515
1577
  async function reposOf(roots) {
1516
- const starts = roots.length > 0 ? roots : [await toplevelOf(".") ?? process19.cwd()];
1578
+ const starts = roots.length > 0 ? roots : [await toplevelOf(".") ?? process20.cwd()];
1517
1579
  const found = await Promise.all(starts.map(async (root) => reposUnder(root)));
1518
1580
  return [...new Set(found.flat())].sort();
1519
1581
  }
1520
1582
  async function repoState(dir) {
1521
1583
  const [read, log] = await Promise.all([git2(["-C", dir, "status", "--porcelain=v2", "--branch"]), git2(["-C", dir, "log", "-1", "--format=%h%x00%s"])]);
1522
1584
  const [sha, title = ""] = log.code === 0 && log.stdout.trim() !== "" ? log.stdout.trim().split("\x00") : [];
1523
- return { path: relative(process19.cwd(), dir) || ".", dir, status: read.code === 0 ? parseStatus(read.stdout) : null, head: sha === undefined ? null : { sha, title } };
1585
+ return { path: relative(process20.cwd(), dir) || ".", dir, status: read.code === 0 ? parseStatus(read.stdout) : null, head: sha === undefined ? null : { sha, title } };
1524
1586
  }
1525
1587
  function trackingOf(status) {
1526
1588
  if (status.upstream === null)
@@ -1565,9 +1627,9 @@ var OPTIONS = {
1565
1627
  log: { type: "string", short: "l", description: "the former spelling of --limit" },
1566
1628
  repos: { type: "boolean", short: "r", description: "one line for each repository nested below, the current one included", conflicts: ["limit", "log"] },
1567
1629
  watch: watchOption("the status"),
1568
- json: jsonOption("{branch, oid, upstream, ahead, behind, head, staged, unstaged, untracked, conflicted, commits}; with --repos an array of them, each with its path and no commits, a repository git cannot read being {path, error}")
1630
+ json: jsonOption("{branch, oid, upstream, ahead, behind, head, staged, unstaged, untracked, conflicted, operation, stash, commits}, operation being {kind, step?, total?} while a rebase, merge, cherry-pick, revert or bisect is in progress and null otherwise; with --repos an array of them, each with its path and no commits, a repository git cannot read being {path, error}")
1569
1631
  };
1570
- function jsonOf(status, head, commits) {
1632
+ function jsonOf(status, head, commits, extra) {
1571
1633
  return {
1572
1634
  branch: status.branch,
1573
1635
  oid: status.oid,
@@ -1579,6 +1641,7 @@ function jsonOf(status, head, commits) {
1579
1641
  unstaged: status.changes.filter((change) => change.worktree !== ".").map(({ worktree, path }) => ({ status: worktree, path })),
1580
1642
  untracked: status.untracked,
1581
1643
  conflicted: status.conflicted,
1644
+ ...extra === undefined ? {} : { operation: extra.operation, stash: extra.stash },
1582
1645
  ...commits === undefined ? {} : { commits: commits.map(([commitSha = "", commitTitle = ""]) => ({ sha: commitSha, title: commitTitle })) }
1583
1646
  };
1584
1647
  }
@@ -1591,18 +1654,18 @@ async function listRepos(roots, json) {
1591
1654
  printJson(repos.map(({ path, status, head }) => status === null ? { path, error: "git could not read it" } : { path, ...jsonOf(status, head) }));
1592
1655
  return 0;
1593
1656
  }
1594
- const dim = paint(process20.stdout).dim;
1657
+ const dim = paint(process21.stdout).dim;
1595
1658
  const cells = (repo) => {
1596
1659
  if (repo.status === null)
1597
- return [role("path", process20.stdout)(repo.path), "", "", "git could not read it"];
1660
+ return [role("path", process21.stdout)(repo.path), "", "", "git could not read it"];
1598
1661
  const changes = changesOf(repo.status);
1599
- return [role("path", process20.stdout)(repo.path), branchOf(repo.status), trackingOf(repo.status), changes === "clean" ? dim(changes) : changes];
1662
+ return [role("path", process21.stdout)(repo.path), branchOf(repo.status), trackingOf(repo.status), changes === "clean" ? dim(changes) : changes];
1600
1663
  };
1601
1664
  console.log(table(repos.map(cells)));
1602
1665
  return 0;
1603
1666
  }
1604
1667
  function group(title, lines) {
1605
- return lines.length === 0 ? [] : [paint(process20.stdout).bold(`${title}:`), ...lines.map((line) => ` ${line}`)];
1668
+ return lines.length === 0 ? [] : [paint(process21.stdout).bold(`${title}:`), ...lines.map((line) => ` ${line}`)];
1606
1669
  }
1607
1670
  function staged({ index, from, path }) {
1608
1671
  return `${letter(index)} ${from === undefined ? "" : `${from} -> `}${path}`;
@@ -1621,31 +1684,33 @@ ${USAGE}`);
1621
1684
  fail("--limit and --log are the same flag, give one");
1622
1685
  const asked = parsed.values.limit ?? parsed.values.log;
1623
1686
  const count = asked === undefined ? 0 : wholeNumber(asked, "limit", 1);
1624
- const [read, head, log] = await Promise.all([
1625
- git2(["status", "--porcelain=v2", "--branch"]),
1687
+ const [read, head, log, gitDir] = await Promise.all([
1688
+ git2(["status", "--porcelain=v2", "--branch", "--show-stash"]),
1626
1689
  git2(["log", "-1", "--format=%h%x00%s"]),
1627
- count === 0 ? undefined : git2(["log", `-${count}`, "--format=%h%x00%s"])
1690
+ count === 0 ? undefined : git2(["log", `-${count}`, "--format=%h%x00%s"]),
1691
+ git2(["rev-parse", "--absolute-git-dir"])
1628
1692
  ]);
1629
1693
  const status = read.code === 0 ? parseStatus(read.stdout) : null;
1630
1694
  if (status === null)
1631
1695
  fail(read.stderr.trim() || "not inside a git repository");
1696
+ const extra = { operation: gitDir.code === 0 ? operationOf(gitDir.stdout.trim()) : null, stash: stashOf(read.stdout) };
1632
1697
  const commits = log?.code === 0 ? log.stdout.trimEnd().split(`
1633
1698
  `).filter(Boolean).map((line) => line.split("\x00")) : [];
1634
1699
  if (parsed.values.json === true) {
1635
1700
  const [sha, title] = head.code === 0 && head.stdout.trim() !== "" ? head.stdout.trim().split("\x00") : [];
1636
- printJson(jsonOf(status, sha === undefined ? null : { sha, title: title ?? "" }, commits));
1701
+ printJson(jsonOf(status, sha === undefined ? null : { sha, title: title ?? "" }, commits, extra));
1637
1702
  return 0;
1638
1703
  }
1639
1704
  const lines = [
1640
- summary(status, head.code === 0 ? head.stdout : ""),
1705
+ summary(status, head.code === 0 ? head.stdout : "", extra),
1641
1706
  ...group("staged", status.changes.filter((change) => change.index !== ".").map(staged)),
1642
1707
  ...group("unstaged", status.changes.filter((change) => change.worktree !== ".").map((change) => `${letter(change.worktree)} ${change.path}`)),
1643
- ...group("untracked", status.untracked.map((file) => paint(process20.stdout).dim(file))),
1644
- ...group("conflicted", status.conflicted.map((file) => paint(process20.stdout).red(file))),
1645
- ...group("commits", commits.map(([commitSha = "", commitTitle = ""]) => `${role("id", process20.stdout)(commitSha)} ${commitTitle}`))
1708
+ ...group("untracked", status.untracked.map((file) => paint(process21.stdout).dim(file))),
1709
+ ...group("conflicted", status.conflicted.map((file) => paint(process21.stdout).red(file))),
1710
+ ...group("commits", commits.map(([commitSha = "", commitTitle = ""]) => `${role("id", process21.stdout)(commitSha)} ${commitTitle}`))
1646
1711
  ];
1647
1712
  console.log(lines.join(`
1648
1713
  `));
1649
1714
  return 0;
1650
1715
  }
1651
- process20.exitCode = await runMain({ name: "gst", run: main });
1716
+ process21.exitCode = await runMain({ name: "gst", run: main });
package/dist/gu.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // src/gu.ts
5
5
  import { mkdirSync as mkdirSync2, writeFileSync } from "fs";
6
6
  import { join as join7, resolve as resolve5 } from "path";
7
- import process18 from "process";
7
+ import process19 from "process";
8
8
  // ../kit/src/args.ts
9
9
  import process9 from "process";
10
10
  import { parseArgs } from "util";
@@ -495,7 +495,7 @@ function printJson(value) {
495
495
 
496
496
  // ../kit/src/help.ts
497
497
  import process8 from "process";
498
- var OPTIONAL = /\[[^\]]+\]/g;
498
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
499
499
  var USAGE_PREFIX = /^usage:\s*/i;
500
500
  var FULL_STOP = /\.$/;
501
501
  function usageLine(usage, colors = paint(process8.stdout)) {
@@ -534,29 +534,41 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
534
534
  return [];
535
535
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
536
536
  }
537
+ var MAX_INLINE_CHOICES = 24;
537
538
  function optionRows(options, colors = paint(process8.stdout)) {
538
539
  const rows = Object.entries(options).map(([name, option]) => {
539
540
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
540
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
541
+ const choices = option.choices?.join("|");
542
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
543
+ const named = inline ? `<${choices}>` : "<value>";
541
544
  const placeholder = option.optional === undefined ? named : `[${named}]`;
542
545
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
543
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
546
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
547
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
544
548
  });
545
549
  const width = Math.max(0, ...rows.map((row) => row.width));
546
550
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
547
551
  }
548
552
 
549
553
  // ../kit/src/text.ts
550
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
554
+ var ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
551
555
  function distance(a, b) {
552
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
553
- for (const [i, left] of [...a].entries()) {
556
+ const left = [...a];
557
+ const right = [...b];
558
+ let before = [];
559
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
560
+ for (const [i, x] of left.entries()) {
554
561
  const current = [i + 1];
555
- for (const [j, right] of [...b].entries())
556
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
562
+ for (const [j, y] of right.entries()) {
563
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
564
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
565
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
566
+ current.push(cost);
567
+ }
568
+ before = previous;
557
569
  previous = current;
558
570
  }
559
- return previous[b.length] ?? 0;
571
+ return previous[right.length] ?? 0;
560
572
  }
561
573
  function closest(name, names) {
562
574
  const started = names.find((known) => known.startsWith(name));
@@ -1140,13 +1152,31 @@ function interceptOutput(clear) {
1140
1152
  // ../kit/src/cli.ts
1141
1153
  import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
1142
1154
  import { dirname as dirname3, join as join5 } from "path";
1143
- import process14 from "process";
1155
+ import process15 from "process";
1156
+
1157
+ // ../kit/src/notify.ts
1158
+ import process13 from "process";
1159
+ var NOTIFY_AFTER_MS = 1e4;
1160
+ var CANCELLED = 130;
1161
+ function base64(text) {
1162
+ return Buffer.from(text).toString("base64");
1163
+ }
1164
+ function notification(title, body, env = process13.env) {
1165
+ const id = `kit${process13.pid}`;
1166
+ 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\\`];
1167
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1168
+ }
1169
+ function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
1170
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1171
+ return;
1172
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1173
+ }
1144
1174
 
1145
1175
  // ../kit/src/usage.ts
1146
1176
  import { appendFileSync, mkdirSync } from "fs";
1147
1177
  import { homedir as homedir3 } from "os";
1148
1178
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
1149
- import process13 from "process";
1179
+ import process14 from "process";
1150
1180
 
1151
1181
  // ../kit/src/logs.ts
1152
1182
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -1160,14 +1190,14 @@ var usageError;
1160
1190
  function noteUsageError(message) {
1161
1191
  usageError = message;
1162
1192
  }
1163
- function stateHome(env = process13.env) {
1193
+ function stateHome(env = process14.env) {
1164
1194
  const dir = env.XDG_STATE_HOME;
1165
1195
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1166
1196
  }
1167
- function usagePath(env = process13.env) {
1197
+ function usagePath(env = process14.env) {
1168
1198
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
1169
1199
  }
1170
- function usageRecorded(env = process13.env) {
1200
+ function usageRecorded(env = process14.env) {
1171
1201
  const off = env.KAYNOOO_CLI_NO_USAGE;
1172
1202
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1173
1203
  }
@@ -1181,7 +1211,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
1181
1211
  usageError = undefined;
1182
1212
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1183
1213
  }
1184
- function recordUsage(entry, env = process13.env) {
1214
+ function recordUsage(entry, env = process14.env) {
1185
1215
  if (!usageRecorded(env))
1186
1216
  return;
1187
1217
  try {
@@ -1199,8 +1229,8 @@ var LEVEL_OPTIONS = {
1199
1229
  };
1200
1230
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
1201
1231
  function printError(prefix, message, hint, cause) {
1202
- const colors = paint(process14.stderr);
1203
- const styled = takesControlCodes(process14.stderr);
1232
+ const colors = paint(process15.stderr);
1233
+ const styled = takesControlCodes(process15.stderr);
1204
1234
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1205
1235
  const under = (label, text, tint) => text === undefined ? "" : `
1206
1236
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1308,11 +1338,13 @@ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs(
1308
1338
  return 0;
1309
1339
  }
1310
1340
  let code;
1341
+ const started = performance.now();
1311
1342
  try {
1312
1343
  code = await run(argv);
1313
1344
  } catch (error) {
1314
1345
  code = reportThrown(name, error, redact, wantsJson(argv));
1315
1346
  }
1347
+ notifyEnd(name, code, performance.now() - started);
1316
1348
  if (usage !== false) {
1317
1349
  try {
1318
1350
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1329,7 +1361,7 @@ var {Glob } = globalThis.Bun;
1329
1361
  var SESSION_FILES = new Glob("*.json");
1330
1362
  var ACCOUNT_DIRS = new Glob("*/sessions");
1331
1363
  // ../kit/src/watch.ts
1332
- import process15 from "process";
1364
+ import process16 from "process";
1333
1365
  import { format } from "util";
1334
1366
  var CLEAR_SCREEN = "\x1B[H\x1B[2J";
1335
1367
  var DEFAULT_SECONDS = 2;
@@ -1351,7 +1383,7 @@ function withoutWatch(args) {
1351
1383
  }
1352
1384
  return rest;
1353
1385
  }
1354
- async function watching(value, step, stream = process15.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1386
+ async function watching(value, step, stream = process16.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
1355
1387
  const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
1356
1388
  if (!takesControlCodes(stream))
1357
1389
  badUsage("--watch redraws the screen, so it needs a terminal");
@@ -1359,12 +1391,12 @@ async function watching(value, step, stream = process15.stdout, sleep = Bun.slee
1359
1391
  for (let round = 0;round < rounds; round++) {
1360
1392
  const held = [];
1361
1393
  const { log, info } = console;
1362
- const write = process15.stdout.write.bind(process15.stdout);
1394
+ const write = process16.stdout.write.bind(process16.stdout);
1363
1395
  const hold = (...parts) => void held.push(`${format(...parts)}
1364
1396
  `);
1365
1397
  console.log = hold;
1366
1398
  console.info = hold;
1367
- process15.stdout.write = (text) => {
1399
+ process16.stdout.write = (text) => {
1368
1400
  held.push(typeof text === "string" ? text : Buffer.from(text).toString());
1369
1401
  return true;
1370
1402
  };
@@ -1373,7 +1405,7 @@ async function watching(value, step, stream = process15.stdout, sleep = Bun.slee
1373
1405
  } finally {
1374
1406
  console.log = log;
1375
1407
  console.info = info;
1376
- process15.stdout.write = write;
1408
+ process16.stdout.write = write;
1377
1409
  }
1378
1410
  stream.write(`${CLEAR_SCREEN}${held.join("")}`);
1379
1411
  await sleep(interval);
@@ -1383,7 +1415,7 @@ async function watching(value, step, stream = process15.stdout, sleep = Bun.slee
1383
1415
  // ../kit/src/workspace-root.ts
1384
1416
  import { homedir as homedir4 } from "os";
1385
1417
  import { dirname as dirname4, join as join6, resolve as resolve4 } from "path";
1386
- import process16 from "process";
1418
+ import process17 from "process";
1387
1419
  function expandHome(path, home) {
1388
1420
  if (path === "~")
1389
1421
  return home;
@@ -1393,7 +1425,7 @@ function configured(env, home) {
1393
1425
  const folder = readUserConfig("config", { home, xdg: env.XDG_CONFIG_HOME }).workspace;
1394
1426
  return typeof folder === "string" && folder !== "" ? folder : undefined;
1395
1427
  }
1396
- function workspaceRoot({ given, env = process16.env, home = homedir4() } = {}) {
1428
+ function workspaceRoot({ given, env = process17.env, home = homedir4() } = {}) {
1397
1429
  const fromEnv = env.KAYNOOO_WORKSPACE === "" ? undefined : env.KAYNOOO_WORKSPACE;
1398
1430
  return resolve4(expandHome(given ?? fromEnv ?? configured(env, home) ?? join6(home, "Workspace"), home));
1399
1431
  }
@@ -1415,7 +1447,8 @@ var OPTIONS = {
1415
1447
  commit: { type: "boolean", short: "c", description: "undo the last commit, keeping its changes staged" },
1416
1448
  json: jsonOption("{action, paths?, saved?, commit?} of what was undone, saved being the patch of a discard")
1417
1449
  };
1418
- var LITERAL = { ...process18.env, GIT_LITERAL_PATHSPECS: "1" };
1450
+ var LITERAL = { ...process19.env, GIT_LITERAL_PATHSPECS: "1" };
1451
+ var PLAIN_PATCH = ["--binary", "--no-ext-diff", "--no-textconv", "--no-color", "--no-relative", "--submodule=short", "--src-prefix=a/", "--dst-prefix=b/"];
1419
1452
  var NOT_A_REPOSITORY = /not a git repository/i;
1420
1453
  async function checked(args) {
1421
1454
  const { code, stdout, stderr } = await git2(args, LITERAL);
@@ -1462,18 +1495,24 @@ async function main(argv) {
1462
1495
  fail(`no ${staged ? "staged" : "unstaged"} change in ${unchanged.join(", ")}, nothing undone`, 1);
1463
1496
  const paths = [...new Set(each.flat())];
1464
1497
  if (staged) {
1465
- await checked(["restore", "--staged", "--", ...positionals]);
1498
+ const hasHead = (await git2(["rev-parse", "--verify", "-q", "HEAD"], LITERAL)).code === 0;
1499
+ await checked(hasHead ? ["restore", "--staged", "--", ...positionals] : ["rm", "--cached", "-r", "--quiet", "--", ...positionals]);
1466
1500
  if (values.json === true)
1467
1501
  printJson({ action: "unstage", paths });
1468
1502
  else
1469
1503
  console.log(`unstaged ${paths.join(", ")}`);
1470
1504
  return 0;
1471
1505
  }
1472
- const patch = await checked(["diff", "--binary", "--", ...positionals]);
1506
+ const patch = await checked(["diff", ...PLAIN_PATCH, "--", ...positionals]);
1473
1507
  const folder = join7(resolve5((await checked(["rev-parse", "--git-dir"])).trim()), "gu");
1474
1508
  const saved = join7(folder, `${new Date().toISOString().replaceAll(":", "-")}.patch`);
1509
+ const top = (await checked(["rev-parse", "--show-toplevel"])).trim();
1475
1510
  mkdirSync2(folder, { recursive: true });
1476
1511
  writeFileSync(saved, patch);
1512
+ const reverts = await git2(["-C", top, "apply", "--check", "--reverse", "--whitespace=nowarn", saved]);
1513
+ if (reverts.code !== 0)
1514
+ fail(`the patch saved to ${saved} would not put the change back, nothing discarded:
1515
+ ${reverts.stderr.trim()}`, 1);
1477
1516
  await checked(["restore", "--", ...positionals]);
1478
1517
  if (values.json === true)
1479
1518
  printJson({ action: "discard", paths, saved });
@@ -1481,4 +1520,4 @@ async function main(argv) {
1481
1520
  console.log(`discarded ${paths.join(", ")}, saved to ${saved} (git apply puts it back)`);
1482
1521
  return 0;
1483
1522
  }
1484
- process18.exitCode = await runMain({ name: "gu", run: main });
1523
+ process19.exitCode = await runMain({ name: "gu", run: main });