@kaynooo/cli-proc 0.7.2 → 0.7.5
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/pid-cli.js +163 -33
- package/dist/ports-cli.js +232 -44
- package/dist/proc-cli.js +239 -51
- package/dist/procs-cli.js +166 -36
- package/package.json +2 -2
- package/src/read.ts +19 -3
package/dist/proc-cli.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// @bun
|
|
3
3
|
|
|
4
4
|
// src/proc-cli.ts
|
|
5
|
-
import
|
|
5
|
+
import process22 from "process";
|
|
6
6
|
// ../kit/src/args.ts
|
|
7
7
|
import process9 from "process";
|
|
8
8
|
import { parseArgs } from "util";
|
|
@@ -390,6 +390,9 @@ function formatSeconds(total) {
|
|
|
390
390
|
const next = amounts[first + 1];
|
|
391
391
|
return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
|
|
392
392
|
}
|
|
393
|
+
function formatDuration(ms) {
|
|
394
|
+
return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
|
|
395
|
+
}
|
|
393
396
|
function upTo(text, separator) {
|
|
394
397
|
const end = text.indexOf(separator);
|
|
395
398
|
return end === -1 ? text : text.slice(0, end);
|
|
@@ -450,7 +453,7 @@ function printJson(value) {
|
|
|
450
453
|
|
|
451
454
|
// ../kit/src/help.ts
|
|
452
455
|
import process8 from "process";
|
|
453
|
-
var OPTIONAL =
|
|
456
|
+
var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
454
457
|
var USAGE_PREFIX = /^usage:\s*/i;
|
|
455
458
|
var FULL_STOP = /\.$/;
|
|
456
459
|
function usageLine(usage, colors = paint(process8.stdout)) {
|
|
@@ -489,29 +492,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
|
489
492
|
return [];
|
|
490
493
|
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
491
494
|
}
|
|
495
|
+
var MAX_INLINE_CHOICES = 24;
|
|
492
496
|
function optionRows(options, colors = paint(process8.stdout)) {
|
|
493
497
|
const rows = Object.entries(options).map(([name, option]) => {
|
|
494
498
|
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
495
|
-
const
|
|
499
|
+
const choices = option.choices?.join("|");
|
|
500
|
+
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
501
|
+
const named = inline ? `<${choices}>` : "<value>";
|
|
496
502
|
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
497
503
|
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
498
|
-
|
|
504
|
+
const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
|
|
505
|
+
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
|
|
499
506
|
});
|
|
500
507
|
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
501
508
|
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
502
509
|
}
|
|
503
510
|
|
|
504
511
|
// ../kit/src/text.ts
|
|
505
|
-
var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
|
|
506
512
|
function distance(a, b) {
|
|
507
|
-
|
|
508
|
-
|
|
513
|
+
const left = [...a];
|
|
514
|
+
const right = [...b];
|
|
515
|
+
let before = [];
|
|
516
|
+
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
517
|
+
for (const [i, x] of left.entries()) {
|
|
509
518
|
const current = [i + 1];
|
|
510
|
-
for (const [j,
|
|
511
|
-
|
|
519
|
+
for (const [j, y] of right.entries()) {
|
|
520
|
+
let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
|
|
521
|
+
if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
|
|
522
|
+
cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
|
|
523
|
+
current.push(cost);
|
|
524
|
+
}
|
|
525
|
+
before = previous;
|
|
512
526
|
previous = current;
|
|
513
527
|
}
|
|
514
|
-
return previous[
|
|
528
|
+
return previous[right.length] ?? 0;
|
|
515
529
|
}
|
|
516
530
|
function closest(name, names) {
|
|
517
531
|
const started = names.find((known) => known.startsWith(name));
|
|
@@ -587,7 +601,7 @@ class Completing {
|
|
|
587
601
|
}
|
|
588
602
|
var completion = { active: false };
|
|
589
603
|
var OUTPUT_OPTIONS = {
|
|
590
|
-
color: { type: "string", description: "auto (on a terminal alone
|
|
604
|
+
color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
|
|
591
605
|
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
592
606
|
};
|
|
593
607
|
function applyOutput(color, plain, env = process9.env) {
|
|
@@ -881,13 +895,91 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
|
881
895
|
// ../kit/src/cli.ts
|
|
882
896
|
import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
|
|
883
897
|
import { dirname as dirname3, join as join5 } from "path";
|
|
884
|
-
import
|
|
898
|
+
import process14 from "process";
|
|
899
|
+
|
|
900
|
+
// ../kit/src/completions.ts
|
|
901
|
+
var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
|
|
902
|
+
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'
|
|
903
|
+
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
904
|
+
set -l current (commandline -ct)
|
|
905
|
+
for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
|
|
906
|
+
if test "$line" = __files__
|
|
907
|
+
__fish_complete_path $current
|
|
908
|
+
else
|
|
909
|
+
echo $line
|
|
910
|
+
end
|
|
911
|
+
end
|
|
912
|
+
end`;
|
|
913
|
+
var BASH_FUNCTION = `__kaynooo_cli_complete() {
|
|
914
|
+
local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
|
|
915
|
+
local -a lines
|
|
916
|
+
COMPREPLY=()
|
|
917
|
+
lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
|
|
918
|
+
for line in "\${lines[@]}"; do
|
|
919
|
+
if [[ $line == __files__ ]]; then
|
|
920
|
+
COMPREPLY+=($(compgen -f -- "$cur"))
|
|
921
|
+
else
|
|
922
|
+
words+="\${line%%$'\\t'*}"$'\\n'
|
|
923
|
+
fi
|
|
924
|
+
done
|
|
925
|
+
COMPREPLY+=($(compgen -W "$words" -- "$cur"))
|
|
926
|
+
}`;
|
|
927
|
+
var ZSH_FUNCTION = `__kaynooo_cli_complete() {
|
|
928
|
+
local line
|
|
929
|
+
local -a described plain
|
|
930
|
+
for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
|
|
931
|
+
if [[ $line == __files__ ]]; then
|
|
932
|
+
_files
|
|
933
|
+
elif [[ $line == *$'\\t'* ]]; then
|
|
934
|
+
described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
|
|
935
|
+
else
|
|
936
|
+
plain+=("$line")
|
|
937
|
+
fi
|
|
938
|
+
done
|
|
939
|
+
(( \${#described} )) && _describe -V value described
|
|
940
|
+
(( \${#plain} )) && compadd -- "\${plain[@]}"
|
|
941
|
+
return 0
|
|
942
|
+
}`;
|
|
943
|
+
function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
|
|
944
|
+
if (shell === "fish")
|
|
945
|
+
return `${header}
|
|
946
|
+
${FISH_FUNCTION}
|
|
947
|
+
${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
948
|
+
`).join("")}`;
|
|
949
|
+
if (shell === "bash")
|
|
950
|
+
return `${header}
|
|
951
|
+
${BASH_FUNCTION}
|
|
952
|
+
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
953
|
+
`;
|
|
954
|
+
return `${header}
|
|
955
|
+
${ZSH_FUNCTION}
|
|
956
|
+
compdef __kaynooo_cli_complete ${bins.join(" ")}
|
|
957
|
+
`;
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
// ../kit/src/notify.ts
|
|
961
|
+
import process12 from "process";
|
|
962
|
+
var NOTIFY_AFTER_MS = 1e4;
|
|
963
|
+
var CANCELLED = 130;
|
|
964
|
+
function base64(text) {
|
|
965
|
+
return Buffer.from(text).toString("base64");
|
|
966
|
+
}
|
|
967
|
+
function notification(title, body, env = process12.env) {
|
|
968
|
+
const id = `kit${process12.pid}`;
|
|
969
|
+
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\\`];
|
|
970
|
+
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
971
|
+
}
|
|
972
|
+
function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
|
|
973
|
+
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
974
|
+
return;
|
|
975
|
+
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
976
|
+
}
|
|
885
977
|
|
|
886
978
|
// ../kit/src/usage.ts
|
|
887
979
|
import { appendFileSync, mkdirSync } from "fs";
|
|
888
980
|
import { homedir as homedir3 } from "os";
|
|
889
981
|
import { dirname as dirname2, isAbsolute, join as join4 } from "path";
|
|
890
|
-
import
|
|
982
|
+
import process13 from "process";
|
|
891
983
|
|
|
892
984
|
// ../kit/src/logs.ts
|
|
893
985
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
@@ -901,14 +993,14 @@ var usageError;
|
|
|
901
993
|
function noteUsageError(message) {
|
|
902
994
|
usageError = message;
|
|
903
995
|
}
|
|
904
|
-
function stateHome(env =
|
|
996
|
+
function stateHome(env = process13.env) {
|
|
905
997
|
const dir = env.XDG_STATE_HOME;
|
|
906
998
|
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
907
999
|
}
|
|
908
|
-
function usagePath(env =
|
|
1000
|
+
function usagePath(env = process13.env) {
|
|
909
1001
|
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
910
1002
|
}
|
|
911
|
-
function usageRecorded(env =
|
|
1003
|
+
function usageRecorded(env = process13.env) {
|
|
912
1004
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
913
1005
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
914
1006
|
}
|
|
@@ -922,7 +1014,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
922
1014
|
usageError = undefined;
|
|
923
1015
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
924
1016
|
}
|
|
925
|
-
function recordUsage(entry, env =
|
|
1017
|
+
function recordUsage(entry, env = process13.env) {
|
|
926
1018
|
if (!usageRecorded(env))
|
|
927
1019
|
return;
|
|
928
1020
|
try {
|
|
@@ -938,7 +1030,11 @@ var LEVEL_OPTIONS = {
|
|
|
938
1030
|
...OUTPUT_OPTIONS,
|
|
939
1031
|
help: { type: "boolean", short: "h", description: "show this help" }
|
|
940
1032
|
};
|
|
941
|
-
var TOP_OPTIONS = {
|
|
1033
|
+
var TOP_OPTIONS = {
|
|
1034
|
+
...LEVEL_OPTIONS,
|
|
1035
|
+
version: { type: "boolean", short: "v", description: "print the version" },
|
|
1036
|
+
completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
|
|
1037
|
+
};
|
|
942
1038
|
async function commandRows(all, colors) {
|
|
943
1039
|
const commands = shown(all);
|
|
944
1040
|
const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
|
|
@@ -1012,8 +1108,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
|
|
|
1012
1108
|
`);
|
|
1013
1109
|
}
|
|
1014
1110
|
function printError(prefix, message, hint, cause) {
|
|
1015
|
-
const colors = paint(
|
|
1016
|
-
const styled = takesControlCodes(
|
|
1111
|
+
const colors = paint(process14.stderr);
|
|
1112
|
+
const styled = takesControlCodes(process14.stderr);
|
|
1017
1113
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
1018
1114
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
1019
1115
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -1056,11 +1152,11 @@ async function dispatch(level, typed, { version, redact }) {
|
|
|
1056
1152
|
}
|
|
1057
1153
|
}
|
|
1058
1154
|
if (name === undefined && level.path.length > 1) {
|
|
1059
|
-
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
1155
|
+
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
|
|
1060
1156
|
return 2;
|
|
1061
1157
|
}
|
|
1062
1158
|
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
1063
|
-
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
1159
|
+
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
|
|
1064
1160
|
return 0;
|
|
1065
1161
|
}
|
|
1066
1162
|
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
@@ -1171,6 +1267,19 @@ async function candidates(scope, defaultCommand, words, before = []) {
|
|
|
1171
1267
|
}
|
|
1172
1268
|
return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
|
|
1173
1269
|
}
|
|
1270
|
+
var COMPLETIONS = "--completions";
|
|
1271
|
+
function flagValue([flag = "", ...rest]) {
|
|
1272
|
+
return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
|
|
1273
|
+
}
|
|
1274
|
+
function printCompletionScript(name, args) {
|
|
1275
|
+
const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
|
|
1276
|
+
if (shell === undefined || args.length !== 1) {
|
|
1277
|
+
printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
|
|
1278
|
+
return 2;
|
|
1279
|
+
}
|
|
1280
|
+
console.log(completionScript(shell, [name]).trimEnd());
|
|
1281
|
+
return 0;
|
|
1282
|
+
}
|
|
1174
1283
|
async function printCandidates(found) {
|
|
1175
1284
|
for (const line of await found)
|
|
1176
1285
|
console.log(line);
|
|
@@ -1195,10 +1304,15 @@ async function runCli(cli, argv = scriptArgs()) {
|
|
|
1195
1304
|
const version = cli.version ?? packageVersion();
|
|
1196
1305
|
if (argv[0] === COMPLETE)
|
|
1197
1306
|
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
1307
|
+
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
1308
|
+
return printCompletionScript(cli.name, flagValue(argv));
|
|
1309
|
+
const started = performance.now();
|
|
1198
1310
|
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 });
|
|
1311
|
+
const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
|
|
1312
|
+
notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
|
|
1199
1313
|
if (cli.usage !== false) {
|
|
1200
1314
|
try {
|
|
1201
|
-
recordUsage(usageEntry(cli.name,
|
|
1315
|
+
recordUsage(usageEntry(cli.name, command, argv, code));
|
|
1202
1316
|
} catch {}
|
|
1203
1317
|
}
|
|
1204
1318
|
return code;
|
|
@@ -1221,16 +1335,20 @@ function commandPath(scope, argv) {
|
|
|
1221
1335
|
async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
|
|
1222
1336
|
if (argv[0] === COMPLETE)
|
|
1223
1337
|
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
1338
|
+
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
1339
|
+
return printCompletionScript(name, flagValue(argv));
|
|
1224
1340
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
1225
1341
|
console.log(version ?? packageVersion());
|
|
1226
1342
|
return 0;
|
|
1227
1343
|
}
|
|
1228
1344
|
let code;
|
|
1345
|
+
const started = performance.now();
|
|
1229
1346
|
try {
|
|
1230
1347
|
code = await run(argv);
|
|
1231
1348
|
} catch (error) {
|
|
1232
1349
|
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
1233
1350
|
}
|
|
1351
|
+
notifyEnd(name, code, performance.now() - started);
|
|
1234
1352
|
if (usage !== false) {
|
|
1235
1353
|
try {
|
|
1236
1354
|
recordUsage(usageEntry(name, undefined, argv, code));
|
|
@@ -1262,7 +1380,7 @@ function parseSize(text, bareUnit = 1) {
|
|
|
1262
1380
|
return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
|
|
1263
1381
|
}
|
|
1264
1382
|
// ../kit/src/watch.ts
|
|
1265
|
-
import
|
|
1383
|
+
import process15 from "process";
|
|
1266
1384
|
import { format } from "util";
|
|
1267
1385
|
var CLEAR_SCREEN = "\x1B[H\x1B[2J";
|
|
1268
1386
|
var DEFAULT_SECONDS = 2;
|
|
@@ -1284,7 +1402,7 @@ function withoutWatch(args) {
|
|
|
1284
1402
|
}
|
|
1285
1403
|
return rest;
|
|
1286
1404
|
}
|
|
1287
|
-
async function watching(value, step, stream =
|
|
1405
|
+
async function watching(value, step, stream = process15.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
|
|
1288
1406
|
const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
|
|
1289
1407
|
if (!takesControlCodes(stream))
|
|
1290
1408
|
badUsage("--watch redraws the screen, so it needs a terminal");
|
|
@@ -1292,12 +1410,12 @@ async function watching(value, step, stream = process14.stdout, sleep = Bun.slee
|
|
|
1292
1410
|
for (let round = 0;round < rounds; round++) {
|
|
1293
1411
|
const held = [];
|
|
1294
1412
|
const { log, info } = console;
|
|
1295
|
-
const write =
|
|
1413
|
+
const write = process15.stdout.write.bind(process15.stdout);
|
|
1296
1414
|
const hold = (...parts) => void held.push(`${format(...parts)}
|
|
1297
1415
|
`);
|
|
1298
1416
|
console.log = hold;
|
|
1299
1417
|
console.info = hold;
|
|
1300
|
-
|
|
1418
|
+
process15.stdout.write = (text) => {
|
|
1301
1419
|
held.push(typeof text === "string" ? text : Buffer.from(text).toString());
|
|
1302
1420
|
return true;
|
|
1303
1421
|
};
|
|
@@ -1306,7 +1424,7 @@ async function watching(value, step, stream = process14.stdout, sleep = Bun.slee
|
|
|
1306
1424
|
} finally {
|
|
1307
1425
|
console.log = log;
|
|
1308
1426
|
console.info = info;
|
|
1309
|
-
|
|
1427
|
+
process15.stdout.write = write;
|
|
1310
1428
|
}
|
|
1311
1429
|
stream.write(`${CLEAR_SCREEN}${held.join("")}`);
|
|
1312
1430
|
await sleep(interval);
|
|
@@ -1314,7 +1432,7 @@ async function watching(value, step, stream = process14.stdout, sleep = Bun.slee
|
|
|
1314
1432
|
return code;
|
|
1315
1433
|
}
|
|
1316
1434
|
// src/pid.ts
|
|
1317
|
-
import
|
|
1435
|
+
import process17 from "process";
|
|
1318
1436
|
|
|
1319
1437
|
// src/mask.ts
|
|
1320
1438
|
import { basename } from "path";
|
|
@@ -1607,10 +1725,22 @@ async function socketsOf(pid, root = "/proc") {
|
|
|
1607
1725
|
return inodes;
|
|
1608
1726
|
}
|
|
1609
1727
|
async function socketOwners(root = "/proc") {
|
|
1610
|
-
const
|
|
1728
|
+
const holders = new Map;
|
|
1611
1729
|
for (const pid of await listPids(root)) {
|
|
1612
1730
|
for (const inode of await socketsOf(pid, root))
|
|
1613
|
-
|
|
1731
|
+
holders.set(inode, [...holders.get(inode) ?? [], pid]);
|
|
1732
|
+
}
|
|
1733
|
+
const owners = new Map;
|
|
1734
|
+
const parents = new Map;
|
|
1735
|
+
for (const [inode, pids] of holders) {
|
|
1736
|
+
const [first = 0] = pids;
|
|
1737
|
+
if (pids.length > 1) {
|
|
1738
|
+
for (const pid of pids) {
|
|
1739
|
+
if (!parents.has(pid))
|
|
1740
|
+
parents.set(pid, parseStat(await text2(`${root}/${pid}/stat`) ?? "")?.ppid);
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
owners.set(inode, pids.find((pid) => !pids.includes(parents.get(pid) ?? -1)) ?? first);
|
|
1614
1744
|
}
|
|
1615
1745
|
return owners;
|
|
1616
1746
|
}
|
|
@@ -1704,7 +1834,7 @@ function limitLine(limits, name) {
|
|
|
1704
1834
|
return limit === undefined ? "-" : `soft ${limit.soft}, hard ${limit.hard}`;
|
|
1705
1835
|
}
|
|
1706
1836
|
function render(info, showEnv) {
|
|
1707
|
-
const colors = paint(
|
|
1837
|
+
const colors = paint(process17.stdout);
|
|
1708
1838
|
const memory = info.memory;
|
|
1709
1839
|
const size = (bytes) => bytes === undefined ? "-" : tt(bytes);
|
|
1710
1840
|
const rows = [
|
|
@@ -1758,10 +1888,24 @@ async function pid(args) {
|
|
|
1758
1888
|
|
|
1759
1889
|
// src/ports.ts
|
|
1760
1890
|
import { basename as basename2 } from "path";
|
|
1761
|
-
import
|
|
1891
|
+
import process20 from "process";
|
|
1762
1892
|
|
|
1763
1893
|
// ../kit/src/prompt.ts
|
|
1764
|
-
import
|
|
1894
|
+
import process19 from "process";
|
|
1895
|
+
|
|
1896
|
+
// ../kit/src/job.ts
|
|
1897
|
+
import process18 from "process";
|
|
1898
|
+
function stopJob() {
|
|
1899
|
+
process18.kill(0, "SIGTSTP");
|
|
1900
|
+
}
|
|
1901
|
+
|
|
1902
|
+
// ../kit/src/picker/line.ts
|
|
1903
|
+
var EDIT_KEYS = new Set(["left", "right", "wordleft", "wordright", "linestart", "lineend", "erase", "delete", "word", "killword", "killnext", "clear", "killend", "yank"]);
|
|
1904
|
+
var BACKWARD_KILLS = new Set(["word", "killword", "clear"]);
|
|
1905
|
+
var FORWARD_KILLS = new Set(["killnext", "killend"]);
|
|
1906
|
+
function isEditKey(key) {
|
|
1907
|
+
return EDIT_KEYS.has(key);
|
|
1908
|
+
}
|
|
1765
1909
|
|
|
1766
1910
|
// ../kit/src/picker/score.ts
|
|
1767
1911
|
var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
|
|
@@ -1793,10 +1937,29 @@ var KEYS = {
|
|
|
1793
1937
|
"\n": "enter",
|
|
1794
1938
|
"\x03": "cancel",
|
|
1795
1939
|
"\x1B": "cancel",
|
|
1940
|
+
"\x1B[D": "left",
|
|
1941
|
+
"\x1BOD": "left",
|
|
1942
|
+
"\x1B[C": "right",
|
|
1943
|
+
"\x1BOC": "right",
|
|
1944
|
+
"\x1B[1;5D": "wordleft",
|
|
1945
|
+
"\x1B[1;3D": "wordleft",
|
|
1946
|
+
"\x1Bb": "wordleft",
|
|
1947
|
+
"\x1B[1;5C": "wordright",
|
|
1948
|
+
"\x1B[1;3C": "wordright",
|
|
1949
|
+
"\x1Bf": "wordright",
|
|
1950
|
+
"\x01": "linestart",
|
|
1951
|
+
"\x05": "lineend",
|
|
1796
1952
|
"\x7F": "erase",
|
|
1797
|
-
"\
|
|
1953
|
+
"\x1B[3~": "delete",
|
|
1954
|
+
"\b": "killword",
|
|
1955
|
+
"\x1B\x7F": "killword",
|
|
1956
|
+
"\x1B[3;5~": "killnext",
|
|
1957
|
+
"\x1Bd": "killnext",
|
|
1798
1958
|
"\x15": "clear",
|
|
1959
|
+
"\v": "killend",
|
|
1799
1960
|
"\x17": "word",
|
|
1961
|
+
"\x19": "yank",
|
|
1962
|
+
"\x1A": "suspend",
|
|
1800
1963
|
"\t": "tab",
|
|
1801
1964
|
"\x1F": "help",
|
|
1802
1965
|
"\x1BOP": "help",
|
|
@@ -1826,10 +1989,21 @@ function parseKeys(input, paste = { active: false }, ctrls = []) {
|
|
|
1826
1989
|
});
|
|
1827
1990
|
}
|
|
1828
1991
|
|
|
1992
|
+
// ../kit/src/redraw.ts
|
|
1993
|
+
var SYNC_START = "\x1B[?2026h";
|
|
1994
|
+
var SYNC_END = "\x1B[?2026l";
|
|
1995
|
+
function overwrite(lines, columns) {
|
|
1996
|
+
return lines.map((line) => textWidth(line) % columns === 0 ? `\x1B[2K${line}` : `${line}\x1B[K`).join(`
|
|
1997
|
+
`);
|
|
1998
|
+
}
|
|
1999
|
+
function rowsTaken(lines, columns) {
|
|
2000
|
+
return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(textWidth(line) / columns)), 0);
|
|
2001
|
+
}
|
|
2002
|
+
|
|
1829
2003
|
// ../kit/src/prompt.ts
|
|
1830
|
-
var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "
|
|
2004
|
+
var PROMPT_KEYS = new Set(["up", "down", "pageup", "pagedown", "home", "end", "enter", "cancel", "suspend", "tab"]);
|
|
1831
2005
|
function readKeys(input, paste = { active: false }) {
|
|
1832
|
-
return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key));
|
|
2006
|
+
return parseKeys(input, paste).filter((key) => typeof key === "object" ? "text" in key : PROMPT_KEYS.has(key) || isEditKey(key));
|
|
1833
2007
|
}
|
|
1834
2008
|
async function confirm(question, { default: fallback, ...settings } = {}) {
|
|
1835
2009
|
let answered = fallback;
|
|
@@ -1853,7 +2027,7 @@ function asking(colors, question, typed, keys) {
|
|
|
1853
2027
|
function answer(colors, question, state, picked) {
|
|
1854
2028
|
return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
|
|
1855
2029
|
}
|
|
1856
|
-
async function ask(question, { hint, terminal =
|
|
2030
|
+
async function ask(question, { hint, terminal = process19 }, render, press) {
|
|
1857
2031
|
const { stdin, stderr } = terminal;
|
|
1858
2032
|
if (!isInteractive(terminal))
|
|
1859
2033
|
fail(`cannot ask "${question}" off a terminal`, 2, hint);
|
|
@@ -1863,12 +2037,22 @@ async function ask(question, { hint, terminal = process17 }, render, press) {
|
|
|
1863
2037
|
const columns = () => stderr.columns || 80;
|
|
1864
2038
|
const draw = (state, last = false) => {
|
|
1865
2039
|
const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
|
|
1866
|
-
|
|
1867
|
-
|
|
2040
|
+
const rows = rowsTaken(frame, columns());
|
|
2041
|
+
stderr.write(`${SYNC_START}\r${overwrite(frame, columns())}\x1B[0J${last || rows < 2 ? "" : `\x1B[${rows - 1}A`}${last ? "" : "\r"}${SYNC_END}`);
|
|
1868
2042
|
current = state;
|
|
1869
2043
|
};
|
|
1870
2044
|
const redraw = () => draw(current);
|
|
1871
2045
|
const paste = { active: false };
|
|
2046
|
+
const stop = terminal.stop ?? (terminal === process19 ? stopJob : undefined);
|
|
2047
|
+
const suspend = () => {
|
|
2048
|
+
if (stop === undefined)
|
|
2049
|
+
return;
|
|
2050
|
+
stderr.write("\x1B[0J\x1B[?25h\x1B[?2004l");
|
|
2051
|
+
stdin.setRawMode(false);
|
|
2052
|
+
stop();
|
|
2053
|
+
stdin.setRawMode(true);
|
|
2054
|
+
stderr.write("\x1B[?25l\x1B[?2004h");
|
|
2055
|
+
};
|
|
1872
2056
|
try {
|
|
1873
2057
|
stderr.on?.("resize", redraw);
|
|
1874
2058
|
stdin.setRawMode(true);
|
|
@@ -1878,6 +2062,10 @@ async function ask(question, { hint, terminal = process17 }, render, press) {
|
|
|
1878
2062
|
return await new Promise((resolve) => {
|
|
1879
2063
|
function onData(data) {
|
|
1880
2064
|
for (const key of readKeys(data.toString(), paste)) {
|
|
2065
|
+
if (key === "suspend") {
|
|
2066
|
+
suspend();
|
|
2067
|
+
continue;
|
|
2068
|
+
}
|
|
1881
2069
|
const pressed = press(key);
|
|
1882
2070
|
if (pressed !== undefined) {
|
|
1883
2071
|
settle(pressed);
|
|
@@ -2038,7 +2226,7 @@ function refusal(row, proc, guard) {
|
|
|
2038
2226
|
return reason === undefined ? undefined : `pid ${row.pid} is ${reason}`;
|
|
2039
2227
|
}
|
|
2040
2228
|
function render2(rows) {
|
|
2041
|
-
const colors = paint(
|
|
2229
|
+
const colors = paint(process20.stdout);
|
|
2042
2230
|
const cells = rows.map((row) => [
|
|
2043
2231
|
colors.cyan(String(row.port)),
|
|
2044
2232
|
row.protocol,
|
|
@@ -2050,7 +2238,7 @@ function render2(rows) {
|
|
|
2050
2238
|
return table([["PORT", "PROTO", "ADDRESS", "PID", "COMMAND", "CWD"], ...cells], { header: true });
|
|
2051
2239
|
}
|
|
2052
2240
|
async function stop(port, rows, procs, values) {
|
|
2053
|
-
const guard = { uid:
|
|
2241
|
+
const guard = { uid: process20.getuid?.() ?? -1, mine: new Set(ancestry(process20.pid, procs)) };
|
|
2054
2242
|
const targets = new Map;
|
|
2055
2243
|
for (const row of rows) {
|
|
2056
2244
|
const reason = refusal(row, row.pid === undefined ? undefined : procs.get(row.pid), guard);
|
|
@@ -2063,7 +2251,7 @@ async function stop(port, rows, procs, values) {
|
|
|
2063
2251
|
return 1;
|
|
2064
2252
|
const names = [...targets].map(([pid, row]) => `${pid} (${truncate(row.command ?? "", 40)})`).join(", ");
|
|
2065
2253
|
if (values.yes !== true) {
|
|
2066
|
-
if (!
|
|
2254
|
+
if (!process20.stdin.isTTY)
|
|
2067
2255
|
fail(`stopping ${names} needs a terminal to ask on: pass --yes`, 2);
|
|
2068
2256
|
if (await confirm(`Stop ${names}?`, { default: false }) !== true)
|
|
2069
2257
|
return 1;
|
|
@@ -2095,7 +2283,7 @@ async function ports(args) {
|
|
|
2095
2283
|
badUsage(`<port> takes a whole number from 1 to 65535, not ${given}`);
|
|
2096
2284
|
if (values.kill === true && port === undefined)
|
|
2097
2285
|
badUsage("--kill takes the port to free: ports <port> --kill");
|
|
2098
|
-
const [sockets, owners, procs] = await Promise.all([readSockets(), socketOwners(), snapshot("/proc", (uid) => uid ===
|
|
2286
|
+
const [sockets, owners, procs] = await Promise.all([readSockets(), socketOwners(), snapshot("/proc", (uid) => uid === process20.getuid?.())]);
|
|
2099
2287
|
const byPid = new Map(procs.map((proc) => [proc.pid, proc]));
|
|
2100
2288
|
const wanted = sockets.filter((socket) => port === undefined || socket.port === port);
|
|
2101
2289
|
const needsDocker = wanted.some((socket) => {
|
|
@@ -2116,14 +2304,14 @@ async function ports(args) {
|
|
|
2116
2304
|
console.log(render2(rows));
|
|
2117
2305
|
const unknown = rows.filter((row) => row.pid === undefined && row.container === undefined).length;
|
|
2118
2306
|
if (unknown > 0)
|
|
2119
|
-
console.error(paint(
|
|
2307
|
+
console.error(paint(process20.stderr).dim(`${unknown} ${unknown === 1 ? "port has" : "ports have"} an owner this user cannot read, shown as -`));
|
|
2120
2308
|
return 0;
|
|
2121
2309
|
}
|
|
2122
2310
|
|
|
2123
2311
|
// src/procs.ts
|
|
2124
2312
|
import { existsSync as existsSync3 } from "fs";
|
|
2125
2313
|
import { homedir as homedir4 } from "os";
|
|
2126
|
-
import
|
|
2314
|
+
import process21 from "process";
|
|
2127
2315
|
|
|
2128
2316
|
// src/select.ts
|
|
2129
2317
|
import { basename as basename3, join as join6, relative } from "path";
|
|
@@ -2272,7 +2460,7 @@ function summary(group) {
|
|
|
2272
2460
|
};
|
|
2273
2461
|
}
|
|
2274
2462
|
function render3(groups) {
|
|
2275
|
-
const colors = paint(
|
|
2463
|
+
const colors = paint(process21.stdout);
|
|
2276
2464
|
const rows = groups.map((group) => [
|
|
2277
2465
|
group.origin,
|
|
2278
2466
|
String(group.members.length),
|
|
@@ -2300,9 +2488,9 @@ async function procs(args) {
|
|
|
2300
2488
|
if (values.watch !== undefined)
|
|
2301
2489
|
return watching(values.watch, async () => procs(withoutWatch(args)));
|
|
2302
2490
|
const olderMs = values.older === undefined ? undefined : duration(values.older, "older", 0, "m");
|
|
2303
|
-
const uid =
|
|
2491
|
+
const uid = process21.getuid?.() ?? -1;
|
|
2304
2492
|
const all = await snapshot("/proc", (owner) => owner === uid);
|
|
2305
|
-
const mine = new Set(ancestry(
|
|
2493
|
+
const mine = new Set(ancestry(process21.pid, new Map(all.map((proc) => [proc.pid, proc]))));
|
|
2306
2494
|
const { groups, protectedCount } = selectGroups(all, { guard: { uid, mine }, now: Date.now(), home: homedir4(), exists: existsSync3, minMem, olderMs });
|
|
2307
2495
|
const pids = groups.flatMap((group) => group.members.map(({ proc }) => proc.pid));
|
|
2308
2496
|
const show = (extra = {}) => {
|
|
@@ -2315,7 +2503,7 @@ async function procs(args) {
|
|
|
2315
2503
|
if (values.kill !== true || pids.length === 0 || values.yes !== true) {
|
|
2316
2504
|
show();
|
|
2317
2505
|
if (values.json !== true && protectedCount > 0)
|
|
2318
|
-
console.error(paint(
|
|
2506
|
+
console.error(paint(process21.stderr).dim(`${protectedCount} more left out: shells, terminals and this command's ancestors are never touched`));
|
|
2319
2507
|
if (values.kill === true && pids.length > 0)
|
|
2320
2508
|
console.error(`dry run: would stop ${pids.length} ${pids.length === 1 ? "process" : "processes"} (${pids.join(" ")}), pass --yes to do it`);
|
|
2321
2509
|
return 0;
|
|
@@ -2331,7 +2519,7 @@ async function procs(args) {
|
|
|
2331
2519
|
}
|
|
2332
2520
|
|
|
2333
2521
|
// src/proc-cli.ts
|
|
2334
|
-
|
|
2522
|
+
process22.exitCode = await runCli({
|
|
2335
2523
|
name: "proc",
|
|
2336
2524
|
about: "what a process is, who listens on a port and which dev processes are worth cleaning, read from /proc",
|
|
2337
2525
|
replaces: "cat /proc/<pid>/..., ss -ltnp, lsof -i and pgrep -f one-liners",
|