@kaynooo/cli-proc 0.7.1 → 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 +212 -59
- package/dist/ports-cli.js +281 -70
- package/dist/proc-cli.js +294 -83
- package/dist/procs-cli.js +215 -62
- package/package.json +2 -2
- package/src/pid.ts +4 -3
- package/src/ports.ts +4 -3
- package/src/procs.ts +4 -3
- 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,24 +453,20 @@ 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)) {
|
|
457
460
|
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
458
461
|
}
|
|
459
|
-
function helpText(usage, options, colors = paint(process8.stdout), { examples = [],
|
|
460
|
-
return [usageLine(usage, colors),
|
|
462
|
+
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
|
|
463
|
+
return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
461
464
|
`);
|
|
462
465
|
}
|
|
463
466
|
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
464
467
|
if (exits.length === 0)
|
|
465
468
|
return [];
|
|
466
|
-
|
|
467
|
-
return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
|
|
468
|
-
}
|
|
469
|
-
function replacesRows(replaces, colors = paint(process8.stdout)) {
|
|
470
|
-
return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
469
|
+
return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
|
|
471
470
|
}
|
|
472
471
|
function wantsHelpJson(env = process8.env) {
|
|
473
472
|
return env.KIT_HELP === "json";
|
|
@@ -493,29 +492,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
|
493
492
|
return [];
|
|
494
493
|
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
495
494
|
}
|
|
495
|
+
var MAX_INLINE_CHOICES = 24;
|
|
496
496
|
function optionRows(options, colors = paint(process8.stdout)) {
|
|
497
497
|
const rows = Object.entries(options).map(([name, option]) => {
|
|
498
498
|
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
499
|
-
const
|
|
499
|
+
const choices = option.choices?.join("|");
|
|
500
|
+
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
501
|
+
const named = inline ? `<${choices}>` : "<value>";
|
|
500
502
|
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
501
503
|
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
502
|
-
|
|
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 };
|
|
503
506
|
});
|
|
504
507
|
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
505
508
|
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
506
509
|
}
|
|
507
510
|
|
|
508
511
|
// ../kit/src/text.ts
|
|
509
|
-
var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
|
|
510
512
|
function distance(a, b) {
|
|
511
|
-
|
|
512
|
-
|
|
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()) {
|
|
513
518
|
const current = [i + 1];
|
|
514
|
-
for (const [j,
|
|
515
|
-
|
|
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;
|
|
516
526
|
previous = current;
|
|
517
527
|
}
|
|
518
|
-
return previous[
|
|
528
|
+
return previous[right.length] ?? 0;
|
|
519
529
|
}
|
|
520
530
|
function closest(name, names) {
|
|
521
531
|
const started = names.find((known) => known.startsWith(name));
|
|
@@ -591,7 +601,7 @@ class Completing {
|
|
|
591
601
|
}
|
|
592
602
|
var completion = { active: false };
|
|
593
603
|
var OUTPUT_OPTIONS = {
|
|
594
|
-
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" },
|
|
595
605
|
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
596
606
|
};
|
|
597
607
|
function applyOutput(color, plain, env = process9.env) {
|
|
@@ -763,9 +773,33 @@ function nearestOption(message, options, allowNegative) {
|
|
|
763
773
|
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
764
774
|
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
765
775
|
}
|
|
776
|
+
// ../kit/src/argv.ts
|
|
777
|
+
import { readFileSync as readFileSync2, realpathSync } from "fs";
|
|
778
|
+
import { resolve as resolve3 } from "path";
|
|
779
|
+
import process10 from "process";
|
|
780
|
+
function commandLine() {
|
|
781
|
+
try {
|
|
782
|
+
return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
|
|
783
|
+
} catch {
|
|
784
|
+
return;
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
function realPath(word) {
|
|
788
|
+
try {
|
|
789
|
+
return realpathSync(resolve3(word));
|
|
790
|
+
} catch {
|
|
791
|
+
return;
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
|
|
795
|
+
const target = script === undefined ? undefined : realPath(script) ?? script;
|
|
796
|
+
const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
|
|
797
|
+
const after = at === -1 ? [] : cmdline.slice(at + 1);
|
|
798
|
+
return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
|
|
799
|
+
}
|
|
766
800
|
// ../kit/src/process.ts
|
|
767
801
|
import { constants } from "os";
|
|
768
|
-
import
|
|
802
|
+
import process11 from "process";
|
|
769
803
|
var KILL_GRACE_MS = 2000;
|
|
770
804
|
function exitCodeOf(code, signal) {
|
|
771
805
|
if (code !== null)
|
|
@@ -785,7 +819,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
|
|
|
785
819
|
return;
|
|
786
820
|
try {
|
|
787
821
|
if (grouped)
|
|
788
|
-
|
|
822
|
+
process11.kill(-proc.pid, killing);
|
|
789
823
|
else
|
|
790
824
|
proc.kill(killing);
|
|
791
825
|
} catch {}
|
|
@@ -859,15 +893,93 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
|
|
|
859
893
|
var RESET_STYLE = `${ESC}[0m`;
|
|
860
894
|
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
861
895
|
// ../kit/src/cli.ts
|
|
862
|
-
import { readFileSync as
|
|
896
|
+
import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
|
|
863
897
|
import { dirname as dirname3, join as join5 } from "path";
|
|
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
|
|
864
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
|
+
}
|
|
865
977
|
|
|
866
978
|
// ../kit/src/usage.ts
|
|
867
979
|
import { appendFileSync, mkdirSync } from "fs";
|
|
868
980
|
import { homedir as homedir3 } from "os";
|
|
869
981
|
import { dirname as dirname2, isAbsolute, join as join4 } from "path";
|
|
870
|
-
import
|
|
982
|
+
import process13 from "process";
|
|
871
983
|
|
|
872
984
|
// ../kit/src/logs.ts
|
|
873
985
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
@@ -881,14 +993,14 @@ var usageError;
|
|
|
881
993
|
function noteUsageError(message) {
|
|
882
994
|
usageError = message;
|
|
883
995
|
}
|
|
884
|
-
function stateHome(env =
|
|
996
|
+
function stateHome(env = process13.env) {
|
|
885
997
|
const dir = env.XDG_STATE_HOME;
|
|
886
998
|
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
887
999
|
}
|
|
888
|
-
function usagePath(env =
|
|
1000
|
+
function usagePath(env = process13.env) {
|
|
889
1001
|
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
890
1002
|
}
|
|
891
|
-
function usageRecorded(env =
|
|
1003
|
+
function usageRecorded(env = process13.env) {
|
|
892
1004
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
893
1005
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
894
1006
|
}
|
|
@@ -902,7 +1014,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
902
1014
|
usageError = undefined;
|
|
903
1015
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
904
1016
|
}
|
|
905
|
-
function recordUsage(entry, env =
|
|
1017
|
+
function recordUsage(entry, env = process13.env) {
|
|
906
1018
|
if (!usageRecorded(env))
|
|
907
1019
|
return;
|
|
908
1020
|
try {
|
|
@@ -918,7 +1030,11 @@ var LEVEL_OPTIONS = {
|
|
|
918
1030
|
...OUTPUT_OPTIONS,
|
|
919
1031
|
help: { type: "boolean", short: "h", description: "show this help" }
|
|
920
1032
|
};
|
|
921
|
-
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
|
+
};
|
|
922
1038
|
async function commandRows(all, colors) {
|
|
923
1039
|
const commands = shown(all);
|
|
924
1040
|
const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
|
|
@@ -979,7 +1095,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
|
|
|
979
1095
|
header(colors, summary),
|
|
980
1096
|
"",
|
|
981
1097
|
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
982
|
-
...replacesRows(replaces, colors),
|
|
983
1098
|
"",
|
|
984
1099
|
...await commandRows(commands, colors),
|
|
985
1100
|
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
@@ -993,8 +1108,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
|
|
|
993
1108
|
`);
|
|
994
1109
|
}
|
|
995
1110
|
function printError(prefix, message, hint, cause) {
|
|
996
|
-
const colors = paint(
|
|
997
|
-
const styled = takesControlCodes(
|
|
1111
|
+
const colors = paint(process14.stderr);
|
|
1112
|
+
const styled = takesControlCodes(process14.stderr);
|
|
998
1113
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
999
1114
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
1000
1115
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -1037,11 +1152,11 @@ async function dispatch(level, typed, { version, redact }) {
|
|
|
1037
1152
|
}
|
|
1038
1153
|
}
|
|
1039
1154
|
if (name === undefined && level.path.length > 1) {
|
|
1040
|
-
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));
|
|
1041
1156
|
return 2;
|
|
1042
1157
|
}
|
|
1043
1158
|
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
1044
|
-
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));
|
|
1045
1160
|
return 0;
|
|
1046
1161
|
}
|
|
1047
1162
|
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
@@ -1097,24 +1212,24 @@ function candidateLine(candidate) {
|
|
|
1097
1212
|
}
|
|
1098
1213
|
function positionalBeingTyped(before, { options, positionals }) {
|
|
1099
1214
|
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
1100
|
-
|
|
1215
|
+
const typed = [];
|
|
1101
1216
|
let at = 0;
|
|
1102
1217
|
while (at < before.length) {
|
|
1103
1218
|
const word = before[at];
|
|
1104
1219
|
if (word === "--") {
|
|
1105
|
-
|
|
1220
|
+
typed.push(...before.slice(at + 1));
|
|
1106
1221
|
break;
|
|
1107
1222
|
}
|
|
1108
1223
|
if (!word.startsWith("-"))
|
|
1109
|
-
|
|
1224
|
+
typed.push(word);
|
|
1110
1225
|
else if (takesValue(word))
|
|
1111
1226
|
at++;
|
|
1112
1227
|
at++;
|
|
1113
1228
|
}
|
|
1114
1229
|
const last = positionals.at(-1);
|
|
1115
|
-
if (
|
|
1116
|
-
return positionals[
|
|
1117
|
-
return last?.replace("]", "").endsWith("...") === true ? last : undefined;
|
|
1230
|
+
if (typed.length < positionals.length)
|
|
1231
|
+
return { name: positionals[typed.length], typed };
|
|
1232
|
+
return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
|
|
1118
1233
|
}
|
|
1119
1234
|
async function leafCandidates(run, words) {
|
|
1120
1235
|
const completing = await completingOf(run);
|
|
@@ -1122,12 +1237,12 @@ async function leafCandidates(run, words) {
|
|
|
1122
1237
|
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
1123
1238
|
const flag = words.at(-2);
|
|
1124
1239
|
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
1240
|
+
const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
|
|
1125
1241
|
if (option?.type === "string") {
|
|
1126
|
-
const values = option.choices === undefined ? await option.candidates?.() : option.choices;
|
|
1242
|
+
const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
|
|
1127
1243
|
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1128
1244
|
}
|
|
1129
|
-
const
|
|
1130
|
-
const values = name === undefined ? undefined : await completing.candidates[name]?.();
|
|
1245
|
+
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
1131
1246
|
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1132
1247
|
}
|
|
1133
1248
|
async function candidates(scope, defaultCommand, words, before = []) {
|
|
@@ -1152,15 +1267,32 @@ async function candidates(scope, defaultCommand, words, before = []) {
|
|
|
1152
1267
|
}
|
|
1153
1268
|
return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
|
|
1154
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
|
+
}
|
|
1155
1283
|
async function printCandidates(found) {
|
|
1156
1284
|
for (const line of await found)
|
|
1157
1285
|
console.log(line);
|
|
1158
1286
|
return 0;
|
|
1159
1287
|
}
|
|
1160
1288
|
function packageVersion(entry = Bun.main) {
|
|
1161
|
-
|
|
1289
|
+
let resolved = entry;
|
|
1290
|
+
try {
|
|
1291
|
+
resolved = realpathSync2(entry);
|
|
1292
|
+
} catch {}
|
|
1293
|
+
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
1162
1294
|
try {
|
|
1163
|
-
const { version } = JSON.parse(
|
|
1295
|
+
const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
|
|
1164
1296
|
if (typeof version === "string")
|
|
1165
1297
|
return version;
|
|
1166
1298
|
} catch {}
|
|
@@ -1168,14 +1300,19 @@ function packageVersion(entry = Bun.main) {
|
|
|
1168
1300
|
return "0.0.0";
|
|
1169
1301
|
}
|
|
1170
1302
|
}
|
|
1171
|
-
async function runCli(cli, argv =
|
|
1303
|
+
async function runCli(cli, argv = scriptArgs()) {
|
|
1172
1304
|
const version = cli.version ?? packageVersion();
|
|
1173
1305
|
if (argv[0] === COMPLETE)
|
|
1174
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();
|
|
1175
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);
|
|
1176
1313
|
if (cli.usage !== false) {
|
|
1177
1314
|
try {
|
|
1178
|
-
recordUsage(usageEntry(cli.name,
|
|
1315
|
+
recordUsage(usageEntry(cli.name, command, argv, code));
|
|
1179
1316
|
} catch {}
|
|
1180
1317
|
}
|
|
1181
1318
|
return code;
|
|
@@ -1195,19 +1332,23 @@ function commandPath(scope, argv) {
|
|
|
1195
1332
|
}
|
|
1196
1333
|
return path.length === 0 ? undefined : path.join(" ");
|
|
1197
1334
|
}
|
|
1198
|
-
async function runMain({ name, version, run, redact, usage }, argv =
|
|
1335
|
+
async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
|
|
1199
1336
|
if (argv[0] === COMPLETE)
|
|
1200
1337
|
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
1338
|
+
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
1339
|
+
return printCompletionScript(name, flagValue(argv));
|
|
1201
1340
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
1202
1341
|
console.log(version ?? packageVersion());
|
|
1203
1342
|
return 0;
|
|
1204
1343
|
}
|
|
1205
1344
|
let code;
|
|
1345
|
+
const started = performance.now();
|
|
1206
1346
|
try {
|
|
1207
1347
|
code = await run(argv);
|
|
1208
1348
|
} catch (error) {
|
|
1209
1349
|
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
1210
1350
|
}
|
|
1351
|
+
notifyEnd(name, code, performance.now() - started);
|
|
1211
1352
|
if (usage !== false) {
|
|
1212
1353
|
try {
|
|
1213
1354
|
recordUsage(usageEntry(name, undefined, argv, code));
|
|
@@ -1239,7 +1380,7 @@ function parseSize(text, bareUnit = 1) {
|
|
|
1239
1380
|
return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
|
|
1240
1381
|
}
|
|
1241
1382
|
// ../kit/src/watch.ts
|
|
1242
|
-
import
|
|
1383
|
+
import process15 from "process";
|
|
1243
1384
|
import { format } from "util";
|
|
1244
1385
|
var CLEAR_SCREEN = "\x1B[H\x1B[2J";
|
|
1245
1386
|
var DEFAULT_SECONDS = 2;
|
|
@@ -1261,7 +1402,7 @@ function withoutWatch(args) {
|
|
|
1261
1402
|
}
|
|
1262
1403
|
return rest;
|
|
1263
1404
|
}
|
|
1264
|
-
async function watching(value, step, stream =
|
|
1405
|
+
async function watching(value, step, stream = process15.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
|
|
1265
1406
|
const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
|
|
1266
1407
|
if (!takesControlCodes(stream))
|
|
1267
1408
|
badUsage("--watch redraws the screen, so it needs a terminal");
|
|
@@ -1269,12 +1410,12 @@ async function watching(value, step, stream = process13.stdout, sleep = Bun.slee
|
|
|
1269
1410
|
for (let round = 0;round < rounds; round++) {
|
|
1270
1411
|
const held = [];
|
|
1271
1412
|
const { log, info } = console;
|
|
1272
|
-
const write =
|
|
1413
|
+
const write = process15.stdout.write.bind(process15.stdout);
|
|
1273
1414
|
const hold = (...parts) => void held.push(`${format(...parts)}
|
|
1274
1415
|
`);
|
|
1275
1416
|
console.log = hold;
|
|
1276
1417
|
console.info = hold;
|
|
1277
|
-
|
|
1418
|
+
process15.stdout.write = (text) => {
|
|
1278
1419
|
held.push(typeof text === "string" ? text : Buffer.from(text).toString());
|
|
1279
1420
|
return true;
|
|
1280
1421
|
};
|
|
@@ -1283,7 +1424,7 @@ async function watching(value, step, stream = process13.stdout, sleep = Bun.slee
|
|
|
1283
1424
|
} finally {
|
|
1284
1425
|
console.log = log;
|
|
1285
1426
|
console.info = info;
|
|
1286
|
-
|
|
1427
|
+
process15.stdout.write = write;
|
|
1287
1428
|
}
|
|
1288
1429
|
stream.write(`${CLEAR_SCREEN}${held.join("")}`);
|
|
1289
1430
|
await sleep(interval);
|
|
@@ -1291,7 +1432,7 @@ async function watching(value, step, stream = process13.stdout, sleep = Bun.slee
|
|
|
1291
1432
|
return code;
|
|
1292
1433
|
}
|
|
1293
1434
|
// src/pid.ts
|
|
1294
|
-
import
|
|
1435
|
+
import process17 from "process";
|
|
1295
1436
|
|
|
1296
1437
|
// src/mask.ts
|
|
1297
1438
|
import { basename } from "path";
|
|
@@ -1584,10 +1725,22 @@ async function socketsOf(pid, root = "/proc") {
|
|
|
1584
1725
|
return inodes;
|
|
1585
1726
|
}
|
|
1586
1727
|
async function socketOwners(root = "/proc") {
|
|
1587
|
-
const
|
|
1728
|
+
const holders = new Map;
|
|
1588
1729
|
for (const pid of await listPids(root)) {
|
|
1589
1730
|
for (const inode of await socketsOf(pid, root))
|
|
1590
|
-
|
|
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);
|
|
1591
1744
|
}
|
|
1592
1745
|
return owners;
|
|
1593
1746
|
}
|
|
@@ -1608,9 +1761,8 @@ async function userName(uid) {
|
|
|
1608
1761
|
var usage2 = `pid <pid>
|
|
1609
1762
|
|
|
1610
1763
|
Shows what a process is: its executable, working directory, command line, parent chain up to init, user, start time and age, memory, open files and limits, the TCP and UDP ports it listens on and its cgroup. Everything is read from /proc; what the calling user cannot read of another user's process is left out and named at the end.
|
|
1611
|
-
The environment is not shown unless --env is given, with every value that looks like a secret masked
|
|
1612
|
-
|
|
1613
|
-
Exits 0 when it showed the process, 1 when no process has this pid, 2 on a usage error.`;
|
|
1764
|
+
The environment is not shown unless --env is given, with every value that looks like a secret masked.`;
|
|
1765
|
+
var EXITS = [[0, "it showed the process"], [1, "no process has this pid"], [2, "a usage error"]];
|
|
1614
1766
|
var DIGITS2 = /^\d+$/;
|
|
1615
1767
|
var options = {
|
|
1616
1768
|
env: { type: "boolean", description: "show the environment, secrets masked" },
|
|
@@ -1682,7 +1834,7 @@ function limitLine(limits, name) {
|
|
|
1682
1834
|
return limit === undefined ? "-" : `soft ${limit.soft}, hard ${limit.hard}`;
|
|
1683
1835
|
}
|
|
1684
1836
|
function render(info, showEnv) {
|
|
1685
|
-
const colors = paint(
|
|
1837
|
+
const colors = paint(process17.stdout);
|
|
1686
1838
|
const memory = info.memory;
|
|
1687
1839
|
const size = (bytes) => bytes === undefined ? "-" : tt(bytes);
|
|
1688
1840
|
const rows = [
|
|
@@ -1712,6 +1864,7 @@ function render(info, showEnv) {
|
|
|
1712
1864
|
}
|
|
1713
1865
|
async function pid(args) {
|
|
1714
1866
|
const { values, positionals } = parse(args, usage2, options, {
|
|
1867
|
+
exits: EXITS,
|
|
1715
1868
|
positionals: ["<pid>"],
|
|
1716
1869
|
replaces: "cat /proc/<pid>/{cmdline,environ,limits}, readlink /proc/<pid>/{exe,cwd}, the fish pid function",
|
|
1717
1870
|
examples: [
|
|
@@ -1735,10 +1888,24 @@ async function pid(args) {
|
|
|
1735
1888
|
|
|
1736
1889
|
// src/ports.ts
|
|
1737
1890
|
import { basename as basename2 } from "path";
|
|
1738
|
-
import
|
|
1891
|
+
import process20 from "process";
|
|
1739
1892
|
|
|
1740
1893
|
// ../kit/src/prompt.ts
|
|
1741
|
-
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
|
+
}
|
|
1742
1909
|
|
|
1743
1910
|
// ../kit/src/picker/score.ts
|
|
1744
1911
|
var BOUNDARY_AFTER = new Set([" ", "/", "-", "_", ".", ":", "\\", "(", "[", ",", "\t"]);
|
|
@@ -1770,10 +1937,29 @@ var KEYS = {
|
|
|
1770
1937
|
"\n": "enter",
|
|
1771
1938
|
"\x03": "cancel",
|
|
1772
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",
|
|
1773
1952
|
"\x7F": "erase",
|
|
1774
|
-
"\
|
|
1953
|
+
"\x1B[3~": "delete",
|
|
1954
|
+
"\b": "killword",
|
|
1955
|
+
"\x1B\x7F": "killword",
|
|
1956
|
+
"\x1B[3;5~": "killnext",
|
|
1957
|
+
"\x1Bd": "killnext",
|
|
1775
1958
|
"\x15": "clear",
|
|
1959
|
+
"\v": "killend",
|
|
1776
1960
|
"\x17": "word",
|
|
1961
|
+
"\x19": "yank",
|
|
1962
|
+
"\x1A": "suspend",
|
|
1777
1963
|
"\t": "tab",
|
|
1778
1964
|
"\x1F": "help",
|
|
1779
1965
|
"\x1BOP": "help",
|
|
@@ -1803,10 +1989,21 @@ function parseKeys(input, paste = { active: false }, ctrls = []) {
|
|
|
1803
1989
|
});
|
|
1804
1990
|
}
|
|
1805
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
|
+
|
|
1806
2003
|
// ../kit/src/prompt.ts
|
|
1807
|
-
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"]);
|
|
1808
2005
|
function readKeys(input, paste = { active: false }) {
|
|
1809
|
-
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));
|
|
1810
2007
|
}
|
|
1811
2008
|
async function confirm(question, { default: fallback, ...settings } = {}) {
|
|
1812
2009
|
let answered = fallback;
|
|
@@ -1830,7 +2027,7 @@ function asking(colors, question, typed, keys) {
|
|
|
1830
2027
|
function answer(colors, question, state, picked) {
|
|
1831
2028
|
return state === "enter" ? `${colors.green("\u2713")} ${question} ${colors.cyan(picked)}` : `${colors.red("\u2717")} ${question} ${colors.dim("cancelled")}`;
|
|
1832
2029
|
}
|
|
1833
|
-
async function ask(question, { hint, terminal =
|
|
2030
|
+
async function ask(question, { hint, terminal = process19 }, render, press) {
|
|
1834
2031
|
const { stdin, stderr } = terminal;
|
|
1835
2032
|
if (!isInteractive(terminal))
|
|
1836
2033
|
fail(`cannot ask "${question}" off a terminal`, 2, hint);
|
|
@@ -1840,12 +2037,22 @@ async function ask(question, { hint, terminal = process16 }, render, press) {
|
|
|
1840
2037
|
const columns = () => stderr.columns || 80;
|
|
1841
2038
|
const draw = (state, last = false) => {
|
|
1842
2039
|
const frame = render(colors, state, { columns: columns(), rows: stderr.rows || 24 });
|
|
1843
|
-
|
|
1844
|
-
|
|
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}`);
|
|
1845
2042
|
current = state;
|
|
1846
2043
|
};
|
|
1847
2044
|
const redraw = () => draw(current);
|
|
1848
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
|
+
};
|
|
1849
2056
|
try {
|
|
1850
2057
|
stderr.on?.("resize", redraw);
|
|
1851
2058
|
stdin.setRawMode(true);
|
|
@@ -1855,6 +2062,10 @@ async function ask(question, { hint, terminal = process16 }, render, press) {
|
|
|
1855
2062
|
return await new Promise((resolve) => {
|
|
1856
2063
|
function onData(data) {
|
|
1857
2064
|
for (const key of readKeys(data.toString(), paste)) {
|
|
2065
|
+
if (key === "suspend") {
|
|
2066
|
+
suspend();
|
|
2067
|
+
continue;
|
|
2068
|
+
}
|
|
1858
2069
|
const pressed = press(key);
|
|
1859
2070
|
if (pressed !== undefined) {
|
|
1860
2071
|
settle(pressed);
|
|
@@ -1965,9 +2176,8 @@ var usage3 = `ports [port]
|
|
|
1965
2176
|
|
|
1966
2177
|
Lists what listens on this machine, TCP and UDP over IPv4 and IPv6, one row per port with its bound address, the owning process, its command and its working directory. A port Docker publishes is held by docker-proxy, and shows as its compose project and service when docker is installed; the owner of a socket of another user cannot be read and shows as -.
|
|
1967
2178
|
\`ports <port>\` keeps that port alone and exits 1 when nothing listens on it.
|
|
1968
|
-
\`ports <port> --kill\` stops its owner with SIGTERM, and with --force SIGKILL once --grace has passed, after asking on a terminal unless --yes is given. It refuses processes of other users, pid 1, this command and its ancestors, and docker-proxy, for which it names the container to stop instead
|
|
1969
|
-
|
|
1970
|
-
Exits 0 when it listed or stopped, 1 when nothing listens on the given port or the owner could not be stopped, 2 on a usage error.`;
|
|
2179
|
+
\`ports <port> --kill\` stops its owner with SIGTERM, and with --force SIGKILL once --grace has passed, after asking on a terminal unless --yes is given. It refuses processes of other users, pid 1, this command and its ancestors, and docker-proxy, for which it names the container to stop instead.`;
|
|
2180
|
+
var EXITS2 = [[0, "it listed or stopped"], [1, "nothing listens on the given port or the owner could not be stopped"], [2, "a usage error"]];
|
|
1971
2181
|
var options2 = {
|
|
1972
2182
|
json: jsonOption("[{ port, protocol, addresses, pid, command, cwd, container }]"),
|
|
1973
2183
|
kill: { type: "boolean", conflicts: ["watch"], description: "stop the owner of the given port" },
|
|
@@ -2016,7 +2226,7 @@ function refusal(row, proc, guard) {
|
|
|
2016
2226
|
return reason === undefined ? undefined : `pid ${row.pid} is ${reason}`;
|
|
2017
2227
|
}
|
|
2018
2228
|
function render2(rows) {
|
|
2019
|
-
const colors = paint(
|
|
2229
|
+
const colors = paint(process20.stdout);
|
|
2020
2230
|
const cells = rows.map((row) => [
|
|
2021
2231
|
colors.cyan(String(row.port)),
|
|
2022
2232
|
row.protocol,
|
|
@@ -2028,7 +2238,7 @@ function render2(rows) {
|
|
|
2028
2238
|
return table([["PORT", "PROTO", "ADDRESS", "PID", "COMMAND", "CWD"], ...cells], { header: true });
|
|
2029
2239
|
}
|
|
2030
2240
|
async function stop(port, rows, procs, values) {
|
|
2031
|
-
const guard = { uid:
|
|
2241
|
+
const guard = { uid: process20.getuid?.() ?? -1, mine: new Set(ancestry(process20.pid, procs)) };
|
|
2032
2242
|
const targets = new Map;
|
|
2033
2243
|
for (const row of rows) {
|
|
2034
2244
|
const reason = refusal(row, row.pid === undefined ? undefined : procs.get(row.pid), guard);
|
|
@@ -2041,7 +2251,7 @@ async function stop(port, rows, procs, values) {
|
|
|
2041
2251
|
return 1;
|
|
2042
2252
|
const names = [...targets].map(([pid, row]) => `${pid} (${truncate(row.command ?? "", 40)})`).join(", ");
|
|
2043
2253
|
if (values.yes !== true) {
|
|
2044
|
-
if (!
|
|
2254
|
+
if (!process20.stdin.isTTY)
|
|
2045
2255
|
fail(`stopping ${names} needs a terminal to ask on: pass --yes`, 2);
|
|
2046
2256
|
if (await confirm(`Stop ${names}?`, { default: false }) !== true)
|
|
2047
2257
|
return 1;
|
|
@@ -2055,6 +2265,7 @@ async function stop(port, rows, procs, values) {
|
|
|
2055
2265
|
}
|
|
2056
2266
|
async function ports(args) {
|
|
2057
2267
|
const { values, positionals } = parse(args, usage3, options2, {
|
|
2268
|
+
exits: EXITS2,
|
|
2058
2269
|
positionals: ["[port]"],
|
|
2059
2270
|
replaces: "ss -ltnp | grep, lsof -i, fuser -k and lookups of docker-proxy by hand",
|
|
2060
2271
|
examples: [
|
|
@@ -2072,7 +2283,7 @@ async function ports(args) {
|
|
|
2072
2283
|
badUsage(`<port> takes a whole number from 1 to 65535, not ${given}`);
|
|
2073
2284
|
if (values.kill === true && port === undefined)
|
|
2074
2285
|
badUsage("--kill takes the port to free: ports <port> --kill");
|
|
2075
|
-
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?.())]);
|
|
2076
2287
|
const byPid = new Map(procs.map((proc) => [proc.pid, proc]));
|
|
2077
2288
|
const wanted = sockets.filter((socket) => port === undefined || socket.port === port);
|
|
2078
2289
|
const needsDocker = wanted.some((socket) => {
|
|
@@ -2093,14 +2304,14 @@ async function ports(args) {
|
|
|
2093
2304
|
console.log(render2(rows));
|
|
2094
2305
|
const unknown = rows.filter((row) => row.pid === undefined && row.container === undefined).length;
|
|
2095
2306
|
if (unknown > 0)
|
|
2096
|
-
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 -`));
|
|
2097
2308
|
return 0;
|
|
2098
2309
|
}
|
|
2099
2310
|
|
|
2100
2311
|
// src/procs.ts
|
|
2101
2312
|
import { existsSync as existsSync3 } from "fs";
|
|
2102
2313
|
import { homedir as homedir4 } from "os";
|
|
2103
|
-
import
|
|
2314
|
+
import process21 from "process";
|
|
2104
2315
|
|
|
2105
2316
|
// src/select.ts
|
|
2106
2317
|
import { basename as basename3, join as join6, relative } from "path";
|
|
@@ -2220,9 +2431,8 @@ var usage4 = `procs
|
|
|
2220
2431
|
|
|
2221
2432
|
Lists the leftover or heavy processes of the calling user that are worth cleaning, grouped by origin: the project folder their working directory is in, a browser profile for a chromium and its helpers, else their command. Each group shows its process count, total resident memory and oldest age.
|
|
2222
2433
|
A process is listed when it is a dev tool (bun, node, vite, nuxt, next, chromium and chrome, playwright and webview browsers and their helpers, language servers, test runners) and either an orphan, reparented to init or to the user's systemd, or heavy (500M resident by default). The processes below a listed one, and those sharing a browser profile with it, are listed too, so a chromium whose main process was killed groups with its leftover helpers.
|
|
2223
|
-
\`--kill\` is a dry run that names what it would stop unless --yes is given; it sends SIGTERM, then SIGKILL after --grace to what is still there. It never signals pid 1, shells, terminals, this command and its ancestors, or processes of other users
|
|
2224
|
-
|
|
2225
|
-
Exits 0 when it listed or stopped everything, 1 when a process survived SIGKILL, 2 on a usage error.`;
|
|
2434
|
+
\`--kill\` is a dry run that names what it would stop unless --yes is given; it sends SIGTERM, then SIGKILL after --grace to what is still there. It never signals pid 1, shells, terminals, this command and its ancestors, or processes of other users.`;
|
|
2435
|
+
var EXITS3 = [[0, "it listed or stopped everything"], [1, "a process survived SIGKILL"], [2, "a usage error"]];
|
|
2226
2436
|
var options3 = {
|
|
2227
2437
|
json: jsonOption("{ groups: [{ origin, kind, count, rss, oldestSeconds, tools, orphans, pids, processes }], skipped }"),
|
|
2228
2438
|
kill: { type: "boolean", conflicts: ["watch"], description: "stop the listed processes: a dry run without --yes" },
|
|
@@ -2250,7 +2460,7 @@ function summary(group) {
|
|
|
2250
2460
|
};
|
|
2251
2461
|
}
|
|
2252
2462
|
function render3(groups) {
|
|
2253
|
-
const colors = paint(
|
|
2463
|
+
const colors = paint(process21.stdout);
|
|
2254
2464
|
const rows = groups.map((group) => [
|
|
2255
2465
|
group.origin,
|
|
2256
2466
|
String(group.members.length),
|
|
@@ -2263,6 +2473,7 @@ function render3(groups) {
|
|
|
2263
2473
|
}
|
|
2264
2474
|
async function procs(args) {
|
|
2265
2475
|
const { values } = parse(args, usage4, options3, {
|
|
2476
|
+
exits: EXITS3,
|
|
2266
2477
|
replaces: "pkill -f and pgrep -f one-liners (which match their own shell), ps aux | grep for leftover chromium, bun or vite processes",
|
|
2267
2478
|
examples: [
|
|
2268
2479
|
["procs", "leftover and heavy dev processes, by origin"],
|
|
@@ -2277,9 +2488,9 @@ async function procs(args) {
|
|
|
2277
2488
|
if (values.watch !== undefined)
|
|
2278
2489
|
return watching(values.watch, async () => procs(withoutWatch(args)));
|
|
2279
2490
|
const olderMs = values.older === undefined ? undefined : duration(values.older, "older", 0, "m");
|
|
2280
|
-
const uid =
|
|
2491
|
+
const uid = process21.getuid?.() ?? -1;
|
|
2281
2492
|
const all = await snapshot("/proc", (owner) => owner === uid);
|
|
2282
|
-
const mine = new Set(ancestry(
|
|
2493
|
+
const mine = new Set(ancestry(process21.pid, new Map(all.map((proc) => [proc.pid, proc]))));
|
|
2283
2494
|
const { groups, protectedCount } = selectGroups(all, { guard: { uid, mine }, now: Date.now(), home: homedir4(), exists: existsSync3, minMem, olderMs });
|
|
2284
2495
|
const pids = groups.flatMap((group) => group.members.map(({ proc }) => proc.pid));
|
|
2285
2496
|
const show = (extra = {}) => {
|
|
@@ -2292,7 +2503,7 @@ async function procs(args) {
|
|
|
2292
2503
|
if (values.kill !== true || pids.length === 0 || values.yes !== true) {
|
|
2293
2504
|
show();
|
|
2294
2505
|
if (values.json !== true && protectedCount > 0)
|
|
2295
|
-
console.error(paint(
|
|
2506
|
+
console.error(paint(process21.stderr).dim(`${protectedCount} more left out: shells, terminals and this command's ancestors are never touched`));
|
|
2296
2507
|
if (values.kill === true && pids.length > 0)
|
|
2297
2508
|
console.error(`dry run: would stop ${pids.length} ${pids.length === 1 ? "process" : "processes"} (${pids.join(" ")}), pass --yes to do it`);
|
|
2298
2509
|
return 0;
|
|
@@ -2308,7 +2519,7 @@ async function procs(args) {
|
|
|
2308
2519
|
}
|
|
2309
2520
|
|
|
2310
2521
|
// src/proc-cli.ts
|
|
2311
|
-
|
|
2522
|
+
process22.exitCode = await runCli({
|
|
2312
2523
|
name: "proc",
|
|
2313
2524
|
about: "what a process is, who listens on a port and which dev processes are worth cleaning, read from /proc",
|
|
2314
2525
|
replaces: "cat /proc/<pid>/..., ss -ltnp, lsof -i and pgrep -f one-liners",
|