@kaynooo/cli-workspace 0.10.1 → 0.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/audit-cli.js +340 -77
- package/dist/cli.js +456 -137
- package/dist/repos-cli.js +210 -72
- package/dist/sweep-cli.js +271 -77
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// @bun
|
|
3
3
|
|
|
4
4
|
// src/cli.ts
|
|
5
|
-
import
|
|
5
|
+
import process24 from "process";
|
|
6
6
|
|
|
7
7
|
// ../kit/src/advisory.ts
|
|
8
8
|
var SEVERITIES = ["low", "moderate", "high", "critical"];
|
|
@@ -517,24 +517,20 @@ function printJson(value) {
|
|
|
517
517
|
|
|
518
518
|
// ../kit/src/help.ts
|
|
519
519
|
import process8 from "process";
|
|
520
|
-
var OPTIONAL =
|
|
520
|
+
var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
521
521
|
var USAGE_PREFIX = /^usage:\s*/i;
|
|
522
522
|
var FULL_STOP = /\.$/;
|
|
523
523
|
function usageLine(usage, colors = paint(process8.stdout)) {
|
|
524
524
|
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
525
525
|
}
|
|
526
|
-
function helpText(usage, options, colors = paint(process8.stdout), { examples = [],
|
|
527
|
-
return [usageLine(usage, colors),
|
|
526
|
+
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
|
|
527
|
+
return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
528
528
|
`);
|
|
529
529
|
}
|
|
530
530
|
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
531
531
|
if (exits.length === 0)
|
|
532
532
|
return [];
|
|
533
|
-
|
|
534
|
-
return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
|
|
535
|
-
}
|
|
536
|
-
function replacesRows(replaces, colors = paint(process8.stdout)) {
|
|
537
|
-
return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
533
|
+
return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
|
|
538
534
|
}
|
|
539
535
|
function wantsHelpJson(env = process8.env) {
|
|
540
536
|
return env.KIT_HELP === "json";
|
|
@@ -560,29 +556,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
|
560
556
|
return [];
|
|
561
557
|
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
562
558
|
}
|
|
559
|
+
var MAX_INLINE_CHOICES = 24;
|
|
563
560
|
function optionRows(options, colors = paint(process8.stdout)) {
|
|
564
561
|
const rows = Object.entries(options).map(([name, option]) => {
|
|
565
562
|
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
566
|
-
const
|
|
563
|
+
const choices = option.choices?.join("|");
|
|
564
|
+
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
565
|
+
const named = inline ? `<${choices}>` : "<value>";
|
|
567
566
|
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
568
567
|
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
569
|
-
|
|
568
|
+
const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
|
|
569
|
+
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
|
|
570
570
|
});
|
|
571
571
|
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
572
572
|
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
573
573
|
}
|
|
574
574
|
|
|
575
575
|
// ../kit/src/text.ts
|
|
576
|
-
var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
|
|
577
576
|
function distance(a, b) {
|
|
578
|
-
|
|
579
|
-
|
|
577
|
+
const left = [...a];
|
|
578
|
+
const right = [...b];
|
|
579
|
+
let before = [];
|
|
580
|
+
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
581
|
+
for (const [i, x] of left.entries()) {
|
|
580
582
|
const current = [i + 1];
|
|
581
|
-
for (const [j,
|
|
582
|
-
|
|
583
|
+
for (const [j, y] of right.entries()) {
|
|
584
|
+
let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
|
|
585
|
+
if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
|
|
586
|
+
cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
|
|
587
|
+
current.push(cost);
|
|
588
|
+
}
|
|
589
|
+
before = previous;
|
|
583
590
|
previous = current;
|
|
584
591
|
}
|
|
585
|
-
return previous[
|
|
592
|
+
return previous[right.length] ?? 0;
|
|
586
593
|
}
|
|
587
594
|
function closest(name, names) {
|
|
588
595
|
const started = names.find((known) => known.startsWith(name));
|
|
@@ -649,7 +656,7 @@ class Completing {
|
|
|
649
656
|
}
|
|
650
657
|
var completion = { active: false };
|
|
651
658
|
var OUTPUT_OPTIONS = {
|
|
652
|
-
color: { type: "string", description: "auto (on a terminal alone
|
|
659
|
+
color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
|
|
653
660
|
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
654
661
|
};
|
|
655
662
|
function applyOutput(color, plain, env = process9.env) {
|
|
@@ -821,9 +828,33 @@ function nearestOption(message, options, allowNegative) {
|
|
|
821
828
|
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
822
829
|
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
823
830
|
}
|
|
831
|
+
// ../kit/src/argv.ts
|
|
832
|
+
import { readFileSync as readFileSync3, realpathSync } from "fs";
|
|
833
|
+
import { resolve as resolve3 } from "path";
|
|
834
|
+
import process10 from "process";
|
|
835
|
+
function commandLine() {
|
|
836
|
+
try {
|
|
837
|
+
return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
|
|
838
|
+
} catch {
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
function realPath(word) {
|
|
843
|
+
try {
|
|
844
|
+
return realpathSync(resolve3(word));
|
|
845
|
+
} catch {
|
|
846
|
+
return;
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
|
|
850
|
+
const target = script === undefined ? undefined : realPath(script) ?? script;
|
|
851
|
+
const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
|
|
852
|
+
const after = at === -1 ? [] : cmdline.slice(at + 1);
|
|
853
|
+
return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
|
|
854
|
+
}
|
|
824
855
|
// ../kit/src/process.ts
|
|
825
856
|
import { constants } from "os";
|
|
826
|
-
import
|
|
857
|
+
import process11 from "process";
|
|
827
858
|
var KILL_GRACE_MS = 2000;
|
|
828
859
|
function exitCodeOf(code, signal) {
|
|
829
860
|
if (code !== null)
|
|
@@ -843,7 +874,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
|
|
|
843
874
|
return;
|
|
844
875
|
try {
|
|
845
876
|
if (grouped)
|
|
846
|
-
|
|
877
|
+
process11.kill(-proc.pid, killing);
|
|
847
878
|
else
|
|
848
879
|
proc.kill(killing);
|
|
849
880
|
} catch {}
|
|
@@ -918,10 +949,10 @@ var RESET_STYLE = `${ESC}[0m`;
|
|
|
918
949
|
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
919
950
|
|
|
920
951
|
// ../kit/src/tool.ts
|
|
921
|
-
import
|
|
952
|
+
import process12 from "process";
|
|
922
953
|
function cwdGone() {
|
|
923
954
|
try {
|
|
924
|
-
|
|
955
|
+
process12.cwd();
|
|
925
956
|
return false;
|
|
926
957
|
} catch {
|
|
927
958
|
return true;
|
|
@@ -943,7 +974,7 @@ function spawnFailure(command, error) {
|
|
|
943
974
|
async function runTool(label, argv, { timeoutMs, cwd, onStart } = {}) {
|
|
944
975
|
let ran;
|
|
945
976
|
try {
|
|
946
|
-
ran = await runCommand(argv, { env:
|
|
977
|
+
ran = await runCommand(argv, { env: process12.env, ...timeoutMs === undefined ? {} : { timeoutMs }, ...cwd === undefined ? {} : { cwd }, ...onStart === undefined ? {} : { onStart } });
|
|
947
978
|
} catch (error) {
|
|
948
979
|
throw spawnFailure(label, error);
|
|
949
980
|
}
|
|
@@ -958,15 +989,93 @@ async function runTool(label, argv, { timeoutMs, cwd, onStart } = {}) {
|
|
|
958
989
|
return { code: ran.code, ...streams };
|
|
959
990
|
}
|
|
960
991
|
// ../kit/src/cli.ts
|
|
961
|
-
import { readFileSync as
|
|
992
|
+
import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
|
|
962
993
|
import { dirname as dirname3, join as join5 } from "path";
|
|
994
|
+
import process15 from "process";
|
|
995
|
+
|
|
996
|
+
// ../kit/src/completions.ts
|
|
997
|
+
var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
|
|
998
|
+
var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
|
|
999
|
+
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
1000
|
+
set -l current (commandline -ct)
|
|
1001
|
+
for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
|
|
1002
|
+
if test "$line" = __files__
|
|
1003
|
+
__fish_complete_path $current
|
|
1004
|
+
else
|
|
1005
|
+
echo $line
|
|
1006
|
+
end
|
|
1007
|
+
end
|
|
1008
|
+
end`;
|
|
1009
|
+
var BASH_FUNCTION = `__kaynooo_cli_complete() {
|
|
1010
|
+
local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
|
|
1011
|
+
local -a lines
|
|
1012
|
+
COMPREPLY=()
|
|
1013
|
+
lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
|
|
1014
|
+
for line in "\${lines[@]}"; do
|
|
1015
|
+
if [[ $line == __files__ ]]; then
|
|
1016
|
+
COMPREPLY+=($(compgen -f -- "$cur"))
|
|
1017
|
+
else
|
|
1018
|
+
words+="\${line%%$'\\t'*}"$'\\n'
|
|
1019
|
+
fi
|
|
1020
|
+
done
|
|
1021
|
+
COMPREPLY+=($(compgen -W "$words" -- "$cur"))
|
|
1022
|
+
}`;
|
|
1023
|
+
var ZSH_FUNCTION = `__kaynooo_cli_complete() {
|
|
1024
|
+
local line
|
|
1025
|
+
local -a described plain
|
|
1026
|
+
for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
|
|
1027
|
+
if [[ $line == __files__ ]]; then
|
|
1028
|
+
_files
|
|
1029
|
+
elif [[ $line == *$'\\t'* ]]; then
|
|
1030
|
+
described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
|
|
1031
|
+
else
|
|
1032
|
+
plain+=("$line")
|
|
1033
|
+
fi
|
|
1034
|
+
done
|
|
1035
|
+
(( \${#described} )) && _describe -V value described
|
|
1036
|
+
(( \${#plain} )) && compadd -- "\${plain[@]}"
|
|
1037
|
+
return 0
|
|
1038
|
+
}`;
|
|
1039
|
+
function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
|
|
1040
|
+
if (shell === "fish")
|
|
1041
|
+
return `${header}
|
|
1042
|
+
${FISH_FUNCTION}
|
|
1043
|
+
${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
1044
|
+
`).join("")}`;
|
|
1045
|
+
if (shell === "bash")
|
|
1046
|
+
return `${header}
|
|
1047
|
+
${BASH_FUNCTION}
|
|
1048
|
+
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
1049
|
+
`;
|
|
1050
|
+
return `${header}
|
|
1051
|
+
${ZSH_FUNCTION}
|
|
1052
|
+
compdef __kaynooo_cli_complete ${bins.join(" ")}
|
|
1053
|
+
`;
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
// ../kit/src/notify.ts
|
|
963
1057
|
import process13 from "process";
|
|
1058
|
+
var NOTIFY_AFTER_MS = 1e4;
|
|
1059
|
+
var CANCELLED = 130;
|
|
1060
|
+
function base64(text) {
|
|
1061
|
+
return Buffer.from(text).toString("base64");
|
|
1062
|
+
}
|
|
1063
|
+
function notification(title, body, env = process13.env) {
|
|
1064
|
+
const id = `kit${process13.pid}`;
|
|
1065
|
+
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\\`];
|
|
1066
|
+
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
1067
|
+
}
|
|
1068
|
+
function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
|
|
1069
|
+
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
1070
|
+
return;
|
|
1071
|
+
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
1072
|
+
}
|
|
964
1073
|
|
|
965
1074
|
// ../kit/src/usage.ts
|
|
966
1075
|
import { appendFileSync, mkdirSync } from "fs";
|
|
967
1076
|
import { homedir as homedir3 } from "os";
|
|
968
1077
|
import { dirname as dirname2, isAbsolute, join as join4 } from "path";
|
|
969
|
-
import
|
|
1078
|
+
import process14 from "process";
|
|
970
1079
|
|
|
971
1080
|
// ../kit/src/logs.ts
|
|
972
1081
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
@@ -980,14 +1089,14 @@ var usageError;
|
|
|
980
1089
|
function noteUsageError(message) {
|
|
981
1090
|
usageError = message;
|
|
982
1091
|
}
|
|
983
|
-
function stateHome(env =
|
|
1092
|
+
function stateHome(env = process14.env) {
|
|
984
1093
|
const dir = env.XDG_STATE_HOME;
|
|
985
1094
|
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
986
1095
|
}
|
|
987
|
-
function usagePath(env =
|
|
1096
|
+
function usagePath(env = process14.env) {
|
|
988
1097
|
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
989
1098
|
}
|
|
990
|
-
function usageRecorded(env =
|
|
1099
|
+
function usageRecorded(env = process14.env) {
|
|
991
1100
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
992
1101
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
993
1102
|
}
|
|
@@ -1001,7 +1110,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
1001
1110
|
usageError = undefined;
|
|
1002
1111
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
1003
1112
|
}
|
|
1004
|
-
function recordUsage(entry, env =
|
|
1113
|
+
function recordUsage(entry, env = process14.env) {
|
|
1005
1114
|
if (!usageRecorded(env))
|
|
1006
1115
|
return;
|
|
1007
1116
|
try {
|
|
@@ -1017,7 +1126,11 @@ var LEVEL_OPTIONS = {
|
|
|
1017
1126
|
...OUTPUT_OPTIONS,
|
|
1018
1127
|
help: { type: "boolean", short: "h", description: "show this help" }
|
|
1019
1128
|
};
|
|
1020
|
-
var TOP_OPTIONS = {
|
|
1129
|
+
var TOP_OPTIONS = {
|
|
1130
|
+
...LEVEL_OPTIONS,
|
|
1131
|
+
version: { type: "boolean", short: "v", description: "print the version" },
|
|
1132
|
+
completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
|
|
1133
|
+
};
|
|
1021
1134
|
async function commandRows(all, colors) {
|
|
1022
1135
|
const commands = shown(all);
|
|
1023
1136
|
const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
|
|
@@ -1078,7 +1191,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
|
|
|
1078
1191
|
header(colors, summary),
|
|
1079
1192
|
"",
|
|
1080
1193
|
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
1081
|
-
...replacesRows(replaces, colors),
|
|
1082
1194
|
"",
|
|
1083
1195
|
...await commandRows(commands, colors),
|
|
1084
1196
|
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
@@ -1092,8 +1204,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
|
|
|
1092
1204
|
`);
|
|
1093
1205
|
}
|
|
1094
1206
|
function printError(prefix, message, hint, cause) {
|
|
1095
|
-
const colors = paint(
|
|
1096
|
-
const styled = takesControlCodes(
|
|
1207
|
+
const colors = paint(process15.stderr);
|
|
1208
|
+
const styled = takesControlCodes(process15.stderr);
|
|
1097
1209
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
1098
1210
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
1099
1211
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -1136,11 +1248,11 @@ async function dispatch(level, typed, { version, redact }) {
|
|
|
1136
1248
|
}
|
|
1137
1249
|
}
|
|
1138
1250
|
if (name === undefined && level.path.length > 1) {
|
|
1139
|
-
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
1251
|
+
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stderr));
|
|
1140
1252
|
return 2;
|
|
1141
1253
|
}
|
|
1142
1254
|
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
1143
|
-
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
1255
|
+
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stdout));
|
|
1144
1256
|
return 0;
|
|
1145
1257
|
}
|
|
1146
1258
|
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
@@ -1196,24 +1308,24 @@ function candidateLine(candidate) {
|
|
|
1196
1308
|
}
|
|
1197
1309
|
function positionalBeingTyped(before, { options, positionals }) {
|
|
1198
1310
|
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
1199
|
-
|
|
1311
|
+
const typed = [];
|
|
1200
1312
|
let at = 0;
|
|
1201
1313
|
while (at < before.length) {
|
|
1202
1314
|
const word = before[at];
|
|
1203
1315
|
if (word === "--") {
|
|
1204
|
-
|
|
1316
|
+
typed.push(...before.slice(at + 1));
|
|
1205
1317
|
break;
|
|
1206
1318
|
}
|
|
1207
1319
|
if (!word.startsWith("-"))
|
|
1208
|
-
|
|
1320
|
+
typed.push(word);
|
|
1209
1321
|
else if (takesValue(word))
|
|
1210
1322
|
at++;
|
|
1211
1323
|
at++;
|
|
1212
1324
|
}
|
|
1213
1325
|
const last = positionals.at(-1);
|
|
1214
|
-
if (
|
|
1215
|
-
return positionals[
|
|
1216
|
-
return last?.replace("]", "").endsWith("...") === true ? last : undefined;
|
|
1326
|
+
if (typed.length < positionals.length)
|
|
1327
|
+
return { name: positionals[typed.length], typed };
|
|
1328
|
+
return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
|
|
1217
1329
|
}
|
|
1218
1330
|
async function leafCandidates(run, words) {
|
|
1219
1331
|
const completing = await completingOf(run);
|
|
@@ -1221,12 +1333,12 @@ async function leafCandidates(run, words) {
|
|
|
1221
1333
|
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
1222
1334
|
const flag = words.at(-2);
|
|
1223
1335
|
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
1336
|
+
const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
|
|
1224
1337
|
if (option?.type === "string") {
|
|
1225
|
-
const values = option.choices === undefined ? await option.candidates?.() : option.choices;
|
|
1338
|
+
const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
|
|
1226
1339
|
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1227
1340
|
}
|
|
1228
|
-
const
|
|
1229
|
-
const values = name === undefined ? undefined : await completing.candidates[name]?.();
|
|
1341
|
+
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
1230
1342
|
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1231
1343
|
}
|
|
1232
1344
|
async function candidates(scope, defaultCommand, words, before = []) {
|
|
@@ -1251,15 +1363,32 @@ async function candidates(scope, defaultCommand, words, before = []) {
|
|
|
1251
1363
|
}
|
|
1252
1364
|
return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
|
|
1253
1365
|
}
|
|
1366
|
+
var COMPLETIONS = "--completions";
|
|
1367
|
+
function flagValue([flag = "", ...rest]) {
|
|
1368
|
+
return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
|
|
1369
|
+
}
|
|
1370
|
+
function printCompletionScript(name, args) {
|
|
1371
|
+
const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
|
|
1372
|
+
if (shell === undefined || args.length !== 1) {
|
|
1373
|
+
printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
|
|
1374
|
+
return 2;
|
|
1375
|
+
}
|
|
1376
|
+
console.log(completionScript(shell, [name]).trimEnd());
|
|
1377
|
+
return 0;
|
|
1378
|
+
}
|
|
1254
1379
|
async function printCandidates(found) {
|
|
1255
1380
|
for (const line of await found)
|
|
1256
1381
|
console.log(line);
|
|
1257
1382
|
return 0;
|
|
1258
1383
|
}
|
|
1259
1384
|
function packageVersion(entry = Bun.main) {
|
|
1260
|
-
|
|
1385
|
+
let resolved = entry;
|
|
1386
|
+
try {
|
|
1387
|
+
resolved = realpathSync2(entry);
|
|
1388
|
+
} catch {}
|
|
1389
|
+
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
1261
1390
|
try {
|
|
1262
|
-
const { version } = JSON.parse(
|
|
1391
|
+
const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
|
|
1263
1392
|
if (typeof version === "string")
|
|
1264
1393
|
return version;
|
|
1265
1394
|
} catch {}
|
|
@@ -1267,14 +1396,19 @@ function packageVersion(entry = Bun.main) {
|
|
|
1267
1396
|
return "0.0.0";
|
|
1268
1397
|
}
|
|
1269
1398
|
}
|
|
1270
|
-
async function runCli(cli, argv =
|
|
1399
|
+
async function runCli(cli, argv = scriptArgs()) {
|
|
1271
1400
|
const version = cli.version ?? packageVersion();
|
|
1272
1401
|
if (argv[0] === COMPLETE)
|
|
1273
1402
|
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
1403
|
+
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
1404
|
+
return printCompletionScript(cli.name, flagValue(argv));
|
|
1405
|
+
const started = performance.now();
|
|
1274
1406
|
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 });
|
|
1407
|
+
const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
|
|
1408
|
+
notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
|
|
1275
1409
|
if (cli.usage !== false) {
|
|
1276
1410
|
try {
|
|
1277
|
-
recordUsage(usageEntry(cli.name,
|
|
1411
|
+
recordUsage(usageEntry(cli.name, command, argv, code));
|
|
1278
1412
|
} catch {}
|
|
1279
1413
|
}
|
|
1280
1414
|
return code;
|
|
@@ -1294,19 +1428,23 @@ function commandPath(scope, argv) {
|
|
|
1294
1428
|
}
|
|
1295
1429
|
return path.length === 0 ? undefined : path.join(" ");
|
|
1296
1430
|
}
|
|
1297
|
-
async function runMain({ name, version, run, redact, usage }, argv =
|
|
1431
|
+
async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
|
|
1298
1432
|
if (argv[0] === COMPLETE)
|
|
1299
1433
|
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
1434
|
+
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
1435
|
+
return printCompletionScript(name, flagValue(argv));
|
|
1300
1436
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
1301
1437
|
console.log(version ?? packageVersion());
|
|
1302
1438
|
return 0;
|
|
1303
1439
|
}
|
|
1304
1440
|
let code;
|
|
1441
|
+
const started = performance.now();
|
|
1305
1442
|
try {
|
|
1306
1443
|
code = await run(argv);
|
|
1307
1444
|
} catch (error) {
|
|
1308
1445
|
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
1309
1446
|
}
|
|
1447
|
+
notifyEnd(name, code, performance.now() - started);
|
|
1310
1448
|
if (usage !== false) {
|
|
1311
1449
|
try {
|
|
1312
1450
|
recordUsage(usageEntry(name, undefined, argv, code));
|
|
@@ -1346,7 +1484,7 @@ function parseSize(text, bareUnit = 1) {
|
|
|
1346
1484
|
return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
|
|
1347
1485
|
}
|
|
1348
1486
|
// ../kit/src/watch.ts
|
|
1349
|
-
import
|
|
1487
|
+
import process16 from "process";
|
|
1350
1488
|
import { format } from "util";
|
|
1351
1489
|
var CLEAR_SCREEN = "\x1B[H\x1B[2J";
|
|
1352
1490
|
var DEFAULT_SECONDS = 2;
|
|
@@ -1368,7 +1506,7 @@ function withoutWatch(args) {
|
|
|
1368
1506
|
}
|
|
1369
1507
|
return rest;
|
|
1370
1508
|
}
|
|
1371
|
-
async function watching(value, step, stream =
|
|
1509
|
+
async function watching(value, step, stream = process16.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
|
|
1372
1510
|
const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
|
|
1373
1511
|
if (!takesControlCodes(stream))
|
|
1374
1512
|
badUsage("--watch redraws the screen, so it needs a terminal");
|
|
@@ -1376,12 +1514,12 @@ async function watching(value, step, stream = process14.stdout, sleep = Bun.slee
|
|
|
1376
1514
|
for (let round = 0;round < rounds; round++) {
|
|
1377
1515
|
const held = [];
|
|
1378
1516
|
const { log, info } = console;
|
|
1379
|
-
const write =
|
|
1517
|
+
const write = process16.stdout.write.bind(process16.stdout);
|
|
1380
1518
|
const hold = (...parts) => void held.push(`${format(...parts)}
|
|
1381
1519
|
`);
|
|
1382
1520
|
console.log = hold;
|
|
1383
1521
|
console.info = hold;
|
|
1384
|
-
|
|
1522
|
+
process16.stdout.write = (text) => {
|
|
1385
1523
|
held.push(typeof text === "string" ? text : Buffer.from(text).toString());
|
|
1386
1524
|
return true;
|
|
1387
1525
|
};
|
|
@@ -1390,7 +1528,7 @@ async function watching(value, step, stream = process14.stdout, sleep = Bun.slee
|
|
|
1390
1528
|
} finally {
|
|
1391
1529
|
console.log = log;
|
|
1392
1530
|
console.info = info;
|
|
1393
|
-
|
|
1531
|
+
process16.stdout.write = write;
|
|
1394
1532
|
}
|
|
1395
1533
|
stream.write(`${CLEAR_SCREEN}${held.join("")}`);
|
|
1396
1534
|
await sleep(interval);
|
|
@@ -1399,8 +1537,8 @@ async function watching(value, step, stream = process14.stdout, sleep = Bun.slee
|
|
|
1399
1537
|
}
|
|
1400
1538
|
// ../kit/src/workspace-root.ts
|
|
1401
1539
|
import { homedir as homedir4 } from "os";
|
|
1402
|
-
import { dirname as dirname4, join as join6, resolve as
|
|
1403
|
-
import
|
|
1540
|
+
import { dirname as dirname4, join as join6, resolve as resolve4 } from "path";
|
|
1541
|
+
import process17 from "process";
|
|
1404
1542
|
function expandHome(path, home) {
|
|
1405
1543
|
if (path === "~")
|
|
1406
1544
|
return home;
|
|
@@ -1410,18 +1548,22 @@ function configured(env, home) {
|
|
|
1410
1548
|
const folder = readUserConfig("config", { home, xdg: env.XDG_CONFIG_HOME }).workspace;
|
|
1411
1549
|
return typeof folder === "string" && folder !== "" ? folder : undefined;
|
|
1412
1550
|
}
|
|
1413
|
-
function workspaceRoot({ given, env =
|
|
1551
|
+
function workspaceRoot({ given, env = process17.env, home = homedir4() } = {}) {
|
|
1414
1552
|
const fromEnv = env.KAYNOOO_WORKSPACE === "" ? undefined : env.KAYNOOO_WORKSPACE;
|
|
1415
|
-
return
|
|
1553
|
+
return resolve4(expandHome(given ?? fromEnv ?? configured(env, home) ?? join6(home, "Workspace"), home));
|
|
1416
1554
|
}
|
|
1417
1555
|
// src/audit.ts
|
|
1418
|
-
import { existsSync as
|
|
1556
|
+
import { existsSync as existsSync6, readdirSync, readFileSync as readFileSync7, statSync as statSync2 } from "fs";
|
|
1419
1557
|
import { readdir } from "fs/promises";
|
|
1420
|
-
import { join as
|
|
1421
|
-
import
|
|
1558
|
+
import { join as join9, relative, resolve as resolve5 } from "path";
|
|
1559
|
+
import process19 from "process";
|
|
1560
|
+
|
|
1561
|
+
// src/osv.ts
|
|
1562
|
+
import { existsSync as existsSync5, readFileSync as readFileSync6 } from "fs";
|
|
1563
|
+
import { join as join8 } from "path";
|
|
1422
1564
|
|
|
1423
1565
|
// src/report.ts
|
|
1424
|
-
import { existsSync as existsSync4, readFileSync as
|
|
1566
|
+
import { existsSync as existsSync4, readFileSync as readFileSync5 } from "fs";
|
|
1425
1567
|
import { join as join7 } from "path";
|
|
1426
1568
|
var UPPER_BOUND = /<\s*(\d[\w.+-]*)/;
|
|
1427
1569
|
var DEPENDENCY_KINDS = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"];
|
|
@@ -1505,7 +1647,7 @@ function reachedFrom(graph, direct, targets) {
|
|
|
1505
1647
|
}
|
|
1506
1648
|
function readManifest(path) {
|
|
1507
1649
|
try {
|
|
1508
|
-
return existsSync4(path) ? JSON.parse(
|
|
1650
|
+
return existsSync4(path) ? JSON.parse(readFileSync5(path, "utf8")) : {};
|
|
1509
1651
|
} catch {
|
|
1510
1652
|
return {};
|
|
1511
1653
|
}
|
|
@@ -1535,14 +1677,121 @@ function workspaceFolders(root, children) {
|
|
|
1535
1677
|
return patterns.filter((pattern) => typeof pattern === "string").flatMap((pattern) => pattern.endsWith("/*") ? children(pattern.slice(0, -2)).map((name) => join7(pattern.slice(0, -2), name)) : [pattern]);
|
|
1536
1678
|
}
|
|
1537
1679
|
|
|
1680
|
+
// src/osv.ts
|
|
1681
|
+
var OSV = "https://api.osv.dev/v1";
|
|
1682
|
+
var BATCH = 1000;
|
|
1683
|
+
var DETAIL_CONCURRENCY = 8;
|
|
1684
|
+
var TIMEOUT_MS = 20000;
|
|
1685
|
+
var PACKAGE_BLOCK = /^\[\[package\]\]\s*$/m;
|
|
1686
|
+
var FIELD = /^(name|version|source) = (.+)$/gm;
|
|
1687
|
+
var QUOTED = /^"([^"]*)"$/;
|
|
1688
|
+
var LEADING_V = /^v/;
|
|
1689
|
+
function parseComposerLock(text) {
|
|
1690
|
+
const lock = JSON.parse(text);
|
|
1691
|
+
const entry = (prod) => (each) => ({ name: each.name, version: each.version.replace(LEADING_V, ""), prod });
|
|
1692
|
+
return [...(lock.packages ?? []).map(entry(true)), ...(lock["packages-dev"] ?? []).map(entry(false))];
|
|
1693
|
+
}
|
|
1694
|
+
function tomlPackages(text, fromRegistry) {
|
|
1695
|
+
const found = [];
|
|
1696
|
+
for (const block of text.split(PACKAGE_BLOCK).slice(1)) {
|
|
1697
|
+
const fields = new Map;
|
|
1698
|
+
for (const [, key, value] of block.matchAll(FIELD))
|
|
1699
|
+
fields.set(key, QUOTED.exec(value.trim())?.[1] ?? value.trim());
|
|
1700
|
+
const source = fields.get("source");
|
|
1701
|
+
const name = fields.get("name");
|
|
1702
|
+
const version = fields.get("version");
|
|
1703
|
+
if (name !== undefined && version !== undefined && source !== undefined && fromRegistry(source))
|
|
1704
|
+
found.push({ name, version, prod: true });
|
|
1705
|
+
}
|
|
1706
|
+
return found;
|
|
1707
|
+
}
|
|
1708
|
+
function parseCargoLock(text) {
|
|
1709
|
+
return tomlPackages(text, (source) => source.startsWith("registry+"));
|
|
1710
|
+
}
|
|
1711
|
+
function parseUvLock(text) {
|
|
1712
|
+
return tomlPackages(text, (source) => source.includes("registry"));
|
|
1713
|
+
}
|
|
1714
|
+
var ECOSYSTEMS = [
|
|
1715
|
+
{ lockfile: "composer.lock", osv: "Packagist", parse: parseComposerLock },
|
|
1716
|
+
{ lockfile: "Cargo.lock", osv: "crates.io", parse: parseCargoLock },
|
|
1717
|
+
{ lockfile: "uv.lock", osv: "PyPI", parse: parseUvLock }
|
|
1718
|
+
];
|
|
1719
|
+
function holdsOsvLock(dir) {
|
|
1720
|
+
return ECOSYSTEMS.some((each) => existsSync5(join8(dir, each.lockfile)));
|
|
1721
|
+
}
|
|
1722
|
+
var SEVERITY_NAMES = { LOW: "low", MODERATE: "moderate", MEDIUM: "moderate", HIGH: "high", CRITICAL: "critical" };
|
|
1723
|
+
async function ok2(response) {
|
|
1724
|
+
if (!response.ok)
|
|
1725
|
+
throw new Error(`osv.dev answered ${response.status}`);
|
|
1726
|
+
return response.json();
|
|
1727
|
+
}
|
|
1728
|
+
function rowOf(vuln, name) {
|
|
1729
|
+
const fixes = (vuln.affected ?? []).filter((each) => each.package?.name === name).flatMap((each) => each.ranges ?? []).flatMap((range) => range.events ?? []).map((event) => event.fixed).filter((fixed) => fixed !== undefined);
|
|
1730
|
+
return { id: 0, ghsa: vuln.id, url: `https://osv.dev/vulnerability/${vuln.id}`, title: vuln.summary ?? vuln.id, severity: SEVERITY_NAMES[vuln.database_specific?.severity?.toUpperCase() ?? ""] ?? "moderate", fixed: fixes.length === 0 ? undefined : fixedAt(fixes.map((fix) => `<${fix}`).join(" || ")) };
|
|
1731
|
+
}
|
|
1732
|
+
async function osvFindings(locked, ecosystem, direct, level, ignore, fetcher = fetch) {
|
|
1733
|
+
const hits = new Map;
|
|
1734
|
+
for (let start = 0;start < locked.length; start += BATCH) {
|
|
1735
|
+
const chunk = locked.slice(start, start + BATCH);
|
|
1736
|
+
const queries = chunk.map((each) => ({ package: { name: each.name, ecosystem }, version: each.version }));
|
|
1737
|
+
const answer = await ok2(await fetcher(`${OSV}/querybatch`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ queries }), signal: AbortSignal.timeout(TIMEOUT_MS) }));
|
|
1738
|
+
for (const [index, each] of chunk.entries()) {
|
|
1739
|
+
const ids = (answer.results[index]?.vulns ?? []).map((vuln) => vuln.id).filter((id) => !ignore.includes(id));
|
|
1740
|
+
if (ids.length > 0)
|
|
1741
|
+
hits.set(each, ids);
|
|
1742
|
+
}
|
|
1743
|
+
}
|
|
1744
|
+
const details = new Map;
|
|
1745
|
+
await pool([...new Set([...hits.values()].flat())], DETAIL_CONCURRENCY, async (id) => {
|
|
1746
|
+
details.set(id, await ok2(await fetcher(`${OSV}/vulns/${encodeURIComponent(id)}`, { signal: AbortSignal.timeout(TIMEOUT_MS) })));
|
|
1747
|
+
});
|
|
1748
|
+
const findings = [];
|
|
1749
|
+
let below = 0;
|
|
1750
|
+
for (const [each, ids] of hits) {
|
|
1751
|
+
const rows = ids.map((id) => rowOf(details.get(id), each.name));
|
|
1752
|
+
const advisories = rows.filter((row) => severityRank(row.severity) >= severityRank(level));
|
|
1753
|
+
below += rows.length - advisories.length;
|
|
1754
|
+
if (advisories.length === 0)
|
|
1755
|
+
continue;
|
|
1756
|
+
const fixes = advisories.map((row) => row.fixed);
|
|
1757
|
+
findings.push({
|
|
1758
|
+
package: each.name,
|
|
1759
|
+
severity: advisories.reduce((worst, row) => severityRank(row.severity) > severityRank(worst) ? row.severity : worst, advisories[0].severity),
|
|
1760
|
+
advisories,
|
|
1761
|
+
scope: each.prod ? "prod" : "dev",
|
|
1762
|
+
direct: direct.has(each.name),
|
|
1763
|
+
via: [],
|
|
1764
|
+
fix: fixes.includes(undefined) ? undefined : fixes.reduce((highest, fix) => Bun.semver.order(fix, highest) > 0 ? fix : highest)
|
|
1765
|
+
});
|
|
1766
|
+
}
|
|
1767
|
+
return { findings: findings.toSorted((a, b) => severityRank(b.severity) - severityRank(a.severity) || Number(b.scope === "prod") - Number(a.scope === "prod") || a.package.localeCompare(b.package)), below };
|
|
1768
|
+
}
|
|
1769
|
+
function manifestNames(dir) {
|
|
1770
|
+
try {
|
|
1771
|
+
const manifest = JSON.parse(readFileSync6(join8(dir, "composer.json"), "utf8"));
|
|
1772
|
+
return new Set([...Object.keys(manifest.require ?? {}), ...Object.keys(manifest["require-dev"] ?? {})]);
|
|
1773
|
+
} catch {
|
|
1774
|
+
return new Set;
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
async function osvAudit(dir, level, ignore, fetcher = fetch) {
|
|
1778
|
+
const all = { findings: [], below: 0 };
|
|
1779
|
+
for (const each of ECOSYSTEMS.filter((each) => existsSync5(join8(dir, each.lockfile)))) {
|
|
1780
|
+
const done = await osvFindings(each.parse(readFileSync6(join8(dir, each.lockfile), "utf8")), each.osv, each.lockfile === "composer.lock" ? manifestNames(dir) : new Set, level, ignore, fetcher);
|
|
1781
|
+
all.findings.push(...done.findings);
|
|
1782
|
+
all.below += done.below;
|
|
1783
|
+
}
|
|
1784
|
+
return all;
|
|
1785
|
+
}
|
|
1786
|
+
|
|
1538
1787
|
// src/audit.ts
|
|
1539
|
-
var USAGE = `audit [options] [root]: the known vulnerabilities of the Bun repositories under root (the current folder by default), one table per repository
|
|
1788
|
+
var USAGE = `audit [options] [root]: the known vulnerabilities of the Bun, Composer, Cargo and uv repositories under root (the current folder by default), one table per repository
|
|
1540
1789
|
|
|
1541
1790
|
Each package with an advisory is one row: its worst severity, how many advisories, whether a production dependency needs it (prod) or only a development one (dev), whether the repository asks for it itself (direct) or a dependency does (the row then says via and the direct dependencies leading to it, upgrading one of which is what fixes it), and the version that fixes every advisory at once, "-" when an advisory names none. The worst and the production ones come first.
|
|
1542
|
-
Advisories under --level (moderate by default) are counted under the table, and what \`bun audit\` warned about, such as a private registry that would not audit its packages, is repeated there. It runs \`bun audit --json\` in each repository holding a bun.lock, which reaches the registry; the walk goes three levels deep, stops at a
|
|
1791
|
+
Advisories under --level (moderate by default) are counted under the table, and what \`bun audit\` warned about, such as a private registry that would not audit its packages, is repeated there. It runs \`bun audit --json\` in each repository holding a bun.lock, which reaches the registry, and asks osv.dev about the packages of a composer.lock, Cargo.lock or uv.lock (a severity the source leaves out reads as moderate, and only composer's manifest tells direct from pulled in); the walk goes three levels deep, stops at a lockfile and skips node_modules and hidden folders.
|
|
1543
1792
|
|
|
1544
1793
|
Reach for it to sweep many repositories at once; \`pkg audit\` vets the one repository in a folder (package age, install scripts, licences) as well as its advisories, and shares --level, --prod and --ignore.`;
|
|
1545
|
-
var EXITS = [[0, "no repository has an advisory at the level asked"], [1, "one has"], [2, "a repository's audit failed, no
|
|
1794
|
+
var EXITS = [[0, "no repository has an advisory at the level asked"], [1, "one has"], [2, "a repository's audit failed, no lockfile sits under root, a usage error or a root that is no folder"]];
|
|
1546
1795
|
var OPTIONS = {
|
|
1547
1796
|
level: { type: "string", choices: SEVERITIES, default: "moderate", description: "only the advisories at least this severe: low, moderate, high or critical" },
|
|
1548
1797
|
prod: { type: "boolean", description: "only the packages a production dependency needs" },
|
|
@@ -1557,8 +1806,11 @@ var VIA_SHOWN = 2;
|
|
|
1557
1806
|
function countAdvisories(findings) {
|
|
1558
1807
|
return findings.reduce((sum, found) => sum + found.advisories.length, 0);
|
|
1559
1808
|
}
|
|
1809
|
+
function holdsBunLock(dir) {
|
|
1810
|
+
return existsSync6(join9(dir, "bun.lock")) || existsSync6(join9(dir, "bun.lockb"));
|
|
1811
|
+
}
|
|
1560
1812
|
function holdsLock(dir) {
|
|
1561
|
-
return
|
|
1813
|
+
return holdsBunLock(dir) || holdsOsvLock(dir);
|
|
1562
1814
|
}
|
|
1563
1815
|
async function findRepos(root) {
|
|
1564
1816
|
if (holdsLock(root))
|
|
@@ -1574,7 +1826,7 @@ async function findRepos(root) {
|
|
|
1574
1826
|
for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
|
|
1575
1827
|
if (!entry.isDirectory() || entry.name === "node_modules" || entry.name.startsWith("."))
|
|
1576
1828
|
continue;
|
|
1577
|
-
const path =
|
|
1829
|
+
const path = join9(dir, entry.name);
|
|
1578
1830
|
if (holdsLock(path))
|
|
1579
1831
|
found.push(path);
|
|
1580
1832
|
else if (depth < MAX_DEPTH)
|
|
@@ -1587,13 +1839,24 @@ async function findRepos(root) {
|
|
|
1587
1839
|
function children(root) {
|
|
1588
1840
|
return (folder) => {
|
|
1589
1841
|
try {
|
|
1590
|
-
return readdirSync(
|
|
1842
|
+
return readdirSync(join9(root, folder), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
|
|
1591
1843
|
} catch {
|
|
1592
1844
|
return [];
|
|
1593
1845
|
}
|
|
1594
1846
|
};
|
|
1595
1847
|
}
|
|
1596
1848
|
async function audited(path, shown, level, ignore) {
|
|
1849
|
+
const bun = holdsBunLock(path) ? await bunAudited(path, shown, level, ignore) : { repo: shown, path, findings: [], below: 0, warnings: [], error: undefined };
|
|
1850
|
+
if (bun.error !== undefined || !holdsOsvLock(path))
|
|
1851
|
+
return bun;
|
|
1852
|
+
try {
|
|
1853
|
+
const osv = await osvAudit(path, level, ignore);
|
|
1854
|
+
return { ...bun, findings: [...bun.findings, ...osv.findings], below: bun.below + osv.below };
|
|
1855
|
+
} catch (error) {
|
|
1856
|
+
return { ...bun, error: `osv.dev: ${error instanceof Error ? error.message : String(error)}` };
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
async function bunAudited(path, shown, level, ignore) {
|
|
1597
1860
|
const [all, production] = await Promise.all([
|
|
1598
1861
|
runCommand(["bun", "audit", "--json"], { cwd: path, timeoutMs: AUDIT_MS }),
|
|
1599
1862
|
runCommand(["bun", "audit", "--json", "--prod"], { cwd: path, timeoutMs: AUDIT_MS })
|
|
@@ -1610,7 +1873,7 @@ async function audited(path, shown, level, ignore) {
|
|
|
1610
1873
|
}
|
|
1611
1874
|
function lockText(path) {
|
|
1612
1875
|
try {
|
|
1613
|
-
return
|
|
1876
|
+
return readFileSync7(join9(path, "bun.lock"), "utf8");
|
|
1614
1877
|
} catch {
|
|
1615
1878
|
return "";
|
|
1616
1879
|
}
|
|
@@ -1630,7 +1893,7 @@ function failure(ran) {
|
|
|
1630
1893
|
`).at(-1) ?? `exit ${ran.code}`;
|
|
1631
1894
|
}
|
|
1632
1895
|
function tint(severity) {
|
|
1633
|
-
const colors = paint(
|
|
1896
|
+
const colors = paint(process19.stdout);
|
|
1634
1897
|
if (severity === "critical" || severity === "high")
|
|
1635
1898
|
return colors.red;
|
|
1636
1899
|
return severity === "moderate" ? colors.yellow : colors.dim;
|
|
@@ -1647,13 +1910,13 @@ function rows(findings) {
|
|
|
1647
1910
|
}
|
|
1648
1911
|
async function audit(args) {
|
|
1649
1912
|
const { values, positionals } = parse(args, USAGE, OPTIONS, { positionals: ["[root]"], exits: EXITS, replaces: "a bun audit run in each repository and a read of every advisory to find what is worth fixing", examples: ["audit", "audit ~/Workspace --level high --prod"] });
|
|
1650
|
-
const root =
|
|
1651
|
-
if (!
|
|
1913
|
+
const root = resolve5(positionals[0] ?? ".");
|
|
1914
|
+
if (!existsSync6(root) || !statSync2(root).isDirectory())
|
|
1652
1915
|
fail(`no folder ${root}`);
|
|
1653
1916
|
const level = oneOf(values.level, "level", SEVERITIES);
|
|
1654
1917
|
const paths = await findRepos(root);
|
|
1655
1918
|
if (paths.length === 0)
|
|
1656
|
-
fail(`no bun.lock under ${root}`);
|
|
1919
|
+
fail(`no bun.lock, composer.lock, Cargo.lock or uv.lock under ${root}`);
|
|
1657
1920
|
const audits = await pool(paths, configuredNumber("audit", "concurrency", CONCURRENCY), async (path) => audited(path, relative(root, path) || ".", level, values.ignore ?? []));
|
|
1658
1921
|
const kept = audits.map((each) => ({ ...each, findings: values.prod === true ? each.findings.filter((found) => found.scope === "prod") : each.findings }));
|
|
1659
1922
|
if (values.json === true)
|
|
@@ -1665,8 +1928,8 @@ async function audit(args) {
|
|
|
1665
1928
|
return kept.some((each) => each.findings.length > 0) ? 1 : 0;
|
|
1666
1929
|
}
|
|
1667
1930
|
function show(audits, total) {
|
|
1668
|
-
const label = role("label",
|
|
1669
|
-
const path = role("path",
|
|
1931
|
+
const label = role("label", process19.stdout);
|
|
1932
|
+
const path = role("path", process19.stdout);
|
|
1670
1933
|
const flagged = audits.filter((each) => each.error !== undefined || each.findings.length > 0);
|
|
1671
1934
|
if (flagged.length === 0) {
|
|
1672
1935
|
console.log(label(`no advisory in ${total} ${total === 1 ? "repository" : "repositories"}`));
|
|
@@ -1686,15 +1949,15 @@ function show(audits, total) {
|
|
|
1686
1949
|
}
|
|
1687
1950
|
|
|
1688
1951
|
// src/repos.ts
|
|
1689
|
-
import { existsSync as
|
|
1952
|
+
import { existsSync as existsSync8, statSync as statSync3 } from "fs";
|
|
1690
1953
|
import { basename as basename2, relative as relative2 } from "path";
|
|
1691
|
-
import
|
|
1954
|
+
import process21 from "process";
|
|
1692
1955
|
|
|
1693
1956
|
// src/repos-scan.ts
|
|
1694
|
-
import { existsSync as
|
|
1957
|
+
import { existsSync as existsSync7 } from "fs";
|
|
1695
1958
|
import { readdir as readdir2 } from "fs/promises";
|
|
1696
|
-
import { basename, join as
|
|
1697
|
-
import
|
|
1959
|
+
import { basename, join as join10 } from "path";
|
|
1960
|
+
import process20 from "process";
|
|
1698
1961
|
var MAX_DEPTH2 = 3;
|
|
1699
1962
|
var CONCURRENCY2 = 8;
|
|
1700
1963
|
var PACKAGE_CONCURRENCY = 4;
|
|
@@ -1716,7 +1979,7 @@ function reasonsOf(repo) {
|
|
|
1716
1979
|
return reasons;
|
|
1717
1980
|
}
|
|
1718
1981
|
async function findRepos2(root, skip) {
|
|
1719
|
-
if (
|
|
1982
|
+
if (existsSync7(join10(root, ".git")))
|
|
1720
1983
|
return [root];
|
|
1721
1984
|
const found = [];
|
|
1722
1985
|
async function walk(dir, depth) {
|
|
@@ -1729,8 +1992,8 @@ async function findRepos2(root, skip) {
|
|
|
1729
1992
|
for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
|
|
1730
1993
|
if (!entry.isDirectory() || entry.name === "node_modules" || entry.name.startsWith(".") || skip.has(entry.name))
|
|
1731
1994
|
continue;
|
|
1732
|
-
const path =
|
|
1733
|
-
if (
|
|
1995
|
+
const path = join10(dir, entry.name);
|
|
1996
|
+
if (existsSync7(join10(path, ".git")))
|
|
1734
1997
|
found.push(path);
|
|
1735
1998
|
else if (depth < MAX_DEPTH2)
|
|
1736
1999
|
await walk(path, depth + 1);
|
|
@@ -1741,7 +2004,7 @@ async function findRepos2(root, skip) {
|
|
|
1741
2004
|
}
|
|
1742
2005
|
async function read(path, args, timeoutMs = GIT_MS) {
|
|
1743
2006
|
try {
|
|
1744
|
-
const ran = await runCommand(["git", "--no-optional-locks", ...args], { cwd: path, env: { ...
|
|
2007
|
+
const ran = await runCommand(["git", "--no-optional-locks", ...args], { cwd: path, env: { ...process20.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs });
|
|
1745
2008
|
return ran.code === 0 && !ran.timedOut ? ran.text.trim() : undefined;
|
|
1746
2009
|
} catch {
|
|
1747
2010
|
return;
|
|
@@ -1760,14 +2023,14 @@ async function packageReleases(path) {
|
|
|
1760
2023
|
names.add(name);
|
|
1761
2024
|
}
|
|
1762
2025
|
const releases = await pool([...names].toSorted(), PACKAGE_CONCURRENCY, async (name) => {
|
|
1763
|
-
const folder = [
|
|
2026
|
+
const folder = [join10("packages", name), name].find((candidate) => existsSync7(join10(path, candidate)));
|
|
1764
2027
|
const tag = folder === undefined ? undefined : await read(path, ["describe", "--tags", "--abbrev=0", "--match", `${name}-v*`]);
|
|
1765
2028
|
return folder !== undefined && tag !== undefined && tag !== "" ? { name, tag, unreleased: await commitsSince(path, tag, folder) } : undefined;
|
|
1766
2029
|
});
|
|
1767
2030
|
return releases.filter((release) => release !== undefined);
|
|
1768
2031
|
}
|
|
1769
|
-
async function inspect(path,
|
|
1770
|
-
const fetched =
|
|
2032
|
+
async function inspect(path, fetch2) {
|
|
2033
|
+
const fetched = fetch2 ? await read(path, ["fetch", "--quiet"], FETCH_MS) : "";
|
|
1771
2034
|
const [status, worktrees, packages] = await Promise.all([
|
|
1772
2035
|
read(path, ["status", "--porcelain=v2", "--branch"]),
|
|
1773
2036
|
read(path, ["worktree", "list", "--porcelain"]),
|
|
@@ -1818,7 +2081,7 @@ function firstLine(text) {
|
|
|
1818
2081
|
}
|
|
1819
2082
|
async function fastForward(path) {
|
|
1820
2083
|
try {
|
|
1821
|
-
const ran = await runCommand(["git", "--no-optional-locks", "merge", "--ff-only", "--quiet", "@{upstream}"], { cwd: path, env: { ...
|
|
2084
|
+
const ran = await runCommand(["git", "--no-optional-locks", "merge", "--ff-only", "--quiet", "@{upstream}"], { cwd: path, env: { ...process20.env, GIT_TERMINAL_PROMPT: "0" }, timeoutMs: GIT_MS });
|
|
1822
2085
|
if (ran.timedOut)
|
|
1823
2086
|
return "timed out";
|
|
1824
2087
|
return ran.code === 0 ? undefined : firstLine(ran.text.trim()) || `exit ${ran.code}`;
|
|
@@ -1847,7 +2110,7 @@ var OPTIONS2 = {
|
|
|
1847
2110
|
};
|
|
1848
2111
|
async function skipped() {
|
|
1849
2112
|
const file = userConfigReadPath("repos");
|
|
1850
|
-
if (!
|
|
2113
|
+
if (!existsSync8(file))
|
|
1851
2114
|
return new Set;
|
|
1852
2115
|
try {
|
|
1853
2116
|
const config = await Bun.file(file).json();
|
|
@@ -1861,7 +2124,7 @@ function releasedCell(repo) {
|
|
|
1861
2124
|
return repo.packages.filter((release) => release.unreleased > 0).map((release) => `${release.name} ${release.unreleased}`).join(", ") || "-";
|
|
1862
2125
|
return repo.tag === null || repo.unreleased === 0 ? "-" : `${repo.unreleased} since ${repo.tag}`;
|
|
1863
2126
|
}
|
|
1864
|
-
function syncCell(repo, stream =
|
|
2127
|
+
function syncCell(repo, stream = process21.stdout) {
|
|
1865
2128
|
const colors = paint(stream);
|
|
1866
2129
|
const ahead = repo.ahead ?? 0;
|
|
1867
2130
|
const behind = repo.behind ?? 0;
|
|
@@ -1872,7 +2135,7 @@ function syncCell(repo, stream = process19.stdout) {
|
|
|
1872
2135
|
return parts.length === 0 ? colors.dim("-") : `${parts.join(" ")}${diverged ? colors.yellow(" diverged") : ""}`;
|
|
1873
2136
|
}
|
|
1874
2137
|
var DEFAULT_BRANCHES = new Set(["main", "master"]);
|
|
1875
|
-
function branchCell(repo, stream =
|
|
2138
|
+
function branchCell(repo, stream = process21.stdout) {
|
|
1876
2139
|
const colors = paint(stream);
|
|
1877
2140
|
if (repo.unreadable)
|
|
1878
2141
|
return colors.red("? (unreadable)");
|
|
@@ -1881,8 +2144,8 @@ function branchCell(repo, stream = process19.stdout) {
|
|
|
1881
2144
|
return DEFAULT_BRANCHES.has(repo.branch) ? repo.branch : role("accent", stream)(repo.branch);
|
|
1882
2145
|
}
|
|
1883
2146
|
function row(repo, shown) {
|
|
1884
|
-
const colors = paint(
|
|
1885
|
-
const tint = role("path",
|
|
2147
|
+
const colors = paint(process21.stdout);
|
|
2148
|
+
const tint = role("path", process21.stdout);
|
|
1886
2149
|
const unreleased = releasedCell(repo);
|
|
1887
2150
|
return [
|
|
1888
2151
|
tint(shown),
|
|
@@ -1898,9 +2161,9 @@ async function repos(args) {
|
|
|
1898
2161
|
if (values.watch !== undefined)
|
|
1899
2162
|
return watching(values.watch, async () => repos(withoutWatch(args)));
|
|
1900
2163
|
const root = workspaceRoot({ given: positionals[0] });
|
|
1901
|
-
if (!
|
|
2164
|
+
if (!existsSync8(root) || !statSync3(root).isDirectory())
|
|
1902
2165
|
fail(`no folder ${root}`);
|
|
1903
|
-
const only = values.only
|
|
2166
|
+
const only = values.only;
|
|
1904
2167
|
const paths = await findRepos2(root, await skipped());
|
|
1905
2168
|
const states = await pool(paths, configuredNumber("repos", "concurrency", CONCURRENCY2), async (path) => inspect(path, values.fetch === true || values.pull === true));
|
|
1906
2169
|
const keeps = (repo) => {
|
|
@@ -1916,12 +2179,12 @@ async function repos(args) {
|
|
|
1916
2179
|
const blocker = pullBlocker(repo);
|
|
1917
2180
|
const refused = blocker === undefined ? await fastForward(repo.path) : undefined;
|
|
1918
2181
|
if (blocker !== undefined) {
|
|
1919
|
-
log(marked("note", `${repo.name} skipped`,
|
|
2182
|
+
log(marked("note", `${repo.name} skipped`, process21.stdout, blocker));
|
|
1920
2183
|
} else if (refused !== undefined) {
|
|
1921
2184
|
failedPulls++;
|
|
1922
|
-
log(marked("problem", `${repo.name} not pulled`,
|
|
2185
|
+
log(marked("problem", `${repo.name} not pulled`, process21.stdout, refused));
|
|
1923
2186
|
} else {
|
|
1924
|
-
log(marked("ok", `${repo.name} pulled`,
|
|
2187
|
+
log(marked("ok", `${repo.name} pulled`, process21.stdout, `${repo.behind} ${repo.behind === 1 ? "commit" : "commits"}`));
|
|
1925
2188
|
states[index] = await inspect(repo.path, false);
|
|
1926
2189
|
}
|
|
1927
2190
|
}
|
|
@@ -1936,7 +2199,7 @@ async function repos(args) {
|
|
|
1936
2199
|
printJson(kept.map((repo) => ({ ...repo, reasons: reasonsOf(repo) })));
|
|
1937
2200
|
return failedPulls > 0 ? 1 : 0;
|
|
1938
2201
|
}
|
|
1939
|
-
const label = role("label",
|
|
2202
|
+
const label = role("label", process21.stdout);
|
|
1940
2203
|
printHeader("repos", `${basename2(root)} \xB7 ${states.length} ${states.length === 1 ? "repository" : "repositories"}`);
|
|
1941
2204
|
if (kept.length === 0) {
|
|
1942
2205
|
console.log(label(`nothing needs attention in ${states.length} repositories`));
|
|
@@ -1952,12 +2215,26 @@ async function repos(args) {
|
|
|
1952
2215
|
}
|
|
1953
2216
|
|
|
1954
2217
|
// src/sweep.ts
|
|
1955
|
-
import { existsSync as
|
|
2218
|
+
import { existsSync as existsSync11, statSync as statSync4 } from "fs";
|
|
1956
2219
|
import { homedir as homedir6 } from "os";
|
|
1957
2220
|
import { relative as relative3 } from "path";
|
|
1958
2221
|
|
|
1959
2222
|
// ../kit/src/prompt.ts
|
|
1960
|
-
import
|
|
2223
|
+
import process23 from "process";
|
|
2224
|
+
|
|
2225
|
+
// ../kit/src/job.ts
|
|
2226
|
+
import process22 from "process";
|
|
2227
|
+
function stopJob() {
|
|
2228
|
+
process22.kill(0, "SIGTSTP");
|
|
2229
|
+
}
|
|
2230
|
+
|
|
2231
|
+
// ../kit/src/picker/line.ts
|
|
2232
|
+
var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
|
|
2233
|
+
var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
|
|
2234
|
+
var FORWARD_KILLS = new Set(["killnext", "killend"]);
|
|
2235
|
+
function isEditKey(key) {
|
|
2236
|
+
return EDIT_KEYS.has(key);
|
|
2237
|
+
}
|
|
1961
2238
|
|
|
1962
2239
|
// ../kit/src/picker/score.ts
|
|
1963
2240
|
var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
|
|
@@ -1989,10 +2266,29 @@ var KEYS = {
|
|
|
1989
2266
|
"\n": "enter",
|
|
1990
2267
|
"\x03": "cancel",
|
|
1991
2268
|
"\x1B": "cancel",
|
|
2269
|
+
"\x1B[D": "left",
|
|
2270
|
+
"\x1BOD": "left",
|
|
2271
|
+
"\x1B[C": "right",
|
|
2272
|
+
"\x1BOC": "right",
|
|
2273
|
+
"\x1B[1;5D": "wordleft",
|
|
2274
|
+
"\x1B[1;3D": "wordleft",
|
|
2275
|
+
"\x1Bb": "wordleft",
|
|
2276
|
+
"\x1B[1;5C": "wordright",
|
|
2277
|
+
"\x1B[1;3C": "wordright",
|
|
2278
|
+
"\x1Bf": "wordright",
|
|
2279
|
+
"\x01": "linestart",
|
|
2280
|
+
"\x05": "lineend",
|
|
1992
2281
|
"\x7F": "erase",
|
|
1993
|
-
"\
|
|
2282
|
+
"\x1B[3~": "delete",
|
|
2283
|
+
"\b": "killword",
|
|
2284
|
+
"\x1B\x7F": "killword",
|
|
2285
|
+
"\x1B[3;5~": "killnext",
|
|
2286
|
+
"\x1Bd": "killnext",
|
|
1994
2287
|
"\x15": "clear",
|
|
2288
|
+
"\v": "killend",
|
|
1995
2289
|
"\x17": "word",
|
|
2290
|
+
"\x19": "yank",
|
|
2291
|
+
"\x1A": "suspend",
|
|
1996
2292
|
"\t": "tab",
|
|
1997
2293
|
"\x1F": "help",
|
|
1998
2294
|
"\x1BOP": "help",
|
|
@@ -2022,10 +2318,21 @@ function parseKeys(input, paste = { active: false }, ctrls = []) {
|
|
|
2022
2318
|
});
|
|
2023
2319
|
}
|
|
2024
2320
|
|
|
2321
|
+
// ../kit/src/redraw.ts
|
|
2322
|
+
var SYNC_START = "\x1B[?2026h";
|
|
2323
|
+
var SYNC_END = "\x1B[?2026l";
|
|
2324
|
+
function overwrite(lines, columns) {
|
|
2325
|
+
return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
|
|
2326
|
+
`);
|
|
2327
|
+
}
|
|
2328
|
+
function rowsTaken(lines, columns) {
|
|
2329
|
+
return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
|
|
2330
|
+
}
|
|
2331
|
+
|
|
2025
2332
|
// ../kit/src/prompt.ts
|
|
2026
|
-
var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "
|
|
2333
|
+
var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
|
|
2027
2334
|
function readKeys(input, paste = { active: false }) {
|
|
2028
|
-
return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key));
|
|
2335
|
+
return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
|
|
2029
2336
|
}
|
|
2030
2337
|
async function confirm(question, { default: fallback, ...settings } = {}) {
|
|
2031
2338
|
let answered = fallback;
|
|
@@ -2049,7 +2356,7 @@ function asking(colors, question, typed, keys) {
|
|
|
2049
2356
|
function answer(colors, question, state, picked) {
|
|
2050
2357
|
return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
|
|
2051
2358
|
}
|
|
2052
|
-
async function ask(question, { hint, terminal =
|
|
2359
|
+
async function ask(question, { hint, terminal = process23 }, render, press) {
|
|
2053
2360
|
const { stdin, stderr } = terminal;
|
|
2054
2361
|
if (!isInteractive(terminal))
|
|
2055
2362
|
fail(`cannot ask "${question}" off a terminal`, 2, hint);
|
|
@@ -2059,12 +2366,22 @@ async function ask(question, { hint, terminal = process20 }, render, press) {
|
|
|
2059
2366
|
const columns = () => stderr.columns || 80;
|
|
2060
2367
|
const draw = (state, last = false) => {
|
|
2061
2368
|
const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
|
|
2062
|
-
|
|
2063
|
-
|
|
2369
|
+
const rows = rowsTaken(frame, columns());
|
|
2370
|
+
stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
|
|
2064
2371
|
current = state;
|
|
2065
2372
|
};
|
|
2066
2373
|
const redraw = () => draw(current);
|
|
2067
2374
|
const paste = { active: false };
|
|
2375
|
+
const stop = terminal.stop ?? (terminal === process23 ? stopJob : undefined);
|
|
2376
|
+
const suspend = () => {
|
|
2377
|
+
if (stop === undefined)
|
|
2378
|
+
return;
|
|
2379
|
+
stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
|
|
2380
|
+
stdin.setRawMode(false);
|
|
2381
|
+
stop();
|
|
2382
|
+
stdin.setRawMode(true);
|
|
2383
|
+
stderr.write("\x1B[?25l\x1B[?2004h");
|
|
2384
|
+
};
|
|
2068
2385
|
try {
|
|
2069
2386
|
stderr.on?.("resize", redraw);
|
|
2070
2387
|
stdin.setRawMode(true);
|
|
@@ -2074,6 +2391,10 @@ async function ask(question, { hint, terminal = process20 }, render, press) {
|
|
|
2074
2391
|
return await new Promise((resolve) => {
|
|
2075
2392
|
function onData(data) {
|
|
2076
2393
|
for (const key of readKeys(data.toString(), paste)) {
|
|
2394
|
+
if (key === "suspend") {
|
|
2395
|
+
suspend();
|
|
2396
|
+
continue;
|
|
2397
|
+
}
|
|
2077
2398
|
const pressed = press(key);
|
|
2078
2399
|
if (pressed !== undefined) {
|
|
2079
2400
|
settle(pressed);
|
|
@@ -2105,19 +2426,19 @@ async function ask(question, { hint, terminal = process20 }, render, press) {
|
|
|
2105
2426
|
}
|
|
2106
2427
|
|
|
2107
2428
|
// src/apply.ts
|
|
2108
|
-
import { existsSync as
|
|
2429
|
+
import { existsSync as existsSync10 } from "fs";
|
|
2109
2430
|
import { lstat as lstat3, rm } from "fs/promises";
|
|
2110
|
-
import { basename as basename4, join as
|
|
2431
|
+
import { basename as basename4, join as join13 } from "path";
|
|
2111
2432
|
|
|
2112
2433
|
// src/sweep-scan.ts
|
|
2113
|
-
import { existsSync as
|
|
2434
|
+
import { existsSync as existsSync9 } from "fs";
|
|
2114
2435
|
import { lstat as lstat2, readdir as readdir4, realpath } from "fs/promises";
|
|
2115
2436
|
import { homedir as homedir5 } from "os";
|
|
2116
|
-
import { basename as basename3, dirname as dirname5, join as
|
|
2437
|
+
import { basename as basename3, dirname as dirname5, join as join12 } from "path";
|
|
2117
2438
|
|
|
2118
2439
|
// src/size.ts
|
|
2119
2440
|
import { lstat, readdir as readdir3 } from "fs/promises";
|
|
2120
|
-
import { join as
|
|
2441
|
+
import { join as join11 } from "path";
|
|
2121
2442
|
var FS_LIMIT = 32;
|
|
2122
2443
|
var FIND_MS = 60000;
|
|
2123
2444
|
var FIND_LINE = /^(\d+) (\S+) (\d+)$/gm;
|
|
@@ -2145,7 +2466,7 @@ async function walkSize(folder) {
|
|
|
2145
2466
|
return;
|
|
2146
2467
|
}
|
|
2147
2468
|
await Promise.all(entries.map(async (entry) => {
|
|
2148
|
-
const path =
|
|
2469
|
+
const path = join11(dir, entry.name);
|
|
2149
2470
|
if (entry.isDirectory())
|
|
2150
2471
|
return visit(path);
|
|
2151
2472
|
try {
|
|
@@ -2189,12 +2510,13 @@ async function sizeOf(folder) {
|
|
|
2189
2510
|
}
|
|
2190
2511
|
|
|
2191
2512
|
// src/sweep-scan.ts
|
|
2192
|
-
var FOLDER_NAMES = new Set(["node_modules", ".nuxt", ".next", ".output", "dist", "build", ".turbo", ".svelte-kit", "target"]);
|
|
2513
|
+
var FOLDER_NAMES = new Set(["node_modules", ".nuxt", ".next", ".output", "dist", "build", ".turbo", ".svelte-kit", "target", "vendor", ".venv", "__pycache__", ".gradle"]);
|
|
2514
|
+
var NEEDS_BESIDE = { target: ["Cargo.toml"], vendor: ["composer.json", "composer.lock"] };
|
|
2193
2515
|
var MAX_DEPTH3 = 3;
|
|
2194
|
-
var PROJECT_CACHE_NAMES = new Set([".turbo", ".nuxt", ".next", ".svelte-kit"]);
|
|
2516
|
+
var PROJECT_CACHE_NAMES = new Set([".turbo", ".nuxt", ".next", ".svelte-kit", "__pycache__", ".gradle"]);
|
|
2195
2517
|
var GLOBAL_CACHES = [".bun/install/cache", ".npm/_cacache", ".cache/pip", ".cache/uv", ".cache/ms-playwright", ".cache/puppeteer", ".cache/go-build", ".cache/typescript", ".cargo/registry"];
|
|
2196
2518
|
function isCachePath(path, home = homedir5()) {
|
|
2197
|
-
return GLOBAL_CACHES.some((cache) =>
|
|
2519
|
+
return GLOBAL_CACHES.some((cache) => join12(home, cache) === path) || basename3(path) === ".cache" && basename3(dirname5(path)) === "node_modules";
|
|
2198
2520
|
}
|
|
2199
2521
|
async function listing(dir) {
|
|
2200
2522
|
try {
|
|
@@ -2205,7 +2527,7 @@ async function listing(dir) {
|
|
|
2205
2527
|
}
|
|
2206
2528
|
async function addGlobalCaches(found, home) {
|
|
2207
2529
|
for (const cache of GLOBAL_CACHES) {
|
|
2208
|
-
const path =
|
|
2530
|
+
const path = join12(home, cache);
|
|
2209
2531
|
try {
|
|
2210
2532
|
const stat = await lstat2(path);
|
|
2211
2533
|
if (stat.isSymbolicLink())
|
|
@@ -2220,7 +2542,7 @@ async function findCandidates(root, home = homedir5(), withGlobal = true) {
|
|
|
2220
2542
|
const visit = async (dir, depth) => {
|
|
2221
2543
|
const entries = await listing(dir);
|
|
2222
2544
|
for (const entry of entries) {
|
|
2223
|
-
const path =
|
|
2545
|
+
const path = join12(dir, entry.name);
|
|
2224
2546
|
if (entry.name === ".git")
|
|
2225
2547
|
continue;
|
|
2226
2548
|
if (entry.name === ".worktrees" || entry.name === "worktrees" && basename3(dir) === ".claude") {
|
|
@@ -2230,13 +2552,13 @@ async function findCandidates(root, home = homedir5(), withGlobal = true) {
|
|
|
2230
2552
|
}
|
|
2231
2553
|
for (const worktree of await listing(path)) {
|
|
2232
2554
|
if (worktree.isDirectory())
|
|
2233
|
-
found.candidates.push({ path:
|
|
2555
|
+
found.candidates.push({ path: join12(path, worktree.name), kind: "worktree" });
|
|
2234
2556
|
else if (worktree.isSymbolicLink())
|
|
2235
|
-
found.skipped.push({ path:
|
|
2557
|
+
found.skipped.push({ path: join12(path, worktree.name), reason: "symlink" });
|
|
2236
2558
|
}
|
|
2237
2559
|
continue;
|
|
2238
2560
|
}
|
|
2239
|
-
if (FOLDER_NAMES.has(entry.name) && (entry.name
|
|
2561
|
+
if (FOLDER_NAMES.has(entry.name) && (NEEDS_BESIDE[entry.name]?.some((file) => existsSync9(join12(dir, file))) ?? true)) {
|
|
2240
2562
|
if (entry.isSymbolicLink()) {
|
|
2241
2563
|
found.skipped.push({ path, reason: "symlink" });
|
|
2242
2564
|
} else if (entry.isDirectory()) {
|
|
@@ -2244,9 +2566,9 @@ async function findCandidates(root, home = homedir5(), withGlobal = true) {
|
|
|
2244
2566
|
if (entry.name === "node_modules") {
|
|
2245
2567
|
const cache = (await listing(path)).find((inner) => inner.name === ".cache");
|
|
2246
2568
|
if (cache?.isSymbolicLink())
|
|
2247
|
-
found.skipped.push({ path:
|
|
2569
|
+
found.skipped.push({ path: join12(path, ".cache"), reason: "symlink" });
|
|
2248
2570
|
else if (cache?.isDirectory())
|
|
2249
|
-
found.candidates.push({ path:
|
|
2571
|
+
found.candidates.push({ path: join12(path, ".cache"), kind: "cache", inside: path });
|
|
2250
2572
|
}
|
|
2251
2573
|
}
|
|
2252
2574
|
continue;
|
|
@@ -2322,7 +2644,7 @@ async function judgeFolder(path, kind, inside) {
|
|
|
2322
2644
|
const located = await toplevelOf(parent);
|
|
2323
2645
|
if (located === "failed")
|
|
2324
2646
|
return { skip: "git failed" };
|
|
2325
|
-
if (
|
|
2647
|
+
if (existsSync9(join12(path, ".git")))
|
|
2326
2648
|
return { skip: "holds a git repository" };
|
|
2327
2649
|
if (located === "none")
|
|
2328
2650
|
return name === "node_modules" || inside !== undefined ? { entry: { path, kind, committedAt: undefined, action: "remove", inside } } : { skip: "not in a git repository" };
|
|
@@ -2390,7 +2712,7 @@ async function removeFolder(entry) {
|
|
|
2390
2712
|
const stat = await lstat3(entry.path);
|
|
2391
2713
|
if (stat.isSymbolicLink() || !stat.isDirectory() || !(FOLDER_NAMES.has(basename4(entry.path)) || entry.kind === "cache" && isCachePath(entry.path)))
|
|
2392
2714
|
return { path: entry.path, removed: false, error: "no longer a plain folder" };
|
|
2393
|
-
if (
|
|
2715
|
+
if (existsSync10(join13(entry.path, ".git")))
|
|
2394
2716
|
return { path: entry.path, removed: false, error: "holds a git repository" };
|
|
2395
2717
|
await rm(entry.path, { recursive: true, force: true });
|
|
2396
2718
|
return { path: entry.path, removed: true };
|
|
@@ -2423,18 +2745,17 @@ async function applyAll(entries, done) {
|
|
|
2423
2745
|
// src/sweep.ts
|
|
2424
2746
|
var LARGE = 100 * 1024 ** 2;
|
|
2425
2747
|
var BIG = 1024 ** 3;
|
|
2426
|
-
var USAGE3 = `sweep [options] [root]: lists the regenerable folders (node_modules, .output, dist, build, target beside a Cargo.toml), the caches (.nuxt, .next, .turbo, .svelte-kit and node_modules/.cache per project; ~/.bun/install/cache, ~/.npm/_cacache, ~/.cache/{pip,uv,ms-playwright,puppeteer,go-build,typescript} and ~/.cargo/registry, exact paths only, listed only when no root is given or with --only caches) and the .worktrees/* and .claude/worktrees/* entries under root (the configured workspace, ~/Workspace by default, ${MAX_DEPTH3} levels down), largest first with the age of the repo's last commit; --only worktrees, folders or caches keeps one kind
|
|
2427
|
-
|
|
2428
|
-
Dry unless --apply, which deletes after a confirm showing the total (read from the terminal; off one, pass --yes). A folder is deleted for good, not trashed. Never touched: a symlink, a folder git tracks files in, a build folder git does not ignore. A worktree is removed with git worktree remove, never forced, and only when it is clean and every commit of its branch is on another branch or a remote; the others stay listed as kept and count for nothing in the total. With --docker the Docker usage comes after the list, left to dclean.
|
|
2748
|
+
var USAGE3 = `sweep [options] [root]: lists the regenerable folders (node_modules, .output, dist, build, .venv, target beside a Cargo.toml, vendor beside a composer.json or composer.lock), the caches (.nuxt, .next, .turbo, .svelte-kit, __pycache__, .gradle and node_modules/.cache per project; ~/.bun/install/cache, ~/.npm/_cacache, ~/.cache/{pip,uv,ms-playwright,puppeteer,go-build,typescript} and ~/.cargo/registry, exact paths only, listed only when no root is given or with --only caches) and the .worktrees/* and .claude/worktrees/* entries under root (the configured workspace, ~/Workspace by default, ${MAX_DEPTH3} levels down), largest first with the age of the repo's last commit; --only worktrees, folders or caches keeps one kind
|
|
2429
2749
|
|
|
2430
|
-
|
|
2750
|
+
Dry unless --apply, which deletes after a confirm showing the total (read from the terminal; off one, pass --yes). A folder is deleted for good, not trashed. Never touched: a symlink, a folder git tracks files in, a build folder git does not ignore. A worktree is removed with git worktree remove, never forced, and only when it is clean and every commit of its branch is on another branch or a remote; the others stay listed as kept and count for nothing in the total. With --docker the Docker usage comes after the list, left to dclean.`;
|
|
2751
|
+
var EXITS3 = [[0, "it listed, or removed every entry it was allowed to"], [1, "a removal failed or the confirm was declined"], [2, "a usage error, a missing root, or --apply off a terminal without --yes"]];
|
|
2431
2752
|
var ONLY_KINDS = { worktrees: "worktree", folders: "folder", caches: "cache" };
|
|
2432
2753
|
var OPTIONS3 = {
|
|
2433
2754
|
apply: { type: "boolean", description: "delete what is listed as removable, after the confirm" },
|
|
2434
2755
|
yes: { type: "boolean", short: "y", description: "with --apply, skip the confirm" },
|
|
2435
2756
|
older: { type: "string", description: "only the entries whose repo last committed longer ago than this (30d, 12h)" },
|
|
2436
2757
|
min: { type: "string", description: "only the entries of at least this size (500K, 10M, 1G)" },
|
|
2437
|
-
only: { type: "string",
|
|
2758
|
+
only: { type: "string", choices: Object.keys(ONLY_KINDS), description: "leave the other kinds out (.nuxt, .next, .turbo, .svelte-kit, __pycache__ and .gradle are caches; the global caches are listed with no root or with caches)" },
|
|
2438
2759
|
docker: { type: "boolean", description: "add the docker system df output, which alone takes about ten seconds" },
|
|
2439
2760
|
json: jsonOption("{root, entries: [{path, kind (folder, worktree or cache), bytes, committedAt, action (remove or keep), reason}], skipped: [{path, reason}], reclaimable, docker, removed?}")
|
|
2440
2761
|
};
|
|
@@ -2449,14 +2770,12 @@ async function dockerUsage() {
|
|
|
2449
2770
|
}
|
|
2450
2771
|
}
|
|
2451
2772
|
async function sweep(args) {
|
|
2452
|
-
const { values, positionals } = parse(args, USAGE3, OPTIONS3, { positionals: ["[root]"], replaces: "find ~/Workspace -name node_modules, du -sh and rm -rf by hand", examples: ["sweep", "sweep ~/Workspace --older 30d --min 100M --apply", "sweep --only worktrees --apply"] });
|
|
2773
|
+
const { values, positionals } = parse(args, USAGE3, OPTIONS3, { exits: EXITS3, positionals: ["[root]"], replaces: "find ~/Workspace -name node_modules, du -sh and rm -rf by hand", examples: ["sweep", "sweep ~/Workspace --older 30d --min 100M --apply", "sweep --only worktrees --apply"] });
|
|
2453
2774
|
if (positionals.length > 1)
|
|
2454
2775
|
badUsage("give one root");
|
|
2455
2776
|
const root = workspaceRoot({ given: positionals[0] });
|
|
2456
|
-
if (!
|
|
2777
|
+
if (!existsSync11(root) || !statSync4(root).isDirectory())
|
|
2457
2778
|
fail(`${root} is not a folder`);
|
|
2458
|
-
if (values.only !== undefined && !Object.hasOwn(ONLY_KINDS, values.only))
|
|
2459
|
-
badUsage(`--only takes worktrees, folders or caches, not ${values.only}`);
|
|
2460
2779
|
const olderMs = values.older === undefined ? undefined : duration(values.older, "older", 0);
|
|
2461
2780
|
const minBytes = values.min === undefined ? 0 : parseSize(values.min);
|
|
2462
2781
|
if (minBytes === undefined)
|
|
@@ -2527,7 +2846,7 @@ ${tt(reclaimable)} reclaimable${skipped === 0 ? "" : `, ${skipped} skipped (syml
|
|
|
2527
2846
|
}
|
|
2528
2847
|
|
|
2529
2848
|
// src/cli.ts
|
|
2530
|
-
|
|
2849
|
+
process24.exitCode = await runCli({
|
|
2531
2850
|
name: "ws",
|
|
2532
2851
|
about: "the repositories under a root: the ones needing attention, the folders worth reclaiming and their known vulnerabilities",
|
|
2533
2852
|
replaces: "a cd, git status and du loop over each repository of the workspace, and a bun audit run in each",
|
|
@@ -2535,6 +2854,6 @@ process21.exitCode = await runCli({
|
|
|
2535
2854
|
commands: {
|
|
2536
2855
|
repos: { summary: "the git repositories that need attention: dirty, ahead or behind, worktrees, unreleased commits", run: repos },
|
|
2537
2856
|
sweep: { summary: "the regenerable folders, caches and clean worktrees, largest first, deleted only on --apply", run: sweep },
|
|
2538
|
-
audit: { summary: "the known vulnerabilities of the Bun repositories, one table per repository", run: audit }
|
|
2857
|
+
audit: { summary: "the known vulnerabilities of the Bun, Composer, Cargo and uv repositories, one table per repository", run: audit }
|
|
2539
2858
|
}
|
|
2540
2859
|
});
|