@kaynooo/cli-base 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -26,7 +26,9 @@ base --keep tests/NewTest.php -- vendor/bin/phpunit tests/NewTest.php
26
26
  proof --keep tests/NewTest.php -- vendor/bin/phpunit tests/NewTest.php
27
27
  ```
28
28
 
29
- - `--ref`, `--keep`, `--no-link` and the single spaced argument through `sh -c` behave as in `base`.
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
+ - `--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
+ - `--keep`, `--no-link` and the single spaced argument through `sh -c` behave as in `base`.
30
32
  - 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.
31
- - `--json` prints `{outcome, proved, ref, sha, before: {code, output}, now: {code, output}}`, `outcome` being `proved`, `passes-before`, `fails-both` or `regressed`.
32
- - Exit codes: 0 fails before and passes now, 1 any other outcome, 2 a usage error, an unknown ref, a refused command or one that cannot start.
33
+ - `--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).
package/dist/cli.js CHANGED
@@ -2,14 +2,13 @@
2
2
  // @bun
3
3
 
4
4
  // src/cli.ts
5
- import process9 from "process";
6
-
5
+ import process10 from "process";
7
6
  // ../kit/src/args.ts
8
- import process3 from "process";
7
+ import process4 from "process";
9
8
  import { parseArgs } from "util";
10
9
 
11
10
  // ../kit/src/style.ts
12
- import process from "process";
11
+ import process2 from "process";
13
12
 
14
13
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
15
14
  function x(s) {
@@ -273,10 +272,10 @@ function le(i = {}) {
273
272
  var t = le();
274
273
 
275
274
  // ../kit/src/style.ts
276
- function takesControlCodes(stream, env = process.env) {
275
+ function takesControlCodes(stream, env = process2.env) {
277
276
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
278
277
  }
279
- function paint(stream, env = process.env) {
278
+ function paint(stream, env = process2.env) {
280
279
  return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
281
280
  }
282
281
  var STATUSES = {
@@ -299,24 +298,30 @@ function printJson(value) {
299
298
  }
300
299
 
301
300
  // ../kit/src/help.ts
302
- import process2 from "process";
301
+ import process3 from "process";
303
302
  var OPTIONAL = /\[[^\]]+\]/g;
304
303
  var USAGE_PREFIX = /^usage:\s*/i;
305
304
  var FULL_STOP = /\.$/;
306
- function usageLine(usage, colors = paint(process2.stdout)) {
305
+ function usageLine(usage, colors = paint(process3.stdout)) {
307
306
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
308
307
  }
309
- function helpText(usage, options, colors = paint(process2.stdout), { examples = [], replaces } = {}) {
310
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
308
+ function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces, exits = [] } = {}) {
309
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
311
310
  `);
312
311
  }
313
- function replacesRows(replaces, colors = paint(process2.stdout)) {
312
+ function exitRows(exits, colors = paint(process3.stdout)) {
313
+ if (exits.length === 0)
314
+ return [];
315
+ const width = Math.max(...exits.map(([code]) => String(code).length));
316
+ return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
317
+ }
318
+ function replacesRows(replaces, colors = paint(process3.stdout)) {
314
319
  return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
315
320
  }
316
- function wantsHelpJson(env = process2.env) {
321
+ function wantsHelpJson(env = process3.env) {
317
322
  return env.KIT_HELP === "json";
318
323
  }
319
- function description(usage, { examples = [], replaces } = {}) {
324
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
320
325
  const lines = usage.replace(USAGE_PREFIX, "").split(`
321
326
  `);
322
327
  const first = lines[0];
@@ -327,15 +332,17 @@ function description(usage, { examples = [], replaces } = {}) {
327
332
  synopsis: colon === -1 ? first : first.slice(0, colon),
328
333
  summary: colon === -1 ? fallback : first.slice(colon + 2),
329
334
  ...replaces === undefined ? {} : { replaces },
330
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
335
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
336
+ ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
337
+ ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
331
338
  };
332
339
  }
333
- function exampleRows(examples, colors = paint(process2.stdout)) {
340
+ function exampleRows(examples, colors = paint(process3.stdout)) {
334
341
  if (examples.length === 0)
335
342
  return [];
336
343
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
337
344
  }
338
- function optionRows(options, colors = paint(process2.stdout)) {
345
+ function optionRows(options, colors = paint(process3.stdout)) {
339
346
  const rows = Object.entries(options).map(([name, option]) => {
340
347
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
341
348
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -366,6 +373,16 @@ function closest(name, names) {
366
373
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
367
374
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
368
375
  }
376
+ // ../kit/src/input.ts
377
+ var WHOLE = /^\d+$/;
378
+ function wholeNumber(value, name, fallback, min = 1) {
379
+ if (value === undefined)
380
+ return fallback;
381
+ const number = Number(value);
382
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
383
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
384
+ return number;
385
+ }
369
386
 
370
387
  // ../kit/src/args.ts
371
388
  var DASHES = /^-+/;
@@ -416,7 +433,7 @@ var OUTPUT_OPTIONS = {
416
433
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
417
434
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
418
435
  };
419
- function applyOutput(color, plain, env = process3.env) {
436
+ function applyOutput(color, plain, env = process4.env) {
420
437
  const when = plain === true ? "never" : color ?? "auto";
421
438
  if (when === "auto")
422
439
  return;
@@ -439,7 +456,7 @@ function parse(args, usage, options, settings = {}) {
439
456
  const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
440
457
  let parsed;
441
458
  try {
442
- parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
459
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
443
460
  } catch (error) {
444
461
  const message = parseError(error);
445
462
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -447,7 +464,7 @@ function parse(args, usage, options, settings = {}) {
447
464
  const values = parsed.values;
448
465
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
449
466
  if (values.help === true) {
450
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
467
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
451
468
  throw new HelpShown;
452
469
  }
453
470
  checkChoices(parsed.values, all);
@@ -489,6 +506,18 @@ function listed(options, allowNegative) {
489
506
  return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
490
507
  }));
491
508
  }
509
+ function withAliases(args, options) {
510
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
511
+ if (named.size === 0)
512
+ return args;
513
+ const separator = args.indexOf("--");
514
+ const own = separator === -1 ? args : args.slice(0, separator);
515
+ return [...own.map((arg) => {
516
+ const at = arg.indexOf("=");
517
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
518
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
519
+ }), ...separator === -1 ? [] : args.slice(separator)];
520
+ }
492
521
  function withBare(args, options) {
493
522
  const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
494
523
  if (bare.size === 0)
@@ -575,7 +604,7 @@ function nearestOption(message, options, allowNegative) {
575
604
  }
576
605
  // ../kit/src/process.ts
577
606
  import { constants } from "os";
578
- import process4 from "process";
607
+ import process5 from "process";
579
608
  var KILL_GRACE_MS = 2000;
580
609
  var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
581
610
  function exitCodeOf(code, signal) {
@@ -597,7 +626,7 @@ function holdSignals(cleanup) {
597
626
  },
598
627
  release: () => {
599
628
  for (const signal of SIGNALS)
600
- process4.off(signal, onSignal);
629
+ process5.off(signal, onSignal);
601
630
  }
602
631
  };
603
632
  function onSignal(signal) {
@@ -610,10 +639,10 @@ function holdSignals(cleanup) {
610
639
  return;
611
640
  held.release();
612
641
  cleanup(signal);
613
- process4.kill(process4.pid, signal);
642
+ process5.kill(process5.pid, signal);
614
643
  }
615
644
  for (const signal of SIGNALS)
616
- process4.on(signal, onSignal);
645
+ process5.on(signal, onSignal);
617
646
  return held;
618
647
  }
619
648
  async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
@@ -627,7 +656,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
627
656
  return;
628
657
  try {
629
658
  if (grouped)
630
- process4.kill(-proc.pid, killing);
659
+ process5.kill(-proc.pid, killing);
631
660
  else
632
661
  proc.kill(killing);
633
662
  } catch {}
@@ -701,13 +730,15 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
701
730
  var RESET_STYLE = `${ESC}[0m`;
702
731
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
703
732
  // ../kit/src/cli.ts
704
- import process6 from "process";
733
+ import { readFileSync, realpathSync } from "fs";
734
+ import { dirname as dirname2, join as join2 } from "path";
735
+ import process7 from "process";
705
736
 
706
737
  // ../kit/src/usage.ts
707
738
  import { appendFileSync, mkdirSync } from "fs";
708
739
  import { homedir } from "os";
709
740
  import { dirname, isAbsolute, join } from "path";
710
- import process5 from "process";
741
+ import process6 from "process";
711
742
 
712
743
  // ../kit/src/logs.ts
713
744
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -721,14 +752,14 @@ var usageError;
721
752
  function noteUsageError(message) {
722
753
  usageError = message;
723
754
  }
724
- function stateHome(env = process5.env) {
755
+ function stateHome(env = process6.env) {
725
756
  const dir = env.XDG_STATE_HOME;
726
757
  return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
727
758
  }
728
- function usagePath(env = process5.env) {
759
+ function usagePath(env = process6.env) {
729
760
  return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
730
761
  }
731
- function usageRecorded(env = process5.env) {
762
+ function usageRecorded(env = process6.env) {
732
763
  const off = env.KAYNOOO_CLI_NO_USAGE;
733
764
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
734
765
  }
@@ -742,7 +773,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
742
773
  usageError = undefined;
743
774
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
744
775
  }
745
- function recordUsage(entry, env = process5.env) {
776
+ function recordUsage(entry, env = process6.env) {
746
777
  if (!usageRecorded(env))
747
778
  return;
748
779
  try {
@@ -760,8 +791,8 @@ var LEVEL_OPTIONS = {
760
791
  };
761
792
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
762
793
  function printError(prefix, message, hint, cause) {
763
- const colors = paint(process6.stderr);
764
- const styled = takesControlCodes(process6.stderr);
794
+ const colors = paint(process7.stderr);
795
+ const styled = takesControlCodes(process7.stderr);
765
796
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
766
797
  const under = (label, text, tint) => text === undefined ? "" : `
767
798
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -843,11 +874,22 @@ async function printCandidates(found) {
843
874
  console.log(line);
844
875
  return 0;
845
876
  }
846
- async function runMain({ name, version, run, redact, usage }, argv = process6.argv.slice(2)) {
877
+ function packageVersion(entry = Bun.main) {
878
+ for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
879
+ try {
880
+ const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
881
+ if (typeof version === "string")
882
+ return version;
883
+ } catch {}
884
+ if (dirname2(dir) === dir)
885
+ return "0.0.0";
886
+ }
887
+ }
888
+ async function runMain({ name, version, run, redact, usage }, argv = process7.argv.slice(2)) {
847
889
  if (argv[0] === COMPLETE)
848
890
  return printCandidates(leafCandidates(run, argv.slice(1)));
849
891
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
850
- console.log(version);
892
+ console.log(version ?? packageVersion());
851
893
  return 0;
852
894
  }
853
895
  let code;
@@ -856,8 +898,11 @@ async function runMain({ name, version, run, redact, usage }, argv = process6.ar
856
898
  } catch (error) {
857
899
  code = reportThrown(name, error, redact, wantsJson(argv));
858
900
  }
859
- if (usage !== false)
860
- recordUsage(usageEntry(name, undefined, argv, code));
901
+ if (usage !== false) {
902
+ try {
903
+ recordUsage(usageEntry(name, undefined, argv, code));
904
+ } catch {}
905
+ }
861
906
  return code;
862
907
  }
863
908
  // ../kit/src/secrets.ts
@@ -866,14 +911,11 @@ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "ses
866
911
  var {Glob } = globalThis.Bun;
867
912
  var SESSION_FILES = new Glob("*.json");
868
913
  var ACCOUNT_DIRS = new Glob("*/sessions");
869
- // package.json
870
- var version = "0.4.1";
871
-
872
914
  // src/worktree.ts
873
- import { cpSync, existsSync, lstatSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, realpathSync, rmSync, symlinkSync, unlinkSync } from "fs";
915
+ import { cpSync, existsSync, lstatSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, realpathSync as realpathSync2, rmSync, symlinkSync, unlinkSync } from "fs";
874
916
  import { tmpdir } from "os";
875
- import { basename, dirname as dirname2, isAbsolute as isAbsolute2, join as join2, relative, resolve, sep } from "path";
876
- import process8 from "process";
917
+ import { basename, dirname as dirname3, isAbsolute as isAbsolute2, join as join3, relative, resolve, sep } from "path";
918
+ import process9 from "process";
877
919
  var WHITESPACE = /\s/;
878
920
  var ENV_FILE = /^\.env(?:\..+)?$/;
879
921
  var DEPENDENCIES = new Set(["node_modules", "vendor", ".venv"]);
@@ -904,11 +946,21 @@ async function resolveRef(root, ref) {
904
946
  fail(`no commit ${ref} in this repository`);
905
947
  return stdoutOf(ran);
906
948
  }
949
+ async function defaultProofRef(root) {
950
+ const branch = await git2(["symbolic-ref", "--quiet", "--short", "HEAD"], root);
951
+ if (branch.code !== 0 || stdoutOf(branch) === "main")
952
+ return "HEAD";
953
+ const base = await git2(["merge-base", "HEAD", "origin/main"], root);
954
+ const head = await git2(["rev-parse", "HEAD"], root);
955
+ return base.code === 0 && stdoutOf(base) !== stdoutOf(head) ? stdoutOf(base) : "HEAD";
956
+ }
907
957
  function keptPaths(root, cwd, paths) {
908
- const realRoot = realpathSync(root);
958
+ const realRoot = realpathSync2(root);
909
959
  return paths.map((path) => {
910
960
  const absolute = resolve(cwd, path);
911
- const inRepo = relative(realRoot, join2(realpathSync(dirname2(absolute)), basename(absolute)));
961
+ if (!existsSync(dirname3(absolute)))
962
+ fail(`--keep ${path}: no such file`);
963
+ const inRepo = relative(realRoot, join3(realpathSync2(dirname3(absolute)), basename(absolute)));
912
964
  if (inRepo === "" || inRepo === ".." || inRepo.startsWith(PARENT) || isAbsolute2(inRepo))
913
965
  fail(`--keep ${path} is outside the repository`);
914
966
  if (!existsSync(absolute))
@@ -918,8 +970,8 @@ function keptPaths(root, cwd, paths) {
918
970
  }
919
971
  function checkNoSymlink(dir, path) {
920
972
  let current = dir;
921
- for (const part of dirname2(path).split(sep)) {
922
- current = join2(current, part);
973
+ for (const part of dirname3(path).split(sep)) {
974
+ current = join3(current, part);
923
975
  if (lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink() === true)
924
976
  fail(`--keep ${path} goes through the symlink ${relative(dir, current)} of the ref, which would write outside the worktree`);
925
977
  }
@@ -935,10 +987,10 @@ async function linkedEntries(root) {
935
987
  }).map((entry) => entry.replace(TRAILING_SLASH, ""));
936
988
  }
937
989
  async function addWorktree(root, sha) {
938
- const dir = join2(mkdtempSync(join2(tmpdir(), "base-")), basename(root));
990
+ const dir = join3(mkdtempSync(join3(tmpdir(), "base-")), basename(root));
939
991
  const ran = await git2(["worktree", "add", "--detach", dir, sha], root);
940
992
  if (ran.code !== 0) {
941
- rmSync(dirname2(dir), { recursive: true, force: true });
993
+ rmSync(dirname3(dir), { recursive: true, force: true });
942
994
  fail(`git worktree add failed:
943
995
  ${ran.text.trim()}`);
944
996
  }
@@ -947,41 +999,41 @@ ${ran.text.trim()}`);
947
999
  function copyKept(root, dir, paths) {
948
1000
  for (const path of paths) {
949
1001
  checkNoSymlink(dir, path);
950
- const target = join2(dir, path);
1002
+ const target = join3(dir, path);
951
1003
  rmSync(target, { recursive: true, force: true });
952
- mkdirSync2(dirname2(target), { recursive: true });
953
- cpSync(join2(root, path), target, { recursive: true });
1004
+ mkdirSync2(dirname3(target), { recursive: true });
1005
+ cpSync(join3(root, path), target, { recursive: true });
954
1006
  }
955
1007
  }
956
1008
  function linkEntries(root, dir, entries) {
957
1009
  const links = [];
958
1010
  for (const entry of entries) {
959
- const link = join2(dir, entry);
1011
+ const link = join3(dir, entry);
960
1012
  if (existsSync(link))
961
1013
  continue;
962
- mkdirSync2(dirname2(link), { recursive: true });
1014
+ mkdirSync2(dirname3(link), { recursive: true });
963
1015
  if (basename(entry) === "node_modules" && hasWorkspaceLinks(root, entry)) {
964
1016
  links.push(...linkModules(root, dir, entry));
965
1017
  continue;
966
1018
  }
967
- symlinkSync(join2(root, entry), link);
1019
+ symlinkSync(join3(root, entry), link);
968
1020
  links.push(link);
969
1021
  }
970
1022
  return links;
971
1023
  }
972
1024
  function moduleLinks(root, folder) {
973
1025
  const found = [];
974
- for (const entry of readdirSync(join2(root, folder), { withFileTypes: true })) {
1026
+ for (const entry of readdirSync(join3(root, folder), { withFileTypes: true })) {
975
1027
  if (entry.isSymbolicLink())
976
- found.push({ path: join2(folder, entry.name), name: entry.name });
1028
+ found.push({ path: join3(folder, entry.name), name: entry.name });
977
1029
  else if (entry.isDirectory() && entry.name.startsWith("@"))
978
- found.push(...moduleLinks(root, join2(folder, entry.name)));
1030
+ found.push(...moduleLinks(root, join3(folder, entry.name)));
979
1031
  }
980
1032
  return found;
981
1033
  }
982
1034
  function workspaceTarget(root, path) {
983
1035
  try {
984
- const inRepo = relative(realpathSync(root), realpathSync(join2(root, path)));
1036
+ const inRepo = relative(realpathSync2(root), realpathSync2(join3(root, path)));
985
1037
  return inRepo === "" || inRepo.startsWith(PARENT) || inRepo.split(sep).includes("node_modules") ? undefined : inRepo;
986
1038
  } catch {
987
1039
  return;
@@ -992,16 +1044,16 @@ function hasWorkspaceLinks(root, folder) {
992
1044
  }
993
1045
  function linkModules(root, dir, folder) {
994
1046
  const links = [];
995
- mkdirSync2(join2(dir, folder), { recursive: true });
996
- for (const entry of readdirSync(join2(root, folder), { withFileTypes: true })) {
997
- const path = join2(folder, entry.name);
998
- const link = join2(dir, path);
1047
+ mkdirSync2(join3(dir, folder), { recursive: true });
1048
+ for (const entry of readdirSync(join3(root, folder), { withFileTypes: true })) {
1049
+ const path = join3(folder, entry.name);
1050
+ const link = join3(dir, path);
999
1051
  if (entry.isDirectory() && entry.name.startsWith("@")) {
1000
1052
  links.push(...linkModules(root, dir, path));
1001
1053
  continue;
1002
1054
  }
1003
1055
  const workspace = entry.isSymbolicLink() ? workspaceTarget(root, path) : undefined;
1004
- symlinkSync(workspace === undefined ? join2(root, path) : join2(dir, workspace), link);
1056
+ symlinkSync(workspace === undefined ? join3(root, path) : join3(dir, workspace), link);
1005
1057
  links.push(link);
1006
1058
  }
1007
1059
  return links;
@@ -1011,9 +1063,9 @@ async function sweepStale(root) {
1011
1063
  for (const name of readdirSync(tmpdir())) {
1012
1064
  if (!BASE_DIR.test(name))
1013
1065
  continue;
1014
- const path = join2(tmpdir(), name);
1066
+ const path = join3(tmpdir(), name);
1015
1067
  const stat = lstatSync(path, { throwIfNoEntry: false });
1016
- if (stat?.isDirectory() === true && stat.uid === process8.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
1068
+ if (stat?.isDirectory() === true && stat.uid === process9.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
1017
1069
  rmSync(path, { recursive: true, force: true });
1018
1070
  }
1019
1071
  await git2(["worktree", "prune"], root);
@@ -1024,7 +1076,7 @@ async function removeWorktree(root, dir, links) {
1024
1076
  unlinkSync(link);
1025
1077
  }
1026
1078
  await git2(["worktree", "remove", "--force", dir], root);
1027
- rmSync(dirname2(dir), { recursive: true, force: true });
1079
+ rmSync(dirname3(dir), { recursive: true, force: true });
1028
1080
  await git2(["worktree", "prune"], root);
1029
1081
  }
1030
1082
  function shellCommand(given) {
@@ -1072,7 +1124,7 @@ async function inWorktree(options, body) {
1072
1124
  try {
1073
1125
  copyKept(root, dir, kept);
1074
1126
  links = link ? linkEntries(root, dir, await linkedEntries(root)) : [];
1075
- const runDir = join2(dir, prefix);
1127
+ const runDir = join3(dir, prefix);
1076
1128
  if (!existsSync(runDir))
1077
1129
  fail(`${prefix} does not exist at ${ref}`);
1078
1130
  return await body(runDir, signals);
@@ -1103,7 +1155,7 @@ ${USAGE}`);
1103
1155
  if (runsInContainer(given))
1104
1156
  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");
1105
1157
  const command = shellCommand(given);
1106
- const cwd = process9.cwd();
1158
+ const cwd = process10.cwd();
1107
1159
  const { root, prefix } = await checkout(cwd);
1108
1160
  const ref = parsed.values.ref ?? "HEAD";
1109
1161
  const sha = await resolveRef(root, ref);
@@ -1114,4 +1166,4 @@ ${USAGE}`);
1114
1166
  console.error(`base: ran at ${ref} (${sha.slice(0, 7)}), exit ${ran.code}`);
1115
1167
  return ran.code;
1116
1168
  }
1117
- process9.exitCode = await runMain({ name: "base", version, run: main });
1169
+ process10.exitCode = await runMain({ name: "base", run: main });
package/dist/proof.js CHANGED
@@ -2,14 +2,13 @@
2
2
  // @bun
3
3
 
4
4
  // src/proof.ts
5
- import process9 from "process";
6
-
5
+ import process10 from "process";
7
6
  // ../kit/src/args.ts
8
- import process3 from "process";
7
+ import process4 from "process";
9
8
  import { parseArgs } from "util";
10
9
 
11
10
  // ../kit/src/style.ts
12
- import process from "process";
11
+ import process2 from "process";
13
12
 
14
13
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
15
14
  function x(s) {
@@ -273,10 +272,10 @@ function le(i = {}) {
273
272
  var t = le();
274
273
 
275
274
  // ../kit/src/style.ts
276
- function takesControlCodes(stream, env = process.env) {
275
+ function takesControlCodes(stream, env = process2.env) {
277
276
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
278
277
  }
279
- function paint(stream, env = process.env) {
278
+ function paint(stream, env = process2.env) {
280
279
  return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
281
280
  }
282
281
  var STATUSES = {
@@ -299,24 +298,30 @@ function printJson(value) {
299
298
  }
300
299
 
301
300
  // ../kit/src/help.ts
302
- import process2 from "process";
301
+ import process3 from "process";
303
302
  var OPTIONAL = /\[[^\]]+\]/g;
304
303
  var USAGE_PREFIX = /^usage:\s*/i;
305
304
  var FULL_STOP = /\.$/;
306
- function usageLine(usage, colors = paint(process2.stdout)) {
305
+ function usageLine(usage, colors = paint(process3.stdout)) {
307
306
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
308
307
  }
309
- function helpText(usage, options, colors = paint(process2.stdout), { examples = [], replaces } = {}) {
310
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
308
+ function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces, exits = [] } = {}) {
309
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
311
310
  `);
312
311
  }
313
- function replacesRows(replaces, colors = paint(process2.stdout)) {
312
+ function exitRows(exits, colors = paint(process3.stdout)) {
313
+ if (exits.length === 0)
314
+ return [];
315
+ const width = Math.max(...exits.map(([code]) => String(code).length));
316
+ return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
317
+ }
318
+ function replacesRows(replaces, colors = paint(process3.stdout)) {
314
319
  return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
315
320
  }
316
- function wantsHelpJson(env = process2.env) {
321
+ function wantsHelpJson(env = process3.env) {
317
322
  return env.KIT_HELP === "json";
318
323
  }
319
- function description(usage, { examples = [], replaces } = {}) {
324
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
320
325
  const lines = usage.replace(USAGE_PREFIX, "").split(`
321
326
  `);
322
327
  const first = lines[0];
@@ -327,15 +332,17 @@ function description(usage, { examples = [], replaces } = {}) {
327
332
  synopsis: colon === -1 ? first : first.slice(0, colon),
328
333
  summary: colon === -1 ? fallback : first.slice(colon + 2),
329
334
  ...replaces === undefined ? {} : { replaces },
330
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
335
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
336
+ ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
337
+ ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
331
338
  };
332
339
  }
333
- function exampleRows(examples, colors = paint(process2.stdout)) {
340
+ function exampleRows(examples, colors = paint(process3.stdout)) {
334
341
  if (examples.length === 0)
335
342
  return [];
336
343
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
337
344
  }
338
- function optionRows(options, colors = paint(process2.stdout)) {
345
+ function optionRows(options, colors = paint(process3.stdout)) {
339
346
  const rows = Object.entries(options).map(([name, option]) => {
340
347
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
341
348
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -366,6 +373,16 @@ function closest(name, names) {
366
373
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
367
374
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
368
375
  }
376
+ // ../kit/src/input.ts
377
+ var WHOLE = /^\d+$/;
378
+ function wholeNumber(value, name, fallback, min = 1) {
379
+ if (value === undefined)
380
+ return fallback;
381
+ const number = Number(value);
382
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
383
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
384
+ return number;
385
+ }
369
386
 
370
387
  // ../kit/src/args.ts
371
388
  var DASHES = /^-+/;
@@ -416,7 +433,7 @@ var OUTPUT_OPTIONS = {
416
433
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
417
434
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
418
435
  };
419
- function applyOutput(color, plain, env = process3.env) {
436
+ function applyOutput(color, plain, env = process4.env) {
420
437
  const when = plain === true ? "never" : color ?? "auto";
421
438
  if (when === "auto")
422
439
  return;
@@ -439,7 +456,7 @@ function parse(args, usage, options, settings = {}) {
439
456
  const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
440
457
  let parsed;
441
458
  try {
442
- parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
459
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
443
460
  } catch (error) {
444
461
  const message = parseError(error);
445
462
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -447,7 +464,7 @@ function parse(args, usage, options, settings = {}) {
447
464
  const values = parsed.values;
448
465
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
449
466
  if (values.help === true) {
450
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
467
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
451
468
  throw new HelpShown;
452
469
  }
453
470
  checkChoices(parsed.values, all);
@@ -489,6 +506,18 @@ function listed(options, allowNegative) {
489
506
  return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
490
507
  }));
491
508
  }
509
+ function withAliases(args, options) {
510
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
511
+ if (named.size === 0)
512
+ return args;
513
+ const separator = args.indexOf("--");
514
+ const own = separator === -1 ? args : args.slice(0, separator);
515
+ return [...own.map((arg) => {
516
+ const at = arg.indexOf("=");
517
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
518
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
519
+ }), ...separator === -1 ? [] : args.slice(separator)];
520
+ }
492
521
  function withBare(args, options) {
493
522
  const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
494
523
  if (bare.size === 0)
@@ -575,7 +604,7 @@ function nearestOption(message, options, allowNegative) {
575
604
  }
576
605
  // ../kit/src/process.ts
577
606
  import { constants } from "os";
578
- import process4 from "process";
607
+ import process5 from "process";
579
608
  var KILL_GRACE_MS = 2000;
580
609
  var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
581
610
  function exitCodeOf(code, signal) {
@@ -597,7 +626,7 @@ function holdSignals(cleanup) {
597
626
  },
598
627
  release: () => {
599
628
  for (const signal of SIGNALS)
600
- process4.off(signal, onSignal);
629
+ process5.off(signal, onSignal);
601
630
  }
602
631
  };
603
632
  function onSignal(signal) {
@@ -610,10 +639,10 @@ function holdSignals(cleanup) {
610
639
  return;
611
640
  held.release();
612
641
  cleanup(signal);
613
- process4.kill(process4.pid, signal);
642
+ process5.kill(process5.pid, signal);
614
643
  }
615
644
  for (const signal of SIGNALS)
616
- process4.on(signal, onSignal);
645
+ process5.on(signal, onSignal);
617
646
  return held;
618
647
  }
619
648
  async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
@@ -627,7 +656,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
627
656
  return;
628
657
  try {
629
658
  if (grouped)
630
- process4.kill(-proc.pid, killing);
659
+ process5.kill(-proc.pid, killing);
631
660
  else
632
661
  proc.kill(killing);
633
662
  } catch {}
@@ -701,13 +730,15 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
701
730
  var RESET_STYLE = `${ESC}[0m`;
702
731
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
703
732
  // ../kit/src/cli.ts
704
- import process6 from "process";
733
+ import { readFileSync, realpathSync } from "fs";
734
+ import { dirname as dirname2, join as join2 } from "path";
735
+ import process7 from "process";
705
736
 
706
737
  // ../kit/src/usage.ts
707
738
  import { appendFileSync, mkdirSync } from "fs";
708
739
  import { homedir } from "os";
709
740
  import { dirname, isAbsolute, join } from "path";
710
- import process5 from "process";
741
+ import process6 from "process";
711
742
 
712
743
  // ../kit/src/logs.ts
713
744
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -721,14 +752,14 @@ var usageError;
721
752
  function noteUsageError(message) {
722
753
  usageError = message;
723
754
  }
724
- function stateHome(env = process5.env) {
755
+ function stateHome(env = process6.env) {
725
756
  const dir = env.XDG_STATE_HOME;
726
757
  return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
727
758
  }
728
- function usagePath(env = process5.env) {
759
+ function usagePath(env = process6.env) {
729
760
  return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
730
761
  }
731
- function usageRecorded(env = process5.env) {
762
+ function usageRecorded(env = process6.env) {
732
763
  const off = env.KAYNOOO_CLI_NO_USAGE;
733
764
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
734
765
  }
@@ -742,7 +773,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
742
773
  usageError = undefined;
743
774
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
744
775
  }
745
- function recordUsage(entry, env = process5.env) {
776
+ function recordUsage(entry, env = process6.env) {
746
777
  if (!usageRecorded(env))
747
778
  return;
748
779
  try {
@@ -760,8 +791,8 @@ var LEVEL_OPTIONS = {
760
791
  };
761
792
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
762
793
  function printError(prefix, message, hint, cause) {
763
- const colors = paint(process6.stderr);
764
- const styled = takesControlCodes(process6.stderr);
794
+ const colors = paint(process7.stderr);
795
+ const styled = takesControlCodes(process7.stderr);
765
796
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
766
797
  const under = (label, text, tint) => text === undefined ? "" : `
767
798
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -843,11 +874,22 @@ async function printCandidates(found) {
843
874
  console.log(line);
844
875
  return 0;
845
876
  }
846
- async function runMain({ name, version, run, redact, usage }, argv = process6.argv.slice(2)) {
877
+ function packageVersion(entry = Bun.main) {
878
+ for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
879
+ try {
880
+ const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
881
+ if (typeof version === "string")
882
+ return version;
883
+ } catch {}
884
+ if (dirname2(dir) === dir)
885
+ return "0.0.0";
886
+ }
887
+ }
888
+ async function runMain({ name, version, run, redact, usage }, argv = process7.argv.slice(2)) {
847
889
  if (argv[0] === COMPLETE)
848
890
  return printCandidates(leafCandidates(run, argv.slice(1)));
849
891
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
850
- console.log(version);
892
+ console.log(version ?? packageVersion());
851
893
  return 0;
852
894
  }
853
895
  let code;
@@ -856,8 +898,11 @@ async function runMain({ name, version, run, redact, usage }, argv = process6.ar
856
898
  } catch (error) {
857
899
  code = reportThrown(name, error, redact, wantsJson(argv));
858
900
  }
859
- if (usage !== false)
860
- recordUsage(usageEntry(name, undefined, argv, code));
901
+ if (usage !== false) {
902
+ try {
903
+ recordUsage(usageEntry(name, undefined, argv, code));
904
+ } catch {}
905
+ }
861
906
  return code;
862
907
  }
863
908
  // ../kit/src/secrets.ts
@@ -866,14 +911,11 @@ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "ses
866
911
  var {Glob } = globalThis.Bun;
867
912
  var SESSION_FILES = new Glob("*.json");
868
913
  var ACCOUNT_DIRS = new Glob("*/sessions");
869
- // package.json
870
- var version = "0.4.1";
871
-
872
914
  // src/worktree.ts
873
- import { cpSync, existsSync, lstatSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, realpathSync, rmSync, symlinkSync, unlinkSync } from "fs";
915
+ import { cpSync, existsSync, lstatSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, realpathSync as realpathSync2, rmSync, symlinkSync, unlinkSync } from "fs";
874
916
  import { tmpdir } from "os";
875
- import { basename, dirname as dirname2, isAbsolute as isAbsolute2, join as join2, relative, resolve, sep } from "path";
876
- import process8 from "process";
917
+ import { basename, dirname as dirname3, isAbsolute as isAbsolute2, join as join3, relative, resolve, sep } from "path";
918
+ import process9 from "process";
877
919
  var WHITESPACE = /\s/;
878
920
  var ENV_FILE = /^\.env(?:\..+)?$/;
879
921
  var DEPENDENCIES = new Set(["node_modules", "vendor", ".venv"]);
@@ -904,11 +946,21 @@ async function resolveRef(root, ref) {
904
946
  fail(`no commit ${ref} in this repository`);
905
947
  return stdoutOf(ran);
906
948
  }
949
+ async function defaultProofRef(root) {
950
+ const branch = await git2(["symbolic-ref", "--quiet", "--short", "HEAD"], root);
951
+ if (branch.code !== 0 || stdoutOf(branch) === "main")
952
+ return "HEAD";
953
+ const base = await git2(["merge-base", "HEAD", "origin/main"], root);
954
+ const head = await git2(["rev-parse", "HEAD"], root);
955
+ return base.code === 0 && stdoutOf(base) !== stdoutOf(head) ? stdoutOf(base) : "HEAD";
956
+ }
907
957
  function keptPaths(root, cwd, paths) {
908
- const realRoot = realpathSync(root);
958
+ const realRoot = realpathSync2(root);
909
959
  return paths.map((path) => {
910
960
  const absolute = resolve(cwd, path);
911
- const inRepo = relative(realRoot, join2(realpathSync(dirname2(absolute)), basename(absolute)));
961
+ if (!existsSync(dirname3(absolute)))
962
+ fail(`--keep ${path}: no such file`);
963
+ const inRepo = relative(realRoot, join3(realpathSync2(dirname3(absolute)), basename(absolute)));
912
964
  if (inRepo === "" || inRepo === ".." || inRepo.startsWith(PARENT) || isAbsolute2(inRepo))
913
965
  fail(`--keep ${path} is outside the repository`);
914
966
  if (!existsSync(absolute))
@@ -918,8 +970,8 @@ function keptPaths(root, cwd, paths) {
918
970
  }
919
971
  function checkNoSymlink(dir, path) {
920
972
  let current = dir;
921
- for (const part of dirname2(path).split(sep)) {
922
- current = join2(current, part);
973
+ for (const part of dirname3(path).split(sep)) {
974
+ current = join3(current, part);
923
975
  if (lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink() === true)
924
976
  fail(`--keep ${path} goes through the symlink ${relative(dir, current)} of the ref, which would write outside the worktree`);
925
977
  }
@@ -935,10 +987,10 @@ async function linkedEntries(root) {
935
987
  }).map((entry) => entry.replace(TRAILING_SLASH, ""));
936
988
  }
937
989
  async function addWorktree(root, sha) {
938
- const dir = join2(mkdtempSync(join2(tmpdir(), "base-")), basename(root));
990
+ const dir = join3(mkdtempSync(join3(tmpdir(), "base-")), basename(root));
939
991
  const ran = await git2(["worktree", "add", "--detach", dir, sha], root);
940
992
  if (ran.code !== 0) {
941
- rmSync(dirname2(dir), { recursive: true, force: true });
993
+ rmSync(dirname3(dir), { recursive: true, force: true });
942
994
  fail(`git worktree add failed:
943
995
  ${ran.text.trim()}`);
944
996
  }
@@ -947,41 +999,41 @@ ${ran.text.trim()}`);
947
999
  function copyKept(root, dir, paths) {
948
1000
  for (const path of paths) {
949
1001
  checkNoSymlink(dir, path);
950
- const target = join2(dir, path);
1002
+ const target = join3(dir, path);
951
1003
  rmSync(target, { recursive: true, force: true });
952
- mkdirSync2(dirname2(target), { recursive: true });
953
- cpSync(join2(root, path), target, { recursive: true });
1004
+ mkdirSync2(dirname3(target), { recursive: true });
1005
+ cpSync(join3(root, path), target, { recursive: true });
954
1006
  }
955
1007
  }
956
1008
  function linkEntries(root, dir, entries) {
957
1009
  const links = [];
958
1010
  for (const entry of entries) {
959
- const link = join2(dir, entry);
1011
+ const link = join3(dir, entry);
960
1012
  if (existsSync(link))
961
1013
  continue;
962
- mkdirSync2(dirname2(link), { recursive: true });
1014
+ mkdirSync2(dirname3(link), { recursive: true });
963
1015
  if (basename(entry) === "node_modules" && hasWorkspaceLinks(root, entry)) {
964
1016
  links.push(...linkModules(root, dir, entry));
965
1017
  continue;
966
1018
  }
967
- symlinkSync(join2(root, entry), link);
1019
+ symlinkSync(join3(root, entry), link);
968
1020
  links.push(link);
969
1021
  }
970
1022
  return links;
971
1023
  }
972
1024
  function moduleLinks(root, folder) {
973
1025
  const found = [];
974
- for (const entry of readdirSync(join2(root, folder), { withFileTypes: true })) {
1026
+ for (const entry of readdirSync(join3(root, folder), { withFileTypes: true })) {
975
1027
  if (entry.isSymbolicLink())
976
- found.push({ path: join2(folder, entry.name), name: entry.name });
1028
+ found.push({ path: join3(folder, entry.name), name: entry.name });
977
1029
  else if (entry.isDirectory() && entry.name.startsWith("@"))
978
- found.push(...moduleLinks(root, join2(folder, entry.name)));
1030
+ found.push(...moduleLinks(root, join3(folder, entry.name)));
979
1031
  }
980
1032
  return found;
981
1033
  }
982
1034
  function workspaceTarget(root, path) {
983
1035
  try {
984
- const inRepo = relative(realpathSync(root), realpathSync(join2(root, path)));
1036
+ const inRepo = relative(realpathSync2(root), realpathSync2(join3(root, path)));
985
1037
  return inRepo === "" || inRepo.startsWith(PARENT) || inRepo.split(sep).includes("node_modules") ? undefined : inRepo;
986
1038
  } catch {
987
1039
  return;
@@ -992,16 +1044,16 @@ function hasWorkspaceLinks(root, folder) {
992
1044
  }
993
1045
  function linkModules(root, dir, folder) {
994
1046
  const links = [];
995
- mkdirSync2(join2(dir, folder), { recursive: true });
996
- for (const entry of readdirSync(join2(root, folder), { withFileTypes: true })) {
997
- const path = join2(folder, entry.name);
998
- const link = join2(dir, path);
1047
+ mkdirSync2(join3(dir, folder), { recursive: true });
1048
+ for (const entry of readdirSync(join3(root, folder), { withFileTypes: true })) {
1049
+ const path = join3(folder, entry.name);
1050
+ const link = join3(dir, path);
999
1051
  if (entry.isDirectory() && entry.name.startsWith("@")) {
1000
1052
  links.push(...linkModules(root, dir, path));
1001
1053
  continue;
1002
1054
  }
1003
1055
  const workspace = entry.isSymbolicLink() ? workspaceTarget(root, path) : undefined;
1004
- symlinkSync(workspace === undefined ? join2(root, path) : join2(dir, workspace), link);
1056
+ symlinkSync(workspace === undefined ? join3(root, path) : join3(dir, workspace), link);
1005
1057
  links.push(link);
1006
1058
  }
1007
1059
  return links;
@@ -1011,9 +1063,9 @@ async function sweepStale(root) {
1011
1063
  for (const name of readdirSync(tmpdir())) {
1012
1064
  if (!BASE_DIR.test(name))
1013
1065
  continue;
1014
- const path = join2(tmpdir(), name);
1066
+ const path = join3(tmpdir(), name);
1015
1067
  const stat = lstatSync(path, { throwIfNoEntry: false });
1016
- if (stat?.isDirectory() === true && stat.uid === process8.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
1068
+ if (stat?.isDirectory() === true && stat.uid === process9.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
1017
1069
  rmSync(path, { recursive: true, force: true });
1018
1070
  }
1019
1071
  await git2(["worktree", "prune"], root);
@@ -1024,7 +1076,7 @@ async function removeWorktree(root, dir, links) {
1024
1076
  unlinkSync(link);
1025
1077
  }
1026
1078
  await git2(["worktree", "remove", "--force", dir], root);
1027
- rmSync(dirname2(dir), { recursive: true, force: true });
1079
+ rmSync(dirname3(dir), { recursive: true, force: true });
1028
1080
  await git2(["worktree", "prune"], root);
1029
1081
  }
1030
1082
  function shellCommand(given) {
@@ -1072,7 +1124,7 @@ async function inWorktree(options, body) {
1072
1124
  try {
1073
1125
  copyKept(root, dir, kept);
1074
1126
  links = link ? linkEntries(root, dir, await linkedEntries(root)) : [];
1075
- const runDir = join2(dir, prefix);
1127
+ const runDir = join3(dir, prefix);
1076
1128
  if (!existsSync(runDir))
1077
1129
  fail(`${prefix} does not exist at ${ref}`);
1078
1130
  return await body(runDir, signals);
@@ -1084,11 +1136,13 @@ async function inWorktree(options, body) {
1084
1136
  }
1085
1137
 
1086
1138
  // src/proof.ts
1087
- var USAGE = `proof [--ref <rev>] [--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
1139
+ 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
1088
1140
 
1089
- Exits 0 when the command fails before and passes now, 1 when it passes before too, fails now too, or passes before and fails now, 2 on a usage error, an unknown ref, a command that cannot start or ends with exit 126, 127 or a signal, or 128 plus the signal when interrupted.`;
1141
+ The ref defaults to the merge base with origin/main 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.`;
1142
+ 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)"]];
1090
1143
  var OPTIONS = {
1091
- ref: { type: "string", short: "r", description: "the commit to run before at (default HEAD)" },
1144
+ ref: { type: "string", short: "r", description: "the commit to run before at (default: the merge base with origin/main on a branch ahead of it, else HEAD)" },
1145
+ runs: { type: "string", short: "n", description: "run the command this many times now, every run must pass (1)" },
1092
1146
  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" },
1093
1147
  "no-link": { type: "boolean", description: "do not link the ignored env files, node_modules, vendor and .venv of the checkout" },
1094
1148
  json: jsonOption("{outcome, proved, ref, sha, before: {code, output}, now: {code, output}}")
@@ -1097,27 +1151,32 @@ function abnormal(code) {
1097
1151
  return code === 126 || code === 127 || code > 128 && code < 160;
1098
1152
  }
1099
1153
  function outcomeOf(before, now) {
1100
- if (before !== 0 && now === 0)
1154
+ const failed = now.filter((code) => code !== 0).length;
1155
+ if (before !== 0 && failed === 0)
1101
1156
  return "proved";
1102
- if (before === 0 && now === 0)
1157
+ if (before === 0 && failed === 0)
1103
1158
  return "passes-before";
1104
- return before !== 0 ? "fails-both" : "regressed";
1159
+ if (before !== 0)
1160
+ return failed < now.length ? "flaky" : "fails-both";
1161
+ return "regressed";
1105
1162
  }
1106
- function describe(outcome, at) {
1163
+ function describe(outcome, at, now) {
1107
1164
  switch (outcome) {
1108
1165
  case "proved":
1109
- return { message: `fails at ${at}, passes now`, side: "before" };
1166
+ return { message: now.length > 1 ? `fails at ${at}, passes now in ${now.length} of ${now.length} runs` : `fails at ${at}, passes now`, side: "before" };
1110
1167
  case "passes-before":
1111
1168
  return { message: `passes at ${at} too: it does not fail without the change`, side: "before" };
1112
1169
  case "fails-both":
1113
1170
  return { message: `fails at ${at} and fails now too`, side: "now" };
1114
1171
  case "regressed":
1115
1172
  return { message: `passes at ${at}, fails now`, side: "now" };
1173
+ case "flaky":
1174
+ return { message: `fails at ${at}, but ${now.filter((code) => code !== 0).length} of ${now.length} runs fail now`, side: "now" };
1116
1175
  }
1117
1176
  }
1118
1177
  async function main(argv) {
1119
1178
  const bare = argv[0] !== undefined && !argv[0].startsWith("-");
1120
- const parsed = parse(bare ? [] : argv, USAGE, OPTIONS, { rest: true, replaces: "running a test, stashing the change and running it again", examples: [["proof --keep tests/fix.test.ts -- bun test tests/fix.test.ts", "the new test fails at HEAD and passes now"], ["proof --ref v1.2.0 --keep tests/fix.test.ts -- bun test tests/fix.test.ts", "the same against a release"]] });
1179
+ const parsed = parse(bare ? [] : argv, USAGE, OPTIONS, { rest: true, exits: EXITS, replaces: "running a test, stashing the change and running it again", examples: [["proof --keep tests/fix.test.ts -- bun test tests/fix.test.ts", "the new test fails at HEAD and passes now"], ["proof --ref v1.2.0 --keep tests/fix.test.ts -- bun test tests/fix.test.ts", "the same against a release"]] });
1121
1180
  const given = bare ? argv : parsed.rest ?? [];
1122
1181
  if (given.length === 0 || parsed.positionals.length > 0)
1123
1182
  fail(`give the command after --
@@ -1126,24 +1185,25 @@ ${USAGE}`);
1126
1185
  if (runsInContainer(given))
1127
1186
  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");
1128
1187
  const command = shellCommand(given);
1129
- const cwd = process9.cwd();
1188
+ const cwd = process10.cwd();
1130
1189
  const { root, prefix } = await checkout(cwd);
1131
- const ref = parsed.values.ref ?? "HEAD";
1190
+ const runs = wholeNumber(parsed.values.runs, "runs", 1, 1);
1191
+ const ref = parsed.values.ref ?? await defaultProofRef(root);
1132
1192
  const sha = await resolveRef(root, ref);
1133
1193
  const kept = keptPaths(root, cwd, parsed.values.keep ?? []);
1134
1194
  const signals = holdSignals();
1135
1195
  let before;
1136
- let now;
1196
+ const nowRuns = [];
1137
1197
  try {
1138
1198
  before = await inWorktree({ root, prefix, sha, ref, kept, link: parsed.values["no-link"] !== true, signals }, async (runDir, held) => runIn(runDir, command, held, true));
1139
- if (signals.signal === undefined)
1140
- now = await runIn(cwd, command, signals, true);
1199
+ for (let i = 0;i < runs && signals.signal === undefined; i++)
1200
+ nowRuns.push(await runIn(cwd, command, signals, true));
1141
1201
  } finally {
1142
1202
  signals.release();
1143
1203
  }
1144
- if (signals.signal !== undefined || now === undefined)
1204
+ if (signals.signal !== undefined || nowRuns.length < runs)
1145
1205
  return exitCodeOf(null, signals.signal ?? null);
1146
- for (const [run, where] of [[before, `at ${sha.slice(0, 7)}`], [now, "now"]]) {
1206
+ for (const [run, where] of [[before, `at ${sha.slice(0, 7)}`], ...nowRuns.map((each, i) => [each, runs > 1 ? `now (run ${i + 1})` : "now"])]) {
1147
1207
  if (!run.started)
1148
1208
  fail(run.output);
1149
1209
  if (abnormal(run.code))
@@ -1151,18 +1211,22 @@ ${USAGE}`);
1151
1211
 
1152
1212
  ${folded(run.output)}`}`);
1153
1213
  }
1154
- const outcome = outcomeOf(before.code, now.code);
1155
- const { message, side } = describe(outcome, sha.slice(0, 7));
1214
+ const codes = nowRuns.map((run) => run.code);
1215
+ const now = nowRuns.find((run) => run.code !== 0) ?? nowRuns.at(-1) ?? before;
1216
+ const outcome = outcomeOf(before.code, codes);
1217
+ const { message, side } = describe(outcome, sha.slice(0, 7), codes);
1156
1218
  const proved = outcome === "proved";
1157
1219
  if (parsed.values.json === true) {
1158
- printJson({ outcome, proved, ref, sha, before: { code: before.code, output: before.output }, now: { code: now.code, output: now.output } });
1220
+ 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 })) });
1159
1221
  return proved ? 0 : 1;
1160
1222
  }
1161
1223
  console.log(message);
1224
+ if (runs > 1)
1225
+ console.log(`now: ${codes.map((code, i) => `run ${i + 1} ${code === 0 ? "passed" : `failed (exit ${code})`}`).join(", ")}`);
1162
1226
  const shown = side === "before" ? before : now;
1163
1227
  if (shown.code !== 0 && shown.output.trim() !== "")
1164
1228
  console.log(`
1165
1229
  ${folded(shown.output)}`);
1166
1230
  return proved ? 0 : 1;
1167
1231
  }
1168
- process9.exitCode = await runMain({ name: "proof", version, run: main });
1232
+ process10.exitCode = await runMain({ name: "proof", run: main });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-base",
3
3
  "type": "module",
4
- "version": "0.4.1",
4
+ "version": "0.5.0",
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",