@kaynooo/cli-base 0.9.0 → 0.11.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 +2 -1
- package/dist/cli.js +171 -73
- package/dist/proof-cli.js +167 -69
- package/package.json +2 -2
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
|
|
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 =
|
|
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 = [],
|
|
345
|
-
return [usageLine(usage, colors),
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
397
|
-
|
|
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,
|
|
400
|
-
|
|
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[
|
|
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 = /^-+/;
|
|
@@ -637,9 +672,33 @@ function nearestOption(message, options, allowNegative) {
|
|
|
637
672
|
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
638
673
|
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
639
674
|
}
|
|
675
|
+
// ../kit/src/argv.ts
|
|
676
|
+
import { readFileSync as readFileSync2, realpathSync } from "fs";
|
|
677
|
+
import { resolve as resolve3 } from "path";
|
|
678
|
+
import process10 from "process";
|
|
679
|
+
function commandLine() {
|
|
680
|
+
try {
|
|
681
|
+
return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
|
|
682
|
+
} catch {
|
|
683
|
+
return;
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
function realPath(word) {
|
|
687
|
+
try {
|
|
688
|
+
return realpathSync(resolve3(word));
|
|
689
|
+
} catch {
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
|
|
694
|
+
const target = script === undefined ? undefined : realPath(script) ?? script;
|
|
695
|
+
const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
|
|
696
|
+
const after = at === -1 ? [] : cmdline.slice(at + 1);
|
|
697
|
+
return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
|
|
698
|
+
}
|
|
640
699
|
// ../kit/src/process.ts
|
|
641
700
|
import { constants } from "os";
|
|
642
|
-
import
|
|
701
|
+
import process11 from "process";
|
|
643
702
|
var KILL_GRACE_MS = 2000;
|
|
644
703
|
var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
645
704
|
function exitCodeOf(code, signal) {
|
|
@@ -661,7 +720,7 @@ function holdSignals(cleanup) {
|
|
|
661
720
|
},
|
|
662
721
|
release: () => {
|
|
663
722
|
for (const signal of SIGNALS)
|
|
664
|
-
|
|
723
|
+
process11.off(signal, onSignal);
|
|
665
724
|
}
|
|
666
725
|
};
|
|
667
726
|
function onSignal(signal) {
|
|
@@ -674,10 +733,10 @@ function holdSignals(cleanup) {
|
|
|
674
733
|
return;
|
|
675
734
|
held.release();
|
|
676
735
|
cleanup(signal);
|
|
677
|
-
|
|
736
|
+
process11.kill(process11.pid, signal);
|
|
678
737
|
}
|
|
679
738
|
for (const signal of SIGNALS)
|
|
680
|
-
|
|
739
|
+
process11.on(signal, onSignal);
|
|
681
740
|
return held;
|
|
682
741
|
}
|
|
683
742
|
async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
|
|
@@ -691,7 +750,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
|
|
|
691
750
|
return;
|
|
692
751
|
try {
|
|
693
752
|
if (grouped)
|
|
694
|
-
|
|
753
|
+
process11.kill(-proc.pid, killing);
|
|
695
754
|
else
|
|
696
755
|
proc.kill(killing);
|
|
697
756
|
} catch {}
|
|
@@ -765,15 +824,33 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
|
|
|
765
824
|
var RESET_STYLE = `${ESC}[0m`;
|
|
766
825
|
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
767
826
|
// ../kit/src/cli.ts
|
|
768
|
-
import { readFileSync as
|
|
827
|
+
import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
|
|
769
828
|
import { dirname as dirname3, join as join5 } from "path";
|
|
829
|
+
import process14 from "process";
|
|
830
|
+
|
|
831
|
+
// ../kit/src/notify.ts
|
|
770
832
|
import process12 from "process";
|
|
833
|
+
var NOTIFY_AFTER_MS = 1e4;
|
|
834
|
+
var CANCELLED = 130;
|
|
835
|
+
function base64(text) {
|
|
836
|
+
return Buffer.from(text).toString("base64");
|
|
837
|
+
}
|
|
838
|
+
function notification(title, body, env = process12.env) {
|
|
839
|
+
const id = `kit${process12.pid}`;
|
|
840
|
+
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\\`];
|
|
841
|
+
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
842
|
+
}
|
|
843
|
+
function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
|
|
844
|
+
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
845
|
+
return;
|
|
846
|
+
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
847
|
+
}
|
|
771
848
|
|
|
772
849
|
// ../kit/src/usage.ts
|
|
773
850
|
import { appendFileSync, mkdirSync } from "fs";
|
|
774
851
|
import { homedir as homedir3 } from "os";
|
|
775
852
|
import { dirname as dirname2, isAbsolute, join as join4 } from "path";
|
|
776
|
-
import
|
|
853
|
+
import process13 from "process";
|
|
777
854
|
|
|
778
855
|
// ../kit/src/logs.ts
|
|
779
856
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
@@ -787,14 +864,14 @@ var usageError;
|
|
|
787
864
|
function noteUsageError(message) {
|
|
788
865
|
usageError = message;
|
|
789
866
|
}
|
|
790
|
-
function stateHome(env =
|
|
867
|
+
function stateHome(env = process13.env) {
|
|
791
868
|
const dir = env.XDG_STATE_HOME;
|
|
792
869
|
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
793
870
|
}
|
|
794
|
-
function usagePath(env =
|
|
871
|
+
function usagePath(env = process13.env) {
|
|
795
872
|
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
796
873
|
}
|
|
797
|
-
function usageRecorded(env =
|
|
874
|
+
function usageRecorded(env = process13.env) {
|
|
798
875
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
799
876
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
800
877
|
}
|
|
@@ -808,7 +885,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
808
885
|
usageError = undefined;
|
|
809
886
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
810
887
|
}
|
|
811
|
-
function recordUsage(entry, env =
|
|
888
|
+
function recordUsage(entry, env = process13.env) {
|
|
812
889
|
if (!usageRecorded(env))
|
|
813
890
|
return;
|
|
814
891
|
try {
|
|
@@ -885,7 +962,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
|
|
|
885
962
|
header(colors, summary),
|
|
886
963
|
"",
|
|
887
964
|
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
888
|
-
...replacesRows(replaces, colors),
|
|
889
965
|
"",
|
|
890
966
|
...await commandRows(commands, colors),
|
|
891
967
|
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
@@ -899,8 +975,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
|
|
|
899
975
|
`);
|
|
900
976
|
}
|
|
901
977
|
function printError(prefix, message, hint, cause) {
|
|
902
|
-
const colors = paint(
|
|
903
|
-
const styled = takesControlCodes(
|
|
978
|
+
const colors = paint(process14.stderr);
|
|
979
|
+
const styled = takesControlCodes(process14.stderr);
|
|
904
980
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
905
981
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
906
982
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -943,11 +1019,11 @@ async function dispatch(level, typed, { version, redact }) {
|
|
|
943
1019
|
}
|
|
944
1020
|
}
|
|
945
1021
|
if (name === undefined && level.path.length > 1) {
|
|
946
|
-
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
1022
|
+
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
|
|
947
1023
|
return 2;
|
|
948
1024
|
}
|
|
949
1025
|
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
950
|
-
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
1026
|
+
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
|
|
951
1027
|
return 0;
|
|
952
1028
|
}
|
|
953
1029
|
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
@@ -1003,24 +1079,24 @@ function candidateLine(candidate) {
|
|
|
1003
1079
|
}
|
|
1004
1080
|
function positionalBeingTyped(before, { options, positionals }) {
|
|
1005
1081
|
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
1006
|
-
|
|
1082
|
+
const typed = [];
|
|
1007
1083
|
let at = 0;
|
|
1008
1084
|
while (at < before.length) {
|
|
1009
1085
|
const word = before[at];
|
|
1010
1086
|
if (word === "--") {
|
|
1011
|
-
|
|
1087
|
+
typed.push(...before.slice(at + 1));
|
|
1012
1088
|
break;
|
|
1013
1089
|
}
|
|
1014
1090
|
if (!word.startsWith("-"))
|
|
1015
|
-
|
|
1091
|
+
typed.push(word);
|
|
1016
1092
|
else if (takesValue(word))
|
|
1017
1093
|
at++;
|
|
1018
1094
|
at++;
|
|
1019
1095
|
}
|
|
1020
1096
|
const last = positionals.at(-1);
|
|
1021
|
-
if (
|
|
1022
|
-
return positionals[
|
|
1023
|
-
return last?.replace("]", "").endsWith("...") === true ? last : undefined;
|
|
1097
|
+
if (typed.length < positionals.length)
|
|
1098
|
+
return { name: positionals[typed.length], typed };
|
|
1099
|
+
return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
|
|
1024
1100
|
}
|
|
1025
1101
|
async function leafCandidates(run, words) {
|
|
1026
1102
|
const completing = await completingOf(run);
|
|
@@ -1028,12 +1104,12 @@ async function leafCandidates(run, words) {
|
|
|
1028
1104
|
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
1029
1105
|
const flag = words.at(-2);
|
|
1030
1106
|
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
1107
|
+
const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
|
|
1031
1108
|
if (option?.type === "string") {
|
|
1032
|
-
const values = option.choices === undefined ? await option.candidates?.() : option.choices;
|
|
1109
|
+
const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
|
|
1033
1110
|
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1034
1111
|
}
|
|
1035
|
-
const
|
|
1036
|
-
const values = name === undefined ? undefined : await completing.candidates[name]?.();
|
|
1112
|
+
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
1037
1113
|
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1038
1114
|
}
|
|
1039
1115
|
async function candidates(scope, defaultCommand, words, before = []) {
|
|
@@ -1064,9 +1140,13 @@ async function printCandidates(found) {
|
|
|
1064
1140
|
return 0;
|
|
1065
1141
|
}
|
|
1066
1142
|
function packageVersion(entry = Bun.main) {
|
|
1067
|
-
|
|
1143
|
+
let resolved = entry;
|
|
1144
|
+
try {
|
|
1145
|
+
resolved = realpathSync2(entry);
|
|
1146
|
+
} catch {}
|
|
1147
|
+
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
1068
1148
|
try {
|
|
1069
|
-
const { version } = JSON.parse(
|
|
1149
|
+
const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
|
|
1070
1150
|
if (typeof version === "string")
|
|
1071
1151
|
return version;
|
|
1072
1152
|
} catch {}
|
|
@@ -1074,14 +1154,17 @@ function packageVersion(entry = Bun.main) {
|
|
|
1074
1154
|
return "0.0.0";
|
|
1075
1155
|
}
|
|
1076
1156
|
}
|
|
1077
|
-
async function runCli(cli, argv =
|
|
1157
|
+
async function runCli(cli, argv = scriptArgs()) {
|
|
1078
1158
|
const version = cli.version ?? packageVersion();
|
|
1079
1159
|
if (argv[0] === COMPLETE)
|
|
1080
1160
|
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
1161
|
+
const started = performance.now();
|
|
1081
1162
|
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 });
|
|
1163
|
+
const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
|
|
1164
|
+
notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
|
|
1082
1165
|
if (cli.usage !== false) {
|
|
1083
1166
|
try {
|
|
1084
|
-
recordUsage(usageEntry(cli.name,
|
|
1167
|
+
recordUsage(usageEntry(cli.name, command, argv, code));
|
|
1085
1168
|
} catch {}
|
|
1086
1169
|
}
|
|
1087
1170
|
return code;
|
|
@@ -1101,7 +1184,7 @@ function commandPath(scope, argv) {
|
|
|
1101
1184
|
}
|
|
1102
1185
|
return path.length === 0 ? undefined : path.join(" ");
|
|
1103
1186
|
}
|
|
1104
|
-
async function runMain({ name, version, run, redact, usage }, argv =
|
|
1187
|
+
async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
|
|
1105
1188
|
if (argv[0] === COMPLETE)
|
|
1106
1189
|
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
1107
1190
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
@@ -1109,11 +1192,13 @@ async function runMain({ name, version, run, redact, usage }, argv = process12.a
|
|
|
1109
1192
|
return 0;
|
|
1110
1193
|
}
|
|
1111
1194
|
let code;
|
|
1195
|
+
const started = performance.now();
|
|
1112
1196
|
try {
|
|
1113
1197
|
code = await run(argv);
|
|
1114
1198
|
} catch (error) {
|
|
1115
1199
|
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
1116
1200
|
}
|
|
1201
|
+
notifyEnd(name, code, performance.now() - started);
|
|
1117
1202
|
if (usage !== false) {
|
|
1118
1203
|
try {
|
|
1119
1204
|
recordUsage(usageEntry(name, undefined, argv, code));
|
|
@@ -1130,13 +1215,13 @@ var {Glob } = globalThis.Bun;
|
|
|
1130
1215
|
var SESSION_FILES = new Glob("*.json");
|
|
1131
1216
|
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1132
1217
|
// src/base.ts
|
|
1133
|
-
import
|
|
1218
|
+
import process17 from "process";
|
|
1134
1219
|
|
|
1135
1220
|
// src/worktree.ts
|
|
1136
|
-
import { cpSync, existsSync as existsSync3, lstatSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, realpathSync as
|
|
1221
|
+
import { cpSync, existsSync as existsSync3, lstatSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, realpathSync as realpathSync3, rmSync, symlinkSync, unlinkSync } from "fs";
|
|
1137
1222
|
import { tmpdir } from "os";
|
|
1138
|
-
import { basename, dirname as dirname4, isAbsolute as isAbsolute2, join as join6, relative, resolve as
|
|
1139
|
-
import
|
|
1223
|
+
import { basename, dirname as dirname4, isAbsolute as isAbsolute2, join as join6, relative, resolve as resolve4, sep } from "path";
|
|
1224
|
+
import process16 from "process";
|
|
1140
1225
|
var WHITESPACE = /\s/;
|
|
1141
1226
|
var ORIGIN_PREFIX = /^origin\//;
|
|
1142
1227
|
var ENV_FILE = /^\.env(?:\..+)?$/;
|
|
@@ -1182,12 +1267,12 @@ async function defaultProofRef(root) {
|
|
|
1182
1267
|
return base.code === 0 && stdoutOf(base) !== stdoutOf(head) ? stdoutOf(base) : "HEAD";
|
|
1183
1268
|
}
|
|
1184
1269
|
function keptPaths(root, cwd, paths) {
|
|
1185
|
-
const realRoot =
|
|
1270
|
+
const realRoot = realpathSync3(root);
|
|
1186
1271
|
return paths.map((path) => {
|
|
1187
|
-
const absolute =
|
|
1272
|
+
const absolute = resolve4(cwd, path);
|
|
1188
1273
|
if (!existsSync3(dirname4(absolute)))
|
|
1189
1274
|
fail(`--keep ${path}: no such file`);
|
|
1190
|
-
const inRepo = relative(realRoot, join6(
|
|
1275
|
+
const inRepo = relative(realRoot, join6(realpathSync3(dirname4(absolute)), basename(absolute)));
|
|
1191
1276
|
if (inRepo === "" || inRepo === ".." || inRepo.startsWith(PARENT) || isAbsolute2(inRepo))
|
|
1192
1277
|
fail(`--keep ${path} is outside the repository`);
|
|
1193
1278
|
if (!existsSync3(absolute))
|
|
@@ -1260,7 +1345,7 @@ function moduleLinks(root, folder) {
|
|
|
1260
1345
|
}
|
|
1261
1346
|
function workspaceTarget(root, path) {
|
|
1262
1347
|
try {
|
|
1263
|
-
const inRepo = relative(
|
|
1348
|
+
const inRepo = relative(realpathSync3(root), realpathSync3(join6(root, path)));
|
|
1264
1349
|
return inRepo === "" || inRepo.startsWith(PARENT) || inRepo.split(sep).includes("node_modules") ? undefined : inRepo;
|
|
1265
1350
|
} catch {
|
|
1266
1351
|
return;
|
|
@@ -1292,7 +1377,7 @@ async function sweepStale(root) {
|
|
|
1292
1377
|
continue;
|
|
1293
1378
|
const path = join6(tmpdir(), name);
|
|
1294
1379
|
const stat = lstatSync(path, { throwIfNoEntry: false });
|
|
1295
|
-
if (stat?.isDirectory() === true && stat.uid ===
|
|
1380
|
+
if (stat?.isDirectory() === true && stat.uid === process16.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
|
|
1296
1381
|
rmSync(path, { recursive: true, force: true });
|
|
1297
1382
|
}
|
|
1298
1383
|
await git2(["worktree", "prune"], root);
|
|
@@ -1310,7 +1395,8 @@ function shellCommand(given) {
|
|
|
1310
1395
|
const [only] = given;
|
|
1311
1396
|
return given.length === 1 && only !== undefined && WHITESPACE.test(only) ? ["sh", "-c", only] : given;
|
|
1312
1397
|
}
|
|
1313
|
-
|
|
1398
|
+
var TIMEOUT_DRAIN_MS = 500;
|
|
1399
|
+
async function runIn(dir, command, signals, capture = false, timeoutMs) {
|
|
1314
1400
|
if (signals.signal !== undefined)
|
|
1315
1401
|
return { code: exitCodeOf(null, signals.signal), output: "", started: true };
|
|
1316
1402
|
let child;
|
|
@@ -1321,10 +1407,16 @@ async function runIn(dir, command, signals, capture = false) {
|
|
|
1321
1407
|
}
|
|
1322
1408
|
signals.forward(child);
|
|
1323
1409
|
const chunks = [];
|
|
1324
|
-
|
|
1325
|
-
|
|
1410
|
+
let timedOut = false;
|
|
1411
|
+
const timer = timeoutMs === undefined ? undefined : setTimeout(() => {
|
|
1412
|
+
timedOut = true;
|
|
1413
|
+
child.kill("SIGKILL");
|
|
1414
|
+
}, timeoutMs);
|
|
1415
|
+
const collected = capture ? Promise.all([collect(child.stdout, chunks), collect(child.stderr, chunks)]) : Promise.resolve([]);
|
|
1326
1416
|
await child.exited;
|
|
1327
|
-
|
|
1417
|
+
clearTimeout(timer);
|
|
1418
|
+
await (timedOut ? Promise.race([collected, Bun.sleep(TIMEOUT_DRAIN_MS)]) : collected);
|
|
1419
|
+
return { code: exitCodeOf(child.exitCode, child.signalCode ?? null), output: Buffer.concat(chunks).toString(), started: true, ...timedOut ? { timedOut } : {} };
|
|
1328
1420
|
}
|
|
1329
1421
|
async function collect(stream, chunks) {
|
|
1330
1422
|
for await (const chunk of stream)
|
|
@@ -1382,33 +1474,34 @@ ${USAGE}`);
|
|
|
1382
1474
|
if (runsInContainer(given))
|
|
1383
1475
|
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");
|
|
1384
1476
|
const command = shellCommand(given);
|
|
1385
|
-
const cwd =
|
|
1477
|
+
const cwd = process17.cwd();
|
|
1386
1478
|
const { root, prefix } = await checkout(cwd);
|
|
1387
1479
|
const ref = parsed.values.ref ?? "HEAD";
|
|
1388
1480
|
const sha = await resolveRef(root, ref);
|
|
1389
1481
|
const kept = keptPaths(root, cwd, parsed.values.keep ?? []);
|
|
1390
1482
|
const ran = await inWorktree({ root, prefix, sha, ref, kept, link: parsed.values["no-link"] !== true }, async (runDir, signals) => runIn(runDir, command, signals));
|
|
1391
1483
|
if (!ran.started)
|
|
1392
|
-
console.error(
|
|
1393
|
-
console.error(
|
|
1484
|
+
console.error(`${role("problem", process17.stderr)("base:")} ${ran.output}`);
|
|
1485
|
+
console.error(`${role("label", process17.stderr)("base:")} ran at ${ref} (${sha.slice(0, 7)}), exit ${ran.code}`);
|
|
1394
1486
|
return ran.code;
|
|
1395
1487
|
}
|
|
1396
1488
|
|
|
1397
1489
|
// src/proof.ts
|
|
1398
|
-
import
|
|
1399
|
-
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
|
|
1490
|
+
import process18 from "process";
|
|
1491
|
+
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
|
|
1400
1492
|
|
|
1401
|
-
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.`;
|
|
1402
|
-
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
|
|
1493
|
+
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.`;
|
|
1494
|
+
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)"]];
|
|
1403
1495
|
var OPTIONS2 = {
|
|
1404
1496
|
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)" },
|
|
1405
1497
|
runs: { type: "string", short: "n", description: "run the command this many times now, every run must pass (1)" },
|
|
1406
1498
|
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" },
|
|
1499
|
+
timeout: { type: "string", short: "t", description: "kill each run lasting longer than this (30s, 5m, 1h), a result of neither side" },
|
|
1407
1500
|
"no-link": { type: "boolean", description: "do not link the ignored env files, node_modules, vendor and .venv of the checkout" },
|
|
1408
1501
|
json: jsonOption("{outcome, proved, ref, sha, before: {code, output}, now: {code, output}}")
|
|
1409
1502
|
};
|
|
1410
1503
|
function abnormal(code) {
|
|
1411
|
-
return code === 126 || code === 127 || code > 128 && code < 160;
|
|
1504
|
+
return code === 125 || code === 126 || code === 127 || code > 128 && code < 160;
|
|
1412
1505
|
}
|
|
1413
1506
|
function outcomeOf(before, now) {
|
|
1414
1507
|
const failed = now.filter((code) => code !== 0).length;
|
|
@@ -1445,19 +1538,20 @@ ${USAGE2}`);
|
|
|
1445
1538
|
if (runsInContainer(given))
|
|
1446
1539
|
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");
|
|
1447
1540
|
const command = shellCommand(given);
|
|
1448
|
-
const cwd =
|
|
1541
|
+
const cwd = process18.cwd();
|
|
1449
1542
|
const { root, prefix } = await checkout(cwd);
|
|
1450
1543
|
const runs = wholeNumber(parsed.values.runs, "runs", 1, 1);
|
|
1451
1544
|
const ref = parsed.values.ref ?? await defaultProofRef(root);
|
|
1452
1545
|
const sha = await resolveRef(root, ref);
|
|
1453
1546
|
const kept = keptPaths(root, cwd, parsed.values.keep ?? []);
|
|
1547
|
+
const timeoutMs = parsed.values.timeout === undefined ? undefined : duration(parsed.values.timeout, "timeout", 0);
|
|
1454
1548
|
const signals = holdSignals();
|
|
1455
1549
|
let before;
|
|
1456
1550
|
const nowRuns = [];
|
|
1457
1551
|
try {
|
|
1458
|
-
before = await inWorktree({ root, prefix, sha, ref, kept, link: parsed.values["no-link"] !== true, signals }, async (runDir, held) => runIn(runDir, command, held, true));
|
|
1552
|
+
before = await inWorktree({ root, prefix, sha, ref, kept, link: parsed.values["no-link"] !== true, signals }, async (runDir, held) => runIn(runDir, command, held, true, timeoutMs));
|
|
1459
1553
|
for (let i = 0;i < runs && signals.signal === undefined; i++)
|
|
1460
|
-
nowRuns.push(await runIn(cwd, command, signals, true));
|
|
1554
|
+
nowRuns.push(await runIn(cwd, command, signals, true, timeoutMs));
|
|
1461
1555
|
} finally {
|
|
1462
1556
|
signals.release();
|
|
1463
1557
|
}
|
|
@@ -1466,6 +1560,10 @@ ${USAGE2}`);
|
|
|
1466
1560
|
for (const [run, where] of [[before, `at ${sha.slice(0, 7)}`], ...nowRuns.map((each, i) => [each, runs > 1 ? `now (run ${i + 1})` : "now"])]) {
|
|
1467
1561
|
if (!run.started)
|
|
1468
1562
|
fail(run.output);
|
|
1563
|
+
if (run.timedOut === true)
|
|
1564
|
+
fail(`the command ran past --timeout ${parsed.values.timeout} ${where} and was killed, which says nothing about the change${run.output.trim() === "" ? "" : `
|
|
1565
|
+
|
|
1566
|
+
${folded(run.output)}`}`);
|
|
1469
1567
|
if (abnormal(run.code))
|
|
1470
1568
|
fail(`the command did not run properly ${where}: exit ${run.code}, a missing command or a kill, not a test result${run.output.trim() === "" ? "" : `
|
|
1471
1569
|
|
|
@@ -1480,7 +1578,7 @@ ${folded(run.output)}`}`);
|
|
|
1480
1578
|
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 })) });
|
|
1481
1579
|
return proved ? 0 : 1;
|
|
1482
1580
|
}
|
|
1483
|
-
console.log(role(proved ? "ok" : "problem",
|
|
1581
|
+
console.log(role(proved ? "ok" : "problem", process18.stdout)(message));
|
|
1484
1582
|
if (runs > 1)
|
|
1485
1583
|
console.log(`now: ${codes.map((code, i) => `run ${i + 1} ${code === 0 ? "passed" : `failed (exit ${code})`}`).join(", ")}`);
|
|
1486
1584
|
const shown = side === "before" ? before : now;
|
|
@@ -1491,7 +1589,7 @@ ${folded(shown.output)}`);
|
|
|
1491
1589
|
}
|
|
1492
1590
|
|
|
1493
1591
|
// src/cli.ts
|
|
1494
|
-
|
|
1592
|
+
process19.exitCode = await runCli({
|
|
1495
1593
|
name: "base",
|
|
1496
1594
|
about: "runs a command at HEAD or another ref in a temporary worktree, the working tree untouched",
|
|
1497
1595
|
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
|
|
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 =
|
|
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 = [],
|
|
345
|
-
return [usageLine(usage, colors),
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
397
|
-
|
|
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,
|
|
400
|
-
|
|
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[
|
|
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 = /^-+/;
|
|
@@ -637,9 +672,33 @@ function nearestOption(message, options, allowNegative) {
|
|
|
637
672
|
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
638
673
|
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
639
674
|
}
|
|
675
|
+
// ../kit/src/argv.ts
|
|
676
|
+
import { readFileSync as readFileSync2, realpathSync } from "fs";
|
|
677
|
+
import { resolve as resolve3 } from "path";
|
|
678
|
+
import process10 from "process";
|
|
679
|
+
function commandLine() {
|
|
680
|
+
try {
|
|
681
|
+
return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
|
|
682
|
+
} catch {
|
|
683
|
+
return;
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
function realPath(word) {
|
|
687
|
+
try {
|
|
688
|
+
return realpathSync(resolve3(word));
|
|
689
|
+
} catch {
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
|
|
694
|
+
const target = script === undefined ? undefined : realPath(script) ?? script;
|
|
695
|
+
const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
|
|
696
|
+
const after = at === -1 ? [] : cmdline.slice(at + 1);
|
|
697
|
+
return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
|
|
698
|
+
}
|
|
640
699
|
// ../kit/src/process.ts
|
|
641
700
|
import { constants } from "os";
|
|
642
|
-
import
|
|
701
|
+
import process11 from "process";
|
|
643
702
|
var KILL_GRACE_MS = 2000;
|
|
644
703
|
var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
645
704
|
function exitCodeOf(code, signal) {
|
|
@@ -661,7 +720,7 @@ function holdSignals(cleanup) {
|
|
|
661
720
|
},
|
|
662
721
|
release: () => {
|
|
663
722
|
for (const signal of SIGNALS)
|
|
664
|
-
|
|
723
|
+
process11.off(signal, onSignal);
|
|
665
724
|
}
|
|
666
725
|
};
|
|
667
726
|
function onSignal(signal) {
|
|
@@ -674,10 +733,10 @@ function holdSignals(cleanup) {
|
|
|
674
733
|
return;
|
|
675
734
|
held.release();
|
|
676
735
|
cleanup(signal);
|
|
677
|
-
|
|
736
|
+
process11.kill(process11.pid, signal);
|
|
678
737
|
}
|
|
679
738
|
for (const signal of SIGNALS)
|
|
680
|
-
|
|
739
|
+
process11.on(signal, onSignal);
|
|
681
740
|
return held;
|
|
682
741
|
}
|
|
683
742
|
async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
|
|
@@ -691,7 +750,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
|
|
|
691
750
|
return;
|
|
692
751
|
try {
|
|
693
752
|
if (grouped)
|
|
694
|
-
|
|
753
|
+
process11.kill(-proc.pid, killing);
|
|
695
754
|
else
|
|
696
755
|
proc.kill(killing);
|
|
697
756
|
} catch {}
|
|
@@ -765,15 +824,33 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
|
|
|
765
824
|
var RESET_STYLE = `${ESC}[0m`;
|
|
766
825
|
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
767
826
|
// ../kit/src/cli.ts
|
|
768
|
-
import { readFileSync as
|
|
827
|
+
import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
|
|
769
828
|
import { dirname as dirname3, join as join5 } from "path";
|
|
829
|
+
import process14 from "process";
|
|
830
|
+
|
|
831
|
+
// ../kit/src/notify.ts
|
|
770
832
|
import process12 from "process";
|
|
833
|
+
var NOTIFY_AFTER_MS = 1e4;
|
|
834
|
+
var CANCELLED = 130;
|
|
835
|
+
function base64(text) {
|
|
836
|
+
return Buffer.from(text).toString("base64");
|
|
837
|
+
}
|
|
838
|
+
function notification(title, body, env = process12.env) {
|
|
839
|
+
const id = `kit${process12.pid}`;
|
|
840
|
+
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\\`];
|
|
841
|
+
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
842
|
+
}
|
|
843
|
+
function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
|
|
844
|
+
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
845
|
+
return;
|
|
846
|
+
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
847
|
+
}
|
|
771
848
|
|
|
772
849
|
// ../kit/src/usage.ts
|
|
773
850
|
import { appendFileSync, mkdirSync } from "fs";
|
|
774
851
|
import { homedir as homedir3 } from "os";
|
|
775
852
|
import { dirname as dirname2, isAbsolute, join as join4 } from "path";
|
|
776
|
-
import
|
|
853
|
+
import process13 from "process";
|
|
777
854
|
|
|
778
855
|
// ../kit/src/logs.ts
|
|
779
856
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
@@ -787,14 +864,14 @@ var usageError;
|
|
|
787
864
|
function noteUsageError(message) {
|
|
788
865
|
usageError = message;
|
|
789
866
|
}
|
|
790
|
-
function stateHome(env =
|
|
867
|
+
function stateHome(env = process13.env) {
|
|
791
868
|
const dir = env.XDG_STATE_HOME;
|
|
792
869
|
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
793
870
|
}
|
|
794
|
-
function usagePath(env =
|
|
871
|
+
function usagePath(env = process13.env) {
|
|
795
872
|
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
796
873
|
}
|
|
797
|
-
function usageRecorded(env =
|
|
874
|
+
function usageRecorded(env = process13.env) {
|
|
798
875
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
799
876
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
800
877
|
}
|
|
@@ -808,7 +885,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
808
885
|
usageError = undefined;
|
|
809
886
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
810
887
|
}
|
|
811
|
-
function recordUsage(entry, env =
|
|
888
|
+
function recordUsage(entry, env = process13.env) {
|
|
812
889
|
if (!usageRecorded(env))
|
|
813
890
|
return;
|
|
814
891
|
try {
|
|
@@ -885,7 +962,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
|
|
|
885
962
|
header(colors, summary),
|
|
886
963
|
"",
|
|
887
964
|
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
888
|
-
...replacesRows(replaces, colors),
|
|
889
965
|
"",
|
|
890
966
|
...await commandRows(commands, colors),
|
|
891
967
|
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
@@ -899,8 +975,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
|
|
|
899
975
|
`);
|
|
900
976
|
}
|
|
901
977
|
function printError(prefix, message, hint, cause) {
|
|
902
|
-
const colors = paint(
|
|
903
|
-
const styled = takesControlCodes(
|
|
978
|
+
const colors = paint(process14.stderr);
|
|
979
|
+
const styled = takesControlCodes(process14.stderr);
|
|
904
980
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
905
981
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
906
982
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -943,11 +1019,11 @@ async function dispatch(level, typed, { version, redact }) {
|
|
|
943
1019
|
}
|
|
944
1020
|
}
|
|
945
1021
|
if (name === undefined && level.path.length > 1) {
|
|
946
|
-
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
1022
|
+
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
|
|
947
1023
|
return 2;
|
|
948
1024
|
}
|
|
949
1025
|
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
950
|
-
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
1026
|
+
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
|
|
951
1027
|
return 0;
|
|
952
1028
|
}
|
|
953
1029
|
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
@@ -1003,24 +1079,24 @@ function candidateLine(candidate) {
|
|
|
1003
1079
|
}
|
|
1004
1080
|
function positionalBeingTyped(before, { options, positionals }) {
|
|
1005
1081
|
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
1006
|
-
|
|
1082
|
+
const typed = [];
|
|
1007
1083
|
let at = 0;
|
|
1008
1084
|
while (at < before.length) {
|
|
1009
1085
|
const word = before[at];
|
|
1010
1086
|
if (word === "--") {
|
|
1011
|
-
|
|
1087
|
+
typed.push(...before.slice(at + 1));
|
|
1012
1088
|
break;
|
|
1013
1089
|
}
|
|
1014
1090
|
if (!word.startsWith("-"))
|
|
1015
|
-
|
|
1091
|
+
typed.push(word);
|
|
1016
1092
|
else if (takesValue(word))
|
|
1017
1093
|
at++;
|
|
1018
1094
|
at++;
|
|
1019
1095
|
}
|
|
1020
1096
|
const last = positionals.at(-1);
|
|
1021
|
-
if (
|
|
1022
|
-
return positionals[
|
|
1023
|
-
return last?.replace("]", "").endsWith("...") === true ? last : undefined;
|
|
1097
|
+
if (typed.length < positionals.length)
|
|
1098
|
+
return { name: positionals[typed.length], typed };
|
|
1099
|
+
return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
|
|
1024
1100
|
}
|
|
1025
1101
|
async function leafCandidates(run, words) {
|
|
1026
1102
|
const completing = await completingOf(run);
|
|
@@ -1028,12 +1104,12 @@ async function leafCandidates(run, words) {
|
|
|
1028
1104
|
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
1029
1105
|
const flag = words.at(-2);
|
|
1030
1106
|
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
1107
|
+
const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
|
|
1031
1108
|
if (option?.type === "string") {
|
|
1032
|
-
const values = option.choices === undefined ? await option.candidates?.() : option.choices;
|
|
1109
|
+
const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
|
|
1033
1110
|
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1034
1111
|
}
|
|
1035
|
-
const
|
|
1036
|
-
const values = name === undefined ? undefined : await completing.candidates[name]?.();
|
|
1112
|
+
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
1037
1113
|
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1038
1114
|
}
|
|
1039
1115
|
async function candidates(scope, defaultCommand, words, before = []) {
|
|
@@ -1064,9 +1140,13 @@ async function printCandidates(found) {
|
|
|
1064
1140
|
return 0;
|
|
1065
1141
|
}
|
|
1066
1142
|
function packageVersion(entry = Bun.main) {
|
|
1067
|
-
|
|
1143
|
+
let resolved = entry;
|
|
1144
|
+
try {
|
|
1145
|
+
resolved = realpathSync2(entry);
|
|
1146
|
+
} catch {}
|
|
1147
|
+
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
1068
1148
|
try {
|
|
1069
|
-
const { version } = JSON.parse(
|
|
1149
|
+
const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
|
|
1070
1150
|
if (typeof version === "string")
|
|
1071
1151
|
return version;
|
|
1072
1152
|
} catch {}
|
|
@@ -1074,14 +1154,17 @@ function packageVersion(entry = Bun.main) {
|
|
|
1074
1154
|
return "0.0.0";
|
|
1075
1155
|
}
|
|
1076
1156
|
}
|
|
1077
|
-
async function runCli(cli, argv =
|
|
1157
|
+
async function runCli(cli, argv = scriptArgs()) {
|
|
1078
1158
|
const version = cli.version ?? packageVersion();
|
|
1079
1159
|
if (argv[0] === COMPLETE)
|
|
1080
1160
|
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
1161
|
+
const started = performance.now();
|
|
1081
1162
|
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 });
|
|
1163
|
+
const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
|
|
1164
|
+
notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
|
|
1082
1165
|
if (cli.usage !== false) {
|
|
1083
1166
|
try {
|
|
1084
|
-
recordUsage(usageEntry(cli.name,
|
|
1167
|
+
recordUsage(usageEntry(cli.name, command, argv, code));
|
|
1085
1168
|
} catch {}
|
|
1086
1169
|
}
|
|
1087
1170
|
return code;
|
|
@@ -1101,7 +1184,7 @@ function commandPath(scope, argv) {
|
|
|
1101
1184
|
}
|
|
1102
1185
|
return path.length === 0 ? undefined : path.join(" ");
|
|
1103
1186
|
}
|
|
1104
|
-
async function runMain({ name, version, run, redact, usage }, argv =
|
|
1187
|
+
async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
|
|
1105
1188
|
if (argv[0] === COMPLETE)
|
|
1106
1189
|
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
1107
1190
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
@@ -1109,11 +1192,13 @@ async function runMain({ name, version, run, redact, usage }, argv = process12.a
|
|
|
1109
1192
|
return 0;
|
|
1110
1193
|
}
|
|
1111
1194
|
let code;
|
|
1195
|
+
const started = performance.now();
|
|
1112
1196
|
try {
|
|
1113
1197
|
code = await run(argv);
|
|
1114
1198
|
} catch (error) {
|
|
1115
1199
|
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
1116
1200
|
}
|
|
1201
|
+
notifyEnd(name, code, performance.now() - started);
|
|
1117
1202
|
if (usage !== false) {
|
|
1118
1203
|
try {
|
|
1119
1204
|
recordUsage(usageEntry(name, undefined, argv, code));
|
|
@@ -1130,13 +1215,13 @@ var {Glob } = globalThis.Bun;
|
|
|
1130
1215
|
var SESSION_FILES = new Glob("*.json");
|
|
1131
1216
|
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1132
1217
|
// src/proof.ts
|
|
1133
|
-
import
|
|
1218
|
+
import process17 from "process";
|
|
1134
1219
|
|
|
1135
1220
|
// src/worktree.ts
|
|
1136
|
-
import { cpSync, existsSync as existsSync3, lstatSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, realpathSync as
|
|
1221
|
+
import { cpSync, existsSync as existsSync3, lstatSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, realpathSync as realpathSync3, rmSync, symlinkSync, unlinkSync } from "fs";
|
|
1137
1222
|
import { tmpdir } from "os";
|
|
1138
|
-
import { basename, dirname as dirname4, isAbsolute as isAbsolute2, join as join6, relative, resolve as
|
|
1139
|
-
import
|
|
1223
|
+
import { basename, dirname as dirname4, isAbsolute as isAbsolute2, join as join6, relative, resolve as resolve4, sep } from "path";
|
|
1224
|
+
import process16 from "process";
|
|
1140
1225
|
var WHITESPACE = /\s/;
|
|
1141
1226
|
var ORIGIN_PREFIX = /^origin\//;
|
|
1142
1227
|
var ENV_FILE = /^\.env(?:\..+)?$/;
|
|
@@ -1182,12 +1267,12 @@ async function defaultProofRef(root) {
|
|
|
1182
1267
|
return base.code === 0 && stdoutOf(base) !== stdoutOf(head) ? stdoutOf(base) : "HEAD";
|
|
1183
1268
|
}
|
|
1184
1269
|
function keptPaths(root, cwd, paths) {
|
|
1185
|
-
const realRoot =
|
|
1270
|
+
const realRoot = realpathSync3(root);
|
|
1186
1271
|
return paths.map((path) => {
|
|
1187
|
-
const absolute =
|
|
1272
|
+
const absolute = resolve4(cwd, path);
|
|
1188
1273
|
if (!existsSync3(dirname4(absolute)))
|
|
1189
1274
|
fail(`--keep ${path}: no such file`);
|
|
1190
|
-
const inRepo = relative(realRoot, join6(
|
|
1275
|
+
const inRepo = relative(realRoot, join6(realpathSync3(dirname4(absolute)), basename(absolute)));
|
|
1191
1276
|
if (inRepo === "" || inRepo === ".." || inRepo.startsWith(PARENT) || isAbsolute2(inRepo))
|
|
1192
1277
|
fail(`--keep ${path} is outside the repository`);
|
|
1193
1278
|
if (!existsSync3(absolute))
|
|
@@ -1260,7 +1345,7 @@ function moduleLinks(root, folder) {
|
|
|
1260
1345
|
}
|
|
1261
1346
|
function workspaceTarget(root, path) {
|
|
1262
1347
|
try {
|
|
1263
|
-
const inRepo = relative(
|
|
1348
|
+
const inRepo = relative(realpathSync3(root), realpathSync3(join6(root, path)));
|
|
1264
1349
|
return inRepo === "" || inRepo.startsWith(PARENT) || inRepo.split(sep).includes("node_modules") ? undefined : inRepo;
|
|
1265
1350
|
} catch {
|
|
1266
1351
|
return;
|
|
@@ -1292,7 +1377,7 @@ async function sweepStale(root) {
|
|
|
1292
1377
|
continue;
|
|
1293
1378
|
const path = join6(tmpdir(), name);
|
|
1294
1379
|
const stat = lstatSync(path, { throwIfNoEntry: false });
|
|
1295
|
-
if (stat?.isDirectory() === true && stat.uid ===
|
|
1380
|
+
if (stat?.isDirectory() === true && stat.uid === process16.getuid?.() && Date.now() - stat.mtimeMs > STALE_AFTER)
|
|
1296
1381
|
rmSync(path, { recursive: true, force: true });
|
|
1297
1382
|
}
|
|
1298
1383
|
await git2(["worktree", "prune"], root);
|
|
@@ -1310,7 +1395,8 @@ function shellCommand(given) {
|
|
|
1310
1395
|
const [only] = given;
|
|
1311
1396
|
return given.length === 1 && only !== undefined && WHITESPACE.test(only) ? ["sh", "-c", only] : given;
|
|
1312
1397
|
}
|
|
1313
|
-
|
|
1398
|
+
var TIMEOUT_DRAIN_MS = 500;
|
|
1399
|
+
async function runIn(dir, command, signals, capture = false, timeoutMs) {
|
|
1314
1400
|
if (signals.signal !== undefined)
|
|
1315
1401
|
return { code: exitCodeOf(null, signals.signal), output: "", started: true };
|
|
1316
1402
|
let child;
|
|
@@ -1321,10 +1407,16 @@ async function runIn(dir, command, signals, capture = false) {
|
|
|
1321
1407
|
}
|
|
1322
1408
|
signals.forward(child);
|
|
1323
1409
|
const chunks = [];
|
|
1324
|
-
|
|
1325
|
-
|
|
1410
|
+
let timedOut = false;
|
|
1411
|
+
const timer = timeoutMs === undefined ? undefined : setTimeout(() => {
|
|
1412
|
+
timedOut = true;
|
|
1413
|
+
child.kill("SIGKILL");
|
|
1414
|
+
}, timeoutMs);
|
|
1415
|
+
const collected = capture ? Promise.all([collect(child.stdout, chunks), collect(child.stderr, chunks)]) : Promise.resolve([]);
|
|
1326
1416
|
await child.exited;
|
|
1327
|
-
|
|
1417
|
+
clearTimeout(timer);
|
|
1418
|
+
await (timedOut ? Promise.race([collected, Bun.sleep(TIMEOUT_DRAIN_MS)]) : collected);
|
|
1419
|
+
return { code: exitCodeOf(child.exitCode, child.signalCode ?? null), output: Buffer.concat(chunks).toString(), started: true, ...timedOut ? { timedOut } : {} };
|
|
1328
1420
|
}
|
|
1329
1421
|
async function collect(stream, chunks) {
|
|
1330
1422
|
for await (const chunk of stream)
|
|
@@ -1363,19 +1455,20 @@ async function inWorktree(options, body) {
|
|
|
1363
1455
|
}
|
|
1364
1456
|
|
|
1365
1457
|
// src/proof.ts
|
|
1366
|
-
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
|
|
1458
|
+
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
|
|
1367
1459
|
|
|
1368
|
-
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.`;
|
|
1369
|
-
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
|
|
1460
|
+
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.`;
|
|
1461
|
+
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)"]];
|
|
1370
1462
|
var OPTIONS = {
|
|
1371
1463
|
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)" },
|
|
1372
1464
|
runs: { type: "string", short: "n", description: "run the command this many times now, every run must pass (1)" },
|
|
1373
1465
|
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" },
|
|
1466
|
+
timeout: { type: "string", short: "t", description: "kill each run lasting longer than this (30s, 5m, 1h), a result of neither side" },
|
|
1374
1467
|
"no-link": { type: "boolean", description: "do not link the ignored env files, node_modules, vendor and .venv of the checkout" },
|
|
1375
1468
|
json: jsonOption("{outcome, proved, ref, sha, before: {code, output}, now: {code, output}}")
|
|
1376
1469
|
};
|
|
1377
1470
|
function abnormal(code) {
|
|
1378
|
-
return code === 126 || code === 127 || code > 128 && code < 160;
|
|
1471
|
+
return code === 125 || code === 126 || code === 127 || code > 128 && code < 160;
|
|
1379
1472
|
}
|
|
1380
1473
|
function outcomeOf(before, now) {
|
|
1381
1474
|
const failed = now.filter((code) => code !== 0).length;
|
|
@@ -1412,19 +1505,20 @@ ${USAGE}`);
|
|
|
1412
1505
|
if (runsInContainer(given))
|
|
1413
1506
|
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");
|
|
1414
1507
|
const command = shellCommand(given);
|
|
1415
|
-
const cwd =
|
|
1508
|
+
const cwd = process17.cwd();
|
|
1416
1509
|
const { root, prefix } = await checkout(cwd);
|
|
1417
1510
|
const runs = wholeNumber(parsed.values.runs, "runs", 1, 1);
|
|
1418
1511
|
const ref = parsed.values.ref ?? await defaultProofRef(root);
|
|
1419
1512
|
const sha = await resolveRef(root, ref);
|
|
1420
1513
|
const kept = keptPaths(root, cwd, parsed.values.keep ?? []);
|
|
1514
|
+
const timeoutMs = parsed.values.timeout === undefined ? undefined : duration(parsed.values.timeout, "timeout", 0);
|
|
1421
1515
|
const signals = holdSignals();
|
|
1422
1516
|
let before;
|
|
1423
1517
|
const nowRuns = [];
|
|
1424
1518
|
try {
|
|
1425
|
-
before = await inWorktree({ root, prefix, sha, ref, kept, link: parsed.values["no-link"] !== true, signals }, async (runDir, held) => runIn(runDir, command, held, true));
|
|
1519
|
+
before = await inWorktree({ root, prefix, sha, ref, kept, link: parsed.values["no-link"] !== true, signals }, async (runDir, held) => runIn(runDir, command, held, true, timeoutMs));
|
|
1426
1520
|
for (let i = 0;i < runs && signals.signal === undefined; i++)
|
|
1427
|
-
nowRuns.push(await runIn(cwd, command, signals, true));
|
|
1521
|
+
nowRuns.push(await runIn(cwd, command, signals, true, timeoutMs));
|
|
1428
1522
|
} finally {
|
|
1429
1523
|
signals.release();
|
|
1430
1524
|
}
|
|
@@ -1433,6 +1527,10 @@ ${USAGE}`);
|
|
|
1433
1527
|
for (const [run, where] of [[before, `at ${sha.slice(0, 7)}`], ...nowRuns.map((each, i) => [each, runs > 1 ? `now (run ${i + 1})` : "now"])]) {
|
|
1434
1528
|
if (!run.started)
|
|
1435
1529
|
fail(run.output);
|
|
1530
|
+
if (run.timedOut === true)
|
|
1531
|
+
fail(`the command ran past --timeout ${parsed.values.timeout} ${where} and was killed, which says nothing about the change${run.output.trim() === "" ? "" : `
|
|
1532
|
+
|
|
1533
|
+
${folded(run.output)}`}`);
|
|
1436
1534
|
if (abnormal(run.code))
|
|
1437
1535
|
fail(`the command did not run properly ${where}: exit ${run.code}, a missing command or a kill, not a test result${run.output.trim() === "" ? "" : `
|
|
1438
1536
|
|
|
@@ -1447,7 +1545,7 @@ ${folded(run.output)}`}`);
|
|
|
1447
1545
|
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 })) });
|
|
1448
1546
|
return proved ? 0 : 1;
|
|
1449
1547
|
}
|
|
1450
|
-
console.log(role(proved ? "ok" : "problem",
|
|
1548
|
+
console.log(role(proved ? "ok" : "problem", process17.stdout)(message));
|
|
1451
1549
|
if (runs > 1)
|
|
1452
1550
|
console.log(`now: ${codes.map((code, i) => `run ${i + 1} ${code === 0 ? "passed" : `failed (exit ${code})`}`).join(", ")}`);
|
|
1453
1551
|
const shown = side === "before" ? before : now;
|
|
@@ -1458,4 +1556,4 @@ ${folded(shown.output)}`);
|
|
|
1458
1556
|
}
|
|
1459
1557
|
|
|
1460
1558
|
// src/proof-cli.ts
|
|
1461
|
-
|
|
1559
|
+
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.
|
|
4
|
+
"version": "0.11.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",
|
|
@@ -38,6 +38,6 @@
|
|
|
38
38
|
"proof": "$npm_execpath src/proof-cli.ts"
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
41
|
-
"@kaynooo/cli-kit": "0.
|
|
41
|
+
"@kaynooo/cli-kit": "0.39.0"
|
|
42
42
|
}
|
|
43
43
|
}
|