@kaynooo/cli-base 0.5.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +297 -5
- package/dist/{proof.js → proof-cli.js} +191 -5
- package/package.json +5 -5
package/dist/cli.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// @bun
|
|
3
3
|
|
|
4
4
|
// src/cli.ts
|
|
5
|
-
import
|
|
5
|
+
import process12 from "process";
|
|
6
6
|
// ../kit/src/args.ts
|
|
7
7
|
import process4 from "process";
|
|
8
8
|
import { parseArgs } from "util";
|
|
@@ -790,6 +790,79 @@ var LEVEL_OPTIONS = {
|
|
|
790
790
|
help: { type: "boolean", short: "h", description: "show this help" }
|
|
791
791
|
};
|
|
792
792
|
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
793
|
+
async function commandRows(all, colors) {
|
|
794
|
+
const commands = shown(all);
|
|
795
|
+
const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
|
|
796
|
+
const groups = new Map([["Commands:", []]]);
|
|
797
|
+
const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
|
|
798
|
+
for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
|
|
799
|
+
const heading = group === undefined ? "Commands:" : `${group}:`;
|
|
800
|
+
const rows = groups.get(heading) ?? [];
|
|
801
|
+
rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
|
|
802
|
+
groups.set(heading, rows);
|
|
803
|
+
}
|
|
804
|
+
return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
|
|
805
|
+
}
|
|
806
|
+
function shown(commands) {
|
|
807
|
+
return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
|
|
808
|
+
}
|
|
809
|
+
function takeOutputFlags(argv) {
|
|
810
|
+
let index = 0;
|
|
811
|
+
for (;index < argv.length; index++) {
|
|
812
|
+
const word = argv[index];
|
|
813
|
+
if (word === "--plain")
|
|
814
|
+
applyOutput(undefined, true);
|
|
815
|
+
else if (word.startsWith("--color="))
|
|
816
|
+
applyOutput(word.slice("--color=".length), undefined);
|
|
817
|
+
else if (word === "--color" && argv[index + 1] !== undefined)
|
|
818
|
+
applyOutput(argv[++index], undefined);
|
|
819
|
+
else
|
|
820
|
+
break;
|
|
821
|
+
}
|
|
822
|
+
return argv.slice(index);
|
|
823
|
+
}
|
|
824
|
+
async function resolveSummary(summary) {
|
|
825
|
+
return typeof summary === "string" ? summary : summary();
|
|
826
|
+
}
|
|
827
|
+
function scopeOf(commands, extra, aliases) {
|
|
828
|
+
return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
|
|
829
|
+
}
|
|
830
|
+
async function expand(scope, words) {
|
|
831
|
+
if (scope.lazy.length === 0)
|
|
832
|
+
return scope;
|
|
833
|
+
const commands = { ...scope.commands };
|
|
834
|
+
for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
|
|
835
|
+
for (const [name, command] of Object.entries(added))
|
|
836
|
+
commands[name] ??= command;
|
|
837
|
+
}
|
|
838
|
+
return { ...scope, commands, lazy: [] };
|
|
839
|
+
}
|
|
840
|
+
async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
|
|
841
|
+
const colors = paint(stream);
|
|
842
|
+
const prefix = path.join(" ");
|
|
843
|
+
const summary = await resolveSummary(lazySummary);
|
|
844
|
+
if (wantsHelpJson())
|
|
845
|
+
return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
|
|
846
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
847
|
+
const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
|
|
848
|
+
const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
|
|
849
|
+
return [
|
|
850
|
+
header(colors, summary),
|
|
851
|
+
"",
|
|
852
|
+
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
853
|
+
...replacesRows(replaces, colors),
|
|
854
|
+
"",
|
|
855
|
+
...await commandRows(commands, colors),
|
|
856
|
+
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
857
|
+
"",
|
|
858
|
+
colors.bold("Options:"),
|
|
859
|
+
...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
|
|
860
|
+
...exampleRows(examples ?? [], colors),
|
|
861
|
+
"",
|
|
862
|
+
`${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
|
|
863
|
+
].join(`
|
|
864
|
+
`);
|
|
865
|
+
}
|
|
793
866
|
function printError(prefix, message, hint, cause) {
|
|
794
867
|
const colors = paint(process7.stderr);
|
|
795
868
|
const styled = takesControlCodes(process7.stderr);
|
|
@@ -811,12 +884,68 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
|
811
884
|
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
812
885
|
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
813
886
|
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
814
|
-
if (error instanceof
|
|
887
|
+
if (error instanceof Exit && error.code === 2)
|
|
815
888
|
noteUsageError(error.message);
|
|
816
889
|
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
817
890
|
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
818
891
|
return error instanceof Exit ? error.code : 1;
|
|
819
892
|
}
|
|
893
|
+
async function dispatch(level, typed, { version, redact }) {
|
|
894
|
+
const prefix = level.path.join(" ");
|
|
895
|
+
let argv;
|
|
896
|
+
try {
|
|
897
|
+
argv = takeOutputFlags(typed);
|
|
898
|
+
} catch (error) {
|
|
899
|
+
return reportThrown(prefix, error);
|
|
900
|
+
}
|
|
901
|
+
const [name, ...args] = argv;
|
|
902
|
+
const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
|
|
903
|
+
if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
|
|
904
|
+
try {
|
|
905
|
+
return await fallback.run([]);
|
|
906
|
+
} catch (error) {
|
|
907
|
+
return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
if (name === undefined && level.path.length > 1) {
|
|
911
|
+
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process7.stderr));
|
|
912
|
+
return 2;
|
|
913
|
+
}
|
|
914
|
+
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
915
|
+
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process7.stdout));
|
|
916
|
+
return 0;
|
|
917
|
+
}
|
|
918
|
+
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
919
|
+
console.log(version);
|
|
920
|
+
return 0;
|
|
921
|
+
}
|
|
922
|
+
let command = level.commands[level.aliases?.[name] ?? name];
|
|
923
|
+
let rest = args;
|
|
924
|
+
let ran = name;
|
|
925
|
+
if (command === undefined && level.lazy.length > 0) {
|
|
926
|
+
level = await expand(level, [...level.path.slice(1), ...argv]);
|
|
927
|
+
command = level.commands[level.aliases?.[name] ?? name];
|
|
928
|
+
}
|
|
929
|
+
if (command === undefined && level.defaultCommand !== undefined) {
|
|
930
|
+
command = level.commands[level.defaultCommand];
|
|
931
|
+
rest = argv;
|
|
932
|
+
ran = level.defaultCommand;
|
|
933
|
+
}
|
|
934
|
+
if (command === undefined) {
|
|
935
|
+
const meant = closest(name, Object.keys(shown(level.commands)));
|
|
936
|
+
printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
|
|
937
|
+
return 2;
|
|
938
|
+
}
|
|
939
|
+
if ("commands" in command) {
|
|
940
|
+
const { summary } = command;
|
|
941
|
+
return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
|
|
942
|
+
}
|
|
943
|
+
try {
|
|
944
|
+
return await command.run(rest);
|
|
945
|
+
} catch (error) {
|
|
946
|
+
return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
|
|
947
|
+
}
|
|
948
|
+
}
|
|
820
949
|
var COMPLETE = "__complete";
|
|
821
950
|
var FILES = "__files__";
|
|
822
951
|
async function completingOf(run) {
|
|
@@ -831,6 +960,9 @@ async function completingOf(run) {
|
|
|
831
960
|
}
|
|
832
961
|
return new Completing({});
|
|
833
962
|
}
|
|
963
|
+
async function optionsOf(run) {
|
|
964
|
+
return (await completingOf(run)).options;
|
|
965
|
+
}
|
|
834
966
|
function candidateLine(candidate) {
|
|
835
967
|
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
836
968
|
}
|
|
@@ -869,6 +1001,28 @@ async function leafCandidates(run, words) {
|
|
|
869
1001
|
const values = name === undefined ? undefined : await completing.candidates[name]?.();
|
|
870
1002
|
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
871
1003
|
}
|
|
1004
|
+
async function candidates(scope, defaultCommand, words, before = []) {
|
|
1005
|
+
const [word = "", ...rest] = words;
|
|
1006
|
+
const listing = rest.length === 0 && !word.startsWith("-");
|
|
1007
|
+
let { commands, aliases } = scope;
|
|
1008
|
+
let command = commands[aliases?.[word] ?? word];
|
|
1009
|
+
if (listing || command === undefined) {
|
|
1010
|
+
({ commands, aliases } = await expand(scope, [...before, ...words]));
|
|
1011
|
+
command = commands[aliases?.[word] ?? word];
|
|
1012
|
+
}
|
|
1013
|
+
if (listing) {
|
|
1014
|
+
const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
|
|
1015
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1016
|
+
const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
|
|
1017
|
+
const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
|
|
1018
|
+
return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
|
|
1019
|
+
}
|
|
1020
|
+
if (command === undefined) {
|
|
1021
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1022
|
+
return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
|
|
1023
|
+
}
|
|
1024
|
+
return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
|
|
1025
|
+
}
|
|
872
1026
|
async function printCandidates(found) {
|
|
873
1027
|
for (const line of await found)
|
|
874
1028
|
console.log(line);
|
|
@@ -885,6 +1039,33 @@ function packageVersion(entry = Bun.main) {
|
|
|
885
1039
|
return "0.0.0";
|
|
886
1040
|
}
|
|
887
1041
|
}
|
|
1042
|
+
async function runCli(cli, argv = process7.argv.slice(2)) {
|
|
1043
|
+
const version = cli.version ?? packageVersion();
|
|
1044
|
+
if (argv[0] === COMPLETE)
|
|
1045
|
+
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
1046
|
+
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 });
|
|
1047
|
+
if (cli.usage !== false) {
|
|
1048
|
+
try {
|
|
1049
|
+
recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
|
|
1050
|
+
} catch {}
|
|
1051
|
+
}
|
|
1052
|
+
return code;
|
|
1053
|
+
}
|
|
1054
|
+
function commandPath(scope, argv) {
|
|
1055
|
+
const path = [];
|
|
1056
|
+
let level = scope;
|
|
1057
|
+
for (const word of argv.filter((each) => !each.startsWith("-"))) {
|
|
1058
|
+
const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
|
|
1059
|
+
const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
|
|
1060
|
+
if (command === undefined)
|
|
1061
|
+
break;
|
|
1062
|
+
path.push(word);
|
|
1063
|
+
if (!("commands" in command))
|
|
1064
|
+
break;
|
|
1065
|
+
level = scopeOf(command.commands, command.extraCommands, command.aliases);
|
|
1066
|
+
}
|
|
1067
|
+
return path.length === 0 ? undefined : path.join(" ");
|
|
1068
|
+
}
|
|
888
1069
|
async function runMain({ name, version, run, redact, usage }, argv = process7.argv.slice(2)) {
|
|
889
1070
|
if (argv[0] === COMPLETE)
|
|
890
1071
|
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
@@ -911,6 +1092,9 @@ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "ses
|
|
|
911
1092
|
var {Glob } = globalThis.Bun;
|
|
912
1093
|
var SESSION_FILES = new Glob("*.json");
|
|
913
1094
|
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1095
|
+
// src/base.ts
|
|
1096
|
+
import process10 from "process";
|
|
1097
|
+
|
|
914
1098
|
// src/worktree.ts
|
|
915
1099
|
import { cpSync, existsSync, lstatSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, realpathSync as realpathSync2, rmSync, symlinkSync, unlinkSync } from "fs";
|
|
916
1100
|
import { tmpdir } from "os";
|
|
@@ -1135,7 +1319,7 @@ async function inWorktree(options, body) {
|
|
|
1135
1319
|
}
|
|
1136
1320
|
}
|
|
1137
1321
|
|
|
1138
|
-
// src/
|
|
1322
|
+
// src/base.ts
|
|
1139
1323
|
var USAGE = `base [--ref <rev>] [--keep <path>...] [--no-link] -- <command> [args...]: runs the command at HEAD or another ref in a temporary worktree, the working tree untouched, exiting with its code
|
|
1140
1324
|
|
|
1141
1325
|
Exits with the code of the command, 127 when it cannot be started, 2 on a usage error, an unknown ref or a refused command.`;
|
|
@@ -1144,7 +1328,7 @@ var OPTIONS = {
|
|
|
1144
1328
|
keep: { type: "string", short: "k", multiple: true, description: "a working-tree file or folder copied over, such as the new test, repeatable" },
|
|
1145
1329
|
"no-link": { type: "boolean", description: "do not link the ignored env files, node_modules, vendor and .venv of the checkout" }
|
|
1146
1330
|
};
|
|
1147
|
-
async function
|
|
1331
|
+
async function base(argv) {
|
|
1148
1332
|
const bare = argv[0] !== undefined && !argv[0].startsWith("-");
|
|
1149
1333
|
const parsed = parse(bare ? [] : argv, USAGE, OPTIONS, { rest: true, replaces: "git stash, a test run, then git stash pop", examples: [["base -- bun test tests/api.test.ts", "the test at HEAD, the working tree changes left out"], ["base --ref main~3 --keep tests/new.test.ts -- bun test tests/new.test.ts", "a new test against an older commit"]] });
|
|
1150
1334
|
const given = bare ? argv : parsed.rest ?? [];
|
|
@@ -1166,4 +1350,112 @@ ${USAGE}`);
|
|
|
1166
1350
|
console.error(`base: ran at ${ref} (${sha.slice(0, 7)}), exit ${ran.code}`);
|
|
1167
1351
|
return ran.code;
|
|
1168
1352
|
}
|
|
1169
|
-
|
|
1353
|
+
|
|
1354
|
+
// src/proof.ts
|
|
1355
|
+
import process11 from "process";
|
|
1356
|
+
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
|
|
1357
|
+
|
|
1358
|
+
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.`;
|
|
1359
|
+
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)"]];
|
|
1360
|
+
var OPTIONS2 = {
|
|
1361
|
+
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)" },
|
|
1362
|
+
runs: { type: "string", short: "n", description: "run the command this many times now, every run must pass (1)" },
|
|
1363
|
+
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" },
|
|
1364
|
+
"no-link": { type: "boolean", description: "do not link the ignored env files, node_modules, vendor and .venv of the checkout" },
|
|
1365
|
+
json: jsonOption("{outcome, proved, ref, sha, before: {code, output}, now: {code, output}}")
|
|
1366
|
+
};
|
|
1367
|
+
function abnormal(code) {
|
|
1368
|
+
return code === 126 || code === 127 || code > 128 && code < 160;
|
|
1369
|
+
}
|
|
1370
|
+
function outcomeOf(before, now) {
|
|
1371
|
+
const failed = now.filter((code) => code !== 0).length;
|
|
1372
|
+
if (before !== 0 && failed === 0)
|
|
1373
|
+
return "proved";
|
|
1374
|
+
if (before === 0 && failed === 0)
|
|
1375
|
+
return "passes-before";
|
|
1376
|
+
if (before !== 0)
|
|
1377
|
+
return failed < now.length ? "flaky" : "fails-both";
|
|
1378
|
+
return "regressed";
|
|
1379
|
+
}
|
|
1380
|
+
function describe(outcome, at, now) {
|
|
1381
|
+
switch (outcome) {
|
|
1382
|
+
case "proved":
|
|
1383
|
+
return { message: now.length > 1 ? `fails at ${at}, passes now in ${now.length} of ${now.length} runs` : `fails at ${at}, passes now`, side: "before" };
|
|
1384
|
+
case "passes-before":
|
|
1385
|
+
return { message: `passes at ${at} too: it does not fail without the change`, side: "before" };
|
|
1386
|
+
case "fails-both":
|
|
1387
|
+
return { message: `fails at ${at} and fails now too`, side: "now" };
|
|
1388
|
+
case "regressed":
|
|
1389
|
+
return { message: `passes at ${at}, fails now`, side: "now" };
|
|
1390
|
+
case "flaky":
|
|
1391
|
+
return { message: `fails at ${at}, but ${now.filter((code) => code !== 0).length} of ${now.length} runs fail now`, side: "now" };
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
async function proof(argv) {
|
|
1395
|
+
const bare = argv[0] !== undefined && !argv[0].startsWith("-");
|
|
1396
|
+
const parsed = parse(bare ? [] : argv, USAGE2, OPTIONS2, { 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"]] });
|
|
1397
|
+
const given = bare ? argv : parsed.rest ?? [];
|
|
1398
|
+
if (given.length === 0 || parsed.positionals.length > 0)
|
|
1399
|
+
fail(`give the command after --
|
|
1400
|
+
|
|
1401
|
+
${USAGE2}`);
|
|
1402
|
+
if (runsInContainer(given))
|
|
1403
|
+
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");
|
|
1404
|
+
const command = shellCommand(given);
|
|
1405
|
+
const cwd = process11.cwd();
|
|
1406
|
+
const { root, prefix } = await checkout(cwd);
|
|
1407
|
+
const runs = wholeNumber(parsed.values.runs, "runs", 1, 1);
|
|
1408
|
+
const ref = parsed.values.ref ?? await defaultProofRef(root);
|
|
1409
|
+
const sha = await resolveRef(root, ref);
|
|
1410
|
+
const kept = keptPaths(root, cwd, parsed.values.keep ?? []);
|
|
1411
|
+
const signals = holdSignals();
|
|
1412
|
+
let before;
|
|
1413
|
+
const nowRuns = [];
|
|
1414
|
+
try {
|
|
1415
|
+
before = await inWorktree({ root, prefix, sha, ref, kept, link: parsed.values["no-link"] !== true, signals }, async (runDir, held) => runIn(runDir, command, held, true));
|
|
1416
|
+
for (let i = 0;i < runs && signals.signal === undefined; i++)
|
|
1417
|
+
nowRuns.push(await runIn(cwd, command, signals, true));
|
|
1418
|
+
} finally {
|
|
1419
|
+
signals.release();
|
|
1420
|
+
}
|
|
1421
|
+
if (signals.signal !== undefined || nowRuns.length < runs)
|
|
1422
|
+
return exitCodeOf(null, signals.signal ?? null);
|
|
1423
|
+
for (const [run, where] of [[before, `at ${sha.slice(0, 7)}`], ...nowRuns.map((each, i) => [each, runs > 1 ? `now (run ${i + 1})` : "now"])]) {
|
|
1424
|
+
if (!run.started)
|
|
1425
|
+
fail(run.output);
|
|
1426
|
+
if (abnormal(run.code))
|
|
1427
|
+
fail(`the command did not run properly ${where}: exit ${run.code}, a missing command or a kill, not a test result${run.output.trim() === "" ? "" : `
|
|
1428
|
+
|
|
1429
|
+
${folded(run.output)}`}`);
|
|
1430
|
+
}
|
|
1431
|
+
const codes = nowRuns.map((run) => run.code);
|
|
1432
|
+
const now = nowRuns.find((run) => run.code !== 0) ?? nowRuns.at(-1) ?? before;
|
|
1433
|
+
const outcome = outcomeOf(before.code, codes);
|
|
1434
|
+
const { message, side } = describe(outcome, sha.slice(0, 7), codes);
|
|
1435
|
+
const proved = outcome === "proved";
|
|
1436
|
+
if (parsed.values.json === true) {
|
|
1437
|
+
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 })) });
|
|
1438
|
+
return proved ? 0 : 1;
|
|
1439
|
+
}
|
|
1440
|
+
console.log(message);
|
|
1441
|
+
if (runs > 1)
|
|
1442
|
+
console.log(`now: ${codes.map((code, i) => `run ${i + 1} ${code === 0 ? "passed" : `failed (exit ${code})`}`).join(", ")}`);
|
|
1443
|
+
const shown = side === "before" ? before : now;
|
|
1444
|
+
if (shown.code !== 0 && shown.output.trim() !== "")
|
|
1445
|
+
console.log(`
|
|
1446
|
+
${folded(shown.output)}`);
|
|
1447
|
+
return proved ? 0 : 1;
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
// src/cli.ts
|
|
1451
|
+
process12.exitCode = await runCli({
|
|
1452
|
+
name: "base",
|
|
1453
|
+
about: "runs a command at HEAD or another ref in a temporary worktree, the working tree untouched",
|
|
1454
|
+
replaces: "git stash, a test run, then git stash pop",
|
|
1455
|
+
examples: [["base -- bun test tests/api.test.ts", "the test at HEAD, the working tree changes left out"], ["base proof -- bun test tests/new.test.ts", "it fails at HEAD and passes in the working tree"]],
|
|
1456
|
+
commands: {
|
|
1457
|
+
run: { summary: "the command at HEAD or --ref, exiting with its code (the command when none is named)", run: base },
|
|
1458
|
+
proof: { summary: "the command at HEAD or --ref, then in the working tree: proves a test fails before a change and passes after it", run: proof }
|
|
1459
|
+
},
|
|
1460
|
+
defaultCommand: "run"
|
|
1461
|
+
});
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env -S bun --no-env-file
|
|
2
2
|
// @bun
|
|
3
3
|
|
|
4
|
-
// src/proof.ts
|
|
5
|
-
import
|
|
4
|
+
// src/proof-cli.ts
|
|
5
|
+
import process11 from "process";
|
|
6
6
|
// ../kit/src/args.ts
|
|
7
7
|
import process4 from "process";
|
|
8
8
|
import { parseArgs } from "util";
|
|
@@ -790,6 +790,79 @@ var LEVEL_OPTIONS = {
|
|
|
790
790
|
help: { type: "boolean", short: "h", description: "show this help" }
|
|
791
791
|
};
|
|
792
792
|
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
793
|
+
async function commandRows(all, colors) {
|
|
794
|
+
const commands = shown(all);
|
|
795
|
+
const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
|
|
796
|
+
const groups = new Map([["Commands:", []]]);
|
|
797
|
+
const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
|
|
798
|
+
for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
|
|
799
|
+
const heading = group === undefined ? "Commands:" : `${group}:`;
|
|
800
|
+
const rows = groups.get(heading) ?? [];
|
|
801
|
+
rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
|
|
802
|
+
groups.set(heading, rows);
|
|
803
|
+
}
|
|
804
|
+
return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
|
|
805
|
+
}
|
|
806
|
+
function shown(commands) {
|
|
807
|
+
return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
|
|
808
|
+
}
|
|
809
|
+
function takeOutputFlags(argv) {
|
|
810
|
+
let index = 0;
|
|
811
|
+
for (;index < argv.length; index++) {
|
|
812
|
+
const word = argv[index];
|
|
813
|
+
if (word === "--plain")
|
|
814
|
+
applyOutput(undefined, true);
|
|
815
|
+
else if (word.startsWith("--color="))
|
|
816
|
+
applyOutput(word.slice("--color=".length), undefined);
|
|
817
|
+
else if (word === "--color" && argv[index + 1] !== undefined)
|
|
818
|
+
applyOutput(argv[++index], undefined);
|
|
819
|
+
else
|
|
820
|
+
break;
|
|
821
|
+
}
|
|
822
|
+
return argv.slice(index);
|
|
823
|
+
}
|
|
824
|
+
async function resolveSummary(summary) {
|
|
825
|
+
return typeof summary === "string" ? summary : summary();
|
|
826
|
+
}
|
|
827
|
+
function scopeOf(commands, extra, aliases) {
|
|
828
|
+
return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
|
|
829
|
+
}
|
|
830
|
+
async function expand(scope, words) {
|
|
831
|
+
if (scope.lazy.length === 0)
|
|
832
|
+
return scope;
|
|
833
|
+
const commands = { ...scope.commands };
|
|
834
|
+
for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
|
|
835
|
+
for (const [name, command] of Object.entries(added))
|
|
836
|
+
commands[name] ??= command;
|
|
837
|
+
}
|
|
838
|
+
return { ...scope, commands, lazy: [] };
|
|
839
|
+
}
|
|
840
|
+
async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
|
|
841
|
+
const colors = paint(stream);
|
|
842
|
+
const prefix = path.join(" ");
|
|
843
|
+
const summary = await resolveSummary(lazySummary);
|
|
844
|
+
if (wantsHelpJson())
|
|
845
|
+
return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
|
|
846
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
847
|
+
const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
|
|
848
|
+
const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
|
|
849
|
+
return [
|
|
850
|
+
header(colors, summary),
|
|
851
|
+
"",
|
|
852
|
+
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
853
|
+
...replacesRows(replaces, colors),
|
|
854
|
+
"",
|
|
855
|
+
...await commandRows(commands, colors),
|
|
856
|
+
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
857
|
+
"",
|
|
858
|
+
colors.bold("Options:"),
|
|
859
|
+
...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
|
|
860
|
+
...exampleRows(examples ?? [], colors),
|
|
861
|
+
"",
|
|
862
|
+
`${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
|
|
863
|
+
].join(`
|
|
864
|
+
`);
|
|
865
|
+
}
|
|
793
866
|
function printError(prefix, message, hint, cause) {
|
|
794
867
|
const colors = paint(process7.stderr);
|
|
795
868
|
const styled = takesControlCodes(process7.stderr);
|
|
@@ -811,12 +884,68 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
|
811
884
|
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
812
885
|
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
813
886
|
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
814
|
-
if (error instanceof
|
|
887
|
+
if (error instanceof Exit && error.code === 2)
|
|
815
888
|
noteUsageError(error.message);
|
|
816
889
|
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
817
890
|
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
818
891
|
return error instanceof Exit ? error.code : 1;
|
|
819
892
|
}
|
|
893
|
+
async function dispatch(level, typed, { version, redact }) {
|
|
894
|
+
const prefix = level.path.join(" ");
|
|
895
|
+
let argv;
|
|
896
|
+
try {
|
|
897
|
+
argv = takeOutputFlags(typed);
|
|
898
|
+
} catch (error) {
|
|
899
|
+
return reportThrown(prefix, error);
|
|
900
|
+
}
|
|
901
|
+
const [name, ...args] = argv;
|
|
902
|
+
const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
|
|
903
|
+
if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
|
|
904
|
+
try {
|
|
905
|
+
return await fallback.run([]);
|
|
906
|
+
} catch (error) {
|
|
907
|
+
return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
if (name === undefined && level.path.length > 1) {
|
|
911
|
+
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process7.stderr));
|
|
912
|
+
return 2;
|
|
913
|
+
}
|
|
914
|
+
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
915
|
+
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process7.stdout));
|
|
916
|
+
return 0;
|
|
917
|
+
}
|
|
918
|
+
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
919
|
+
console.log(version);
|
|
920
|
+
return 0;
|
|
921
|
+
}
|
|
922
|
+
let command = level.commands[level.aliases?.[name] ?? name];
|
|
923
|
+
let rest = args;
|
|
924
|
+
let ran = name;
|
|
925
|
+
if (command === undefined && level.lazy.length > 0) {
|
|
926
|
+
level = await expand(level, [...level.path.slice(1), ...argv]);
|
|
927
|
+
command = level.commands[level.aliases?.[name] ?? name];
|
|
928
|
+
}
|
|
929
|
+
if (command === undefined && level.defaultCommand !== undefined) {
|
|
930
|
+
command = level.commands[level.defaultCommand];
|
|
931
|
+
rest = argv;
|
|
932
|
+
ran = level.defaultCommand;
|
|
933
|
+
}
|
|
934
|
+
if (command === undefined) {
|
|
935
|
+
const meant = closest(name, Object.keys(shown(level.commands)));
|
|
936
|
+
printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
|
|
937
|
+
return 2;
|
|
938
|
+
}
|
|
939
|
+
if ("commands" in command) {
|
|
940
|
+
const { summary } = command;
|
|
941
|
+
return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
|
|
942
|
+
}
|
|
943
|
+
try {
|
|
944
|
+
return await command.run(rest);
|
|
945
|
+
} catch (error) {
|
|
946
|
+
return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
|
|
947
|
+
}
|
|
948
|
+
}
|
|
820
949
|
var COMPLETE = "__complete";
|
|
821
950
|
var FILES = "__files__";
|
|
822
951
|
async function completingOf(run) {
|
|
@@ -831,6 +960,9 @@ async function completingOf(run) {
|
|
|
831
960
|
}
|
|
832
961
|
return new Completing({});
|
|
833
962
|
}
|
|
963
|
+
async function optionsOf(run) {
|
|
964
|
+
return (await completingOf(run)).options;
|
|
965
|
+
}
|
|
834
966
|
function candidateLine(candidate) {
|
|
835
967
|
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
836
968
|
}
|
|
@@ -869,6 +1001,28 @@ async function leafCandidates(run, words) {
|
|
|
869
1001
|
const values = name === undefined ? undefined : await completing.candidates[name]?.();
|
|
870
1002
|
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
871
1003
|
}
|
|
1004
|
+
async function candidates(scope, defaultCommand, words, before = []) {
|
|
1005
|
+
const [word = "", ...rest] = words;
|
|
1006
|
+
const listing = rest.length === 0 && !word.startsWith("-");
|
|
1007
|
+
let { commands, aliases } = scope;
|
|
1008
|
+
let command = commands[aliases?.[word] ?? word];
|
|
1009
|
+
if (listing || command === undefined) {
|
|
1010
|
+
({ commands, aliases } = await expand(scope, [...before, ...words]));
|
|
1011
|
+
command = commands[aliases?.[word] ?? word];
|
|
1012
|
+
}
|
|
1013
|
+
if (listing) {
|
|
1014
|
+
const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
|
|
1015
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1016
|
+
const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
|
|
1017
|
+
const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
|
|
1018
|
+
return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
|
|
1019
|
+
}
|
|
1020
|
+
if (command === undefined) {
|
|
1021
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1022
|
+
return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
|
|
1023
|
+
}
|
|
1024
|
+
return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
|
|
1025
|
+
}
|
|
872
1026
|
async function printCandidates(found) {
|
|
873
1027
|
for (const line of await found)
|
|
874
1028
|
console.log(line);
|
|
@@ -885,6 +1039,33 @@ function packageVersion(entry = Bun.main) {
|
|
|
885
1039
|
return "0.0.0";
|
|
886
1040
|
}
|
|
887
1041
|
}
|
|
1042
|
+
async function runCli(cli, argv = process7.argv.slice(2)) {
|
|
1043
|
+
const version = cli.version ?? packageVersion();
|
|
1044
|
+
if (argv[0] === COMPLETE)
|
|
1045
|
+
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
1046
|
+
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 });
|
|
1047
|
+
if (cli.usage !== false) {
|
|
1048
|
+
try {
|
|
1049
|
+
recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
|
|
1050
|
+
} catch {}
|
|
1051
|
+
}
|
|
1052
|
+
return code;
|
|
1053
|
+
}
|
|
1054
|
+
function commandPath(scope, argv) {
|
|
1055
|
+
const path = [];
|
|
1056
|
+
let level = scope;
|
|
1057
|
+
for (const word of argv.filter((each) => !each.startsWith("-"))) {
|
|
1058
|
+
const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
|
|
1059
|
+
const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
|
|
1060
|
+
if (command === undefined)
|
|
1061
|
+
break;
|
|
1062
|
+
path.push(word);
|
|
1063
|
+
if (!("commands" in command))
|
|
1064
|
+
break;
|
|
1065
|
+
level = scopeOf(command.commands, command.extraCommands, command.aliases);
|
|
1066
|
+
}
|
|
1067
|
+
return path.length === 0 ? undefined : path.join(" ");
|
|
1068
|
+
}
|
|
888
1069
|
async function runMain({ name, version, run, redact, usage }, argv = process7.argv.slice(2)) {
|
|
889
1070
|
if (argv[0] === COMPLETE)
|
|
890
1071
|
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
@@ -911,6 +1092,9 @@ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "ses
|
|
|
911
1092
|
var {Glob } = globalThis.Bun;
|
|
912
1093
|
var SESSION_FILES = new Glob("*.json");
|
|
913
1094
|
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1095
|
+
// src/proof.ts
|
|
1096
|
+
import process10 from "process";
|
|
1097
|
+
|
|
914
1098
|
// src/worktree.ts
|
|
915
1099
|
import { cpSync, existsSync, lstatSync, mkdirSync as mkdirSync2, mkdtempSync, readdirSync, realpathSync as realpathSync2, rmSync, symlinkSync, unlinkSync } from "fs";
|
|
916
1100
|
import { tmpdir } from "os";
|
|
@@ -1174,7 +1358,7 @@ function describe(outcome, at, now) {
|
|
|
1174
1358
|
return { message: `fails at ${at}, but ${now.filter((code) => code !== 0).length} of ${now.length} runs fail now`, side: "now" };
|
|
1175
1359
|
}
|
|
1176
1360
|
}
|
|
1177
|
-
async function
|
|
1361
|
+
async function proof(argv) {
|
|
1178
1362
|
const bare = argv[0] !== undefined && !argv[0].startsWith("-");
|
|
1179
1363
|
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"]] });
|
|
1180
1364
|
const given = bare ? argv : parsed.rest ?? [];
|
|
@@ -1229,4 +1413,6 @@ ${folded(run.output)}`}`);
|
|
|
1229
1413
|
${folded(shown.output)}`);
|
|
1230
1414
|
return proved ? 0 : 1;
|
|
1231
1415
|
}
|
|
1232
|
-
|
|
1416
|
+
|
|
1417
|
+
// src/proof-cli.ts
|
|
1418
|
+
process11.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.6.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",
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
],
|
|
22
22
|
"bin": {
|
|
23
23
|
"base": "./dist/cli.js",
|
|
24
|
-
"proof": "./dist/proof.js"
|
|
24
|
+
"proof": "./dist/proof-cli.js"
|
|
25
25
|
},
|
|
26
26
|
"files": [
|
|
27
27
|
"dist"
|
|
@@ -33,11 +33,11 @@
|
|
|
33
33
|
"registry": "https://git.kaynooo.fr/api/packages/kaynooo/npm/"
|
|
34
34
|
},
|
|
35
35
|
"scripts": {
|
|
36
|
-
"build": "$npm_execpath build src/cli.ts src/proof.ts --target bun --outdir dist",
|
|
36
|
+
"build": "$npm_execpath build src/cli.ts src/proof-cli.ts --target bun --outdir dist",
|
|
37
37
|
"base": "$npm_execpath src/cli.ts",
|
|
38
|
-
"proof": "$npm_execpath src/proof.ts"
|
|
38
|
+
"proof": "$npm_execpath src/proof-cli.ts"
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
41
|
-
"@kaynooo/cli-kit": "0.21.
|
|
41
|
+
"@kaynooo/cli-kit": "0.21.1"
|
|
42
42
|
}
|
|
43
43
|
}
|