@kaynooo/cli-base 0.10.0 → 0.11.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/README.md CHANGED
@@ -28,7 +28,8 @@ proof --keep tests/NewTest.php -- vendor/bin/phpunit tests/NewTest.php
28
28
 
29
29
  - `--ref` defaults to the merge base with `origin/main` when HEAD is on a branch other than `main` that is ahead of it, else HEAD; `--ref HEAD` forces the old default. The `--json` `ref` and the line name the commit it resolved to.
30
30
  - `--runs <n>` (`-n`) runs the command n times in the working tree, for a flaky test: every run must pass, the outcome is `flaky` (exit 1) when it failed before and only some runs fail now, and a line lists each run (`now: run 1 passed, run 2 failed (exit 1), run 3 passed`). The ref side runs once. `--json` adds `runs: [{code}]`.
31
+ - `--timeout <duration>` kills a run that lasts longer (a hung test) and ends with exit 2, a timeout telling nothing of the change.
31
32
  - `--keep`, `--no-link` and the single spaced argument through `sh -c` behave as in `base`.
32
33
  - Four outcomes, each printed as one line followed by the output of the side that explains it: `fails at 1a2b3c4, passes now` (the proof, exit 0, the output before), `passes at 1a2b3c4 too: it does not fail without the change`, `fails at 1a2b3c4 and fails now too` (the output now) and `passes at 1a2b3c4, fails now` (the output now), all three exit 1.
33
34
  - `--json` prints `{outcome, proved, ref, sha, before: {code, output}, now: {code, output}}`, `outcome` being `proved`, `passes-before`, `fails-both` `regressed` or `flaky`.
34
- - Exit codes: 0 fails before and passes now, 1 any other outcome, 2 a usage error, an unknown ref, a refused command, one that cannot start or one that ends with exit 126, 127 or a signal (or 128 plus the signal when interrupted).
35
+ - Exit codes: 0 fails before and passes now, 1 any other outcome, 2 a usage error, an unknown ref, a refused command, one that cannot start or one that ends with exit 125, 126, 127 or a signal, or one that runs past `--timeout` (or 128 plus the signal when interrupted).
package/dist/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/cli.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";
@@ -321,6 +321,23 @@ var STATUS_WORDS = {
321
321
  var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
322
322
 
323
323
  // ../kit/src/format.ts
324
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
325
+ function formatSeconds(total) {
326
+ let rest = Math.max(0, Math.round(total));
327
+ const amounts = UNITS.map(([unit, size]) => {
328
+ const amount = Math.floor(rest / size);
329
+ rest -= amount * size;
330
+ return `${amount}${unit}`;
331
+ });
332
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
333
+ if (first === -1)
334
+ return "0s";
335
+ const next = amounts[first + 1];
336
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
337
+ }
338
+ function formatDuration(ms) {
339
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
340
+ }
324
341
  function upTo(text, separator) {
325
342
  const end = text.indexOf(separator);
326
343
  return end === -1 ? text : text.slice(0, end);
@@ -335,24 +352,20 @@ function printJson(value) {
335
352
 
336
353
  // ../kit/src/help.ts
337
354
  import process8 from "process";
338
- var OPTIONAL = /\[[^\]]+\]/g;
355
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
339
356
  var USAGE_PREFIX = /^usage:\s*/i;
340
357
  var FULL_STOP = /\.$/;
341
358
  function usageLine(usage, colors = paint(process8.stdout)) {
342
359
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
343
360
  }
344
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
345
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
361
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
362
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
346
363
  `);
347
364
  }
348
365
  function exitRows(exits, colors = paint(process8.stdout)) {
349
366
  if (exits.length === 0)
350
367
  return [];
351
- const width = Math.max(...exits.map(([code]) => String(code).length));
352
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
353
- }
354
- function replacesRows(replaces, colors = paint(process8.stdout)) {
355
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
368
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
356
369
  }
357
370
  function wantsHelpJson(env = process8.env) {
358
371
  return env.KIT_HELP === "json";
@@ -378,29 +391,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
378
391
  return [];
379
392
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
380
393
  }
394
+ var MAX_INLINE_CHOICES = 24;
381
395
  function optionRows(options, colors = paint(process8.stdout)) {
382
396
  const rows = Object.entries(options).map(([name, option]) => {
383
397
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
384
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
398
+ const choices = option.choices?.join("|");
399
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
400
+ const named = inline ? `<${choices}>` : "<value>";
385
401
  const placeholder = option.optional === undefined ? named : `[${named}]`;
386
402
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
387
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
403
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
404
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
388
405
  });
389
406
  const width = Math.max(0, ...rows.map((row) => row.width));
390
407
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
391
408
  }
392
409
 
393
410
  // ../kit/src/text.ts
394
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
395
411
  function distance(a, b) {
396
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
397
- for (const [i, left] of [...a].entries()) {
412
+ const left = [...a];
413
+ const right = [...b];
414
+ let before = [];
415
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
416
+ for (const [i, x] of left.entries()) {
398
417
  const current = [i + 1];
399
- for (const [j, right] of [...b].entries())
400
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
418
+ for (const [j, y] of right.entries()) {
419
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
420
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
421
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
422
+ current.push(cost);
423
+ }
424
+ before = previous;
401
425
  previous = current;
402
426
  }
403
- return previous[b.length] ?? 0;
427
+ return previous[right.length] ?? 0;
404
428
  }
405
429
  function closest(name, names) {
406
430
  const started = names.find((known) => known.startsWith(name));
@@ -419,6 +443,17 @@ function wholeNumber(value, name, fallback, min = 1) {
419
443
  badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
420
444
  return number;
421
445
  }
446
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
447
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
448
+ function duration(value, name, fallback, unit = "s") {
449
+ if (value === undefined)
450
+ return fallback;
451
+ const match = DURATION.exec(value.trim());
452
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
453
+ if (ms < 1)
454
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
455
+ return ms;
456
+ }
422
457
 
423
458
  // ../kit/src/args.ts
424
459
  var DASHES = /^-+/;
@@ -465,7 +500,7 @@ class Completing {
465
500
  }
466
501
  var completion = { active: false };
467
502
  var OUTPUT_OPTIONS = {
468
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
503
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
469
504
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
470
505
  };
471
506
  function applyOutput(color, plain, env = process9.env) {
@@ -791,13 +826,91 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
791
826
  // ../kit/src/cli.ts
792
827
  import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
793
828
  import { dirname as dirname3, join as join5 } from "path";
794
- import process13 from "process";
829
+ import process14 from "process";
830
+
831
+ // ../kit/src/completions.ts
832
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
833
+ 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'
834
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
835
+ set -l current (commandline -ct)
836
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
837
+ if test "$line" = __files__
838
+ __fish_complete_path $current
839
+ else
840
+ echo $line
841
+ end
842
+ end
843
+ end`;
844
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
845
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
846
+ local -a lines
847
+ COMPREPLY=()
848
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
849
+ for line in "\${lines[@]}"; do
850
+ if [[ $line == __files__ ]]; then
851
+ COMPREPLY+=($(compgen -f -- "$cur"))
852
+ else
853
+ words+="\${line%%$'\\t'*}"$'\\n'
854
+ fi
855
+ done
856
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
857
+ }`;
858
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
859
+ local line
860
+ local -a described plain
861
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
862
+ if [[ $line == __files__ ]]; then
863
+ _files
864
+ elif [[ $line == *$'\\t'* ]]; then
865
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
866
+ else
867
+ plain+=("$line")
868
+ fi
869
+ done
870
+ (( \${#described} )) && _describe -V value described
871
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
872
+ return 0
873
+ }`;
874
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
875
+ if (shell === "fish")
876
+ return `${header}
877
+ ${FISH_FUNCTION}
878
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
879
+ `).join("")}`;
880
+ if (shell === "bash")
881
+ return `${header}
882
+ ${BASH_FUNCTION}
883
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
884
+ `;
885
+ return `${header}
886
+ ${ZSH_FUNCTION}
887
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
888
+ `;
889
+ }
890
+
891
+ // ../kit/src/notify.ts
892
+ import process12 from "process";
893
+ var NOTIFY_AFTER_MS = 1e4;
894
+ var CANCELLED = 130;
895
+ function base64(text) {
896
+ return Buffer.from(text).toString("base64");
897
+ }
898
+ function notification(title, body, env = process12.env) {
899
+ const id = `kit${process12.pid}`;
900
+ 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\\`];
901
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
902
+ }
903
+ function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
904
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
905
+ return;
906
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
907
+ }
795
908
 
796
909
  // ../kit/src/usage.ts
797
910
  import { appendFileSync, mkdirSync } from "fs";
798
911
  import { homedir as homedir3 } from "os";
799
912
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
800
- import process12 from "process";
913
+ import process13 from "process";
801
914
 
802
915
  // ../kit/src/logs.ts
803
916
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -811,14 +924,14 @@ var usageError;
811
924
  function noteUsageError(message) {
812
925
  usageError = message;
813
926
  }
814
- function stateHome(env = process12.env) {
927
+ function stateHome(env = process13.env) {
815
928
  const dir = env.XDG_STATE_HOME;
816
929
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
817
930
  }
818
- function usagePath(env = process12.env) {
931
+ function usagePath(env = process13.env) {
819
932
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
820
933
  }
821
- function usageRecorded(env = process12.env) {
934
+ function usageRecorded(env = process13.env) {
822
935
  const off = env.KAYNOOO_CLI_NO_USAGE;
823
936
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
824
937
  }
@@ -832,7 +945,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
832
945
  usageError = undefined;
833
946
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
834
947
  }
835
- function recordUsage(entry, env = process12.env) {
948
+ function recordUsage(entry, env = process13.env) {
836
949
  if (!usageRecorded(env))
837
950
  return;
838
951
  try {
@@ -848,7 +961,11 @@ var LEVEL_OPTIONS = {
848
961
  ...OUTPUT_OPTIONS,
849
962
  help: { type: "boolean", short: "h", description: "show this help" }
850
963
  };
851
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
964
+ var TOP_OPTIONS = {
965
+ ...LEVEL_OPTIONS,
966
+ version: { type: "boolean", short: "v", description: "print the version" },
967
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
968
+ };
852
969
  async function commandRows(all, colors) {
853
970
  const commands = shown(all);
854
971
  const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
@@ -909,7 +1026,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
909
1026
  header(colors, summary),
910
1027
  "",
911
1028
  usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
912
- ...replacesRows(replaces, colors),
913
1029
  "",
914
1030
  ...await commandRows(commands, colors),
915
1031
  ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
@@ -923,8 +1039,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
923
1039
  `);
924
1040
  }
925
1041
  function printError(prefix, message, hint, cause) {
926
- const colors = paint(process13.stderr);
927
- const styled = takesControlCodes(process13.stderr);
1042
+ const colors = paint(process14.stderr);
1043
+ const styled = takesControlCodes(process14.stderr);
928
1044
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
929
1045
  const under = (label, text, tint) => text === undefined ? "" : `
930
1046
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -967,11 +1083,11 @@ async function dispatch(level, typed, { version, redact }) {
967
1083
  }
968
1084
  }
969
1085
  if (name === undefined && level.path.length > 1) {
970
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
1086
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
971
1087
  return 2;
972
1088
  }
973
1089
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
974
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
1090
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
975
1091
  return 0;
976
1092
  }
977
1093
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1082,6 +1198,19 @@ async function candidates(scope, defaultCommand, words, before = []) {
1082
1198
  }
1083
1199
  return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1084
1200
  }
1201
+ var COMPLETIONS = "--completions";
1202
+ function flagValue([flag = "", ...rest]) {
1203
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1204
+ }
1205
+ function printCompletionScript(name, args) {
1206
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1207
+ if (shell === undefined || args.length !== 1) {
1208
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1209
+ return 2;
1210
+ }
1211
+ console.log(completionScript(shell, [name]).trimEnd());
1212
+ return 0;
1213
+ }
1085
1214
  async function printCandidates(found) {
1086
1215
  for (const line of await found)
1087
1216
  console.log(line);
@@ -1106,10 +1235,15 @@ async function runCli(cli, argv = scriptArgs()) {
1106
1235
  const version = cli.version ?? packageVersion();
1107
1236
  if (argv[0] === COMPLETE)
1108
1237
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1238
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1239
+ return printCompletionScript(cli.name, flagValue(argv));
1240
+ const started = performance.now();
1109
1241
  const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
1242
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1243
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1110
1244
  if (cli.usage !== false) {
1111
1245
  try {
1112
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1246
+ recordUsage(usageEntry(cli.name, command, argv, code));
1113
1247
  } catch {}
1114
1248
  }
1115
1249
  return code;
@@ -1132,16 +1266,20 @@ function commandPath(scope, argv) {
1132
1266
  async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1133
1267
  if (argv[0] === COMPLETE)
1134
1268
  return printCandidates(leafCandidates(run, argv.slice(1)));
1269
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1270
+ return printCompletionScript(name, flagValue(argv));
1135
1271
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1136
1272
  console.log(version ?? packageVersion());
1137
1273
  return 0;
1138
1274
  }
1139
1275
  let code;
1276
+ const started = performance.now();
1140
1277
  try {
1141
1278
  code = await run(argv);
1142
1279
  } catch (error) {
1143
1280
  code = reportThrown(name, error, redact, wantsJson(argv));
1144
1281
  }
1282
+ notifyEnd(name, code, performance.now() - started);
1145
1283
  if (usage !== false) {
1146
1284
  try {
1147
1285
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1158,13 +1296,13 @@ var {Glob } = globalThis.Bun;
1158
1296
  var SESSION_FILES = new Glob("*.json");
1159
1297
  var ACCOUNT_DIRS = new Glob("*/sessions");
1160
1298
  // src/base.ts
1161
- import process16 from "process";
1299
+ import process17 from "process";
1162
1300
 
1163
1301
  // src/worktree.ts
1164
1302
  import { cpSync, existsSync as existsSync3, lstatSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, realpathSync as realpathSync3, rmSync, symlinkSync, unlinkSync } from "fs";
1165
1303
  import { tmpdir } from "os";
1166
1304
  import { basename, dirname as dirname4, isAbsolute as isAbsolute2, join as join6, relative, resolve as resolve4, sep } from "path";
1167
- import process15 from "process";
1305
+ import process16 from "process";
1168
1306
  var WHITESPACE = /\s/;
1169
1307
  var ORIGIN_PREFIX = /^origin\//;
1170
1308
  var ENV_FILE = /^\.env(?:\..+)?$/;
@@ -1320,7 +1458,7 @@ async function sweepStale(root) {
1320
1458
  continue;
1321
1459
  const path = join6(tmpdir(), name);
1322
1460
  const stat = lstatSync(path, { throwIfNoEntry: false });
1323
- if (stat?.isDirectory() === true && stat.uid === process15.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
1461
+ if (stat?.isDirectory() === true && stat.uid === process16.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
1324
1462
  rmSync(path, { recursive: true, force: true });
1325
1463
  }
1326
1464
  await git2(["worktree", "prune"], root);
@@ -1338,7 +1476,8 @@ function shellCommand(given) {
1338
1476
  const [only] = given;
1339
1477
  return given.length === 1 && only !== undefined && WHITESPACE.test(only) ? ["sh", "-c", only] : given;
1340
1478
  }
1341
- async function runIn(dir, command, signals, capture = false) {
1479
+ var TIMEOUT_DRAIN_MS = 500;
1480
+ async function runIn(dir, command, signals, capture = false, timeoutMs) {
1342
1481
  if (signals.signal !== undefined)
1343
1482
  return { code: exitCodeOf(null, signals.signal), output: "", started: true };
1344
1483
  let child;
@@ -1349,10 +1488,16 @@ async function runIn(dir, command, signals, capture = false) {
1349
1488
  }
1350
1489
  signals.forward(child);
1351
1490
  const chunks = [];
1352
- if (capture)
1353
- await Promise.all([collect(child.stdout, chunks), collect(child.stderr, chunks)]);
1491
+ let timedOut = false;
1492
+ const timer = timeoutMs === undefined ? undefined : setTimeout(() => {
1493
+ timedOut = true;
1494
+ child.kill("SIGKILL");
1495
+ }, timeoutMs);
1496
+ const collected = capture ? Promise.all([collect(child.stdout, chunks), collect(child.stderr, chunks)]) : Promise.resolve([]);
1354
1497
  await child.exited;
1355
- return { code: exitCodeOf(child.exitCode, child.signalCode ?? null), output: Buffer.concat(chunks).toString(), started: true };
1498
+ clearTimeout(timer);
1499
+ await (timedOut ? Promise.race([collected, Bun.sleep(TIMEOUT_DRAIN_MS)]) : collected);
1500
+ return { code: exitCodeOf(child.exitCode, child.signalCode ?? null), output: Buffer.concat(chunks).toString(), started: true, ...timedOut ? { timedOut } : {} };
1356
1501
  }
1357
1502
  async function collect(stream, chunks) {
1358
1503
  for await (const chunk of stream)
@@ -1410,33 +1555,34 @@ ${USAGE}`);
1410
1555
  if (runsInContainer(given))
1411
1556
  fail("a container of the compose project mounts the main checkout, not the temporary worktree, so the command would not run at the ref: run the tool on the host, or check the ref out by hand");
1412
1557
  const command = shellCommand(given);
1413
- const cwd = process16.cwd();
1558
+ const cwd = process17.cwd();
1414
1559
  const { root, prefix } = await checkout(cwd);
1415
1560
  const ref = parsed.values.ref ?? "HEAD";
1416
1561
  const sha = await resolveRef(root, ref);
1417
1562
  const kept = keptPaths(root, cwd, parsed.values.keep ?? []);
1418
1563
  const ran = await inWorktree({ root, prefix, sha, ref, kept, link: parsed.values["no-link"] !== true }, async (runDir, signals) => runIn(runDir, command, signals));
1419
1564
  if (!ran.started)
1420
- console.error(`${role("problem", process16.stderr)("base:")} ${ran.output}`);
1421
- console.error(`${role("label", process16.stderr)("base:")} ran at ${ref} (${sha.slice(0, 7)}), exit ${ran.code}`);
1565
+ console.error(`${role("problem", process17.stderr)("base:")} ${ran.output}`);
1566
+ console.error(`${role("label", process17.stderr)("base:")} ran at ${ref} (${sha.slice(0, 7)}), exit ${ran.code}`);
1422
1567
  return ran.code;
1423
1568
  }
1424
1569
 
1425
1570
  // src/proof.ts
1426
- import process17 from "process";
1427
- var USAGE2 = `proof [--ref <rev>] [--runs <n>] [--keep <path>...] [--no-link] [--json] -- <command> [args...]: runs the command at HEAD or another ref in a temporary worktree, then in the working tree, to show that a test fails before a change and passes after it
1571
+ import process18 from "process";
1572
+ var USAGE2 = `proof [--ref <rev>] [--runs <n>] [--keep <path>...] [--timeout <duration>] [--no-link] [--json] -- <command> [args...]: runs the command at HEAD or another ref in a temporary worktree, then in the working tree, to show that a test fails before a change and passes after it
1428
1573
 
1429
- The ref defaults to the merge base with the default branch of origin (origin/main unless origin/HEAD names another) when HEAD is on a branch ahead of it, else HEAD. --runs <n> runs the command n times now, for a flaky test, and every run must pass.`;
1430
- var EXITS = [[0, "the command fails before and passes in every run now"], [1, "it passes before too, fails in any run now, or passes before and fails now"], [2, "a usage error, an unknown ref, a command that cannot start or ends with exit 126, 127 or a signal"], [130, "interrupted (128 plus the signal)"]];
1574
+ The ref defaults to the merge base with the default branch of origin (origin/main unless origin/HEAD names another) when HEAD is on a branch ahead of it, else HEAD. --runs <n> runs the command n times now, for a flaky test, and every run must pass. --timeout kills a run that lasts longer (a hung test), which says nothing about the change and ends with exit 2.`;
1575
+ var EXITS = [[0, "the command fails before and passes in every run now"], [1, "it passes before too, fails in any run now, or passes before and fails now"], [2, "a usage error, an unknown ref, a command that cannot start, ends with exit 126, 127, 125 or a signal, or runs past --timeout"], [130, "interrupted (128 plus the signal)"]];
1431
1576
  var OPTIONS2 = {
1432
1577
  ref: { type: "string", short: "r", description: "the commit to run before at (default: the merge base with the default branch of origin on a branch ahead of it, else HEAD)" },
1433
1578
  runs: { type: "string", short: "n", description: "run the command this many times now, every run must pass (1)" },
1434
1579
  keep: { type: "string", short: "k", multiple: true, description: "a working-tree file or folder copied over to the ref, such as the new test, repeatable" },
1580
+ timeout: { type: "string", short: "t", description: "kill each run lasting longer than this (30s, 5m, 1h), a result of neither side" },
1435
1581
  "no-link": { type: "boolean", description: "do not link the ignored env files, node_modules, vendor and .venv of the checkout" },
1436
1582
  json: jsonOption("{outcome, proved, ref, sha, before: {code, output}, now: {code, output}}")
1437
1583
  };
1438
1584
  function abnormal(code) {
1439
- return code === 126 || code === 127 || code > 128 && code < 160;
1585
+ return code === 125 || code === 126 || code === 127 || code > 128 && code < 160;
1440
1586
  }
1441
1587
  function outcomeOf(before, now) {
1442
1588
  const failed = now.filter((code) => code !== 0).length;
@@ -1473,19 +1619,20 @@ ${USAGE2}`);
1473
1619
  if (runsInContainer(given))
1474
1620
  fail("a container of the compose project mounts the main checkout, not the temporary worktree, so the command would not run at the ref: run the tool on the host, or check the ref out by hand");
1475
1621
  const command = shellCommand(given);
1476
- const cwd = process17.cwd();
1622
+ const cwd = process18.cwd();
1477
1623
  const { root, prefix } = await checkout(cwd);
1478
1624
  const runs = wholeNumber(parsed.values.runs, "runs", 1, 1);
1479
1625
  const ref = parsed.values.ref ?? await defaultProofRef(root);
1480
1626
  const sha = await resolveRef(root, ref);
1481
1627
  const kept = keptPaths(root, cwd, parsed.values.keep ?? []);
1628
+ const timeoutMs = parsed.values.timeout === undefined ? undefined : duration(parsed.values.timeout, "timeout", 0);
1482
1629
  const signals = holdSignals();
1483
1630
  let before;
1484
1631
  const nowRuns = [];
1485
1632
  try {
1486
- before = await inWorktree({ root, prefix, sha, ref, kept, link: parsed.values["no-link"] !== true, signals }, async (runDir, held) => runIn(runDir, command, held, true));
1633
+ before = await inWorktree({ root, prefix, sha, ref, kept, link: parsed.values["no-link"] !== true, signals }, async (runDir, held) => runIn(runDir, command, held, true, timeoutMs));
1487
1634
  for (let i = 0;i < runs && signals.signal === undefined; i++)
1488
- nowRuns.push(await runIn(cwd, command, signals, true));
1635
+ nowRuns.push(await runIn(cwd, command, signals, true, timeoutMs));
1489
1636
  } finally {
1490
1637
  signals.release();
1491
1638
  }
@@ -1494,6 +1641,10 @@ ${USAGE2}`);
1494
1641
  for (const [run, where] of [[before, `at ${sha.slice(0, 7)}`], ...nowRuns.map((each, i) => [each, runs > 1 ? `now (run ${i + 1})` : "now"])]) {
1495
1642
  if (!run.started)
1496
1643
  fail(run.output);
1644
+ if (run.timedOut === true)
1645
+ fail(`the command ran past --timeout ${parsed.values.timeout} ${where} and was killed, which says nothing about the change${run.output.trim() === "" ? "" : `
1646
+
1647
+ ${folded(run.output)}`}`);
1497
1648
  if (abnormal(run.code))
1498
1649
  fail(`the command did not run properly ${where}: exit ${run.code}, a missing command or a kill, not a test result${run.output.trim() === "" ? "" : `
1499
1650
 
@@ -1508,7 +1659,7 @@ ${folded(run.output)}`}`);
1508
1659
  printJson({ outcome, proved, ref, sha, before: { code: before.code, output: before.output }, now: { code: now.code, output: now.output }, runs: nowRuns.map((run) => ({ code: run.code })) });
1509
1660
  return proved ? 0 : 1;
1510
1661
  }
1511
- console.log(role(proved ? "ok" : "problem", process17.stdout)(message));
1662
+ console.log(role(proved ? "ok" : "problem", process18.stdout)(message));
1512
1663
  if (runs > 1)
1513
1664
  console.log(`now: ${codes.map((code, i) => `run ${i + 1} ${code === 0 ? "passed" : `failed (exit ${code})`}`).join(", ")}`);
1514
1665
  const shown = side === "before" ? before : now;
@@ -1519,7 +1670,7 @@ ${folded(shown.output)}`);
1519
1670
  }
1520
1671
 
1521
1672
  // src/cli.ts
1522
- process18.exitCode = await runCli({
1673
+ process19.exitCode = await runCli({
1523
1674
  name: "base",
1524
1675
  about: "runs a command at HEAD or another ref in a temporary worktree, the working tree untouched",
1525
1676
  replaces: "git stash, a test run, then git stash pop",
package/dist/proof-cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/proof-cli.ts
5
- import process17 from "process";
5
+ import process18 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process9 from "process";
8
8
  import { parseArgs } from "util";
@@ -321,6 +321,23 @@ var STATUS_WORDS = {
321
321
  var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
322
322
 
323
323
  // ../kit/src/format.ts
324
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
325
+ function formatSeconds(total) {
326
+ let rest = Math.max(0, Math.round(total));
327
+ const amounts = UNITS.map(([unit, size]) => {
328
+ const amount = Math.floor(rest / size);
329
+ rest -= amount * size;
330
+ return `${amount}${unit}`;
331
+ });
332
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
333
+ if (first === -1)
334
+ return "0s";
335
+ const next = amounts[first + 1];
336
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
337
+ }
338
+ function formatDuration(ms) {
339
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
340
+ }
324
341
  function upTo(text, separator) {
325
342
  const end = text.indexOf(separator);
326
343
  return end === -1 ? text : text.slice(0, end);
@@ -335,24 +352,20 @@ function printJson(value) {
335
352
 
336
353
  // ../kit/src/help.ts
337
354
  import process8 from "process";
338
- var OPTIONAL = /\[[^\]]+\]/g;
355
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
339
356
  var USAGE_PREFIX = /^usage:\s*/i;
340
357
  var FULL_STOP = /\.$/;
341
358
  function usageLine(usage, colors = paint(process8.stdout)) {
342
359
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
343
360
  }
344
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
345
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
361
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
362
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
346
363
  `);
347
364
  }
348
365
  function exitRows(exits, colors = paint(process8.stdout)) {
349
366
  if (exits.length === 0)
350
367
  return [];
351
- const width = Math.max(...exits.map(([code]) => String(code).length));
352
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
353
- }
354
- function replacesRows(replaces, colors = paint(process8.stdout)) {
355
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
368
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
356
369
  }
357
370
  function wantsHelpJson(env = process8.env) {
358
371
  return env.KIT_HELP === "json";
@@ -378,29 +391,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
378
391
  return [];
379
392
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
380
393
  }
394
+ var MAX_INLINE_CHOICES = 24;
381
395
  function optionRows(options, colors = paint(process8.stdout)) {
382
396
  const rows = Object.entries(options).map(([name, option]) => {
383
397
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
384
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
398
+ const choices = option.choices?.join("|");
399
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
400
+ const named = inline ? `<${choices}>` : "<value>";
385
401
  const placeholder = option.optional === undefined ? named : `[${named}]`;
386
402
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
387
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
403
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
404
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
388
405
  });
389
406
  const width = Math.max(0, ...rows.map((row) => row.width));
390
407
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
391
408
  }
392
409
 
393
410
  // ../kit/src/text.ts
394
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
395
411
  function distance(a, b) {
396
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
397
- for (const [i, left] of [...a].entries()) {
412
+ const left = [...a];
413
+ const right = [...b];
414
+ let before = [];
415
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
416
+ for (const [i, x] of left.entries()) {
398
417
  const current = [i + 1];
399
- for (const [j, right] of [...b].entries())
400
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
418
+ for (const [j, y] of right.entries()) {
419
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
420
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
421
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
422
+ current.push(cost);
423
+ }
424
+ before = previous;
401
425
  previous = current;
402
426
  }
403
- return previous[b.length] ?? 0;
427
+ return previous[right.length] ?? 0;
404
428
  }
405
429
  function closest(name, names) {
406
430
  const started = names.find((known) => known.startsWith(name));
@@ -419,6 +443,17 @@ function wholeNumber(value, name, fallback, min = 1) {
419
443
  badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
420
444
  return number;
421
445
  }
446
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
447
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
448
+ function duration(value, name, fallback, unit = "s") {
449
+ if (value === undefined)
450
+ return fallback;
451
+ const match = DURATION.exec(value.trim());
452
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
453
+ if (ms < 1)
454
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
455
+ return ms;
456
+ }
422
457
 
423
458
  // ../kit/src/args.ts
424
459
  var DASHES = /^-+/;
@@ -465,7 +500,7 @@ class Completing {
465
500
  }
466
501
  var completion = { active: false };
467
502
  var OUTPUT_OPTIONS = {
468
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
503
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
469
504
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
470
505
  };
471
506
  function applyOutput(color, plain, env = process9.env) {
@@ -791,13 +826,91 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
791
826
  // ../kit/src/cli.ts
792
827
  import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
793
828
  import { dirname as dirname3, join as join5 } from "path";
794
- import process13 from "process";
829
+ import process14 from "process";
830
+
831
+ // ../kit/src/completions.ts
832
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
833
+ 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'
834
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
835
+ set -l current (commandline -ct)
836
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
837
+ if test "$line" = __files__
838
+ __fish_complete_path $current
839
+ else
840
+ echo $line
841
+ end
842
+ end
843
+ end`;
844
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
845
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
846
+ local -a lines
847
+ COMPREPLY=()
848
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
849
+ for line in "\${lines[@]}"; do
850
+ if [[ $line == __files__ ]]; then
851
+ COMPREPLY+=($(compgen -f -- "$cur"))
852
+ else
853
+ words+="\${line%%$'\\t'*}"$'\\n'
854
+ fi
855
+ done
856
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
857
+ }`;
858
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
859
+ local line
860
+ local -a described plain
861
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
862
+ if [[ $line == __files__ ]]; then
863
+ _files
864
+ elif [[ $line == *$'\\t'* ]]; then
865
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
866
+ else
867
+ plain+=("$line")
868
+ fi
869
+ done
870
+ (( \${#described} )) && _describe -V value described
871
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
872
+ return 0
873
+ }`;
874
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
875
+ if (shell === "fish")
876
+ return `${header}
877
+ ${FISH_FUNCTION}
878
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
879
+ `).join("")}`;
880
+ if (shell === "bash")
881
+ return `${header}
882
+ ${BASH_FUNCTION}
883
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
884
+ `;
885
+ return `${header}
886
+ ${ZSH_FUNCTION}
887
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
888
+ `;
889
+ }
890
+
891
+ // ../kit/src/notify.ts
892
+ import process12 from "process";
893
+ var NOTIFY_AFTER_MS = 1e4;
894
+ var CANCELLED = 130;
895
+ function base64(text) {
896
+ return Buffer.from(text).toString("base64");
897
+ }
898
+ function notification(title, body, env = process12.env) {
899
+ const id = `kit${process12.pid}`;
900
+ 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\\`];
901
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
902
+ }
903
+ function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
904
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
905
+ return;
906
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
907
+ }
795
908
 
796
909
  // ../kit/src/usage.ts
797
910
  import { appendFileSync, mkdirSync } from "fs";
798
911
  import { homedir as homedir3 } from "os";
799
912
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
800
- import process12 from "process";
913
+ import process13 from "process";
801
914
 
802
915
  // ../kit/src/logs.ts
803
916
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -811,14 +924,14 @@ var usageError;
811
924
  function noteUsageError(message) {
812
925
  usageError = message;
813
926
  }
814
- function stateHome(env = process12.env) {
927
+ function stateHome(env = process13.env) {
815
928
  const dir = env.XDG_STATE_HOME;
816
929
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
817
930
  }
818
- function usagePath(env = process12.env) {
931
+ function usagePath(env = process13.env) {
819
932
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
820
933
  }
821
- function usageRecorded(env = process12.env) {
934
+ function usageRecorded(env = process13.env) {
822
935
  const off = env.KAYNOOO_CLI_NO_USAGE;
823
936
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
824
937
  }
@@ -832,7 +945,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
832
945
  usageError = undefined;
833
946
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
834
947
  }
835
- function recordUsage(entry, env = process12.env) {
948
+ function recordUsage(entry, env = process13.env) {
836
949
  if (!usageRecorded(env))
837
950
  return;
838
951
  try {
@@ -848,7 +961,11 @@ var LEVEL_OPTIONS = {
848
961
  ...OUTPUT_OPTIONS,
849
962
  help: { type: "boolean", short: "h", description: "show this help" }
850
963
  };
851
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
964
+ var TOP_OPTIONS = {
965
+ ...LEVEL_OPTIONS,
966
+ version: { type: "boolean", short: "v", description: "print the version" },
967
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
968
+ };
852
969
  async function commandRows(all, colors) {
853
970
  const commands = shown(all);
854
971
  const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
@@ -909,7 +1026,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
909
1026
  header(colors, summary),
910
1027
  "",
911
1028
  usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
912
- ...replacesRows(replaces, colors),
913
1029
  "",
914
1030
  ...await commandRows(commands, colors),
915
1031
  ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
@@ -923,8 +1039,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
923
1039
  `);
924
1040
  }
925
1041
  function printError(prefix, message, hint, cause) {
926
- const colors = paint(process13.stderr);
927
- const styled = takesControlCodes(process13.stderr);
1042
+ const colors = paint(process14.stderr);
1043
+ const styled = takesControlCodes(process14.stderr);
928
1044
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
929
1045
  const under = (label, text, tint) => text === undefined ? "" : `
930
1046
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -967,11 +1083,11 @@ async function dispatch(level, typed, { version, redact }) {
967
1083
  }
968
1084
  }
969
1085
  if (name === undefined && level.path.length > 1) {
970
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
1086
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
971
1087
  return 2;
972
1088
  }
973
1089
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
974
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
1090
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
975
1091
  return 0;
976
1092
  }
977
1093
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1082,6 +1198,19 @@ async function candidates(scope, defaultCommand, words, before = []) {
1082
1198
  }
1083
1199
  return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1084
1200
  }
1201
+ var COMPLETIONS = "--completions";
1202
+ function flagValue([flag = "", ...rest]) {
1203
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1204
+ }
1205
+ function printCompletionScript(name, args) {
1206
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1207
+ if (shell === undefined || args.length !== 1) {
1208
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1209
+ return 2;
1210
+ }
1211
+ console.log(completionScript(shell, [name]).trimEnd());
1212
+ return 0;
1213
+ }
1085
1214
  async function printCandidates(found) {
1086
1215
  for (const line of await found)
1087
1216
  console.log(line);
@@ -1106,10 +1235,15 @@ async function runCli(cli, argv = scriptArgs()) {
1106
1235
  const version = cli.version ?? packageVersion();
1107
1236
  if (argv[0] === COMPLETE)
1108
1237
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1238
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1239
+ return printCompletionScript(cli.name, flagValue(argv));
1240
+ const started = performance.now();
1109
1241
  const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
1242
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1243
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1110
1244
  if (cli.usage !== false) {
1111
1245
  try {
1112
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1246
+ recordUsage(usageEntry(cli.name, command, argv, code));
1113
1247
  } catch {}
1114
1248
  }
1115
1249
  return code;
@@ -1132,16 +1266,20 @@ function commandPath(scope, argv) {
1132
1266
  async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1133
1267
  if (argv[0] === COMPLETE)
1134
1268
  return printCandidates(leafCandidates(run, argv.slice(1)));
1269
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1270
+ return printCompletionScript(name, flagValue(argv));
1135
1271
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1136
1272
  console.log(version ?? packageVersion());
1137
1273
  return 0;
1138
1274
  }
1139
1275
  let code;
1276
+ const started = performance.now();
1140
1277
  try {
1141
1278
  code = await run(argv);
1142
1279
  } catch (error) {
1143
1280
  code = reportThrown(name, error, redact, wantsJson(argv));
1144
1281
  }
1282
+ notifyEnd(name, code, performance.now() - started);
1145
1283
  if (usage !== false) {
1146
1284
  try {
1147
1285
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1158,13 +1296,13 @@ var {Glob } = globalThis.Bun;
1158
1296
  var SESSION_FILES = new Glob("*.json");
1159
1297
  var ACCOUNT_DIRS = new Glob("*/sessions");
1160
1298
  // src/proof.ts
1161
- import process16 from "process";
1299
+ import process17 from "process";
1162
1300
 
1163
1301
  // src/worktree.ts
1164
1302
  import { cpSync, existsSync as existsSync3, lstatSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, realpathSync as realpathSync3, rmSync, symlinkSync, unlinkSync } from "fs";
1165
1303
  import { tmpdir } from "os";
1166
1304
  import { basename, dirname as dirname4, isAbsolute as isAbsolute2, join as join6, relative, resolve as resolve4, sep } from "path";
1167
- import process15 from "process";
1305
+ import process16 from "process";
1168
1306
  var WHITESPACE = /\s/;
1169
1307
  var ORIGIN_PREFIX = /^origin\//;
1170
1308
  var ENV_FILE = /^\.env(?:\..+)?$/;
@@ -1320,7 +1458,7 @@ async function sweepStale(root) {
1320
1458
  continue;
1321
1459
  const path = join6(tmpdir(), name);
1322
1460
  const stat = lstatSync(path, { throwIfNoEntry: false });
1323
- if (stat?.isDirectory() === true && stat.uid === process15.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
1461
+ if (stat?.isDirectory() === true && stat.uid === process16.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
1324
1462
  rmSync(path, { recursive: true, force: true });
1325
1463
  }
1326
1464
  await git2(["worktree", "prune"], root);
@@ -1338,7 +1476,8 @@ function shellCommand(given) {
1338
1476
  const [only] = given;
1339
1477
  return given.length === 1 && only !== undefined && WHITESPACE.test(only) ? ["sh", "-c", only] : given;
1340
1478
  }
1341
- async function runIn(dir, command, signals, capture = false) {
1479
+ var TIMEOUT_DRAIN_MS = 500;
1480
+ async function runIn(dir, command, signals, capture = false, timeoutMs) {
1342
1481
  if (signals.signal !== undefined)
1343
1482
  return { code: exitCodeOf(null, signals.signal), output: "", started: true };
1344
1483
  let child;
@@ -1349,10 +1488,16 @@ async function runIn(dir, command, signals, capture = false) {
1349
1488
  }
1350
1489
  signals.forward(child);
1351
1490
  const chunks = [];
1352
- if (capture)
1353
- await Promise.all([collect(child.stdout, chunks), collect(child.stderr, chunks)]);
1491
+ let timedOut = false;
1492
+ const timer = timeoutMs === undefined ? undefined : setTimeout(() => {
1493
+ timedOut = true;
1494
+ child.kill("SIGKILL");
1495
+ }, timeoutMs);
1496
+ const collected = capture ? Promise.all([collect(child.stdout, chunks), collect(child.stderr, chunks)]) : Promise.resolve([]);
1354
1497
  await child.exited;
1355
- return { code: exitCodeOf(child.exitCode, child.signalCode ?? null), output: Buffer.concat(chunks).toString(), started: true };
1498
+ clearTimeout(timer);
1499
+ await (timedOut ? Promise.race([collected, Bun.sleep(TIMEOUT_DRAIN_MS)]) : collected);
1500
+ return { code: exitCodeOf(child.exitCode, child.signalCode ?? null), output: Buffer.concat(chunks).toString(), started: true, ...timedOut ? { timedOut } : {} };
1356
1501
  }
1357
1502
  async function collect(stream, chunks) {
1358
1503
  for await (const chunk of stream)
@@ -1391,19 +1536,20 @@ async function inWorktree(options, body) {
1391
1536
  }
1392
1537
 
1393
1538
  // src/proof.ts
1394
- var USAGE = `proof [--ref <rev>] [--runs <n>] [--keep <path>...] [--no-link] [--json] -- <command> [args...]: runs the command at HEAD or another ref in a temporary worktree, then in the working tree, to show that a test fails before a change and passes after it
1539
+ var USAGE = `proof [--ref <rev>] [--runs <n>] [--keep <path>...] [--timeout <duration>] [--no-link] [--json] -- <command> [args...]: runs the command at HEAD or another ref in a temporary worktree, then in the working tree, to show that a test fails before a change and passes after it
1395
1540
 
1396
- The ref defaults to the merge base with the default branch of origin (origin/main unless origin/HEAD names another) when HEAD is on a branch ahead of it, else HEAD. --runs <n> runs the command n times now, for a flaky test, and every run must pass.`;
1397
- var EXITS = [[0, "the command fails before and passes in every run now"], [1, "it passes before too, fails in any run now, or passes before and fails now"], [2, "a usage error, an unknown ref, a command that cannot start or ends with exit 126, 127 or a signal"], [130, "interrupted (128 plus the signal)"]];
1541
+ The ref defaults to the merge base with the default branch of origin (origin/main unless origin/HEAD names another) when HEAD is on a branch ahead of it, else HEAD. --runs <n> runs the command n times now, for a flaky test, and every run must pass. --timeout kills a run that lasts longer (a hung test), which says nothing about the change and ends with exit 2.`;
1542
+ var EXITS = [[0, "the command fails before and passes in every run now"], [1, "it passes before too, fails in any run now, or passes before and fails now"], [2, "a usage error, an unknown ref, a command that cannot start, ends with exit 126, 127, 125 or a signal, or runs past --timeout"], [130, "interrupted (128 plus the signal)"]];
1398
1543
  var OPTIONS = {
1399
1544
  ref: { type: "string", short: "r", description: "the commit to run before at (default: the merge base with the default branch of origin on a branch ahead of it, else HEAD)" },
1400
1545
  runs: { type: "string", short: "n", description: "run the command this many times now, every run must pass (1)" },
1401
1546
  keep: { type: "string", short: "k", multiple: true, description: "a working-tree file or folder copied over to the ref, such as the new test, repeatable" },
1547
+ timeout: { type: "string", short: "t", description: "kill each run lasting longer than this (30s, 5m, 1h), a result of neither side" },
1402
1548
  "no-link": { type: "boolean", description: "do not link the ignored env files, node_modules, vendor and .venv of the checkout" },
1403
1549
  json: jsonOption("{outcome, proved, ref, sha, before: {code, output}, now: {code, output}}")
1404
1550
  };
1405
1551
  function abnormal(code) {
1406
- return code === 126 || code === 127 || code > 128 && code < 160;
1552
+ return code === 125 || code === 126 || code === 127 || code > 128 && code < 160;
1407
1553
  }
1408
1554
  function outcomeOf(before, now) {
1409
1555
  const failed = now.filter((code) => code !== 0).length;
@@ -1440,19 +1586,20 @@ ${USAGE}`);
1440
1586
  if (runsInContainer(given))
1441
1587
  fail("a container of the compose project mounts the main checkout, not the temporary worktree, so the command would not run at the ref: run the tool on the host, or check the ref out by hand");
1442
1588
  const command = shellCommand(given);
1443
- const cwd = process16.cwd();
1589
+ const cwd = process17.cwd();
1444
1590
  const { root, prefix } = await checkout(cwd);
1445
1591
  const runs = wholeNumber(parsed.values.runs, "runs", 1, 1);
1446
1592
  const ref = parsed.values.ref ?? await defaultProofRef(root);
1447
1593
  const sha = await resolveRef(root, ref);
1448
1594
  const kept = keptPaths(root, cwd, parsed.values.keep ?? []);
1595
+ const timeoutMs = parsed.values.timeout === undefined ? undefined : duration(parsed.values.timeout, "timeout", 0);
1449
1596
  const signals = holdSignals();
1450
1597
  let before;
1451
1598
  const nowRuns = [];
1452
1599
  try {
1453
- before = await inWorktree({ root, prefix, sha, ref, kept, link: parsed.values["no-link"] !== true, signals }, async (runDir, held) => runIn(runDir, command, held, true));
1600
+ before = await inWorktree({ root, prefix, sha, ref, kept, link: parsed.values["no-link"] !== true, signals }, async (runDir, held) => runIn(runDir, command, held, true, timeoutMs));
1454
1601
  for (let i = 0;i < runs && signals.signal === undefined; i++)
1455
- nowRuns.push(await runIn(cwd, command, signals, true));
1602
+ nowRuns.push(await runIn(cwd, command, signals, true, timeoutMs));
1456
1603
  } finally {
1457
1604
  signals.release();
1458
1605
  }
@@ -1461,6 +1608,10 @@ ${USAGE}`);
1461
1608
  for (const [run, where] of [[before, `at ${sha.slice(0, 7)}`], ...nowRuns.map((each, i) => [each, runs > 1 ? `now (run ${i + 1})` : "now"])]) {
1462
1609
  if (!run.started)
1463
1610
  fail(run.output);
1611
+ if (run.timedOut === true)
1612
+ fail(`the command ran past --timeout ${parsed.values.timeout} ${where} and was killed, which says nothing about the change${run.output.trim() === "" ? "" : `
1613
+
1614
+ ${folded(run.output)}`}`);
1464
1615
  if (abnormal(run.code))
1465
1616
  fail(`the command did not run properly ${where}: exit ${run.code}, a missing command or a kill, not a test result${run.output.trim() === "" ? "" : `
1466
1617
 
@@ -1475,7 +1626,7 @@ ${folded(run.output)}`}`);
1475
1626
  printJson({ outcome, proved, ref, sha, before: { code: before.code, output: before.output }, now: { code: now.code, output: now.output }, runs: nowRuns.map((run) => ({ code: run.code })) });
1476
1627
  return proved ? 0 : 1;
1477
1628
  }
1478
- console.log(role(proved ? "ok" : "problem", process16.stdout)(message));
1629
+ console.log(role(proved ? "ok" : "problem", process17.stdout)(message));
1479
1630
  if (runs > 1)
1480
1631
  console.log(`now: ${codes.map((code, i) => `run ${i + 1} ${code === 0 ? "passed" : `failed (exit ${code})`}`).join(", ")}`);
1481
1632
  const shown = side === "before" ? before : now;
@@ -1486,4 +1637,4 @@ ${folded(shown.output)}`);
1486
1637
  }
1487
1638
 
1488
1639
  // src/proof-cli.ts
1489
- process17.exitCode = await runMain({ name: "proof", run: proof });
1640
+ process18.exitCode = await runMain({ name: "proof", run: proof });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-base",
3
3
  "type": "module",
4
- "version": "0.10.0",
4
+ "version": "0.11.1",
5
5
  "description": "base: a command run at HEAD or another ref in a temporary worktree, the working tree left untouched.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -38,6 +38,6 @@
38
38
  "proof": "$npm_execpath src/proof-cli.ts"
39
39
  },
40
40
  "devDependencies": {
41
- "@kaynooo/cli-kit": "0.38.2"
41
+ "@kaynooo/cli-kit": "0.41.0"
42
42
  }
43
43
  }