@kaynooo/cli-proc 0.2.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/pid-cli.js +310 -45
- package/dist/ports-cli.js +396 -65
- package/dist/proc-cli.js +2262 -0
- package/dist/procs-cli.js +317 -49
- package/package.json +5 -3
- package/src/ports.ts +7 -2
- package/src/proc-cli.ts +19 -0
- package/src/procs.ts +6 -2
package/dist/procs-cli.js
CHANGED
|
@@ -2,16 +2,37 @@
|
|
|
2
2
|
// @bun
|
|
3
3
|
|
|
4
4
|
// src/procs-cli.ts
|
|
5
|
-
import
|
|
5
|
+
import process13 from "process";
|
|
6
6
|
// ../kit/src/args.ts
|
|
7
|
-
import
|
|
7
|
+
import process6 from "process";
|
|
8
8
|
import { parseArgs } from "util";
|
|
9
9
|
|
|
10
10
|
// ../kit/src/format.ts
|
|
11
|
-
import
|
|
11
|
+
import process4 from "process";
|
|
12
12
|
|
|
13
|
-
// ../kit/src/
|
|
13
|
+
// ../kit/src/mode.ts
|
|
14
14
|
import process2 from "process";
|
|
15
|
+
var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
16
|
+
var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
|
|
17
|
+
function isSet(value) {
|
|
18
|
+
return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
19
|
+
}
|
|
20
|
+
function outputMode(stream = process2.stdout, env = process2.env) {
|
|
21
|
+
const chosen = env.KIT_MODE;
|
|
22
|
+
if (chosen !== undefined && MODES.has(chosen))
|
|
23
|
+
return chosen;
|
|
24
|
+
if (AGENT_VARIABLES.some((name) => isSet(env[name])))
|
|
25
|
+
return "agent";
|
|
26
|
+
if (stream.isTTY === true)
|
|
27
|
+
return "terminal";
|
|
28
|
+
return isSet(env.CI) ? "ci" : "pipe";
|
|
29
|
+
}
|
|
30
|
+
function isInteractive(streams = process2) {
|
|
31
|
+
return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// ../kit/src/style.ts
|
|
35
|
+
import process3 from "process";
|
|
15
36
|
|
|
16
37
|
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
|
|
17
38
|
function x(s) {
|
|
@@ -274,21 +295,26 @@ function le(i = {}) {
|
|
|
274
295
|
}
|
|
275
296
|
var t = le();
|
|
276
297
|
|
|
298
|
+
// ../kit/src/theme.ts
|
|
299
|
+
var STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
|
|
300
|
+
var MAX_FILE_BYTES = 64 * 1024;
|
|
301
|
+
var warned = new Set;
|
|
302
|
+
|
|
277
303
|
// ../kit/src/style.ts
|
|
278
|
-
function takesControlCodes(stream, env =
|
|
279
|
-
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
|
|
304
|
+
function takesControlCodes(stream, env = process3.env) {
|
|
305
|
+
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
|
|
280
306
|
}
|
|
281
|
-
function paint(stream, env =
|
|
307
|
+
function paint(stream, env = process3.env) {
|
|
282
308
|
return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
283
309
|
}
|
|
284
|
-
var
|
|
285
|
-
passed:
|
|
286
|
-
failed:
|
|
287
|
-
running:
|
|
288
|
-
queued:
|
|
289
|
-
skipped:
|
|
310
|
+
var STATUS_WORDS = {
|
|
311
|
+
passed: ["passed", "success", "succeeded", "ok"],
|
|
312
|
+
failed: ["failed", "failure", "error", "errored"],
|
|
313
|
+
running: ["running", "in_progress", "started", "holding"],
|
|
314
|
+
queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
|
|
315
|
+
skipped: ["skipped", "cancelled", "canceled", "manual"]
|
|
290
316
|
};
|
|
291
|
-
var STATUS_OF = new Map(Object.entries(
|
|
317
|
+
var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
292
318
|
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-hrsswv1w.js
|
|
293
319
|
function $e(t, e = false, i = 1) {
|
|
294
320
|
let n = typeof e === "object" ? e : { units: e ? "si" : "iec", dp: i }, { units: s = "iec", dp: u = 1 } = n, r = s === "si" ? 1000 : 1024;
|
|
@@ -328,15 +354,18 @@ var ESCAPE = String.fromCharCode(27);
|
|
|
328
354
|
function textWidth(text) {
|
|
329
355
|
return Bun.stringWidth(text);
|
|
330
356
|
}
|
|
331
|
-
function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
|
|
357
|
+
function table(rows, { cellWidth, header = false, align = [], fit, stream = process4.stdout, env = process4.env } = {}) {
|
|
332
358
|
const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
|
|
359
|
+
if (outputMode(stream, env) === "agent")
|
|
360
|
+
return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
|
|
361
|
+
`);
|
|
333
362
|
const widths = [];
|
|
334
363
|
for (const row of cells) {
|
|
335
364
|
for (const [index, cell] of row.entries())
|
|
336
365
|
widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
|
|
337
366
|
}
|
|
338
367
|
const shown = fit === undefined ? cells : narrow(cells, widths, fit);
|
|
339
|
-
const colors = paint(
|
|
368
|
+
const colors = paint(stream);
|
|
340
369
|
const lines = shown.map((row) => row.map((cell, index) => {
|
|
341
370
|
const width = widths[index] ?? 0;
|
|
342
371
|
const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
|
|
@@ -344,7 +373,8 @@ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
|
|
|
344
373
|
return `${gap}${cell}`;
|
|
345
374
|
return index === row.length - 1 ? cell : `${cell}${gap}`;
|
|
346
375
|
}).join(" ").trimEnd());
|
|
347
|
-
|
|
376
|
+
const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
|
|
377
|
+
return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
|
|
348
378
|
`);
|
|
349
379
|
}
|
|
350
380
|
function narrow(rows, widths, limit) {
|
|
@@ -363,32 +393,35 @@ function narrow(rows, widths, limit) {
|
|
|
363
393
|
}
|
|
364
394
|
return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
|
|
365
395
|
}
|
|
396
|
+
function jsonText(value, replacer, { stream = process4.stdout, env = process4.env } = {}) {
|
|
397
|
+
return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
|
|
398
|
+
}
|
|
366
399
|
function printJson(value) {
|
|
367
|
-
console.log(
|
|
400
|
+
console.log(jsonText(value));
|
|
368
401
|
}
|
|
369
402
|
|
|
370
403
|
// ../kit/src/help.ts
|
|
371
|
-
import
|
|
404
|
+
import process5 from "process";
|
|
372
405
|
var OPTIONAL = /\[[^\]]+\]/g;
|
|
373
406
|
var USAGE_PREFIX = /^usage:\s*/i;
|
|
374
407
|
var FULL_STOP = /\.$/;
|
|
375
|
-
function usageLine(usage, colors = paint(
|
|
408
|
+
function usageLine(usage, colors = paint(process5.stdout)) {
|
|
376
409
|
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
377
410
|
}
|
|
378
|
-
function helpText(usage, options, colors = paint(
|
|
411
|
+
function helpText(usage, options, colors = paint(process5.stdout), { examples = [], replaces, exits = [] } = {}) {
|
|
379
412
|
return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
380
413
|
`);
|
|
381
414
|
}
|
|
382
|
-
function exitRows(exits, colors = paint(
|
|
415
|
+
function exitRows(exits, colors = paint(process5.stdout)) {
|
|
383
416
|
if (exits.length === 0)
|
|
384
417
|
return [];
|
|
385
418
|
const width = Math.max(...exits.map(([code]) => String(code).length));
|
|
386
419
|
return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
|
|
387
420
|
}
|
|
388
|
-
function replacesRows(replaces, colors = paint(
|
|
389
|
-
return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
421
|
+
function replacesRows(replaces, colors = paint(process5.stdout)) {
|
|
422
|
+
return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
390
423
|
}
|
|
391
|
-
function wantsHelpJson(env =
|
|
424
|
+
function wantsHelpJson(env = process5.env) {
|
|
392
425
|
return env.KIT_HELP === "json";
|
|
393
426
|
}
|
|
394
427
|
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
@@ -407,12 +440,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
|
407
440
|
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
408
441
|
};
|
|
409
442
|
}
|
|
410
|
-
function exampleRows(examples, colors = paint(
|
|
411
|
-
if (examples.length === 0)
|
|
443
|
+
function exampleRows(examples, colors = paint(process5.stdout)) {
|
|
444
|
+
if (examples.length === 0 || outputMode() === "agent")
|
|
412
445
|
return [];
|
|
413
446
|
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
414
447
|
}
|
|
415
|
-
function optionRows(options, colors = paint(
|
|
448
|
+
function optionRows(options, colors = paint(process5.stdout)) {
|
|
416
449
|
const rows = Object.entries(options).map(([name, option]) => {
|
|
417
450
|
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
418
451
|
const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
|
|
@@ -470,7 +503,6 @@ var DASHES = /^-+/;
|
|
|
470
503
|
function jsonOption(holds) {
|
|
471
504
|
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
472
505
|
}
|
|
473
|
-
|
|
474
506
|
class Exit extends Error {
|
|
475
507
|
code;
|
|
476
508
|
hint;
|
|
@@ -514,7 +546,7 @@ var OUTPUT_OPTIONS = {
|
|
|
514
546
|
color: { type: "string", description: "auto (on a terminal alone), always or never" },
|
|
515
547
|
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
516
548
|
};
|
|
517
|
-
function applyOutput(color, plain, env =
|
|
549
|
+
function applyOutput(color, plain, env = process6.env) {
|
|
518
550
|
const when = plain === true ? "never" : color ?? "auto";
|
|
519
551
|
if (when === "auto")
|
|
520
552
|
return;
|
|
@@ -685,7 +717,7 @@ function nearestOption(message, options, allowNegative) {
|
|
|
685
717
|
}
|
|
686
718
|
// ../kit/src/process.ts
|
|
687
719
|
import { constants } from "os";
|
|
688
|
-
import
|
|
720
|
+
import process7 from "process";
|
|
689
721
|
var KILL_GRACE_MS = 2000;
|
|
690
722
|
function exitCodeOf(code, signal) {
|
|
691
723
|
if (code !== null)
|
|
@@ -705,7 +737,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
|
|
|
705
737
|
return;
|
|
706
738
|
try {
|
|
707
739
|
if (grouped)
|
|
708
|
-
|
|
740
|
+
process7.kill(-proc.pid, killing);
|
|
709
741
|
else
|
|
710
742
|
proc.kill(killing);
|
|
711
743
|
} catch {}
|
|
@@ -781,13 +813,13 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
|
781
813
|
// ../kit/src/cli.ts
|
|
782
814
|
import { readFileSync, realpathSync } from "fs";
|
|
783
815
|
import { dirname as dirname2, join as join2 } from "path";
|
|
784
|
-
import
|
|
816
|
+
import process9 from "process";
|
|
785
817
|
|
|
786
818
|
// ../kit/src/usage.ts
|
|
787
819
|
import { appendFileSync, mkdirSync } from "fs";
|
|
788
820
|
import { homedir } from "os";
|
|
789
821
|
import { dirname, isAbsolute, join } from "path";
|
|
790
|
-
import
|
|
822
|
+
import process8 from "process";
|
|
791
823
|
|
|
792
824
|
// ../kit/src/logs.ts
|
|
793
825
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
@@ -801,14 +833,14 @@ var usageError;
|
|
|
801
833
|
function noteUsageError(message) {
|
|
802
834
|
usageError = message;
|
|
803
835
|
}
|
|
804
|
-
function stateHome(env =
|
|
836
|
+
function stateHome(env = process8.env) {
|
|
805
837
|
const dir = env.XDG_STATE_HOME;
|
|
806
838
|
return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
|
|
807
839
|
}
|
|
808
|
-
function usagePath(env =
|
|
840
|
+
function usagePath(env = process8.env) {
|
|
809
841
|
return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
810
842
|
}
|
|
811
|
-
function usageRecorded(env =
|
|
843
|
+
function usageRecorded(env = process8.env) {
|
|
812
844
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
813
845
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
814
846
|
}
|
|
@@ -822,7 +854,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
822
854
|
usageError = undefined;
|
|
823
855
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
824
856
|
}
|
|
825
|
-
function recordUsage(entry, env =
|
|
857
|
+
function recordUsage(entry, env = process8.env) {
|
|
826
858
|
if (!usageRecorded(env))
|
|
827
859
|
return;
|
|
828
860
|
try {
|
|
@@ -839,9 +871,82 @@ var LEVEL_OPTIONS = {
|
|
|
839
871
|
help: { type: "boolean", short: "h", description: "show this help" }
|
|
840
872
|
};
|
|
841
873
|
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
874
|
+
async function commandRows(all, colors) {
|
|
875
|
+
const commands = shown(all);
|
|
876
|
+
const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
|
|
877
|
+
const groups = new Map([["Commands:", []]]);
|
|
878
|
+
const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
|
|
879
|
+
for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
|
|
880
|
+
const heading = group === undefined ? "Commands:" : `${group}:`;
|
|
881
|
+
const rows = groups.get(heading) ?? [];
|
|
882
|
+
rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
|
|
883
|
+
groups.set(heading, rows);
|
|
884
|
+
}
|
|
885
|
+
return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
|
|
886
|
+
}
|
|
887
|
+
function shown(commands) {
|
|
888
|
+
return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
|
|
889
|
+
}
|
|
890
|
+
function takeOutputFlags(argv) {
|
|
891
|
+
let index = 0;
|
|
892
|
+
for (;index < argv.length; index++) {
|
|
893
|
+
const word = argv[index];
|
|
894
|
+
if (word === "--plain")
|
|
895
|
+
applyOutput(undefined, true);
|
|
896
|
+
else if (word.startsWith("--color="))
|
|
897
|
+
applyOutput(word.slice("--color=".length), undefined);
|
|
898
|
+
else if (word === "--color" && argv[index + 1] !== undefined)
|
|
899
|
+
applyOutput(argv[++index], undefined);
|
|
900
|
+
else
|
|
901
|
+
break;
|
|
902
|
+
}
|
|
903
|
+
return argv.slice(index);
|
|
904
|
+
}
|
|
905
|
+
async function resolveSummary(summary) {
|
|
906
|
+
return typeof summary === "string" ? summary : summary();
|
|
907
|
+
}
|
|
908
|
+
function scopeOf(commands, extra, aliases) {
|
|
909
|
+
return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
|
|
910
|
+
}
|
|
911
|
+
async function expand(scope, words) {
|
|
912
|
+
if (scope.lazy.length === 0)
|
|
913
|
+
return scope;
|
|
914
|
+
const commands = { ...scope.commands };
|
|
915
|
+
for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
|
|
916
|
+
for (const [name, command] of Object.entries(added))
|
|
917
|
+
commands[name] ??= command;
|
|
918
|
+
}
|
|
919
|
+
return { ...scope, commands, lazy: [] };
|
|
920
|
+
}
|
|
921
|
+
async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
|
|
922
|
+
const colors = paint(stream);
|
|
923
|
+
const prefix = path.join(" ");
|
|
924
|
+
const summary = await resolveSummary(lazySummary);
|
|
925
|
+
if (wantsHelpJson())
|
|
926
|
+
return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
|
|
927
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
928
|
+
const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
|
|
929
|
+
const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
|
|
930
|
+
return [
|
|
931
|
+
header(colors, summary),
|
|
932
|
+
"",
|
|
933
|
+
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
934
|
+
...replacesRows(replaces, colors),
|
|
935
|
+
"",
|
|
936
|
+
...await commandRows(commands, colors),
|
|
937
|
+
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
938
|
+
"",
|
|
939
|
+
colors.bold("Options:"),
|
|
940
|
+
...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
|
|
941
|
+
...exampleRows(examples ?? [], colors),
|
|
942
|
+
"",
|
|
943
|
+
`${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
|
|
944
|
+
].join(`
|
|
945
|
+
`);
|
|
946
|
+
}
|
|
842
947
|
function printError(prefix, message, hint, cause) {
|
|
843
|
-
const colors = paint(
|
|
844
|
-
const styled = takesControlCodes(
|
|
948
|
+
const colors = paint(process9.stderr);
|
|
949
|
+
const styled = takesControlCodes(process9.stderr);
|
|
845
950
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
846
951
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
847
952
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -860,12 +965,68 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
|
860
965
|
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
861
966
|
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
862
967
|
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
863
|
-
if (error instanceof
|
|
968
|
+
if (error instanceof Exit && error.code === 2)
|
|
864
969
|
noteUsageError(error.message);
|
|
865
970
|
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
866
971
|
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
867
972
|
return error instanceof Exit ? error.code : 1;
|
|
868
973
|
}
|
|
974
|
+
async function dispatch(level, typed, { version, redact }) {
|
|
975
|
+
const prefix = level.path.join(" ");
|
|
976
|
+
let argv;
|
|
977
|
+
try {
|
|
978
|
+
argv = takeOutputFlags(typed);
|
|
979
|
+
} catch (error) {
|
|
980
|
+
return reportThrown(prefix, error);
|
|
981
|
+
}
|
|
982
|
+
const [name, ...args] = argv;
|
|
983
|
+
const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
|
|
984
|
+
if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
|
|
985
|
+
try {
|
|
986
|
+
return await fallback.run([]);
|
|
987
|
+
} catch (error) {
|
|
988
|
+
return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
if (name === undefined && level.path.length > 1) {
|
|
992
|
+
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stderr));
|
|
993
|
+
return 2;
|
|
994
|
+
}
|
|
995
|
+
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
996
|
+
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stdout));
|
|
997
|
+
return 0;
|
|
998
|
+
}
|
|
999
|
+
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
1000
|
+
console.log(version);
|
|
1001
|
+
return 0;
|
|
1002
|
+
}
|
|
1003
|
+
let command = level.commands[level.aliases?.[name] ?? name];
|
|
1004
|
+
let rest = args;
|
|
1005
|
+
let ran = name;
|
|
1006
|
+
if (command === undefined && level.lazy.length > 0) {
|
|
1007
|
+
level = await expand(level, [...level.path.slice(1), ...argv]);
|
|
1008
|
+
command = level.commands[level.aliases?.[name] ?? name];
|
|
1009
|
+
}
|
|
1010
|
+
if (command === undefined && level.defaultCommand !== undefined) {
|
|
1011
|
+
command = level.commands[level.defaultCommand];
|
|
1012
|
+
rest = argv;
|
|
1013
|
+
ran = level.defaultCommand;
|
|
1014
|
+
}
|
|
1015
|
+
if (command === undefined) {
|
|
1016
|
+
const meant = closest(name, Object.keys(shown(level.commands)));
|
|
1017
|
+
printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
|
|
1018
|
+
return 2;
|
|
1019
|
+
}
|
|
1020
|
+
if ("commands" in command) {
|
|
1021
|
+
const { summary } = command;
|
|
1022
|
+
return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
|
|
1023
|
+
}
|
|
1024
|
+
try {
|
|
1025
|
+
return await command.run(rest);
|
|
1026
|
+
} catch (error) {
|
|
1027
|
+
return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
869
1030
|
var COMPLETE = "__complete";
|
|
870
1031
|
var FILES = "__files__";
|
|
871
1032
|
async function completingOf(run) {
|
|
@@ -880,6 +1041,9 @@ async function completingOf(run) {
|
|
|
880
1041
|
}
|
|
881
1042
|
return new Completing({});
|
|
882
1043
|
}
|
|
1044
|
+
async function optionsOf(run) {
|
|
1045
|
+
return (await completingOf(run)).options;
|
|
1046
|
+
}
|
|
883
1047
|
function candidateLine(candidate) {
|
|
884
1048
|
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
885
1049
|
}
|
|
@@ -918,6 +1082,28 @@ async function leafCandidates(run, words) {
|
|
|
918
1082
|
const values = name === undefined ? undefined : await completing.candidates[name]?.();
|
|
919
1083
|
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
920
1084
|
}
|
|
1085
|
+
async function candidates(scope, defaultCommand, words, before = []) {
|
|
1086
|
+
const [word = "", ...rest] = words;
|
|
1087
|
+
const listing = rest.length === 0 && !word.startsWith("-");
|
|
1088
|
+
let { commands, aliases } = scope;
|
|
1089
|
+
let command = commands[aliases?.[word] ?? word];
|
|
1090
|
+
if (listing || command === undefined) {
|
|
1091
|
+
({ commands, aliases } = await expand(scope, [...before, ...words]));
|
|
1092
|
+
command = commands[aliases?.[word] ?? word];
|
|
1093
|
+
}
|
|
1094
|
+
if (listing) {
|
|
1095
|
+
const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
|
|
1096
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1097
|
+
const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
|
|
1098
|
+
const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
|
|
1099
|
+
return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
|
|
1100
|
+
}
|
|
1101
|
+
if (command === undefined) {
|
|
1102
|
+
const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
|
|
1103
|
+
return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
|
|
1104
|
+
}
|
|
1105
|
+
return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
|
|
1106
|
+
}
|
|
921
1107
|
async function printCandidates(found) {
|
|
922
1108
|
for (const line of await found)
|
|
923
1109
|
console.log(line);
|
|
@@ -934,7 +1120,34 @@ function packageVersion(entry = Bun.main) {
|
|
|
934
1120
|
return "0.0.0";
|
|
935
1121
|
}
|
|
936
1122
|
}
|
|
937
|
-
async function
|
|
1123
|
+
async function runCli(cli, argv = process9.argv.slice(2)) {
|
|
1124
|
+
const version = cli.version ?? packageVersion();
|
|
1125
|
+
if (argv[0] === COMPLETE)
|
|
1126
|
+
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
1127
|
+
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 });
|
|
1128
|
+
if (cli.usage !== false) {
|
|
1129
|
+
try {
|
|
1130
|
+
recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
|
|
1131
|
+
} catch {}
|
|
1132
|
+
}
|
|
1133
|
+
return code;
|
|
1134
|
+
}
|
|
1135
|
+
function commandPath(scope, argv) {
|
|
1136
|
+
const path = [];
|
|
1137
|
+
let level = scope;
|
|
1138
|
+
for (const word of argv.filter((each) => !each.startsWith("-"))) {
|
|
1139
|
+
const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
|
|
1140
|
+
const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
|
|
1141
|
+
if (command === undefined)
|
|
1142
|
+
break;
|
|
1143
|
+
path.push(word);
|
|
1144
|
+
if (!("commands" in command))
|
|
1145
|
+
break;
|
|
1146
|
+
level = scopeOf(command.commands, command.extraCommands, command.aliases);
|
|
1147
|
+
}
|
|
1148
|
+
return path.length === 0 ? undefined : path.join(" ");
|
|
1149
|
+
}
|
|
1150
|
+
async function runMain({ name, version, run, redact, usage }, argv = process9.argv.slice(2)) {
|
|
938
1151
|
if (argv[0] === COMPLETE)
|
|
939
1152
|
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
940
1153
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
@@ -975,10 +1188,62 @@ function parseSize(text, bareUnit = 1) {
|
|
|
975
1188
|
const suffix = match[2].toLowerCase();
|
|
976
1189
|
return Math.round(Number(match[1]) * (suffix === "" ? bareUnit : 1024 ** POWERS[suffix]));
|
|
977
1190
|
}
|
|
1191
|
+
// ../kit/src/watch.ts
|
|
1192
|
+
import process10 from "process";
|
|
1193
|
+
import { format } from "util";
|
|
1194
|
+
var CLEAR_SCREEN = "\x1B[H\x1B[2J";
|
|
1195
|
+
var DEFAULT_SECONDS = 2;
|
|
1196
|
+
var ATTACHED_SHORT = /^-w./;
|
|
1197
|
+
var INTERVAL = /^\d+(?:\.\d+)?(?:ms|[smh])?$/;
|
|
1198
|
+
function watchOption(what) {
|
|
1199
|
+
return { type: "string", short: "w", optional: { bare: "", accepts: INTERVAL }, description: `redraw ${what} every 2s, or every interval given (500ms, 5s), until ctrl-c` };
|
|
1200
|
+
}
|
|
1201
|
+
function withoutWatch(args) {
|
|
1202
|
+
const rest = [];
|
|
1203
|
+
for (let at = 0;at < args.length; at++) {
|
|
1204
|
+
const arg = args[at];
|
|
1205
|
+
if (arg === "--watch" || arg === "-w") {
|
|
1206
|
+
if (args[at + 1] !== undefined && INTERVAL.test(args[at + 1]))
|
|
1207
|
+
at++;
|
|
1208
|
+
} else if (!arg.startsWith("--watch=") && !ATTACHED_SHORT.test(arg)) {
|
|
1209
|
+
rest.push(arg);
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
return rest;
|
|
1213
|
+
}
|
|
1214
|
+
async function watching(value, step, stream = process10.stdout, sleep = Bun.sleep, rounds = Number.POSITIVE_INFINITY) {
|
|
1215
|
+
const interval = value === "" ? DEFAULT_SECONDS * 1000 : duration(value, "watch", DEFAULT_SECONDS * 1000);
|
|
1216
|
+
if (!takesControlCodes(stream))
|
|
1217
|
+
badUsage("--watch redraws the screen, so it needs a terminal");
|
|
1218
|
+
let code = 0;
|
|
1219
|
+
for (let round = 0;round < rounds; round++) {
|
|
1220
|
+
const held = [];
|
|
1221
|
+
const { log, info } = console;
|
|
1222
|
+
const write = process10.stdout.write.bind(process10.stdout);
|
|
1223
|
+
const hold = (...parts) => void held.push(`${format(...parts)}
|
|
1224
|
+
`);
|
|
1225
|
+
console.log = hold;
|
|
1226
|
+
console.info = hold;
|
|
1227
|
+
process10.stdout.write = (text) => {
|
|
1228
|
+
held.push(typeof text === "string" ? text : Buffer.from(text).toString());
|
|
1229
|
+
return true;
|
|
1230
|
+
};
|
|
1231
|
+
try {
|
|
1232
|
+
code = await step();
|
|
1233
|
+
} finally {
|
|
1234
|
+
console.log = log;
|
|
1235
|
+
console.info = info;
|
|
1236
|
+
process10.stdout.write = write;
|
|
1237
|
+
}
|
|
1238
|
+
stream.write(`${CLEAR_SCREEN}${held.join("")}`);
|
|
1239
|
+
await sleep(interval);
|
|
1240
|
+
}
|
|
1241
|
+
return code;
|
|
1242
|
+
}
|
|
978
1243
|
// src/procs.ts
|
|
979
1244
|
import { existsSync } from "fs";
|
|
980
1245
|
import { homedir as homedir2 } from "os";
|
|
981
|
-
import
|
|
1246
|
+
import process12 from "process";
|
|
982
1247
|
|
|
983
1248
|
// src/read.ts
|
|
984
1249
|
import { readdir, readFile, readlink } from "fs/promises";
|
|
@@ -1478,7 +1743,8 @@ A process is listed when it is a dev tool (bun, node, vite, nuxt, next, chromium
|
|
|
1478
1743
|
Exits 0 when it listed or stopped everything, 1 when a process survived SIGKILL, 2 on a usage error.`;
|
|
1479
1744
|
var options = {
|
|
1480
1745
|
json: jsonOption("{ groups: [{ origin, kind, count, rss, oldestSeconds, tools, orphans, pids, processes }], skipped }"),
|
|
1481
|
-
kill: { type: "boolean", description: "stop the listed processes: a dry run without --yes" },
|
|
1746
|
+
kill: { type: "boolean", conflicts: ["watch"], description: "stop the listed processes: a dry run without --yes" },
|
|
1747
|
+
watch: watchOption("the processes"),
|
|
1482
1748
|
yes: { type: "boolean", short: "y", description: "with --kill, really stop them, without asking" },
|
|
1483
1749
|
"min-mem": { type: "string", description: "heavy from this resident size (500M), and the least a left over process must use to be listed; a bare number counts megabytes" },
|
|
1484
1750
|
older: { type: "string", description: "only processes at least this old: 30m, 2h, 1d" },
|
|
@@ -1501,7 +1767,7 @@ function summary(group) {
|
|
|
1501
1767
|
};
|
|
1502
1768
|
}
|
|
1503
1769
|
function render(groups) {
|
|
1504
|
-
const colors = paint(
|
|
1770
|
+
const colors = paint(process12.stdout);
|
|
1505
1771
|
const rows = groups.map((group) => [
|
|
1506
1772
|
group.origin,
|
|
1507
1773
|
String(group.members.length),
|
|
@@ -1525,10 +1791,12 @@ async function procs(args) {
|
|
|
1525
1791
|
const minMem = values["min-mem"] === undefined ? undefined : parseSize(values["min-mem"], 1024 ** 2);
|
|
1526
1792
|
if (values["min-mem"] !== undefined && minMem === undefined)
|
|
1527
1793
|
fail(`--min-mem takes a size such as 500M or 1.5G, not ${values["min-mem"]}`, 2);
|
|
1794
|
+
if (values.watch !== undefined)
|
|
1795
|
+
return watching(values.watch, async () => procs(withoutWatch(args)));
|
|
1528
1796
|
const olderMs = values.older === undefined ? undefined : duration(values.older, "older", 0, "m");
|
|
1529
|
-
const uid =
|
|
1797
|
+
const uid = process12.getuid?.() ?? -1;
|
|
1530
1798
|
const all = await snapshot("/proc", (owner) => owner === uid);
|
|
1531
|
-
const mine = new Set(ancestry(
|
|
1799
|
+
const mine = new Set(ancestry(process12.pid, new Map(all.map((proc) => [proc.pid, proc]))));
|
|
1532
1800
|
const { groups, protectedCount } = selectGroups(all, { guard: { uid, mine }, now: Date.now(), home: homedir2(), exists: existsSync, minMem, olderMs });
|
|
1533
1801
|
const pids = groups.flatMap((group) => group.members.map(({ proc }) => proc.pid));
|
|
1534
1802
|
const show = (extra = {}) => {
|
|
@@ -1540,7 +1808,7 @@ async function procs(args) {
|
|
|
1540
1808
|
if (values.kill !== true || pids.length === 0 || values.yes !== true) {
|
|
1541
1809
|
show();
|
|
1542
1810
|
if (values.json !== true && protectedCount > 0)
|
|
1543
|
-
console.error(paint(
|
|
1811
|
+
console.error(paint(process12.stderr).dim(`${protectedCount} more left out: shells, terminals and this command's ancestors are never touched`));
|
|
1544
1812
|
if (values.kill === true && pids.length > 0)
|
|
1545
1813
|
console.error(`dry run: would stop ${pids.length} ${pids.length === 1 ? "process" : "processes"} (${pids.join(" ")}), pass --yes to do it`);
|
|
1546
1814
|
return 0;
|
|
@@ -1555,4 +1823,4 @@ async function procs(args) {
|
|
|
1555
1823
|
}
|
|
1556
1824
|
|
|
1557
1825
|
// src/procs-cli.ts
|
|
1558
|
-
|
|
1826
|
+
process13.exitCode = await runMain({ name: "procs", run: procs });
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kaynooo/cli-proc",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.4.0",
|
|
5
5
|
"description": "pid, ports, procs: one process inspected, who listens on a port, and leftover or heavy dev processes cleaned, read straight from /proc (Linux).",
|
|
6
6
|
"author": "Kaynooo <contact@kaynooo.fr>",
|
|
7
7
|
"license": "MIT",
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
"keywords": ["process", "port", "proc", "kill", "cli", "bun"],
|
|
16
16
|
"os": ["linux"],
|
|
17
17
|
"bin": {
|
|
18
|
+
"proc": "./dist/proc-cli.js",
|
|
18
19
|
"pid": "./dist/pid-cli.js",
|
|
19
20
|
"ports": "./dist/ports-cli.js",
|
|
20
21
|
"procs": "./dist/procs-cli.js"
|
|
@@ -27,12 +28,13 @@
|
|
|
27
28
|
"registry": "https://git.kaynooo.fr/api/packages/kaynooo/npm/"
|
|
28
29
|
},
|
|
29
30
|
"scripts": {
|
|
30
|
-
"build": "$npm_execpath build src/pid-cli.ts src/ports-cli.ts src/procs-cli.ts --target bun --outdir dist",
|
|
31
|
+
"build": "$npm_execpath build src/proc-cli.ts src/pid-cli.ts src/ports-cli.ts src/procs-cli.ts --target bun --outdir dist",
|
|
32
|
+
"proc": "$npm_execpath src/proc-cli.ts",
|
|
31
33
|
"pid": "$npm_execpath src/pid-cli.ts",
|
|
32
34
|
"ports": "$npm_execpath src/ports-cli.ts",
|
|
33
35
|
"procs": "$npm_execpath src/procs-cli.ts"
|
|
34
36
|
},
|
|
35
37
|
"devDependencies": {
|
|
36
|
-
"@kaynooo/cli-kit": "0.
|
|
38
|
+
"@kaynooo/cli-kit": "0.26.0"
|
|
37
39
|
}
|
|
38
40
|
}
|
package/src/ports.ts
CHANGED
|
@@ -2,7 +2,7 @@ import type { Container, Protocol, Socket } from './parse'
|
|
|
2
2
|
import type { ProcInfo } from './read'
|
|
3
3
|
import { basename } from 'node:path'
|
|
4
4
|
import process from 'node:process'
|
|
5
|
-
import { badUsage, duration, fail, jsonOption, paint, parse, printJson, table, truncate, wholeNumber } from '@kaynooo/cli-kit'
|
|
5
|
+
import { badUsage, duration, fail, jsonOption, paint, parse, printJson, table, truncate, watching, watchOption, wholeNumber, withoutWatch } from '@kaynooo/cli-kit'
|
|
6
6
|
import { confirm } from '@kaynooo/cli-kit/prompt'
|
|
7
7
|
import { dockerContainers } from './docker'
|
|
8
8
|
import { protectionOf, terminate } from './kill'
|
|
@@ -19,7 +19,8 @@ Exits 0 when it listed or stopped, 1 when nothing listens on the given port or t
|
|
|
19
19
|
|
|
20
20
|
const options = {
|
|
21
21
|
json: jsonOption('[{ port, protocol, addresses, pid, command, cwd, container }]'),
|
|
22
|
-
kill: { type: 'boolean', description: 'stop the owner of the given port' },
|
|
22
|
+
kill: { type: 'boolean', conflicts: ['watch'], description: 'stop the owner of the given port' },
|
|
23
|
+
watch: watchOption('the ports'),
|
|
23
24
|
force: { type: 'boolean', description: 'with --kill, SIGKILL what SIGTERM did not stop within --grace' },
|
|
24
25
|
yes: { type: 'boolean', short: 'y', description: 'with --kill, do not ask first' },
|
|
25
26
|
grace: { type: 'string', description: 'with --force, how long SIGTERM gets before SIGKILL (5s)' },
|
|
@@ -150,6 +151,10 @@ export async function ports(args: string[]): Promise<number> {
|
|
|
150
151
|
'ports --json',
|
|
151
152
|
],
|
|
152
153
|
})
|
|
154
|
+
|
|
155
|
+
if (values.watch !== undefined)
|
|
156
|
+
return watching(values.watch, async () => ports(withoutWatch(args)))
|
|
157
|
+
|
|
153
158
|
const [given] = positionals
|
|
154
159
|
const port = given === undefined ? undefined : wholeNumber(given, '<port>', 0)
|
|
155
160
|
|