tines 0.0.81 → 0.0.83
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/index.js +3840 -321
- package/package.json +3 -5
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// src/index.ts
|
|
4
|
-
import { existsSync as
|
|
4
|
+
import { existsSync as existsSync3, mkdirSync as mkdirSync4, readdirSync, readFileSync as readFileSync4, statSync, writeFileSync as writeFileSync3 } from "node:fs";
|
|
5
5
|
import { hostname as hostname2 } from "node:os";
|
|
6
|
-
import { basename, dirname as
|
|
6
|
+
import { basename, dirname as dirname4, join as join4 } from "node:path";
|
|
7
7
|
import { createInterface } from "node:readline/promises";
|
|
8
8
|
|
|
9
9
|
// src/body-value.ts
|
|
@@ -39,10 +39,10 @@ function readBodyValue(value, stdin = processStdin) {
|
|
|
39
39
|
}
|
|
40
40
|
|
|
41
41
|
// src/daemon/daemon.ts
|
|
42
|
-
import { spawn } from "node:child_process";
|
|
43
|
-
import { mkdirSync as
|
|
42
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
43
|
+
import { mkdirSync as mkdirSync3, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
|
|
44
44
|
import { hostname, platform, arch } from "node:os";
|
|
45
|
-
import { dirname as
|
|
45
|
+
import { dirname as dirname3, join as join3 } from "node:path";
|
|
46
46
|
|
|
47
47
|
// ../shared/src/types.ts
|
|
48
48
|
function actorLabel(actor) {
|
|
@@ -335,11 +335,11 @@ function query(params) {
|
|
|
335
335
|
function createApiClient(options) {
|
|
336
336
|
const base = options.baseUrl.replace(/\/+$/, "");
|
|
337
337
|
const fetchFn = options.fetch ?? globalThis.fetch;
|
|
338
|
-
async function request(method,
|
|
338
|
+
async function request(method, path2, body) {
|
|
339
339
|
const headers = { accept: "application/json" };
|
|
340
340
|
if (options.apiKey) headers.authorization = `Bearer ${options.apiKey}`;
|
|
341
341
|
if (body !== void 0) headers["content-type"] = "application/json";
|
|
342
|
-
const res = await fetchFn(`${base}${
|
|
342
|
+
const res = await fetchFn(`${base}${path2}`, {
|
|
343
343
|
method,
|
|
344
344
|
headers,
|
|
345
345
|
body: body === void 0 ? void 0 : JSON.stringify(body)
|
|
@@ -350,24 +350,24 @@ function createApiClient(options) {
|
|
|
350
350
|
parsed = (await res.json()).error ?? null;
|
|
351
351
|
} catch {
|
|
352
352
|
}
|
|
353
|
-
throw new ApiError(res.status, parsed, `${method} ${
|
|
353
|
+
throw new ApiError(res.status, parsed, `${method} ${path2} failed: ${res.status}`);
|
|
354
354
|
}
|
|
355
355
|
if (res.status === 204) return void 0;
|
|
356
356
|
return await res.json();
|
|
357
357
|
}
|
|
358
|
-
const get = (
|
|
359
|
-
async function raw(method,
|
|
358
|
+
const get = (path2) => request("GET", path2);
|
|
359
|
+
async function raw(method, path2, opts = {}) {
|
|
360
360
|
const headers = { ...opts.headers ?? {} };
|
|
361
361
|
if (options.apiKey) headers.authorization = `Bearer ${options.apiKey}`;
|
|
362
362
|
const body = opts.body instanceof Uint8Array ? opts.body.buffer.slice(opts.body.byteOffset, opts.body.byteOffset + opts.body.byteLength) : opts.body;
|
|
363
|
-
const res = await fetchFn(`${base}${
|
|
363
|
+
const res = await fetchFn(`${base}${path2}`, { method, headers, body });
|
|
364
364
|
if (!res.ok) {
|
|
365
365
|
let parsed = null;
|
|
366
366
|
try {
|
|
367
367
|
parsed = (await res.json()).error ?? null;
|
|
368
368
|
} catch {
|
|
369
369
|
}
|
|
370
|
-
throw new ApiError(res.status, parsed, `${method} ${
|
|
370
|
+
throw new ApiError(res.status, parsed, `${method} ${path2} failed: ${res.status}`);
|
|
371
371
|
}
|
|
372
372
|
return res;
|
|
373
373
|
}
|
|
@@ -550,80 +550,13 @@ var PLACEHOLDER_DESCRIPTIONS = {
|
|
|
550
550
|
};
|
|
551
551
|
var TEMPLATE_PLACEHOLDERS = Object.keys(PLACEHOLDER_DESCRIPTIONS).map((key) => ({ key, description: PLACEHOLDER_DESCRIPTIONS[key] }));
|
|
552
552
|
|
|
553
|
-
// src/daemon/
|
|
554
|
-
import {
|
|
555
|
-
import {
|
|
553
|
+
// src/daemon/cli-refresh.ts
|
|
554
|
+
import { spawn } from "node:child_process";
|
|
555
|
+
import { existsSync, mkdirSync, readFileSync as readFileSync2 } from "node:fs";
|
|
556
556
|
import { dirname, join } from "node:path";
|
|
557
|
-
function defaultConfigDir() {
|
|
558
|
-
return process.env.TINES_CONFIG_DIR ?? join(homedir(), ".config", "tines");
|
|
559
|
-
}
|
|
560
|
-
function readJsonFile(path) {
|
|
561
|
-
if (!existsSync(path)) return null;
|
|
562
|
-
try {
|
|
563
|
-
return JSON.parse(readFileSync2(path, "utf8"));
|
|
564
|
-
} catch {
|
|
565
|
-
return null;
|
|
566
|
-
}
|
|
567
|
-
}
|
|
568
|
-
function writeJsonFile(path, value, { secret = false } = {}) {
|
|
569
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
570
|
-
writeFileSync(path, `${JSON.stringify(value, null, 2)}
|
|
571
|
-
`, secret ? { mode: 384 } : {});
|
|
572
|
-
}
|
|
573
|
-
function credentialsKey(url, name2) {
|
|
574
|
-
return `${url.replace(/\/+$/, "")}#${name2}`;
|
|
575
|
-
}
|
|
576
|
-
function credentialsPath(dir) {
|
|
577
|
-
return join(dir, "runners.json");
|
|
578
|
-
}
|
|
579
|
-
function loadRunnerCredentials(dir, url, name2) {
|
|
580
|
-
const all = readJsonFile(credentialsPath(dir));
|
|
581
|
-
const entry = all?.[credentialsKey(url, name2)];
|
|
582
|
-
return entry && typeof entry.runner_id === "string" && typeof entry.token === "string" ? entry : null;
|
|
583
|
-
}
|
|
584
|
-
function saveRunnerCredentials(dir, url, name2, creds) {
|
|
585
|
-
const path = credentialsPath(dir);
|
|
586
|
-
const all = readJsonFile(path) ?? {};
|
|
587
|
-
all[credentialsKey(url, name2)] = creds;
|
|
588
|
-
writeJsonFile(path, all, { secret: true });
|
|
589
|
-
}
|
|
590
|
-
function hasRunnerCredentials(dir, url, name2) {
|
|
591
|
-
return loadRunnerCredentials(dir, url, name2) !== null;
|
|
592
|
-
}
|
|
593
|
-
function clearRunnerCredentials(dir, url, name2) {
|
|
594
|
-
const path = credentialsPath(dir);
|
|
595
|
-
const all = readJsonFile(path) ?? {};
|
|
596
|
-
delete all[credentialsKey(url, name2)];
|
|
597
|
-
writeJsonFile(path, all, { secret: true });
|
|
598
|
-
}
|
|
599
|
-
function daemonStatePath(dir, runnerId) {
|
|
600
|
-
return join(dir, `daemon-state-${runnerId}.json`);
|
|
601
|
-
}
|
|
602
|
-
function loadDaemonState(path) {
|
|
603
|
-
const state = readJsonFile(path);
|
|
604
|
-
if (!state || !Array.isArray(state.runs)) return [];
|
|
605
|
-
return state.runs.filter(
|
|
606
|
-
(e) => typeof e === "object" && e !== null && typeof e.run_id === "string" && typeof e.pid === "number" && typeof e.workspace === "string"
|
|
607
|
-
);
|
|
608
|
-
}
|
|
609
|
-
function saveDaemonState(path, runs) {
|
|
610
|
-
writeJsonFile(path, { runs });
|
|
611
|
-
}
|
|
612
|
-
function processStartTimeMs(pid) {
|
|
613
|
-
try {
|
|
614
|
-
const stat = readFileSync2(`/proc/${pid}/stat`, "utf8");
|
|
615
|
-
const afterComm = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
616
|
-
const startTicks = Number(afterComm[19]);
|
|
617
|
-
const btimeLine = readFileSync2("/proc/stat", "utf8").split("\n").find((line) => line.startsWith("btime "));
|
|
618
|
-
const btime = Number(btimeLine?.slice("btime ".length));
|
|
619
|
-
if (!Number.isFinite(startTicks) || !Number.isFinite(btime)) return null;
|
|
620
|
-
return btime * 1e3 + startTicks / 100 * 1e3;
|
|
621
|
-
} catch {
|
|
622
|
-
return null;
|
|
623
|
-
}
|
|
624
|
-
}
|
|
625
557
|
|
|
626
558
|
// src/daemon/support.ts
|
|
559
|
+
import { delimiter } from "node:path";
|
|
627
560
|
var HARNESS_KINDS = ["claude_code", "codex", "custom"];
|
|
628
561
|
function shellQuote(value) {
|
|
629
562
|
return `'${value.replaceAll("'", `'\\''`)}'`;
|
|
@@ -752,9 +685,206 @@ var LogBatcher = class {
|
|
|
752
685
|
return this.sending;
|
|
753
686
|
}
|
|
754
687
|
};
|
|
688
|
+
var AMBIENT_CLI = { binDir: null, version: null, source: "ambient" };
|
|
689
|
+
var CliRefresher = class {
|
|
690
|
+
constructor(install, opts = {}) {
|
|
691
|
+
this.install = install;
|
|
692
|
+
this.opts = opts;
|
|
693
|
+
}
|
|
694
|
+
install;
|
|
695
|
+
opts;
|
|
696
|
+
cached = AMBIENT_CLI;
|
|
697
|
+
lastAttempt = null;
|
|
698
|
+
inFlight = null;
|
|
699
|
+
/** The current CLI, refreshing first when the TTL elapsed. Never rejects. */
|
|
700
|
+
ensure() {
|
|
701
|
+
if (this.inFlight) return this.inFlight;
|
|
702
|
+
const now = (this.opts.now ?? Date.now)();
|
|
703
|
+
if (this.lastAttempt !== null && now - this.lastAttempt < (this.opts.ttlMs ?? 10 * 6e4)) {
|
|
704
|
+
return Promise.resolve(this.cached);
|
|
705
|
+
}
|
|
706
|
+
this.lastAttempt = now;
|
|
707
|
+
this.inFlight = Promise.resolve().then(() => this.install()).catch(() => AMBIENT_CLI).then((cli) => {
|
|
708
|
+
this.cached = cli;
|
|
709
|
+
this.inFlight = null;
|
|
710
|
+
return cli;
|
|
711
|
+
});
|
|
712
|
+
return this.inFlight;
|
|
713
|
+
}
|
|
714
|
+
};
|
|
715
|
+
function buildSpawnEnv(base, opts) {
|
|
716
|
+
const env = {
|
|
717
|
+
...base,
|
|
718
|
+
TINES_API_KEY: opts.apiKey,
|
|
719
|
+
TINES_API_URL: opts.apiUrl
|
|
720
|
+
};
|
|
721
|
+
if (opts.binDir) env.PATH = base.PATH ? `${opts.binDir}${delimiter}${base.PATH}` : opts.binDir;
|
|
722
|
+
return env;
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
// src/daemon/cli-refresh.ts
|
|
726
|
+
var PACKAGE = "tines";
|
|
727
|
+
var NPM_ARGS = ["--min-release-age=0", "--no-audit", "--no-fund", "--loglevel=error"];
|
|
728
|
+
function agentCliPrefix(configDir) {
|
|
729
|
+
return join(configDir, "cli");
|
|
730
|
+
}
|
|
731
|
+
function binDirOf(prefix) {
|
|
732
|
+
return join(prefix, "node_modules", ".bin");
|
|
733
|
+
}
|
|
734
|
+
function installedVersion(prefix) {
|
|
735
|
+
try {
|
|
736
|
+
const pkg = readFileSync2(join(prefix, "node_modules", PACKAGE, "package.json"), "utf8");
|
|
737
|
+
const version = JSON.parse(pkg).version;
|
|
738
|
+
return typeof version === "string" ? version : null;
|
|
739
|
+
} catch {
|
|
740
|
+
return null;
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
function lastGood(prefix) {
|
|
744
|
+
const binDir = binDirOf(prefix);
|
|
745
|
+
if (!existsSync(join(binDir, PACKAGE))) return AMBIENT_CLI;
|
|
746
|
+
return { binDir, version: installedVersion(prefix), source: "stale" };
|
|
747
|
+
}
|
|
748
|
+
function runNpm(file, args, cwd, timeoutMs) {
|
|
749
|
+
return new Promise((resolve) => {
|
|
750
|
+
let output = "";
|
|
751
|
+
let done = false;
|
|
752
|
+
let timedOut = false;
|
|
753
|
+
const child = spawn(file, args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
|
|
754
|
+
const timer = setTimeout(() => {
|
|
755
|
+
if (done) return;
|
|
756
|
+
timedOut = true;
|
|
757
|
+
child.kill("SIGKILL");
|
|
758
|
+
}, timeoutMs);
|
|
759
|
+
timer.unref?.();
|
|
760
|
+
const settle = (result) => {
|
|
761
|
+
if (done) return;
|
|
762
|
+
done = true;
|
|
763
|
+
clearTimeout(timer);
|
|
764
|
+
resolve({ ...result, timedOut, output });
|
|
765
|
+
};
|
|
766
|
+
child.stdout?.on("data", (data) => output += data.toString("utf8"));
|
|
767
|
+
child.stderr?.on("data", (data) => output += data.toString("utf8"));
|
|
768
|
+
child.on("error", (err) => settle({ code: null, signal: null, spawnError: err }));
|
|
769
|
+
child.on("close", (code, signal) => settle({ code, signal, spawnError: null }));
|
|
770
|
+
});
|
|
771
|
+
}
|
|
772
|
+
function npmFailure(result, timeoutMs) {
|
|
773
|
+
if (result.spawnError) return `npm could not be run (${message(result.spawnError)})`;
|
|
774
|
+
if (result.timedOut) return `npm did not finish within ${Math.round(timeoutMs / 1e3)}s`;
|
|
775
|
+
if (result.signal) return `npm was killed by ${result.signal}`;
|
|
776
|
+
return `npm exited with code ${result.code}`;
|
|
777
|
+
}
|
|
778
|
+
async function installAgentCli(opts) {
|
|
779
|
+
const prefix = agentCliPrefix(opts.configDir);
|
|
780
|
+
const timeoutMs = opts.timeoutMs ?? 6e4;
|
|
781
|
+
try {
|
|
782
|
+
mkdirSync(prefix, { recursive: true });
|
|
783
|
+
} catch (err) {
|
|
784
|
+
opts.log(`agent CLI refresh: cannot create ${prefix} (${message(err)})`);
|
|
785
|
+
return AMBIENT_CLI;
|
|
786
|
+
}
|
|
787
|
+
const args = ["install", "--prefix", prefix, `${PACKAGE}@latest`, ...NPM_ARGS];
|
|
788
|
+
let result = await runNpm("npm", args, prefix, timeoutMs);
|
|
789
|
+
if (result.spawnError?.code === "ENOENT") {
|
|
790
|
+
const sibling = join(dirname(process.execPath), "npm");
|
|
791
|
+
if (existsSync(sibling)) result = await runNpm(sibling, args, prefix, timeoutMs);
|
|
792
|
+
}
|
|
793
|
+
if (result.code !== 0) {
|
|
794
|
+
const fallback = lastGood(prefix);
|
|
795
|
+
opts.log(
|
|
796
|
+
`warning: agent CLI refresh failed \u2014 ${npmFailure(result, timeoutMs)}${tail(result.output)}; ${fallback.source === "stale" ? `using the last-good copy (${PACKAGE} ${fallback.version ?? "unknown"}) in ${prefix}` : "the harness will use the ambient PATH"}`
|
|
797
|
+
);
|
|
798
|
+
return fallback;
|
|
799
|
+
}
|
|
800
|
+
const version = installedVersion(prefix);
|
|
801
|
+
opts.log(`agent CLI refreshed: ${PACKAGE} ${version ?? "unknown"} in ${prefix}`);
|
|
802
|
+
return { binDir: binDirOf(prefix), version, source: "fresh" };
|
|
803
|
+
}
|
|
804
|
+
function tail(output) {
|
|
805
|
+
const lines = output.trim().split("\n").filter(Boolean).slice(-3);
|
|
806
|
+
return lines.length > 0 ? `: ${lines.join(" / ")}` : "";
|
|
807
|
+
}
|
|
808
|
+
function message(err) {
|
|
809
|
+
return err instanceof Error ? err.message : String(err);
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
// src/daemon/store.ts
|
|
813
|
+
import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync } from "node:fs";
|
|
814
|
+
import { homedir } from "node:os";
|
|
815
|
+
import { dirname as dirname2, join as join2 } from "node:path";
|
|
816
|
+
function defaultConfigDir() {
|
|
817
|
+
return process.env.TINES_CONFIG_DIR ?? join2(homedir(), ".config", "tines");
|
|
818
|
+
}
|
|
819
|
+
function readJsonFile(path2) {
|
|
820
|
+
if (!existsSync2(path2)) return null;
|
|
821
|
+
try {
|
|
822
|
+
return JSON.parse(readFileSync3(path2, "utf8"));
|
|
823
|
+
} catch {
|
|
824
|
+
return null;
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
function writeJsonFile(path2, value, { secret = false } = {}) {
|
|
828
|
+
mkdirSync2(dirname2(path2), { recursive: true });
|
|
829
|
+
writeFileSync(path2, `${JSON.stringify(value, null, 2)}
|
|
830
|
+
`, secret ? { mode: 384 } : {});
|
|
831
|
+
}
|
|
832
|
+
function credentialsKey(url, name2) {
|
|
833
|
+
return `${url.replace(/\/+$/, "")}#${name2}`;
|
|
834
|
+
}
|
|
835
|
+
function credentialsPath(dir) {
|
|
836
|
+
return join2(dir, "runners.json");
|
|
837
|
+
}
|
|
838
|
+
function loadRunnerCredentials(dir, url, name2) {
|
|
839
|
+
const all = readJsonFile(credentialsPath(dir));
|
|
840
|
+
const entry = all?.[credentialsKey(url, name2)];
|
|
841
|
+
return entry && typeof entry.runner_id === "string" && typeof entry.token === "string" ? entry : null;
|
|
842
|
+
}
|
|
843
|
+
function saveRunnerCredentials(dir, url, name2, creds) {
|
|
844
|
+
const path2 = credentialsPath(dir);
|
|
845
|
+
const all = readJsonFile(path2) ?? {};
|
|
846
|
+
all[credentialsKey(url, name2)] = creds;
|
|
847
|
+
writeJsonFile(path2, all, { secret: true });
|
|
848
|
+
}
|
|
849
|
+
function hasRunnerCredentials(dir, url, name2) {
|
|
850
|
+
return loadRunnerCredentials(dir, url, name2) !== null;
|
|
851
|
+
}
|
|
852
|
+
function clearRunnerCredentials(dir, url, name2) {
|
|
853
|
+
const path2 = credentialsPath(dir);
|
|
854
|
+
const all = readJsonFile(path2) ?? {};
|
|
855
|
+
delete all[credentialsKey(url, name2)];
|
|
856
|
+
writeJsonFile(path2, all, { secret: true });
|
|
857
|
+
}
|
|
858
|
+
function daemonStatePath(dir, runnerId) {
|
|
859
|
+
return join2(dir, `daemon-state-${runnerId}.json`);
|
|
860
|
+
}
|
|
861
|
+
function loadDaemonState(path2) {
|
|
862
|
+
const state = readJsonFile(path2);
|
|
863
|
+
if (!state || !Array.isArray(state.runs)) return [];
|
|
864
|
+
return state.runs.filter(
|
|
865
|
+
(e) => typeof e === "object" && e !== null && typeof e.run_id === "string" && typeof e.pid === "number" && typeof e.workspace === "string"
|
|
866
|
+
);
|
|
867
|
+
}
|
|
868
|
+
function saveDaemonState(path2, runs) {
|
|
869
|
+
writeJsonFile(path2, { runs });
|
|
870
|
+
}
|
|
871
|
+
function processStartTimeMs(pid) {
|
|
872
|
+
try {
|
|
873
|
+
const stat = readFileSync3(`/proc/${pid}/stat`, "utf8");
|
|
874
|
+
const afterComm = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
875
|
+
const startTicks = Number(afterComm[19]);
|
|
876
|
+
const btimeLine = readFileSync3("/proc/stat", "utf8").split("\n").find((line) => line.startsWith("btime "));
|
|
877
|
+
const btime = Number(btimeLine?.slice("btime ".length));
|
|
878
|
+
if (!Number.isFinite(startTicks) || !Number.isFinite(btime)) return null;
|
|
879
|
+
return btime * 1e3 + startTicks / 100 * 1e3;
|
|
880
|
+
} catch {
|
|
881
|
+
return null;
|
|
882
|
+
}
|
|
883
|
+
}
|
|
755
884
|
|
|
756
885
|
// src/daemon/daemon.ts
|
|
757
|
-
var
|
|
886
|
+
var CLI_REFRESH_TTL_MS = 10 * 6e4;
|
|
887
|
+
var log = (message3) => console.log(`[${(/* @__PURE__ */ new Date()).toISOString().slice(11, 19)}] ${message3}`);
|
|
758
888
|
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
759
889
|
function killTree(pid, signal) {
|
|
760
890
|
try {
|
|
@@ -775,7 +905,7 @@ function pidAlive(pid) {
|
|
|
775
905
|
}
|
|
776
906
|
}
|
|
777
907
|
async function runDaemon(opts) {
|
|
778
|
-
|
|
908
|
+
mkdirSync3(opts.configDir, { recursive: true });
|
|
779
909
|
let creds = loadRunnerCredentials(opts.configDir, opts.url, opts.name);
|
|
780
910
|
if (creds) {
|
|
781
911
|
log(`reconnecting as runner "${opts.name}" (${creds.runner_id}) \u2014 token from ${opts.configDir}`);
|
|
@@ -801,6 +931,12 @@ async function runDaemon(opts) {
|
|
|
801
931
|
const client2 = createApiClient({ baseUrl: opts.url, apiKey: creds.token });
|
|
802
932
|
const statePath = daemonStatePath(opts.configDir, creds.runner_id);
|
|
803
933
|
let shuttingDown = false;
|
|
934
|
+
const refresher = new CliRefresher(() => installAgentCli({ configDir: opts.configDir, log }), {
|
|
935
|
+
ttlMs: CLI_REFRESH_TTL_MS
|
|
936
|
+
});
|
|
937
|
+
const ensureCli = () => opts.cliRefresh ? refresher.ensure() : Promise.resolve(AMBIENT_CLI);
|
|
938
|
+
const cliLabel = (cli) => cli.source === "ambient" ? `ambient PATH (${opts.cliRefresh ? "refresh failed" : "refresh disabled"})` : `tines ${cli.version ?? "unknown"} (daemon-managed${cli.source === "stale" ? ", last-good copy" : ""})`;
|
|
939
|
+
log(`agent CLI: ${cliLabel(await ensureCli())}`);
|
|
804
940
|
const table2 = new RunTable({
|
|
805
941
|
finish: async (run, status, error) => {
|
|
806
942
|
await client2.finishRun(run.runId, { status, ...error ? { error } : {} });
|
|
@@ -832,208 +968,3587 @@ async function runDaemon(opts) {
|
|
|
832
968
|
killTree(orphan.pid, "SIGKILL");
|
|
833
969
|
}
|
|
834
970
|
}
|
|
835
|
-
try {
|
|
836
|
-
await client2.finishRun(orphan.run_id, {
|
|
837
|
-
status: "failed",
|
|
838
|
-
error: "daemon restarted; orphaned harness killed"
|
|
971
|
+
try {
|
|
972
|
+
await client2.finishRun(orphan.run_id, {
|
|
973
|
+
status: "failed",
|
|
974
|
+
error: "daemon restarted; orphaned harness killed"
|
|
975
|
+
});
|
|
976
|
+
} catch {
|
|
977
|
+
}
|
|
978
|
+
rmSync(orphan.workspace, { recursive: true, force: true });
|
|
979
|
+
}
|
|
980
|
+
saveDaemonState(statePath, []);
|
|
981
|
+
const killWithoutFinish = (runId) => {
|
|
982
|
+
const run = table2.markCanceled(runId);
|
|
983
|
+
if (!run) return;
|
|
984
|
+
log(`supervisor canceled run ${runId}; killing without finish-reporting`);
|
|
985
|
+
if (run.child?.pid) {
|
|
986
|
+
const pid = run.child.pid;
|
|
987
|
+
killTree(pid, "SIGTERM");
|
|
988
|
+
setTimeout(() => killTree(pid, "SIGKILL"), 5e3).unref?.();
|
|
989
|
+
}
|
|
990
|
+
};
|
|
991
|
+
const launch = async (assignment) => {
|
|
992
|
+
const runId = assignment.run.id;
|
|
993
|
+
if (table2.has(runId)) return;
|
|
994
|
+
const workspace = join3(opts.configDir, "workspaces", runId);
|
|
995
|
+
const run = {
|
|
996
|
+
runId,
|
|
997
|
+
workspace,
|
|
998
|
+
canceled: false,
|
|
999
|
+
timedOut: false,
|
|
1000
|
+
settled: false,
|
|
1001
|
+
keyFingerprint: assignment.run_key.slice(0, 14),
|
|
1002
|
+
batcher: new LogBatcher((chunk) => client2.appendRunLog(runId, { chunk }).then(() => {
|
|
1003
|
+
}), {
|
|
1004
|
+
onError: (err) => log(`log append for run ${runId} failed: ${message2(err)}`)
|
|
1005
|
+
})
|
|
1006
|
+
};
|
|
1007
|
+
run.flush = () => run.batcher.flush();
|
|
1008
|
+
table2.track(run);
|
|
1009
|
+
log(`run ${runId} assigned (issue ${assignment.run.issue_ref ? `${assignment.run.issue_ref.project_name}/${assignment.run.issue_ref.number}` : assignment.run.issue_id}); materializing workspace`);
|
|
1010
|
+
try {
|
|
1011
|
+
rmSync(workspace, { recursive: true, force: true });
|
|
1012
|
+
mkdirSync3(workspace, { recursive: true });
|
|
1013
|
+
writeFileSync2(join3(workspace, "prompt.md"), `${assignment.prompt}
|
|
1014
|
+
`);
|
|
1015
|
+
for (const skill of assignment.bundle.skills) {
|
|
1016
|
+
for (const file of skill.files) {
|
|
1017
|
+
const target = join3(workspace, "skills", skill.name, file.path);
|
|
1018
|
+
mkdirSync3(dirname3(target), { recursive: true });
|
|
1019
|
+
writeFileSync2(target, file.content);
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
writeFileSync2(
|
|
1023
|
+
join3(workspace, "repos.json"),
|
|
1024
|
+
`${JSON.stringify(assignment.bundle.repos, null, 2)}
|
|
1025
|
+
`
|
|
1026
|
+
);
|
|
1027
|
+
for (const repo of assignment.bundle.repos) {
|
|
1028
|
+
if (run.settled) return table2.cleanup(run);
|
|
1029
|
+
const args = ["clone", ...repo.branch ? ["--branch", repo.branch] : [], repo.url, repo.dir];
|
|
1030
|
+
run.batcher.append(`$ git ${args.join(" ")}
|
|
1031
|
+
`);
|
|
1032
|
+
const result = await runGit(args, workspace, run.batcher);
|
|
1033
|
+
if (result !== 0) {
|
|
1034
|
+
return table2.finishAndCleanup(run, "failed", `git clone failed for ${repo.url} (exit ${result})`);
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
if (run.settled) return table2.cleanup(run);
|
|
1038
|
+
const cli = await ensureCli();
|
|
1039
|
+
if (run.settled) return table2.cleanup(run);
|
|
1040
|
+
run.batcher.append(
|
|
1041
|
+
cli.source === "fresh" ? `tines CLI: ${cli.version ?? "unknown"} (daemon-managed)
|
|
1042
|
+
` : cli.source === "stale" ? `warning: agent CLI refresh failed; using last-good tines ${cli.version ?? "unknown"} from ${opts.configDir}/cli
|
|
1043
|
+
` : `warning: no daemon-managed tines CLI; using whatever \`tines\` is on this machine's PATH
|
|
1044
|
+
`
|
|
1045
|
+
);
|
|
1046
|
+
const invocation = buildHarnessInvocation(
|
|
1047
|
+
{ harness: opts.harness, command: opts.command },
|
|
1048
|
+
{
|
|
1049
|
+
workspace,
|
|
1050
|
+
promptFile: join3(workspace, "prompt.md"),
|
|
1051
|
+
prompt: assignment.prompt,
|
|
1052
|
+
model: assignment.run.model
|
|
1053
|
+
}
|
|
1054
|
+
);
|
|
1055
|
+
const child = spawn2(invocation.file, invocation.args, {
|
|
1056
|
+
cwd: workspace,
|
|
1057
|
+
env: buildSpawnEnv(process.env, {
|
|
1058
|
+
binDir: cli.binDir,
|
|
1059
|
+
apiKey: assignment.run_key,
|
|
1060
|
+
apiUrl: opts.url
|
|
1061
|
+
}),
|
|
1062
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1063
|
+
detached: true
|
|
1064
|
+
});
|
|
1065
|
+
run.child = child;
|
|
1066
|
+
run.spawnedAt = Date.now();
|
|
1067
|
+
table2.persist();
|
|
1068
|
+
log(`run ${runId}: launched ${invocation.file} (pid ${child.pid})`);
|
|
1069
|
+
child.stdout?.on("data", (data) => run.batcher.append(data.toString("utf8")));
|
|
1070
|
+
child.stderr?.on("data", (data) => run.batcher.append(data.toString("utf8")));
|
|
1071
|
+
run.timeout = setTimeout(
|
|
1072
|
+
() => {
|
|
1073
|
+
if (run.settled) return;
|
|
1074
|
+
log(`run ${runId} hit its ${assignment.timeout_minutes}m timeout; killing`);
|
|
1075
|
+
run.timedOut = true;
|
|
1076
|
+
if (child.pid) killTree(child.pid, "SIGTERM");
|
|
1077
|
+
if (child.pid) setTimeout(() => killTree(child.pid, "SIGKILL"), 5e3).unref?.();
|
|
1078
|
+
},
|
|
1079
|
+
assignment.timeout_minutes * 6e4
|
|
1080
|
+
);
|
|
1081
|
+
child.on("error", (err) => {
|
|
1082
|
+
void table2.finishAndCleanup(run, "failed", `failed to launch harness: ${message2(err)}`);
|
|
1083
|
+
});
|
|
1084
|
+
child.on("exit", (code, signal) => {
|
|
1085
|
+
if (run.timedOut) {
|
|
1086
|
+
void table2.finishAndCleanup(
|
|
1087
|
+
run,
|
|
1088
|
+
"failed",
|
|
1089
|
+
`run exceeded the ${assignment.timeout_minutes}m timeout; harness killed`
|
|
1090
|
+
);
|
|
1091
|
+
} else if (code === 0) {
|
|
1092
|
+
void table2.finishAndCleanup(run, "completed");
|
|
1093
|
+
} else {
|
|
1094
|
+
void table2.finishAndCleanup(
|
|
1095
|
+
run,
|
|
1096
|
+
"failed",
|
|
1097
|
+
signal ? `harness killed by ${signal}` : `harness exited with code ${code}`
|
|
1098
|
+
);
|
|
1099
|
+
}
|
|
1100
|
+
});
|
|
1101
|
+
} catch (err) {
|
|
1102
|
+
void table2.finishAndCleanup(run, "failed", `workspace setup failed: ${message2(err)}`);
|
|
1103
|
+
}
|
|
1104
|
+
};
|
|
1105
|
+
const shutdown = async () => {
|
|
1106
|
+
if (shuttingDown) return;
|
|
1107
|
+
shuttingDown = true;
|
|
1108
|
+
log("shutting down; failing in-flight runs");
|
|
1109
|
+
await Promise.all(
|
|
1110
|
+
table2.values().map(async (run) => {
|
|
1111
|
+
if (run.child?.pid) killTree(run.child.pid, "SIGTERM");
|
|
1112
|
+
await table2.finishAndCleanup(run, "failed", "daemon shut down");
|
|
1113
|
+
})
|
|
1114
|
+
);
|
|
1115
|
+
process.exit(0);
|
|
1116
|
+
};
|
|
1117
|
+
process.on("SIGINT", () => void shutdown());
|
|
1118
|
+
process.on("SIGTERM", () => void shutdown());
|
|
1119
|
+
log(
|
|
1120
|
+
`polling ${opts.url} every ${Math.round(opts.pollIntervalMs / 1e3)}s (harness ${opts.harness}, max ${opts.maxConcurrent} concurrent) \u2014 Ctrl-C to stop`
|
|
1121
|
+
);
|
|
1122
|
+
let failures = 0;
|
|
1123
|
+
while (!shuttingDown) {
|
|
1124
|
+
try {
|
|
1125
|
+
const res = await client2.pollRunner(creds.runner_id, {
|
|
1126
|
+
owned_runs: table2.ids(),
|
|
1127
|
+
max_concurrent: opts.maxConcurrent
|
|
1128
|
+
});
|
|
1129
|
+
failures = 0;
|
|
1130
|
+
for (const runId of res.cancels) killWithoutFinish(runId);
|
|
1131
|
+
for (const assignment of res.assignments) {
|
|
1132
|
+
if (table2.size >= opts.maxConcurrent) {
|
|
1133
|
+
log(
|
|
1134
|
+
`warning: supervisor delivered ${assignment.run.id} beyond --max-concurrent ${opts.maxConcurrent}; launching anyway (the server cap governs)`
|
|
1135
|
+
);
|
|
1136
|
+
}
|
|
1137
|
+
void launch(assignment);
|
|
1138
|
+
}
|
|
1139
|
+
} catch (err) {
|
|
1140
|
+
if (err instanceof ApiError && err.status === 401) {
|
|
1141
|
+
for (const run of table2.values()) {
|
|
1142
|
+
if (run.child?.pid) killTree(run.child.pid, "SIGKILL");
|
|
1143
|
+
rmSync(run.workspace, { recursive: true, force: true });
|
|
1144
|
+
}
|
|
1145
|
+
saveDaemonState(statePath, []);
|
|
1146
|
+
clearRunnerCredentials(opts.configDir, opts.url, opts.name);
|
|
1147
|
+
throw new Error(
|
|
1148
|
+
`the supervisor rejected this runner's token (was it rotated?) \u2014 the stored token was dropped; restart with the new token via \`tines runners rotate-token ${opts.name}\` on this machine, or with TINES_API_KEY set to re-register`
|
|
1149
|
+
);
|
|
1150
|
+
}
|
|
1151
|
+
failures += 1;
|
|
1152
|
+
log(`poll failed (${message2(err)}); retrying with backoff`);
|
|
1153
|
+
}
|
|
1154
|
+
const backoff = Math.min(
|
|
1155
|
+
opts.pollIntervalMs * 2 ** Math.min(failures, 3),
|
|
1156
|
+
Math.max(6e4, opts.pollIntervalMs * 5)
|
|
1157
|
+
);
|
|
1158
|
+
await sleep(failures > 0 ? backoff : opts.pollIntervalMs);
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
function message2(err) {
|
|
1162
|
+
return err instanceof Error ? err.message : String(err);
|
|
1163
|
+
}
|
|
1164
|
+
function runGit(args, cwd, batcher) {
|
|
1165
|
+
return new Promise((resolve) => {
|
|
1166
|
+
const child = spawn2("git", args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
|
|
1167
|
+
child.stdout?.on("data", (data) => batcher.append(data.toString("utf8")));
|
|
1168
|
+
child.stderr?.on("data", (data) => batcher.append(data.toString("utf8")));
|
|
1169
|
+
child.on("error", () => resolve(127));
|
|
1170
|
+
child.on("exit", (code) => resolve(code ?? 1));
|
|
1171
|
+
});
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
// src/help-guard.ts
|
|
1175
|
+
function helpGuard(command, markdown) {
|
|
1176
|
+
if (markdown === "--help" || markdown === "-h") {
|
|
1177
|
+
command.help();
|
|
1178
|
+
return true;
|
|
1179
|
+
}
|
|
1180
|
+
return false;
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
// ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
|
|
1184
|
+
var CommanderError = class extends Error {
|
|
1185
|
+
/**
|
|
1186
|
+
* Constructs the CommanderError class
|
|
1187
|
+
* @param {number} exitCode suggested exit code which could be used with process.exit
|
|
1188
|
+
* @param {string} code an id string representing the error
|
|
1189
|
+
* @param {string} message human-readable description of the error
|
|
1190
|
+
*/
|
|
1191
|
+
constructor(exitCode, code, message3) {
|
|
1192
|
+
super(message3);
|
|
1193
|
+
Error.captureStackTrace(this, this.constructor);
|
|
1194
|
+
this.name = this.constructor.name;
|
|
1195
|
+
this.code = code;
|
|
1196
|
+
this.exitCode = exitCode;
|
|
1197
|
+
this.nestedError = void 0;
|
|
1198
|
+
}
|
|
1199
|
+
};
|
|
1200
|
+
var InvalidArgumentError = class extends CommanderError {
|
|
1201
|
+
/**
|
|
1202
|
+
* Constructs the InvalidArgumentError class
|
|
1203
|
+
* @param {string} [message] explanation of why argument is invalid
|
|
1204
|
+
*/
|
|
1205
|
+
constructor(message3) {
|
|
1206
|
+
super(1, "commander.invalidArgument", message3);
|
|
1207
|
+
Error.captureStackTrace(this, this.constructor);
|
|
1208
|
+
this.name = this.constructor.name;
|
|
1209
|
+
}
|
|
1210
|
+
};
|
|
1211
|
+
|
|
1212
|
+
// ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/argument.js
|
|
1213
|
+
var Argument = class {
|
|
1214
|
+
/**
|
|
1215
|
+
* Initialize a new command argument with the given name and description.
|
|
1216
|
+
* The default is that the argument is required, and you can explicitly
|
|
1217
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
1218
|
+
*
|
|
1219
|
+
* @param {string} name
|
|
1220
|
+
* @param {string} [description]
|
|
1221
|
+
*/
|
|
1222
|
+
constructor(name2, description) {
|
|
1223
|
+
this.description = description || "";
|
|
1224
|
+
this.variadic = false;
|
|
1225
|
+
this.parseArg = void 0;
|
|
1226
|
+
this.defaultValue = void 0;
|
|
1227
|
+
this.defaultValueDescription = void 0;
|
|
1228
|
+
this.argChoices = void 0;
|
|
1229
|
+
switch (name2[0]) {
|
|
1230
|
+
case "<":
|
|
1231
|
+
this.required = true;
|
|
1232
|
+
this._name = name2.slice(1, -1);
|
|
1233
|
+
break;
|
|
1234
|
+
case "[":
|
|
1235
|
+
this.required = false;
|
|
1236
|
+
this._name = name2.slice(1, -1);
|
|
1237
|
+
break;
|
|
1238
|
+
default:
|
|
1239
|
+
this.required = true;
|
|
1240
|
+
this._name = name2;
|
|
1241
|
+
break;
|
|
1242
|
+
}
|
|
1243
|
+
if (this._name.endsWith("...")) {
|
|
1244
|
+
this.variadic = true;
|
|
1245
|
+
this._name = this._name.slice(0, -3);
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
/**
|
|
1249
|
+
* Return argument name.
|
|
1250
|
+
*
|
|
1251
|
+
* @return {string}
|
|
1252
|
+
*/
|
|
1253
|
+
name() {
|
|
1254
|
+
return this._name;
|
|
1255
|
+
}
|
|
1256
|
+
/**
|
|
1257
|
+
* @package
|
|
1258
|
+
*/
|
|
1259
|
+
_collectValue(value, previous) {
|
|
1260
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
1261
|
+
return [value];
|
|
1262
|
+
}
|
|
1263
|
+
previous.push(value);
|
|
1264
|
+
return previous;
|
|
1265
|
+
}
|
|
1266
|
+
/**
|
|
1267
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
1268
|
+
*
|
|
1269
|
+
* @param {*} value
|
|
1270
|
+
* @param {string} [description]
|
|
1271
|
+
* @return {Argument}
|
|
1272
|
+
*/
|
|
1273
|
+
default(value, description) {
|
|
1274
|
+
this.defaultValue = value;
|
|
1275
|
+
this.defaultValueDescription = description;
|
|
1276
|
+
return this;
|
|
1277
|
+
}
|
|
1278
|
+
/**
|
|
1279
|
+
* Set the custom handler for processing CLI command arguments into argument values.
|
|
1280
|
+
*
|
|
1281
|
+
* @param {Function} [fn]
|
|
1282
|
+
* @return {Argument}
|
|
1283
|
+
*/
|
|
1284
|
+
argParser(fn) {
|
|
1285
|
+
this.parseArg = fn;
|
|
1286
|
+
return this;
|
|
1287
|
+
}
|
|
1288
|
+
/**
|
|
1289
|
+
* Only allow argument value to be one of choices.
|
|
1290
|
+
*
|
|
1291
|
+
* @param {string[]} values
|
|
1292
|
+
* @return {Argument}
|
|
1293
|
+
*/
|
|
1294
|
+
choices(values) {
|
|
1295
|
+
this.argChoices = values.slice();
|
|
1296
|
+
this.parseArg = (arg, previous) => {
|
|
1297
|
+
if (!this.argChoices.includes(arg)) {
|
|
1298
|
+
throw new InvalidArgumentError(
|
|
1299
|
+
`Allowed choices are ${this.argChoices.join(", ")}.`
|
|
1300
|
+
);
|
|
1301
|
+
}
|
|
1302
|
+
if (this.variadic) {
|
|
1303
|
+
return this._collectValue(arg, previous);
|
|
1304
|
+
}
|
|
1305
|
+
return arg;
|
|
1306
|
+
};
|
|
1307
|
+
return this;
|
|
1308
|
+
}
|
|
1309
|
+
/**
|
|
1310
|
+
* Make argument required.
|
|
1311
|
+
*
|
|
1312
|
+
* @returns {Argument}
|
|
1313
|
+
*/
|
|
1314
|
+
argRequired() {
|
|
1315
|
+
this.required = true;
|
|
1316
|
+
return this;
|
|
1317
|
+
}
|
|
1318
|
+
/**
|
|
1319
|
+
* Make argument optional.
|
|
1320
|
+
*
|
|
1321
|
+
* @returns {Argument}
|
|
1322
|
+
*/
|
|
1323
|
+
argOptional() {
|
|
1324
|
+
this.required = false;
|
|
1325
|
+
return this;
|
|
1326
|
+
}
|
|
1327
|
+
};
|
|
1328
|
+
function humanReadableArgName(arg) {
|
|
1329
|
+
const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
|
|
1330
|
+
return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
// ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/command.js
|
|
1334
|
+
import { EventEmitter } from "node:events";
|
|
1335
|
+
import childProcess from "node:child_process";
|
|
1336
|
+
import path from "node:path";
|
|
1337
|
+
import fs from "node:fs";
|
|
1338
|
+
import process2 from "node:process";
|
|
1339
|
+
import { stripVTControlCharacters as stripVTControlCharacters2 } from "node:util";
|
|
1340
|
+
|
|
1341
|
+
// ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/help.js
|
|
1342
|
+
import { stripVTControlCharacters } from "node:util";
|
|
1343
|
+
var Help = class {
|
|
1344
|
+
constructor() {
|
|
1345
|
+
this.helpWidth = void 0;
|
|
1346
|
+
this.minWidthToWrap = 40;
|
|
1347
|
+
this.sortSubcommands = false;
|
|
1348
|
+
this.sortOptions = false;
|
|
1349
|
+
this.showGlobalOptions = false;
|
|
1350
|
+
}
|
|
1351
|
+
/**
|
|
1352
|
+
* prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
|
|
1353
|
+
* and just before calling `formatHelp()`.
|
|
1354
|
+
*
|
|
1355
|
+
* Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
|
|
1356
|
+
*
|
|
1357
|
+
* @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
|
|
1358
|
+
*/
|
|
1359
|
+
prepareContext(contextOptions) {
|
|
1360
|
+
this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
|
|
1361
|
+
}
|
|
1362
|
+
/**
|
|
1363
|
+
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
|
|
1364
|
+
*
|
|
1365
|
+
* @param {Command} cmd
|
|
1366
|
+
* @returns {Command[]}
|
|
1367
|
+
*/
|
|
1368
|
+
visibleCommands(cmd) {
|
|
1369
|
+
const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
|
|
1370
|
+
const helpCommand = cmd._getHelpCommand();
|
|
1371
|
+
if (helpCommand && !helpCommand._hidden) {
|
|
1372
|
+
visibleCommands.push(helpCommand);
|
|
1373
|
+
}
|
|
1374
|
+
if (this.sortSubcommands) {
|
|
1375
|
+
visibleCommands.sort((a, b) => {
|
|
1376
|
+
return a.name().localeCompare(b.name());
|
|
1377
|
+
});
|
|
1378
|
+
}
|
|
1379
|
+
return visibleCommands;
|
|
1380
|
+
}
|
|
1381
|
+
/**
|
|
1382
|
+
* Compare options for sort.
|
|
1383
|
+
*
|
|
1384
|
+
* @param {Option} a
|
|
1385
|
+
* @param {Option} b
|
|
1386
|
+
* @returns {number}
|
|
1387
|
+
*/
|
|
1388
|
+
compareOptions(a, b) {
|
|
1389
|
+
const getSortKey = (option) => {
|
|
1390
|
+
return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
|
|
1391
|
+
};
|
|
1392
|
+
return getSortKey(a).localeCompare(getSortKey(b));
|
|
1393
|
+
}
|
|
1394
|
+
/**
|
|
1395
|
+
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
|
|
1396
|
+
*
|
|
1397
|
+
* @param {Command} cmd
|
|
1398
|
+
* @returns {Option[]}
|
|
1399
|
+
*/
|
|
1400
|
+
visibleOptions(cmd) {
|
|
1401
|
+
const visibleOptions = cmd.options.filter((option) => !option.hidden);
|
|
1402
|
+
const helpOption = cmd._getHelpOption();
|
|
1403
|
+
if (helpOption && !helpOption.hidden) {
|
|
1404
|
+
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
|
|
1405
|
+
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
|
|
1406
|
+
if (!removeShort && !removeLong) {
|
|
1407
|
+
visibleOptions.push(helpOption);
|
|
1408
|
+
} else if (helpOption.long && !removeLong) {
|
|
1409
|
+
visibleOptions.push(
|
|
1410
|
+
cmd.createOption(helpOption.long, helpOption.description)
|
|
1411
|
+
);
|
|
1412
|
+
} else if (helpOption.short && !removeShort) {
|
|
1413
|
+
visibleOptions.push(
|
|
1414
|
+
cmd.createOption(helpOption.short, helpOption.description)
|
|
1415
|
+
);
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
if (this.sortOptions) {
|
|
1419
|
+
visibleOptions.sort(this.compareOptions);
|
|
1420
|
+
}
|
|
1421
|
+
return visibleOptions;
|
|
1422
|
+
}
|
|
1423
|
+
/**
|
|
1424
|
+
* Get an array of the visible global options. (Not including help.)
|
|
1425
|
+
*
|
|
1426
|
+
* @param {Command} cmd
|
|
1427
|
+
* @returns {Option[]}
|
|
1428
|
+
*/
|
|
1429
|
+
visibleGlobalOptions(cmd) {
|
|
1430
|
+
if (!this.showGlobalOptions) return [];
|
|
1431
|
+
const globalOptions = [];
|
|
1432
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
1433
|
+
const visibleOptions = ancestorCmd.options.filter(
|
|
1434
|
+
(option) => !option.hidden
|
|
1435
|
+
);
|
|
1436
|
+
globalOptions.push(...visibleOptions);
|
|
1437
|
+
}
|
|
1438
|
+
if (this.sortOptions) {
|
|
1439
|
+
globalOptions.sort(this.compareOptions);
|
|
1440
|
+
}
|
|
1441
|
+
return globalOptions;
|
|
1442
|
+
}
|
|
1443
|
+
/**
|
|
1444
|
+
* Get an array of the arguments if any have a description.
|
|
1445
|
+
*
|
|
1446
|
+
* @param {Command} cmd
|
|
1447
|
+
* @returns {Argument[]}
|
|
1448
|
+
*/
|
|
1449
|
+
visibleArguments(cmd) {
|
|
1450
|
+
if (cmd._argsDescription) {
|
|
1451
|
+
cmd.registeredArguments.forEach((argument) => {
|
|
1452
|
+
argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
|
|
1453
|
+
});
|
|
1454
|
+
}
|
|
1455
|
+
if (cmd.registeredArguments.find((argument) => argument.description)) {
|
|
1456
|
+
return cmd.registeredArguments;
|
|
1457
|
+
}
|
|
1458
|
+
return [];
|
|
1459
|
+
}
|
|
1460
|
+
/**
|
|
1461
|
+
* Get the command term to show in the list of subcommands.
|
|
1462
|
+
*
|
|
1463
|
+
* @param {Command} cmd
|
|
1464
|
+
* @returns {string}
|
|
1465
|
+
*/
|
|
1466
|
+
subcommandTerm(cmd) {
|
|
1467
|
+
const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
|
|
1468
|
+
return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
|
|
1469
|
+
(args ? " " + args : "");
|
|
1470
|
+
}
|
|
1471
|
+
/**
|
|
1472
|
+
* Get the option term to show in the list of options.
|
|
1473
|
+
*
|
|
1474
|
+
* @param {Option} option
|
|
1475
|
+
* @returns {string}
|
|
1476
|
+
*/
|
|
1477
|
+
optionTerm(option) {
|
|
1478
|
+
return option.flags;
|
|
1479
|
+
}
|
|
1480
|
+
/**
|
|
1481
|
+
* Get the argument term to show in the list of arguments.
|
|
1482
|
+
*
|
|
1483
|
+
* @param {Argument} argument
|
|
1484
|
+
* @returns {string}
|
|
1485
|
+
*/
|
|
1486
|
+
argumentTerm(argument) {
|
|
1487
|
+
return argument.name();
|
|
1488
|
+
}
|
|
1489
|
+
/**
|
|
1490
|
+
* Get the longest command term length.
|
|
1491
|
+
*
|
|
1492
|
+
* @param {Command} cmd
|
|
1493
|
+
* @param {Help} helper
|
|
1494
|
+
* @returns {number}
|
|
1495
|
+
*/
|
|
1496
|
+
longestSubcommandTermLength(cmd, helper) {
|
|
1497
|
+
return helper.visibleCommands(cmd).reduce((max, command) => {
|
|
1498
|
+
return Math.max(
|
|
1499
|
+
max,
|
|
1500
|
+
this.displayWidth(
|
|
1501
|
+
helper.styleSubcommandTerm(helper.subcommandTerm(command))
|
|
1502
|
+
)
|
|
1503
|
+
);
|
|
1504
|
+
}, 0);
|
|
1505
|
+
}
|
|
1506
|
+
/**
|
|
1507
|
+
* Get the longest option term length.
|
|
1508
|
+
*
|
|
1509
|
+
* @param {Command} cmd
|
|
1510
|
+
* @param {Help} helper
|
|
1511
|
+
* @returns {number}
|
|
1512
|
+
*/
|
|
1513
|
+
longestOptionTermLength(cmd, helper) {
|
|
1514
|
+
return helper.visibleOptions(cmd).reduce((max, option) => {
|
|
1515
|
+
return Math.max(
|
|
1516
|
+
max,
|
|
1517
|
+
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
|
|
1518
|
+
);
|
|
1519
|
+
}, 0);
|
|
1520
|
+
}
|
|
1521
|
+
/**
|
|
1522
|
+
* Get the longest global option term length.
|
|
1523
|
+
*
|
|
1524
|
+
* @param {Command} cmd
|
|
1525
|
+
* @param {Help} helper
|
|
1526
|
+
* @returns {number}
|
|
1527
|
+
*/
|
|
1528
|
+
longestGlobalOptionTermLength(cmd, helper) {
|
|
1529
|
+
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
|
|
1530
|
+
return Math.max(
|
|
1531
|
+
max,
|
|
1532
|
+
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
|
|
1533
|
+
);
|
|
1534
|
+
}, 0);
|
|
1535
|
+
}
|
|
1536
|
+
/**
|
|
1537
|
+
* Get the longest argument term length.
|
|
1538
|
+
*
|
|
1539
|
+
* @param {Command} cmd
|
|
1540
|
+
* @param {Help} helper
|
|
1541
|
+
* @returns {number}
|
|
1542
|
+
*/
|
|
1543
|
+
longestArgumentTermLength(cmd, helper) {
|
|
1544
|
+
return helper.visibleArguments(cmd).reduce((max, argument) => {
|
|
1545
|
+
return Math.max(
|
|
1546
|
+
max,
|
|
1547
|
+
this.displayWidth(
|
|
1548
|
+
helper.styleArgumentTerm(helper.argumentTerm(argument))
|
|
1549
|
+
)
|
|
1550
|
+
);
|
|
1551
|
+
}, 0);
|
|
1552
|
+
}
|
|
1553
|
+
/**
|
|
1554
|
+
* Get the command usage to be displayed at the top of the built-in help.
|
|
1555
|
+
*
|
|
1556
|
+
* @param {Command} cmd
|
|
1557
|
+
* @returns {string}
|
|
1558
|
+
*/
|
|
1559
|
+
commandUsage(cmd) {
|
|
1560
|
+
let cmdName = cmd._name;
|
|
1561
|
+
if (cmd._aliases[0]) {
|
|
1562
|
+
cmdName = cmdName + "|" + cmd._aliases[0];
|
|
1563
|
+
}
|
|
1564
|
+
let ancestorCmdNames = "";
|
|
1565
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
1566
|
+
ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
|
|
1567
|
+
}
|
|
1568
|
+
return ancestorCmdNames + cmdName + " " + cmd.usage();
|
|
1569
|
+
}
|
|
1570
|
+
/**
|
|
1571
|
+
* Get the description for the command.
|
|
1572
|
+
*
|
|
1573
|
+
* @param {Command} cmd
|
|
1574
|
+
* @returns {string}
|
|
1575
|
+
*/
|
|
1576
|
+
commandDescription(cmd) {
|
|
1577
|
+
return cmd.description();
|
|
1578
|
+
}
|
|
1579
|
+
/**
|
|
1580
|
+
* Get the subcommand summary to show in the list of subcommands.
|
|
1581
|
+
* (Fallback to description for backwards compatibility.)
|
|
1582
|
+
*
|
|
1583
|
+
* @param {Command} cmd
|
|
1584
|
+
* @returns {string}
|
|
1585
|
+
*/
|
|
1586
|
+
subcommandDescription(cmd) {
|
|
1587
|
+
return cmd.summary() || cmd.description();
|
|
1588
|
+
}
|
|
1589
|
+
/**
|
|
1590
|
+
* Get the option description to show in the list of options.
|
|
1591
|
+
*
|
|
1592
|
+
* @param {Option} option
|
|
1593
|
+
* @return {string}
|
|
1594
|
+
*/
|
|
1595
|
+
optionDescription(option) {
|
|
1596
|
+
const extraInfo = [];
|
|
1597
|
+
if (option.argChoices) {
|
|
1598
|
+
extraInfo.push(
|
|
1599
|
+
// use stringify to match the display of the default value
|
|
1600
|
+
`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
|
|
1601
|
+
);
|
|
1602
|
+
}
|
|
1603
|
+
if (option.defaultValue !== void 0) {
|
|
1604
|
+
const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
|
|
1605
|
+
if (showDefault) {
|
|
1606
|
+
extraInfo.push(
|
|
1607
|
+
`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
|
|
1608
|
+
);
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
if (option.presetArg !== void 0 && option.optional) {
|
|
1612
|
+
extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
|
|
1613
|
+
}
|
|
1614
|
+
if (option.envVar !== void 0) {
|
|
1615
|
+
extraInfo.push(`env: ${option.envVar}`);
|
|
1616
|
+
}
|
|
1617
|
+
if (extraInfo.length > 0) {
|
|
1618
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
1619
|
+
if (option.description) {
|
|
1620
|
+
return `${option.description} ${extraDescription}`;
|
|
1621
|
+
}
|
|
1622
|
+
return extraDescription;
|
|
1623
|
+
}
|
|
1624
|
+
return option.description;
|
|
1625
|
+
}
|
|
1626
|
+
/**
|
|
1627
|
+
* Get the argument description to show in the list of arguments.
|
|
1628
|
+
*
|
|
1629
|
+
* @param {Argument} argument
|
|
1630
|
+
* @return {string}
|
|
1631
|
+
*/
|
|
1632
|
+
argumentDescription(argument) {
|
|
1633
|
+
const extraInfo = [];
|
|
1634
|
+
if (argument.argChoices) {
|
|
1635
|
+
extraInfo.push(
|
|
1636
|
+
// use stringify to match the display of the default value
|
|
1637
|
+
`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
|
|
1638
|
+
);
|
|
1639
|
+
}
|
|
1640
|
+
if (argument.defaultValue !== void 0) {
|
|
1641
|
+
extraInfo.push(
|
|
1642
|
+
`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
|
|
1643
|
+
);
|
|
1644
|
+
}
|
|
1645
|
+
if (extraInfo.length > 0) {
|
|
1646
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
1647
|
+
if (argument.description) {
|
|
1648
|
+
return `${argument.description} ${extraDescription}`;
|
|
1649
|
+
}
|
|
1650
|
+
return extraDescription;
|
|
1651
|
+
}
|
|
1652
|
+
return argument.description;
|
|
1653
|
+
}
|
|
1654
|
+
/**
|
|
1655
|
+
* Format a list of items, given a heading and an array of formatted items.
|
|
1656
|
+
*
|
|
1657
|
+
* @param {string} heading
|
|
1658
|
+
* @param {string[]} items
|
|
1659
|
+
* @param {Help} helper
|
|
1660
|
+
* @returns string[]
|
|
1661
|
+
*/
|
|
1662
|
+
formatItemList(heading, items, helper) {
|
|
1663
|
+
if (items.length === 0) return [];
|
|
1664
|
+
return [helper.styleTitle(heading), ...items, ""];
|
|
1665
|
+
}
|
|
1666
|
+
/**
|
|
1667
|
+
* Group items by their help group heading.
|
|
1668
|
+
*
|
|
1669
|
+
* @param {Command[] | Option[]} unsortedItems
|
|
1670
|
+
* @param {Command[] | Option[]} visibleItems
|
|
1671
|
+
* @param {Function} getGroup
|
|
1672
|
+
* @returns {Map<string, Command[] | Option[]>}
|
|
1673
|
+
*/
|
|
1674
|
+
groupItems(unsortedItems, visibleItems, getGroup) {
|
|
1675
|
+
const result = /* @__PURE__ */ new Map();
|
|
1676
|
+
unsortedItems.forEach((item) => {
|
|
1677
|
+
const group = getGroup(item);
|
|
1678
|
+
if (!result.has(group)) result.set(group, []);
|
|
1679
|
+
});
|
|
1680
|
+
visibleItems.forEach((item) => {
|
|
1681
|
+
const group = getGroup(item);
|
|
1682
|
+
if (!result.has(group)) {
|
|
1683
|
+
result.set(group, []);
|
|
1684
|
+
}
|
|
1685
|
+
result.get(group).push(item);
|
|
1686
|
+
});
|
|
1687
|
+
return result;
|
|
1688
|
+
}
|
|
1689
|
+
/**
|
|
1690
|
+
* Generate the built-in help text.
|
|
1691
|
+
*
|
|
1692
|
+
* @param {Command} cmd
|
|
1693
|
+
* @param {Help} helper
|
|
1694
|
+
* @returns {string}
|
|
1695
|
+
*/
|
|
1696
|
+
formatHelp(cmd, helper) {
|
|
1697
|
+
const termWidth = helper.padWidth(cmd, helper);
|
|
1698
|
+
const helpWidth = helper.helpWidth ?? 80;
|
|
1699
|
+
function callFormatItem(term, description) {
|
|
1700
|
+
return helper.formatItem(term, termWidth, description, helper);
|
|
1701
|
+
}
|
|
1702
|
+
let output = [
|
|
1703
|
+
`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
|
|
1704
|
+
""
|
|
1705
|
+
];
|
|
1706
|
+
const commandDescription = helper.commandDescription(cmd);
|
|
1707
|
+
if (commandDescription.length > 0) {
|
|
1708
|
+
output = output.concat([
|
|
1709
|
+
helper.boxWrap(
|
|
1710
|
+
helper.styleCommandDescription(commandDescription),
|
|
1711
|
+
helpWidth
|
|
1712
|
+
),
|
|
1713
|
+
""
|
|
1714
|
+
]);
|
|
1715
|
+
}
|
|
1716
|
+
const argumentList = helper.visibleArguments(cmd).map((argument) => {
|
|
1717
|
+
return callFormatItem(
|
|
1718
|
+
helper.styleArgumentTerm(helper.argumentTerm(argument)),
|
|
1719
|
+
helper.styleArgumentDescription(helper.argumentDescription(argument))
|
|
1720
|
+
);
|
|
1721
|
+
});
|
|
1722
|
+
output = output.concat(
|
|
1723
|
+
this.formatItemList("Arguments:", argumentList, helper)
|
|
1724
|
+
);
|
|
1725
|
+
const optionGroups = this.groupItems(
|
|
1726
|
+
cmd.options,
|
|
1727
|
+
helper.visibleOptions(cmd),
|
|
1728
|
+
(option) => option.helpGroupHeading ?? "Options:"
|
|
1729
|
+
);
|
|
1730
|
+
optionGroups.forEach((options, group) => {
|
|
1731
|
+
const optionList = options.map((option) => {
|
|
1732
|
+
return callFormatItem(
|
|
1733
|
+
helper.styleOptionTerm(helper.optionTerm(option)),
|
|
1734
|
+
helper.styleOptionDescription(helper.optionDescription(option))
|
|
1735
|
+
);
|
|
1736
|
+
});
|
|
1737
|
+
output = output.concat(this.formatItemList(group, optionList, helper));
|
|
1738
|
+
});
|
|
1739
|
+
if (helper.showGlobalOptions) {
|
|
1740
|
+
const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
|
|
1741
|
+
return callFormatItem(
|
|
1742
|
+
helper.styleOptionTerm(helper.optionTerm(option)),
|
|
1743
|
+
helper.styleOptionDescription(helper.optionDescription(option))
|
|
1744
|
+
);
|
|
1745
|
+
});
|
|
1746
|
+
output = output.concat(
|
|
1747
|
+
this.formatItemList("Global Options:", globalOptionList, helper)
|
|
1748
|
+
);
|
|
1749
|
+
}
|
|
1750
|
+
const commandGroups = this.groupItems(
|
|
1751
|
+
cmd.commands,
|
|
1752
|
+
helper.visibleCommands(cmd),
|
|
1753
|
+
(sub) => sub.helpGroup() || "Commands:"
|
|
1754
|
+
);
|
|
1755
|
+
commandGroups.forEach((commands, group) => {
|
|
1756
|
+
const commandList = commands.map((sub) => {
|
|
1757
|
+
return callFormatItem(
|
|
1758
|
+
helper.styleSubcommandTerm(helper.subcommandTerm(sub)),
|
|
1759
|
+
helper.styleSubcommandDescription(helper.subcommandDescription(sub))
|
|
1760
|
+
);
|
|
1761
|
+
});
|
|
1762
|
+
output = output.concat(this.formatItemList(group, commandList, helper));
|
|
1763
|
+
});
|
|
1764
|
+
return output.join("\n");
|
|
1765
|
+
}
|
|
1766
|
+
/**
|
|
1767
|
+
* Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
|
|
1768
|
+
*
|
|
1769
|
+
* @param {string} str
|
|
1770
|
+
* @returns {number}
|
|
1771
|
+
*/
|
|
1772
|
+
displayWidth(str2) {
|
|
1773
|
+
return stripVTControlCharacters(str2).length;
|
|
1774
|
+
}
|
|
1775
|
+
/**
|
|
1776
|
+
* Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
|
|
1777
|
+
*
|
|
1778
|
+
* @param {string} str
|
|
1779
|
+
* @returns {string}
|
|
1780
|
+
*/
|
|
1781
|
+
styleTitle(str2) {
|
|
1782
|
+
return str2;
|
|
1783
|
+
}
|
|
1784
|
+
styleUsage(str2) {
|
|
1785
|
+
return str2.split(" ").map((word) => {
|
|
1786
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
1787
|
+
if (word === "[command]") return this.styleSubcommandText(word);
|
|
1788
|
+
if (word[0] === "[" || word[0] === "<")
|
|
1789
|
+
return this.styleArgumentText(word);
|
|
1790
|
+
return this.styleCommandText(word);
|
|
1791
|
+
}).join(" ");
|
|
1792
|
+
}
|
|
1793
|
+
styleCommandDescription(str2) {
|
|
1794
|
+
return this.styleDescriptionText(str2);
|
|
1795
|
+
}
|
|
1796
|
+
styleOptionDescription(str2) {
|
|
1797
|
+
return this.styleDescriptionText(str2);
|
|
1798
|
+
}
|
|
1799
|
+
styleSubcommandDescription(str2) {
|
|
1800
|
+
return this.styleDescriptionText(str2);
|
|
1801
|
+
}
|
|
1802
|
+
styleArgumentDescription(str2) {
|
|
1803
|
+
return this.styleDescriptionText(str2);
|
|
1804
|
+
}
|
|
1805
|
+
styleDescriptionText(str2) {
|
|
1806
|
+
return str2;
|
|
1807
|
+
}
|
|
1808
|
+
styleOptionTerm(str2) {
|
|
1809
|
+
return this.styleOptionText(str2);
|
|
1810
|
+
}
|
|
1811
|
+
styleSubcommandTerm(str2) {
|
|
1812
|
+
return str2.split(" ").map((word) => {
|
|
1813
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
1814
|
+
if (word[0] === "[" || word[0] === "<")
|
|
1815
|
+
return this.styleArgumentText(word);
|
|
1816
|
+
return this.styleSubcommandText(word);
|
|
1817
|
+
}).join(" ");
|
|
1818
|
+
}
|
|
1819
|
+
styleArgumentTerm(str2) {
|
|
1820
|
+
return this.styleArgumentText(str2);
|
|
1821
|
+
}
|
|
1822
|
+
styleOptionText(str2) {
|
|
1823
|
+
return str2;
|
|
1824
|
+
}
|
|
1825
|
+
styleArgumentText(str2) {
|
|
1826
|
+
return str2;
|
|
1827
|
+
}
|
|
1828
|
+
styleSubcommandText(str2) {
|
|
1829
|
+
return str2;
|
|
1830
|
+
}
|
|
1831
|
+
styleCommandText(str2) {
|
|
1832
|
+
return str2;
|
|
1833
|
+
}
|
|
1834
|
+
/**
|
|
1835
|
+
* Calculate the pad width from the maximum term length.
|
|
1836
|
+
*
|
|
1837
|
+
* @param {Command} cmd
|
|
1838
|
+
* @param {Help} helper
|
|
1839
|
+
* @returns {number}
|
|
1840
|
+
*/
|
|
1841
|
+
padWidth(cmd, helper) {
|
|
1842
|
+
return Math.max(
|
|
1843
|
+
helper.longestOptionTermLength(cmd, helper),
|
|
1844
|
+
helper.longestGlobalOptionTermLength(cmd, helper),
|
|
1845
|
+
helper.longestSubcommandTermLength(cmd, helper),
|
|
1846
|
+
helper.longestArgumentTermLength(cmd, helper)
|
|
1847
|
+
);
|
|
1848
|
+
}
|
|
1849
|
+
/**
|
|
1850
|
+
* Detect manually wrapped and indented strings by checking for line break followed by whitespace.
|
|
1851
|
+
*
|
|
1852
|
+
* @param {string} str
|
|
1853
|
+
* @returns {boolean}
|
|
1854
|
+
*/
|
|
1855
|
+
preformatted(str2) {
|
|
1856
|
+
return /\n[^\S\r\n]/.test(str2);
|
|
1857
|
+
}
|
|
1858
|
+
/**
|
|
1859
|
+
* Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
|
|
1860
|
+
*
|
|
1861
|
+
* So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
|
|
1862
|
+
* TTT DDD DDDD
|
|
1863
|
+
* DD DDD
|
|
1864
|
+
*
|
|
1865
|
+
* @param {string} term
|
|
1866
|
+
* @param {number} termWidth
|
|
1867
|
+
* @param {string} description
|
|
1868
|
+
* @param {Help} helper
|
|
1869
|
+
* @returns {string}
|
|
1870
|
+
*/
|
|
1871
|
+
formatItem(term, termWidth, description, helper) {
|
|
1872
|
+
const itemIndent = 2;
|
|
1873
|
+
const itemIndentStr = " ".repeat(itemIndent);
|
|
1874
|
+
if (!description) return itemIndentStr + term;
|
|
1875
|
+
const paddedTerm = term.padEnd(
|
|
1876
|
+
termWidth + term.length - helper.displayWidth(term)
|
|
1877
|
+
);
|
|
1878
|
+
const spacerWidth = 2;
|
|
1879
|
+
const helpWidth = this.helpWidth ?? 80;
|
|
1880
|
+
const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
|
|
1881
|
+
let formattedDescription;
|
|
1882
|
+
if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
|
|
1883
|
+
formattedDescription = description;
|
|
1884
|
+
} else {
|
|
1885
|
+
const wrappedDescription = helper.boxWrap(description, remainingWidth);
|
|
1886
|
+
formattedDescription = wrappedDescription.replace(
|
|
1887
|
+
/\n/g,
|
|
1888
|
+
"\n" + " ".repeat(termWidth + spacerWidth)
|
|
1889
|
+
);
|
|
1890
|
+
}
|
|
1891
|
+
return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
|
|
1892
|
+
${itemIndentStr}`);
|
|
1893
|
+
}
|
|
1894
|
+
/**
|
|
1895
|
+
* Wrap a string at whitespace, preserving existing line breaks.
|
|
1896
|
+
* Wrapping is skipped if the width is less than `minWidthToWrap`.
|
|
1897
|
+
*
|
|
1898
|
+
* @param {string} str
|
|
1899
|
+
* @param {number} width
|
|
1900
|
+
* @returns {string}
|
|
1901
|
+
*/
|
|
1902
|
+
boxWrap(str2, width) {
|
|
1903
|
+
if (width < this.minWidthToWrap) return str2;
|
|
1904
|
+
const rawLines = str2.split(/\r\n|\n/);
|
|
1905
|
+
const chunkPattern = /[\s]*[^\s]+/g;
|
|
1906
|
+
const wrappedLines = [];
|
|
1907
|
+
rawLines.forEach((line) => {
|
|
1908
|
+
const chunks = line.match(chunkPattern);
|
|
1909
|
+
if (chunks === null) {
|
|
1910
|
+
wrappedLines.push("");
|
|
1911
|
+
return;
|
|
1912
|
+
}
|
|
1913
|
+
let sumChunks = [chunks.shift()];
|
|
1914
|
+
let sumWidth = this.displayWidth(sumChunks[0]);
|
|
1915
|
+
chunks.forEach((chunk) => {
|
|
1916
|
+
const visibleWidth = this.displayWidth(chunk);
|
|
1917
|
+
if (sumWidth + visibleWidth <= width) {
|
|
1918
|
+
sumChunks.push(chunk);
|
|
1919
|
+
sumWidth += visibleWidth;
|
|
1920
|
+
return;
|
|
1921
|
+
}
|
|
1922
|
+
wrappedLines.push(sumChunks.join(""));
|
|
1923
|
+
const nextChunk = chunk.trimStart();
|
|
1924
|
+
sumChunks = [nextChunk];
|
|
1925
|
+
sumWidth = this.displayWidth(nextChunk);
|
|
1926
|
+
});
|
|
1927
|
+
wrappedLines.push(sumChunks.join(""));
|
|
1928
|
+
});
|
|
1929
|
+
return wrappedLines.join("\n");
|
|
1930
|
+
}
|
|
1931
|
+
};
|
|
1932
|
+
|
|
1933
|
+
// ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/option.js
|
|
1934
|
+
var Option = class {
|
|
1935
|
+
/**
|
|
1936
|
+
* Initialize a new `Option` with the given `flags` and `description`.
|
|
1937
|
+
*
|
|
1938
|
+
* @param {string} flags
|
|
1939
|
+
* @param {string} [description]
|
|
1940
|
+
*/
|
|
1941
|
+
constructor(flags, description) {
|
|
1942
|
+
this.flags = flags;
|
|
1943
|
+
this.description = description || "";
|
|
1944
|
+
this.required = flags.includes("<");
|
|
1945
|
+
this.optional = flags.includes("[");
|
|
1946
|
+
this.variadic = /\w\.\.\.[>\]]$/.test(flags);
|
|
1947
|
+
this.mandatory = false;
|
|
1948
|
+
const optionFlags = splitOptionFlags(flags);
|
|
1949
|
+
this.short = optionFlags.shortFlag;
|
|
1950
|
+
this.long = optionFlags.longFlag;
|
|
1951
|
+
this.negate = false;
|
|
1952
|
+
if (this.long) {
|
|
1953
|
+
this.negate = this.long.startsWith("--no-");
|
|
1954
|
+
}
|
|
1955
|
+
this.defaultValue = void 0;
|
|
1956
|
+
this.defaultValueDescription = void 0;
|
|
1957
|
+
this.presetArg = void 0;
|
|
1958
|
+
this.envVar = void 0;
|
|
1959
|
+
this.parseArg = void 0;
|
|
1960
|
+
this.hidden = false;
|
|
1961
|
+
this.argChoices = void 0;
|
|
1962
|
+
this.conflictsWith = [];
|
|
1963
|
+
this.implied = void 0;
|
|
1964
|
+
this.helpGroupHeading = void 0;
|
|
1965
|
+
}
|
|
1966
|
+
/**
|
|
1967
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
1968
|
+
*
|
|
1969
|
+
* @param {*} value
|
|
1970
|
+
* @param {string} [description]
|
|
1971
|
+
* @return {Option}
|
|
1972
|
+
*/
|
|
1973
|
+
default(value, description) {
|
|
1974
|
+
this.defaultValue = value;
|
|
1975
|
+
this.defaultValueDescription = description;
|
|
1976
|
+
return this;
|
|
1977
|
+
}
|
|
1978
|
+
/**
|
|
1979
|
+
* Preset to use when option used without option-argument, especially optional but also boolean and negated.
|
|
1980
|
+
* The custom processing (parseArg) is called.
|
|
1981
|
+
*
|
|
1982
|
+
* @example
|
|
1983
|
+
* new Option('--color').default('GREYSCALE').preset('RGB');
|
|
1984
|
+
* new Option('--donate [amount]').preset('20').argParser(parseFloat);
|
|
1985
|
+
*
|
|
1986
|
+
* @param {*} arg
|
|
1987
|
+
* @return {Option}
|
|
1988
|
+
*/
|
|
1989
|
+
preset(arg) {
|
|
1990
|
+
this.presetArg = arg;
|
|
1991
|
+
return this;
|
|
1992
|
+
}
|
|
1993
|
+
/**
|
|
1994
|
+
* Add option name(s) that conflict with this option.
|
|
1995
|
+
* An error will be displayed if conflicting options are found during parsing.
|
|
1996
|
+
*
|
|
1997
|
+
* @example
|
|
1998
|
+
* new Option('--rgb').conflicts('cmyk');
|
|
1999
|
+
* new Option('--js').conflicts(['ts', 'jsx']);
|
|
2000
|
+
*
|
|
2001
|
+
* @param {(string | string[])} names
|
|
2002
|
+
* @return {Option}
|
|
2003
|
+
*/
|
|
2004
|
+
conflicts(names) {
|
|
2005
|
+
this.conflictsWith = this.conflictsWith.concat(names);
|
|
2006
|
+
return this;
|
|
2007
|
+
}
|
|
2008
|
+
/**
|
|
2009
|
+
* Specify implied option values for when this option is set and the implied options are not.
|
|
2010
|
+
*
|
|
2011
|
+
* The custom processing (parseArg) is not called on the implied values.
|
|
2012
|
+
*
|
|
2013
|
+
* @example
|
|
2014
|
+
* program
|
|
2015
|
+
* .addOption(new Option('--log', 'write logging information to file'))
|
|
2016
|
+
* .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
|
|
2017
|
+
*
|
|
2018
|
+
* @param {object} impliedOptionValues
|
|
2019
|
+
* @return {Option}
|
|
2020
|
+
*/
|
|
2021
|
+
implies(impliedOptionValues) {
|
|
2022
|
+
let newImplied = impliedOptionValues;
|
|
2023
|
+
if (typeof impliedOptionValues === "string") {
|
|
2024
|
+
newImplied = { [impliedOptionValues]: true };
|
|
2025
|
+
}
|
|
2026
|
+
this.implied = Object.assign(this.implied || {}, newImplied);
|
|
2027
|
+
return this;
|
|
2028
|
+
}
|
|
2029
|
+
/**
|
|
2030
|
+
* Set environment variable to check for option value.
|
|
2031
|
+
*
|
|
2032
|
+
* An environment variable is only used if when processed the current option value is
|
|
2033
|
+
* undefined, or the source of the current value is 'default' or 'config' or 'env'.
|
|
2034
|
+
*
|
|
2035
|
+
* @param {string} name
|
|
2036
|
+
* @return {Option}
|
|
2037
|
+
*/
|
|
2038
|
+
env(name2) {
|
|
2039
|
+
this.envVar = name2;
|
|
2040
|
+
return this;
|
|
2041
|
+
}
|
|
2042
|
+
/**
|
|
2043
|
+
* Set the custom handler for processing CLI option arguments into option values.
|
|
2044
|
+
*
|
|
2045
|
+
* @param {Function} [fn]
|
|
2046
|
+
* @return {Option}
|
|
2047
|
+
*/
|
|
2048
|
+
argParser(fn) {
|
|
2049
|
+
this.parseArg = fn;
|
|
2050
|
+
return this;
|
|
2051
|
+
}
|
|
2052
|
+
/**
|
|
2053
|
+
* Whether the option is mandatory and must have a value after parsing.
|
|
2054
|
+
*
|
|
2055
|
+
* @param {boolean} [mandatory=true]
|
|
2056
|
+
* @return {Option}
|
|
2057
|
+
*/
|
|
2058
|
+
makeOptionMandatory(mandatory = true) {
|
|
2059
|
+
this.mandatory = !!mandatory;
|
|
2060
|
+
return this;
|
|
2061
|
+
}
|
|
2062
|
+
/**
|
|
2063
|
+
* Hide option in help.
|
|
2064
|
+
*
|
|
2065
|
+
* @param {boolean} [hide=true]
|
|
2066
|
+
* @return {Option}
|
|
2067
|
+
*/
|
|
2068
|
+
hideHelp(hide = true) {
|
|
2069
|
+
this.hidden = !!hide;
|
|
2070
|
+
return this;
|
|
2071
|
+
}
|
|
2072
|
+
/**
|
|
2073
|
+
* @package
|
|
2074
|
+
*/
|
|
2075
|
+
_collectValue(value, previous) {
|
|
2076
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
2077
|
+
return [value];
|
|
2078
|
+
}
|
|
2079
|
+
previous.push(value);
|
|
2080
|
+
return previous;
|
|
2081
|
+
}
|
|
2082
|
+
/**
|
|
2083
|
+
* Only allow option value to be one of choices.
|
|
2084
|
+
*
|
|
2085
|
+
* @param {string[]} values
|
|
2086
|
+
* @return {Option}
|
|
2087
|
+
*/
|
|
2088
|
+
choices(values) {
|
|
2089
|
+
this.argChoices = values.slice();
|
|
2090
|
+
this.parseArg = (arg, previous) => {
|
|
2091
|
+
if (!this.argChoices.includes(arg)) {
|
|
2092
|
+
throw new InvalidArgumentError(
|
|
2093
|
+
`Allowed choices are ${this.argChoices.join(", ")}.`
|
|
2094
|
+
);
|
|
2095
|
+
}
|
|
2096
|
+
if (this.variadic) {
|
|
2097
|
+
return this._collectValue(arg, previous);
|
|
2098
|
+
}
|
|
2099
|
+
return arg;
|
|
2100
|
+
};
|
|
2101
|
+
return this;
|
|
2102
|
+
}
|
|
2103
|
+
/**
|
|
2104
|
+
* Return option name.
|
|
2105
|
+
*
|
|
2106
|
+
* @return {string}
|
|
2107
|
+
*/
|
|
2108
|
+
name() {
|
|
2109
|
+
if (this.long) {
|
|
2110
|
+
return this.long.replace(/^--/, "");
|
|
2111
|
+
}
|
|
2112
|
+
return this.short.replace(/^-/, "");
|
|
2113
|
+
}
|
|
2114
|
+
/**
|
|
2115
|
+
* Return option name, in a camelcase format that can be used
|
|
2116
|
+
* as an object attribute key.
|
|
2117
|
+
*
|
|
2118
|
+
* @return {string}
|
|
2119
|
+
*/
|
|
2120
|
+
attributeName() {
|
|
2121
|
+
if (this.negate) {
|
|
2122
|
+
return camelcase(this.name().replace(/^no-/, ""));
|
|
2123
|
+
}
|
|
2124
|
+
return camelcase(this.name());
|
|
2125
|
+
}
|
|
2126
|
+
/**
|
|
2127
|
+
* Set the help group heading.
|
|
2128
|
+
*
|
|
2129
|
+
* @param {string} heading
|
|
2130
|
+
* @return {Option}
|
|
2131
|
+
*/
|
|
2132
|
+
helpGroup(heading) {
|
|
2133
|
+
this.helpGroupHeading = heading;
|
|
2134
|
+
return this;
|
|
2135
|
+
}
|
|
2136
|
+
/**
|
|
2137
|
+
* Check if `arg` matches the short or long flag.
|
|
2138
|
+
*
|
|
2139
|
+
* @param {string} arg
|
|
2140
|
+
* @return {boolean}
|
|
2141
|
+
* @package
|
|
2142
|
+
*/
|
|
2143
|
+
is(arg) {
|
|
2144
|
+
return this.short === arg || this.long === arg;
|
|
2145
|
+
}
|
|
2146
|
+
/**
|
|
2147
|
+
* Return whether a boolean option.
|
|
2148
|
+
*
|
|
2149
|
+
* Options are one of boolean, negated, required argument, or optional argument.
|
|
2150
|
+
*
|
|
2151
|
+
* @return {boolean}
|
|
2152
|
+
* @package
|
|
2153
|
+
*/
|
|
2154
|
+
isBoolean() {
|
|
2155
|
+
return !this.required && !this.optional && !this.negate;
|
|
2156
|
+
}
|
|
2157
|
+
};
|
|
2158
|
+
var DualOptions = class {
|
|
2159
|
+
/**
|
|
2160
|
+
* @param {Option[]} options
|
|
2161
|
+
*/
|
|
2162
|
+
constructor(options) {
|
|
2163
|
+
this.positiveOptions = /* @__PURE__ */ new Map();
|
|
2164
|
+
this.negativeOptions = /* @__PURE__ */ new Map();
|
|
2165
|
+
this.dualOptions = /* @__PURE__ */ new Set();
|
|
2166
|
+
options.forEach((option) => {
|
|
2167
|
+
if (option.negate) {
|
|
2168
|
+
this.negativeOptions.set(option.attributeName(), option);
|
|
2169
|
+
} else {
|
|
2170
|
+
this.positiveOptions.set(option.attributeName(), option);
|
|
2171
|
+
}
|
|
2172
|
+
});
|
|
2173
|
+
this.negativeOptions.forEach((value, key) => {
|
|
2174
|
+
if (this.positiveOptions.has(key)) {
|
|
2175
|
+
this.dualOptions.add(key);
|
|
2176
|
+
}
|
|
2177
|
+
});
|
|
2178
|
+
}
|
|
2179
|
+
/**
|
|
2180
|
+
* Did the value come from the option, and not from possible matching dual option?
|
|
2181
|
+
*
|
|
2182
|
+
* @param {*} value
|
|
2183
|
+
* @param {Option} option
|
|
2184
|
+
* @returns {boolean}
|
|
2185
|
+
*/
|
|
2186
|
+
valueFromOption(value, option) {
|
|
2187
|
+
const optionKey = option.attributeName();
|
|
2188
|
+
if (!this.dualOptions.has(optionKey)) return true;
|
|
2189
|
+
const preset = this.negativeOptions.get(optionKey).presetArg;
|
|
2190
|
+
const negativeValue = preset !== void 0 ? preset : false;
|
|
2191
|
+
return option.negate === (negativeValue === value);
|
|
2192
|
+
}
|
|
2193
|
+
};
|
|
2194
|
+
function camelcase(str2) {
|
|
2195
|
+
return str2.split("-").reduce((str3, word) => {
|
|
2196
|
+
return str3 + word[0].toUpperCase() + word.slice(1);
|
|
2197
|
+
});
|
|
2198
|
+
}
|
|
2199
|
+
function splitOptionFlags(flags) {
|
|
2200
|
+
let shortFlag;
|
|
2201
|
+
let longFlag;
|
|
2202
|
+
const shortFlagExp = /^-[^-]$/;
|
|
2203
|
+
const longFlagExp = /^--[^-]/;
|
|
2204
|
+
const flagParts = flags.split(/[ |,]+/).concat("guard");
|
|
2205
|
+
if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
|
|
2206
|
+
if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
|
|
2207
|
+
if (!shortFlag && shortFlagExp.test(flagParts[0]))
|
|
2208
|
+
shortFlag = flagParts.shift();
|
|
2209
|
+
if (!shortFlag && longFlagExp.test(flagParts[0])) {
|
|
2210
|
+
shortFlag = longFlag;
|
|
2211
|
+
longFlag = flagParts.shift();
|
|
2212
|
+
}
|
|
2213
|
+
if (flagParts[0].startsWith("-")) {
|
|
2214
|
+
const unsupportedFlag = flagParts[0];
|
|
2215
|
+
const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
|
|
2216
|
+
if (/^-[^-][^-]/.test(unsupportedFlag))
|
|
2217
|
+
throw new Error(
|
|
2218
|
+
`${baseError}
|
|
2219
|
+
- a short flag is a single dash and a single character
|
|
2220
|
+
- either use a single dash and a single character (for a short flag)
|
|
2221
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`
|
|
2222
|
+
);
|
|
2223
|
+
if (shortFlagExp.test(unsupportedFlag))
|
|
2224
|
+
throw new Error(`${baseError}
|
|
2225
|
+
- too many short flags`);
|
|
2226
|
+
if (longFlagExp.test(unsupportedFlag))
|
|
2227
|
+
throw new Error(`${baseError}
|
|
2228
|
+
- too many long flags`);
|
|
2229
|
+
throw new Error(`${baseError}
|
|
2230
|
+
- unrecognised flag format`);
|
|
2231
|
+
}
|
|
2232
|
+
if (shortFlag === void 0 && longFlag === void 0)
|
|
2233
|
+
throw new Error(
|
|
2234
|
+
`option creation failed due to no flags found in '${flags}'.`
|
|
2235
|
+
);
|
|
2236
|
+
return { shortFlag, longFlag };
|
|
2237
|
+
}
|
|
2238
|
+
|
|
2239
|
+
// ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/suggestSimilar.js
|
|
2240
|
+
var maxDistance = 3;
|
|
2241
|
+
function editDistance(a, b) {
|
|
2242
|
+
if (Math.abs(a.length - b.length) > maxDistance)
|
|
2243
|
+
return Math.max(a.length, b.length);
|
|
2244
|
+
const d = [];
|
|
2245
|
+
for (let i = 0; i <= a.length; i++) {
|
|
2246
|
+
d[i] = [i];
|
|
2247
|
+
}
|
|
2248
|
+
for (let j = 0; j <= b.length; j++) {
|
|
2249
|
+
d[0][j] = j;
|
|
2250
|
+
}
|
|
2251
|
+
for (let j = 1; j <= b.length; j++) {
|
|
2252
|
+
for (let i = 1; i <= a.length; i++) {
|
|
2253
|
+
let cost;
|
|
2254
|
+
if (a[i - 1] === b[j - 1]) {
|
|
2255
|
+
cost = 0;
|
|
2256
|
+
} else {
|
|
2257
|
+
cost = 1;
|
|
2258
|
+
}
|
|
2259
|
+
d[i][j] = Math.min(
|
|
2260
|
+
d[i - 1][j] + 1,
|
|
2261
|
+
// deletion
|
|
2262
|
+
d[i][j - 1] + 1,
|
|
2263
|
+
// insertion
|
|
2264
|
+
d[i - 1][j - 1] + cost
|
|
2265
|
+
// substitution
|
|
2266
|
+
);
|
|
2267
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
|
|
2268
|
+
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
2269
|
+
}
|
|
2270
|
+
}
|
|
2271
|
+
}
|
|
2272
|
+
return d[a.length][b.length];
|
|
2273
|
+
}
|
|
2274
|
+
function suggestSimilar(word, candidates) {
|
|
2275
|
+
if (!candidates || candidates.length === 0) return "";
|
|
2276
|
+
candidates = Array.from(new Set(candidates));
|
|
2277
|
+
const searchingOptions = word.startsWith("--");
|
|
2278
|
+
if (searchingOptions) {
|
|
2279
|
+
word = word.slice(2);
|
|
2280
|
+
candidates = candidates.map((candidate) => candidate.slice(2));
|
|
2281
|
+
}
|
|
2282
|
+
let similar = [];
|
|
2283
|
+
let bestDistance = maxDistance;
|
|
2284
|
+
const minSimilarity = 0.4;
|
|
2285
|
+
candidates.forEach((candidate) => {
|
|
2286
|
+
if (candidate.length <= 1) return;
|
|
2287
|
+
const distance = editDistance(word, candidate);
|
|
2288
|
+
const length = Math.max(word.length, candidate.length);
|
|
2289
|
+
const similarity = (length - distance) / length;
|
|
2290
|
+
if (similarity > minSimilarity) {
|
|
2291
|
+
if (distance < bestDistance) {
|
|
2292
|
+
bestDistance = distance;
|
|
2293
|
+
similar = [candidate];
|
|
2294
|
+
} else if (distance === bestDistance) {
|
|
2295
|
+
similar.push(candidate);
|
|
2296
|
+
}
|
|
2297
|
+
}
|
|
2298
|
+
});
|
|
2299
|
+
similar.sort((a, b) => a.localeCompare(b));
|
|
2300
|
+
if (searchingOptions) {
|
|
2301
|
+
similar = similar.map((candidate) => `--${candidate}`);
|
|
2302
|
+
}
|
|
2303
|
+
if (similar.length > 1) {
|
|
2304
|
+
return `
|
|
2305
|
+
(Did you mean one of ${similar.join(", ")}?)`;
|
|
2306
|
+
}
|
|
2307
|
+
if (similar.length === 1) {
|
|
2308
|
+
return `
|
|
2309
|
+
(Did you mean ${similar[0]}?)`;
|
|
2310
|
+
}
|
|
2311
|
+
return "";
|
|
2312
|
+
}
|
|
2313
|
+
|
|
2314
|
+
// ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/command.js
|
|
2315
|
+
var Command = class _Command extends EventEmitter {
|
|
2316
|
+
/**
|
|
2317
|
+
* Initialize a new `Command`.
|
|
2318
|
+
*
|
|
2319
|
+
* @param {string} [name]
|
|
2320
|
+
*/
|
|
2321
|
+
constructor(name2) {
|
|
2322
|
+
super();
|
|
2323
|
+
this.commands = [];
|
|
2324
|
+
this.options = [];
|
|
2325
|
+
this.parent = null;
|
|
2326
|
+
this._allowUnknownOption = false;
|
|
2327
|
+
this._allowExcessArguments = false;
|
|
2328
|
+
this.registeredArguments = [];
|
|
2329
|
+
this._args = this.registeredArguments;
|
|
2330
|
+
this.args = [];
|
|
2331
|
+
this.rawArgs = [];
|
|
2332
|
+
this.processedArgs = [];
|
|
2333
|
+
this._scriptPath = null;
|
|
2334
|
+
this._name = name2 || "";
|
|
2335
|
+
this._optionValues = {};
|
|
2336
|
+
this._optionValueSources = {};
|
|
2337
|
+
this._storeOptionsAsProperties = false;
|
|
2338
|
+
this._actionHandler = null;
|
|
2339
|
+
this._executableHandler = false;
|
|
2340
|
+
this._executableFile = null;
|
|
2341
|
+
this._executableDir = null;
|
|
2342
|
+
this._defaultCommandName = null;
|
|
2343
|
+
this._exitCallback = null;
|
|
2344
|
+
this._aliases = [];
|
|
2345
|
+
this._combineFlagAndOptionalValue = true;
|
|
2346
|
+
this._description = "";
|
|
2347
|
+
this._summary = "";
|
|
2348
|
+
this._argsDescription = void 0;
|
|
2349
|
+
this._enablePositionalOptions = false;
|
|
2350
|
+
this._passThroughOptions = false;
|
|
2351
|
+
this._lifeCycleHooks = {};
|
|
2352
|
+
this._showHelpAfterError = false;
|
|
2353
|
+
this._showSuggestionAfterError = true;
|
|
2354
|
+
this._savedState = null;
|
|
2355
|
+
this._outputConfiguration = {
|
|
2356
|
+
writeOut: (str2) => process2.stdout.write(str2),
|
|
2357
|
+
writeErr: (str2) => process2.stderr.write(str2),
|
|
2358
|
+
outputError: (str2, write) => write(str2),
|
|
2359
|
+
getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
|
|
2360
|
+
getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
|
|
2361
|
+
getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
|
|
2362
|
+
getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
|
|
2363
|
+
stripColor: (str2) => stripVTControlCharacters2(str2)
|
|
2364
|
+
};
|
|
2365
|
+
this._hidden = false;
|
|
2366
|
+
this._helpOption = void 0;
|
|
2367
|
+
this._addImplicitHelpCommand = void 0;
|
|
2368
|
+
this._helpCommand = void 0;
|
|
2369
|
+
this._helpConfiguration = {};
|
|
2370
|
+
this._helpGroupHeading = void 0;
|
|
2371
|
+
this._defaultCommandGroup = void 0;
|
|
2372
|
+
this._defaultOptionGroup = void 0;
|
|
2373
|
+
}
|
|
2374
|
+
/**
|
|
2375
|
+
* Copy settings that are useful to have in common across root command and subcommands.
|
|
2376
|
+
*
|
|
2377
|
+
* (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
|
|
2378
|
+
*
|
|
2379
|
+
* @param {Command} sourceCommand
|
|
2380
|
+
* @return {Command} `this` command for chaining
|
|
2381
|
+
*/
|
|
2382
|
+
copyInheritedSettings(sourceCommand) {
|
|
2383
|
+
this._outputConfiguration = sourceCommand._outputConfiguration;
|
|
2384
|
+
this._helpOption = sourceCommand._helpOption;
|
|
2385
|
+
this._helpCommand = sourceCommand._helpCommand;
|
|
2386
|
+
this._helpConfiguration = sourceCommand._helpConfiguration;
|
|
2387
|
+
this._exitCallback = sourceCommand._exitCallback;
|
|
2388
|
+
this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
|
|
2389
|
+
this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
|
|
2390
|
+
this._allowExcessArguments = sourceCommand._allowExcessArguments;
|
|
2391
|
+
this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
|
|
2392
|
+
this._showHelpAfterError = sourceCommand._showHelpAfterError;
|
|
2393
|
+
this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
|
|
2394
|
+
return this;
|
|
2395
|
+
}
|
|
2396
|
+
/**
|
|
2397
|
+
* @returns {Command[]}
|
|
2398
|
+
* @private
|
|
2399
|
+
*/
|
|
2400
|
+
_getCommandAndAncestors() {
|
|
2401
|
+
const result = [];
|
|
2402
|
+
for (let command = this; command; command = command.parent) {
|
|
2403
|
+
result.push(command);
|
|
2404
|
+
}
|
|
2405
|
+
return result;
|
|
2406
|
+
}
|
|
2407
|
+
/**
|
|
2408
|
+
* Define a command.
|
|
2409
|
+
*
|
|
2410
|
+
* There are two styles of command: pay attention to where to put the description.
|
|
2411
|
+
*
|
|
2412
|
+
* @example
|
|
2413
|
+
* // Command implemented using action handler (description is supplied separately to `.command`)
|
|
2414
|
+
* program
|
|
2415
|
+
* .command('clone <source> [destination]')
|
|
2416
|
+
* .description('clone a repository into a newly created directory')
|
|
2417
|
+
* .action((source, destination) => {
|
|
2418
|
+
* console.log('clone command called');
|
|
2419
|
+
* });
|
|
2420
|
+
*
|
|
2421
|
+
* // Command implemented using separate executable file (description is second parameter to `.command`)
|
|
2422
|
+
* program
|
|
2423
|
+
* .command('start <service>', 'start named service')
|
|
2424
|
+
* .command('stop [service]', 'stop named service, or all if no name supplied');
|
|
2425
|
+
*
|
|
2426
|
+
* @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
|
|
2427
|
+
* @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
|
|
2428
|
+
* @param {object} [execOpts] - configuration options (for executable)
|
|
2429
|
+
* @return {Command} returns new command for action handler, or `this` for executable command
|
|
2430
|
+
*/
|
|
2431
|
+
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
|
|
2432
|
+
let desc = actionOptsOrExecDesc;
|
|
2433
|
+
let opts = execOpts;
|
|
2434
|
+
if (typeof desc === "object" && desc !== null) {
|
|
2435
|
+
opts = desc;
|
|
2436
|
+
desc = null;
|
|
2437
|
+
}
|
|
2438
|
+
opts = opts || {};
|
|
2439
|
+
const [, name2, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
2440
|
+
const cmd = this.createCommand(name2);
|
|
2441
|
+
if (desc) {
|
|
2442
|
+
cmd.description(desc);
|
|
2443
|
+
cmd._executableHandler = true;
|
|
2444
|
+
}
|
|
2445
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
2446
|
+
cmd._hidden = !!(opts.noHelp || opts.hidden);
|
|
2447
|
+
cmd._executableFile = opts.executableFile || null;
|
|
2448
|
+
if (args) cmd.arguments(args);
|
|
2449
|
+
this._registerCommand(cmd);
|
|
2450
|
+
cmd.parent = this;
|
|
2451
|
+
cmd.copyInheritedSettings(this);
|
|
2452
|
+
if (desc) return this;
|
|
2453
|
+
return cmd;
|
|
2454
|
+
}
|
|
2455
|
+
/**
|
|
2456
|
+
* Factory routine to create a new unattached command.
|
|
2457
|
+
*
|
|
2458
|
+
* See .command() for creating an attached subcommand, which uses this routine to
|
|
2459
|
+
* create the command. You can override createCommand to customise subcommands.
|
|
2460
|
+
*
|
|
2461
|
+
* @param {string} [name]
|
|
2462
|
+
* @return {Command} new command
|
|
2463
|
+
*/
|
|
2464
|
+
createCommand(name2) {
|
|
2465
|
+
return new _Command(name2);
|
|
2466
|
+
}
|
|
2467
|
+
/**
|
|
2468
|
+
* You can customise the help with a subclass of Help by overriding createHelp,
|
|
2469
|
+
* or by overriding Help properties using configureHelp().
|
|
2470
|
+
*
|
|
2471
|
+
* @return {Help}
|
|
2472
|
+
*/
|
|
2473
|
+
createHelp() {
|
|
2474
|
+
return Object.assign(new Help(), this.configureHelp());
|
|
2475
|
+
}
|
|
2476
|
+
/**
|
|
2477
|
+
* You can customise the help by overriding Help properties using configureHelp(),
|
|
2478
|
+
* or with a subclass of Help by overriding createHelp().
|
|
2479
|
+
*
|
|
2480
|
+
* @param {object} [configuration] - configuration options
|
|
2481
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
2482
|
+
*/
|
|
2483
|
+
configureHelp(configuration) {
|
|
2484
|
+
if (configuration === void 0) return this._helpConfiguration;
|
|
2485
|
+
this._helpConfiguration = configuration;
|
|
2486
|
+
return this;
|
|
2487
|
+
}
|
|
2488
|
+
/**
|
|
2489
|
+
* The default output goes to stdout and stderr. You can customise this for special
|
|
2490
|
+
* applications. You can also customise the display of errors by overriding outputError.
|
|
2491
|
+
*
|
|
2492
|
+
* The configuration properties are all functions:
|
|
2493
|
+
*
|
|
2494
|
+
* // change how output being written, defaults to stdout and stderr
|
|
2495
|
+
* writeOut(str)
|
|
2496
|
+
* writeErr(str)
|
|
2497
|
+
* // change how output being written for errors, defaults to writeErr
|
|
2498
|
+
* outputError(str, write) // used for displaying errors and not used for displaying help
|
|
2499
|
+
* // specify width for wrapping help
|
|
2500
|
+
* getOutHelpWidth()
|
|
2501
|
+
* getErrHelpWidth()
|
|
2502
|
+
* // color support, currently only used with Help
|
|
2503
|
+
* getOutHasColors()
|
|
2504
|
+
* getErrHasColors()
|
|
2505
|
+
* stripColor() // used to remove ANSI escape codes if output does not have colors
|
|
2506
|
+
*
|
|
2507
|
+
* @param {object} [configuration] - configuration options
|
|
2508
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
2509
|
+
*/
|
|
2510
|
+
configureOutput(configuration) {
|
|
2511
|
+
if (configuration === void 0) return this._outputConfiguration;
|
|
2512
|
+
this._outputConfiguration = {
|
|
2513
|
+
...this._outputConfiguration,
|
|
2514
|
+
...configuration
|
|
2515
|
+
};
|
|
2516
|
+
return this;
|
|
2517
|
+
}
|
|
2518
|
+
/**
|
|
2519
|
+
* Display the help or a custom message after an error occurs.
|
|
2520
|
+
*
|
|
2521
|
+
* @param {(boolean|string)} [displayHelp]
|
|
2522
|
+
* @return {Command} `this` command for chaining
|
|
2523
|
+
*/
|
|
2524
|
+
showHelpAfterError(displayHelp = true) {
|
|
2525
|
+
if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
|
|
2526
|
+
this._showHelpAfterError = displayHelp;
|
|
2527
|
+
return this;
|
|
2528
|
+
}
|
|
2529
|
+
/**
|
|
2530
|
+
* Display suggestion of similar commands for unknown commands, or options for unknown options.
|
|
2531
|
+
*
|
|
2532
|
+
* @param {boolean} [displaySuggestion]
|
|
2533
|
+
* @return {Command} `this` command for chaining
|
|
2534
|
+
*/
|
|
2535
|
+
showSuggestionAfterError(displaySuggestion = true) {
|
|
2536
|
+
this._showSuggestionAfterError = !!displaySuggestion;
|
|
2537
|
+
return this;
|
|
2538
|
+
}
|
|
2539
|
+
/**
|
|
2540
|
+
* Add a prepared subcommand.
|
|
2541
|
+
*
|
|
2542
|
+
* See .command() for creating an attached subcommand which inherits settings from its parent.
|
|
2543
|
+
*
|
|
2544
|
+
* @param {Command} cmd - new subcommand
|
|
2545
|
+
* @param {object} [opts] - configuration options
|
|
2546
|
+
* @return {Command} `this` command for chaining
|
|
2547
|
+
*/
|
|
2548
|
+
addCommand(cmd, opts) {
|
|
2549
|
+
if (!cmd._name) {
|
|
2550
|
+
throw new Error(`Command passed to .addCommand() must have a name
|
|
2551
|
+
- specify the name in Command constructor or using .name()`);
|
|
2552
|
+
}
|
|
2553
|
+
opts = opts || {};
|
|
2554
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
2555
|
+
if (opts.noHelp || opts.hidden) cmd._hidden = true;
|
|
2556
|
+
this._registerCommand(cmd);
|
|
2557
|
+
cmd.parent = this;
|
|
2558
|
+
cmd._checkForBrokenPassThrough();
|
|
2559
|
+
return this;
|
|
2560
|
+
}
|
|
2561
|
+
/**
|
|
2562
|
+
* Factory routine to create a new unattached argument.
|
|
2563
|
+
*
|
|
2564
|
+
* See .argument() for creating an attached argument, which uses this routine to
|
|
2565
|
+
* create the argument. You can override createArgument to return a custom argument.
|
|
2566
|
+
*
|
|
2567
|
+
* @param {string} name
|
|
2568
|
+
* @param {string} [description]
|
|
2569
|
+
* @return {Argument} new argument
|
|
2570
|
+
*/
|
|
2571
|
+
createArgument(name2, description) {
|
|
2572
|
+
return new Argument(name2, description);
|
|
2573
|
+
}
|
|
2574
|
+
/**
|
|
2575
|
+
* Define argument syntax for command.
|
|
2576
|
+
*
|
|
2577
|
+
* The default is that the argument is required, and you can explicitly
|
|
2578
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
2579
|
+
*
|
|
2580
|
+
* @example
|
|
2581
|
+
* program.argument('<input-file>');
|
|
2582
|
+
* program.argument('[output-file]');
|
|
2583
|
+
*
|
|
2584
|
+
* @param {string} name
|
|
2585
|
+
* @param {string} [description]
|
|
2586
|
+
* @param {(Function|*)} [parseArg] - custom argument processing function or default value
|
|
2587
|
+
* @param {*} [defaultValue]
|
|
2588
|
+
* @return {Command} `this` command for chaining
|
|
2589
|
+
*/
|
|
2590
|
+
argument(name2, description, parseArg, defaultValue) {
|
|
2591
|
+
const argument = this.createArgument(name2, description);
|
|
2592
|
+
if (typeof parseArg === "function") {
|
|
2593
|
+
argument.default(defaultValue).argParser(parseArg);
|
|
2594
|
+
} else {
|
|
2595
|
+
argument.default(parseArg);
|
|
2596
|
+
}
|
|
2597
|
+
this.addArgument(argument);
|
|
2598
|
+
return this;
|
|
2599
|
+
}
|
|
2600
|
+
/**
|
|
2601
|
+
* Define argument syntax for command, adding multiple at once (without descriptions).
|
|
2602
|
+
*
|
|
2603
|
+
* See also .argument().
|
|
2604
|
+
*
|
|
2605
|
+
* @example
|
|
2606
|
+
* program.arguments('<cmd> [env]');
|
|
2607
|
+
*
|
|
2608
|
+
* @param {string} names
|
|
2609
|
+
* @return {Command} `this` command for chaining
|
|
2610
|
+
*/
|
|
2611
|
+
arguments(names) {
|
|
2612
|
+
names.trim().split(/ +/).forEach((detail) => {
|
|
2613
|
+
this.argument(detail);
|
|
2614
|
+
});
|
|
2615
|
+
return this;
|
|
2616
|
+
}
|
|
2617
|
+
/**
|
|
2618
|
+
* Define argument syntax for command, adding a prepared argument.
|
|
2619
|
+
*
|
|
2620
|
+
* @param {Argument} argument
|
|
2621
|
+
* @return {Command} `this` command for chaining
|
|
2622
|
+
*/
|
|
2623
|
+
addArgument(argument) {
|
|
2624
|
+
const previousArgument = this.registeredArguments.slice(-1)[0];
|
|
2625
|
+
if (previousArgument?.variadic) {
|
|
2626
|
+
throw new Error(
|
|
2627
|
+
`only the last argument can be variadic '${previousArgument.name()}'`
|
|
2628
|
+
);
|
|
2629
|
+
}
|
|
2630
|
+
if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
|
|
2631
|
+
throw new Error(
|
|
2632
|
+
`a default value for a required argument is never used: '${argument.name()}'`
|
|
2633
|
+
);
|
|
2634
|
+
}
|
|
2635
|
+
this.registeredArguments.push(argument);
|
|
2636
|
+
return this;
|
|
2637
|
+
}
|
|
2638
|
+
/**
|
|
2639
|
+
* Customise or override default help command. By default a help command is automatically added if your command has subcommands.
|
|
2640
|
+
*
|
|
2641
|
+
* @example
|
|
2642
|
+
* program.helpCommand('help [cmd]');
|
|
2643
|
+
* program.helpCommand('help [cmd]', 'show help');
|
|
2644
|
+
* program.helpCommand(false); // suppress default help command
|
|
2645
|
+
* program.helpCommand(true); // add help command even if no subcommands
|
|
2646
|
+
*
|
|
2647
|
+
* @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
|
|
2648
|
+
* @param {string} [description] - custom description
|
|
2649
|
+
* @return {Command} `this` command for chaining
|
|
2650
|
+
*/
|
|
2651
|
+
helpCommand(enableOrNameAndArgs, description) {
|
|
2652
|
+
if (typeof enableOrNameAndArgs === "boolean") {
|
|
2653
|
+
this._addImplicitHelpCommand = enableOrNameAndArgs;
|
|
2654
|
+
if (enableOrNameAndArgs && this._defaultCommandGroup) {
|
|
2655
|
+
this._initCommandGroup(this._getHelpCommand());
|
|
2656
|
+
}
|
|
2657
|
+
return this;
|
|
2658
|
+
}
|
|
2659
|
+
const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
|
|
2660
|
+
const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
2661
|
+
const helpDescription = description ?? "display help for command";
|
|
2662
|
+
const helpCommand = this.createCommand(helpName);
|
|
2663
|
+
helpCommand.helpOption(false);
|
|
2664
|
+
if (helpArgs) helpCommand.arguments(helpArgs);
|
|
2665
|
+
if (helpDescription) helpCommand.description(helpDescription);
|
|
2666
|
+
this._addImplicitHelpCommand = true;
|
|
2667
|
+
this._helpCommand = helpCommand;
|
|
2668
|
+
if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
|
|
2669
|
+
return this;
|
|
2670
|
+
}
|
|
2671
|
+
/**
|
|
2672
|
+
* Add prepared custom help command.
|
|
2673
|
+
*
|
|
2674
|
+
* @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
|
|
2675
|
+
* @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
|
|
2676
|
+
* @return {Command} `this` command for chaining
|
|
2677
|
+
*/
|
|
2678
|
+
addHelpCommand(helpCommand, deprecatedDescription) {
|
|
2679
|
+
if (typeof helpCommand !== "object") {
|
|
2680
|
+
this.helpCommand(helpCommand, deprecatedDescription);
|
|
2681
|
+
return this;
|
|
2682
|
+
}
|
|
2683
|
+
this._addImplicitHelpCommand = true;
|
|
2684
|
+
this._helpCommand = helpCommand;
|
|
2685
|
+
this._initCommandGroup(helpCommand);
|
|
2686
|
+
return this;
|
|
2687
|
+
}
|
|
2688
|
+
/**
|
|
2689
|
+
* Lazy create help command.
|
|
2690
|
+
*
|
|
2691
|
+
* @return {(Command|null)}
|
|
2692
|
+
* @package
|
|
2693
|
+
*/
|
|
2694
|
+
_getHelpCommand() {
|
|
2695
|
+
const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
|
|
2696
|
+
if (hasImplicitHelpCommand) {
|
|
2697
|
+
if (this._helpCommand === void 0) {
|
|
2698
|
+
this.helpCommand(void 0, void 0);
|
|
2699
|
+
}
|
|
2700
|
+
return this._helpCommand;
|
|
2701
|
+
}
|
|
2702
|
+
return null;
|
|
2703
|
+
}
|
|
2704
|
+
/**
|
|
2705
|
+
* Add hook for life cycle event.
|
|
2706
|
+
*
|
|
2707
|
+
* @param {string} event
|
|
2708
|
+
* @param {Function} listener
|
|
2709
|
+
* @return {Command} `this` command for chaining
|
|
2710
|
+
*/
|
|
2711
|
+
hook(event, listener) {
|
|
2712
|
+
const allowedValues = ["preSubcommand", "preAction", "postAction"];
|
|
2713
|
+
if (!allowedValues.includes(event)) {
|
|
2714
|
+
throw new Error(`Unexpected value for event passed to hook : '${event}'.
|
|
2715
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
2716
|
+
}
|
|
2717
|
+
if (this._lifeCycleHooks[event]) {
|
|
2718
|
+
this._lifeCycleHooks[event].push(listener);
|
|
2719
|
+
} else {
|
|
2720
|
+
this._lifeCycleHooks[event] = [listener];
|
|
2721
|
+
}
|
|
2722
|
+
return this;
|
|
2723
|
+
}
|
|
2724
|
+
/**
|
|
2725
|
+
* Register callback to use as replacement for calling process.exit.
|
|
2726
|
+
*
|
|
2727
|
+
* @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
|
|
2728
|
+
* @return {Command} `this` command for chaining
|
|
2729
|
+
*/
|
|
2730
|
+
exitOverride(fn) {
|
|
2731
|
+
if (fn) {
|
|
2732
|
+
this._exitCallback = fn;
|
|
2733
|
+
} else {
|
|
2734
|
+
this._exitCallback = (err) => {
|
|
2735
|
+
if (err.code !== "commander.executeSubCommandAsync") {
|
|
2736
|
+
throw err;
|
|
2737
|
+
} else {
|
|
2738
|
+
}
|
|
2739
|
+
};
|
|
2740
|
+
}
|
|
2741
|
+
return this;
|
|
2742
|
+
}
|
|
2743
|
+
/**
|
|
2744
|
+
* Call process.exit, and _exitCallback if defined.
|
|
2745
|
+
*
|
|
2746
|
+
* @param {number} exitCode exit code for using with process.exit
|
|
2747
|
+
* @param {string} code an id string representing the error
|
|
2748
|
+
* @param {string} message human-readable description of the error
|
|
2749
|
+
* @return never
|
|
2750
|
+
* @private
|
|
2751
|
+
*/
|
|
2752
|
+
_exit(exitCode, code, message3) {
|
|
2753
|
+
if (this._exitCallback) {
|
|
2754
|
+
this._exitCallback(new CommanderError(exitCode, code, message3));
|
|
2755
|
+
}
|
|
2756
|
+
process2.exit(exitCode);
|
|
2757
|
+
}
|
|
2758
|
+
/**
|
|
2759
|
+
* Register callback `fn` for the command.
|
|
2760
|
+
*
|
|
2761
|
+
* @example
|
|
2762
|
+
* program
|
|
2763
|
+
* .command('serve')
|
|
2764
|
+
* .description('start service')
|
|
2765
|
+
* .action(function() {
|
|
2766
|
+
* // do work here
|
|
2767
|
+
* });
|
|
2768
|
+
*
|
|
2769
|
+
* @param {Function} fn
|
|
2770
|
+
* @return {Command} `this` command for chaining
|
|
2771
|
+
*/
|
|
2772
|
+
action(fn) {
|
|
2773
|
+
const listener = (args) => {
|
|
2774
|
+
const expectedArgsCount = this.registeredArguments.length;
|
|
2775
|
+
const actionArgs = args.slice(0, expectedArgsCount);
|
|
2776
|
+
if (this._storeOptionsAsProperties) {
|
|
2777
|
+
actionArgs[expectedArgsCount] = this;
|
|
2778
|
+
} else {
|
|
2779
|
+
actionArgs[expectedArgsCount] = this.opts();
|
|
2780
|
+
}
|
|
2781
|
+
actionArgs.push(this);
|
|
2782
|
+
return fn.apply(this, actionArgs);
|
|
2783
|
+
};
|
|
2784
|
+
this._actionHandler = listener;
|
|
2785
|
+
return this;
|
|
2786
|
+
}
|
|
2787
|
+
/**
|
|
2788
|
+
* Factory routine to create a new unattached option.
|
|
2789
|
+
*
|
|
2790
|
+
* See .option() for creating an attached option, which uses this routine to
|
|
2791
|
+
* create the option. You can override createOption to return a custom option.
|
|
2792
|
+
*
|
|
2793
|
+
* @param {string} flags
|
|
2794
|
+
* @param {string} [description]
|
|
2795
|
+
* @return {Option} new option
|
|
2796
|
+
*/
|
|
2797
|
+
createOption(flags, description) {
|
|
2798
|
+
return new Option(flags, description);
|
|
2799
|
+
}
|
|
2800
|
+
/**
|
|
2801
|
+
* Wrap parseArgs to catch 'commander.invalidArgument'.
|
|
2802
|
+
*
|
|
2803
|
+
* @param {(Option | Argument)} target
|
|
2804
|
+
* @param {string} value
|
|
2805
|
+
* @param {*} previous
|
|
2806
|
+
* @param {string} invalidArgumentMessage
|
|
2807
|
+
* @private
|
|
2808
|
+
*/
|
|
2809
|
+
_callParseArg(target, value, previous, invalidArgumentMessage) {
|
|
2810
|
+
try {
|
|
2811
|
+
return target.parseArg(value, previous);
|
|
2812
|
+
} catch (err) {
|
|
2813
|
+
if (err.code === "commander.invalidArgument") {
|
|
2814
|
+
const message3 = `${invalidArgumentMessage} ${err.message}`;
|
|
2815
|
+
this.error(message3, { exitCode: err.exitCode, code: err.code });
|
|
2816
|
+
}
|
|
2817
|
+
throw err;
|
|
2818
|
+
}
|
|
2819
|
+
}
|
|
2820
|
+
/**
|
|
2821
|
+
* Check for option flag conflicts.
|
|
2822
|
+
* Register option if no conflicts found, or throw on conflict.
|
|
2823
|
+
*
|
|
2824
|
+
* @param {Option} option
|
|
2825
|
+
* @private
|
|
2826
|
+
*/
|
|
2827
|
+
_registerOption(option) {
|
|
2828
|
+
const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
|
|
2829
|
+
if (matchingOption) {
|
|
2830
|
+
const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
|
|
2831
|
+
throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
|
|
2832
|
+
- already used by option '${matchingOption.flags}'`);
|
|
2833
|
+
}
|
|
2834
|
+
this._initOptionGroup(option);
|
|
2835
|
+
this.options.push(option);
|
|
2836
|
+
}
|
|
2837
|
+
/**
|
|
2838
|
+
* Check for command name and alias conflicts with existing commands.
|
|
2839
|
+
* Register command if no conflicts found, or throw on conflict.
|
|
2840
|
+
*
|
|
2841
|
+
* @param {Command} command
|
|
2842
|
+
* @private
|
|
2843
|
+
*/
|
|
2844
|
+
_registerCommand(command) {
|
|
2845
|
+
const knownBy = (cmd) => {
|
|
2846
|
+
return [cmd.name()].concat(cmd.aliases());
|
|
2847
|
+
};
|
|
2848
|
+
const alreadyUsed = knownBy(command).find(
|
|
2849
|
+
(name2) => this._findCommand(name2)
|
|
2850
|
+
);
|
|
2851
|
+
if (alreadyUsed) {
|
|
2852
|
+
const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
|
|
2853
|
+
const newCmd = knownBy(command).join("|");
|
|
2854
|
+
throw new Error(
|
|
2855
|
+
`cannot add command '${newCmd}' as already have command '${existingCmd}'`
|
|
2856
|
+
);
|
|
2857
|
+
}
|
|
2858
|
+
this._initCommandGroup(command);
|
|
2859
|
+
this.commands.push(command);
|
|
2860
|
+
}
|
|
2861
|
+
/**
|
|
2862
|
+
* Add an option.
|
|
2863
|
+
*
|
|
2864
|
+
* @param {Option} option
|
|
2865
|
+
* @return {Command} `this` command for chaining
|
|
2866
|
+
*/
|
|
2867
|
+
addOption(option) {
|
|
2868
|
+
this._registerOption(option);
|
|
2869
|
+
const oname = option.name();
|
|
2870
|
+
const name2 = option.attributeName();
|
|
2871
|
+
if (option.defaultValue !== void 0) {
|
|
2872
|
+
this.setOptionValueWithSource(name2, option.defaultValue, "default");
|
|
2873
|
+
}
|
|
2874
|
+
const handleOptionValue = (val, invalidValueMessage, valueSource) => {
|
|
2875
|
+
if (val == null && option.presetArg !== void 0) {
|
|
2876
|
+
val = option.presetArg;
|
|
2877
|
+
}
|
|
2878
|
+
const oldValue = this.getOptionValue(name2);
|
|
2879
|
+
if (val !== null && option.parseArg) {
|
|
2880
|
+
val = this._callParseArg(option, val, oldValue, invalidValueMessage);
|
|
2881
|
+
} else if (val !== null && option.variadic) {
|
|
2882
|
+
val = option._collectValue(val, oldValue);
|
|
2883
|
+
}
|
|
2884
|
+
if (val == null) {
|
|
2885
|
+
if (option.negate) {
|
|
2886
|
+
val = false;
|
|
2887
|
+
} else if (option.isBoolean() || option.optional) {
|
|
2888
|
+
val = true;
|
|
2889
|
+
} else {
|
|
2890
|
+
val = "";
|
|
2891
|
+
}
|
|
2892
|
+
}
|
|
2893
|
+
this.setOptionValueWithSource(name2, val, valueSource);
|
|
2894
|
+
};
|
|
2895
|
+
this.on("option:" + oname, (val) => {
|
|
2896
|
+
const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
|
|
2897
|
+
handleOptionValue(val, invalidValueMessage, "cli");
|
|
2898
|
+
});
|
|
2899
|
+
if (option.envVar) {
|
|
2900
|
+
this.on("optionEnv:" + oname, (val) => {
|
|
2901
|
+
const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
|
|
2902
|
+
handleOptionValue(val, invalidValueMessage, "env");
|
|
2903
|
+
});
|
|
2904
|
+
}
|
|
2905
|
+
return this;
|
|
2906
|
+
}
|
|
2907
|
+
/**
|
|
2908
|
+
* Internal implementation shared by .option() and .requiredOption()
|
|
2909
|
+
*
|
|
2910
|
+
* @return {Command} `this` command for chaining
|
|
2911
|
+
* @private
|
|
2912
|
+
*/
|
|
2913
|
+
_optionEx(config, flags, description, fn, defaultValue) {
|
|
2914
|
+
if (typeof flags === "object" && flags instanceof Option) {
|
|
2915
|
+
throw new Error(
|
|
2916
|
+
"To add an Option object use addOption() instead of option() or requiredOption()"
|
|
2917
|
+
);
|
|
2918
|
+
}
|
|
2919
|
+
const option = this.createOption(flags, description);
|
|
2920
|
+
option.makeOptionMandatory(!!config.mandatory);
|
|
2921
|
+
if (typeof fn === "function") {
|
|
2922
|
+
option.default(defaultValue).argParser(fn);
|
|
2923
|
+
} else if (fn instanceof RegExp) {
|
|
2924
|
+
const regex = fn;
|
|
2925
|
+
fn = (val, def) => {
|
|
2926
|
+
const m = regex.exec(val);
|
|
2927
|
+
return m ? m[0] : def;
|
|
2928
|
+
};
|
|
2929
|
+
option.default(defaultValue).argParser(fn);
|
|
2930
|
+
} else {
|
|
2931
|
+
option.default(fn);
|
|
2932
|
+
}
|
|
2933
|
+
return this.addOption(option);
|
|
2934
|
+
}
|
|
2935
|
+
/**
|
|
2936
|
+
* Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
|
|
2937
|
+
*
|
|
2938
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
|
|
2939
|
+
* option-argument is indicated by `<>` and an optional option-argument by `[]`.
|
|
2940
|
+
*
|
|
2941
|
+
* See the README for more details, and see also addOption() and requiredOption().
|
|
2942
|
+
*
|
|
2943
|
+
* @example
|
|
2944
|
+
* program
|
|
2945
|
+
* .option('-p, --pepper', 'add pepper')
|
|
2946
|
+
* .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
|
|
2947
|
+
* .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
|
|
2948
|
+
* .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
|
|
2949
|
+
*
|
|
2950
|
+
* @param {string} flags
|
|
2951
|
+
* @param {string} [description]
|
|
2952
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
2953
|
+
* @param {*} [defaultValue]
|
|
2954
|
+
* @return {Command} `this` command for chaining
|
|
2955
|
+
*/
|
|
2956
|
+
option(flags, description, parseArg, defaultValue) {
|
|
2957
|
+
return this._optionEx({}, flags, description, parseArg, defaultValue);
|
|
2958
|
+
}
|
|
2959
|
+
/**
|
|
2960
|
+
* Add a required option which must have a value after parsing. This usually means
|
|
2961
|
+
* the option must be specified on the command line. (Otherwise the same as .option().)
|
|
2962
|
+
*
|
|
2963
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
|
|
2964
|
+
*
|
|
2965
|
+
* @param {string} flags
|
|
2966
|
+
* @param {string} [description]
|
|
2967
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
2968
|
+
* @param {*} [defaultValue]
|
|
2969
|
+
* @return {Command} `this` command for chaining
|
|
2970
|
+
*/
|
|
2971
|
+
requiredOption(flags, description, parseArg, defaultValue) {
|
|
2972
|
+
return this._optionEx(
|
|
2973
|
+
{ mandatory: true },
|
|
2974
|
+
flags,
|
|
2975
|
+
description,
|
|
2976
|
+
parseArg,
|
|
2977
|
+
defaultValue
|
|
2978
|
+
);
|
|
2979
|
+
}
|
|
2980
|
+
/**
|
|
2981
|
+
* Alter parsing of short flags with optional values.
|
|
2982
|
+
*
|
|
2983
|
+
* @example
|
|
2984
|
+
* // for `.option('-f,--flag [value]'):
|
|
2985
|
+
* program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
|
|
2986
|
+
* program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
|
|
2987
|
+
*
|
|
2988
|
+
* @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
|
|
2989
|
+
* @return {Command} `this` command for chaining
|
|
2990
|
+
*/
|
|
2991
|
+
combineFlagAndOptionalValue(combine = true) {
|
|
2992
|
+
this._combineFlagAndOptionalValue = !!combine;
|
|
2993
|
+
return this;
|
|
2994
|
+
}
|
|
2995
|
+
/**
|
|
2996
|
+
* Allow unknown options on the command line.
|
|
2997
|
+
*
|
|
2998
|
+
* @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
|
|
2999
|
+
* @return {Command} `this` command for chaining
|
|
3000
|
+
*/
|
|
3001
|
+
allowUnknownOption(allowUnknown = true) {
|
|
3002
|
+
this._allowUnknownOption = !!allowUnknown;
|
|
3003
|
+
return this;
|
|
3004
|
+
}
|
|
3005
|
+
/**
|
|
3006
|
+
* Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
|
|
3007
|
+
*
|
|
3008
|
+
* @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
|
|
3009
|
+
* @return {Command} `this` command for chaining
|
|
3010
|
+
*/
|
|
3011
|
+
allowExcessArguments(allowExcess = true) {
|
|
3012
|
+
this._allowExcessArguments = !!allowExcess;
|
|
3013
|
+
return this;
|
|
3014
|
+
}
|
|
3015
|
+
/**
|
|
3016
|
+
* Enable positional options. Positional means global options are specified before subcommands which lets
|
|
3017
|
+
* subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
|
|
3018
|
+
* The default behaviour is non-positional and global options may appear anywhere on the command line.
|
|
3019
|
+
*
|
|
3020
|
+
* @param {boolean} [positional]
|
|
3021
|
+
* @return {Command} `this` command for chaining
|
|
3022
|
+
*/
|
|
3023
|
+
enablePositionalOptions(positional = true) {
|
|
3024
|
+
this._enablePositionalOptions = !!positional;
|
|
3025
|
+
return this;
|
|
3026
|
+
}
|
|
3027
|
+
/**
|
|
3028
|
+
* Pass through options that come after command-arguments rather than treat them as command-options,
|
|
3029
|
+
* so actual command-options come before command-arguments. Turning this on for a subcommand requires
|
|
3030
|
+
* positional options to have been enabled on the program (parent commands).
|
|
3031
|
+
* The default behaviour is non-positional and options may appear before or after command-arguments.
|
|
3032
|
+
*
|
|
3033
|
+
* @param {boolean} [passThrough] for unknown options.
|
|
3034
|
+
* @return {Command} `this` command for chaining
|
|
3035
|
+
*/
|
|
3036
|
+
passThroughOptions(passThrough = true) {
|
|
3037
|
+
this._passThroughOptions = !!passThrough;
|
|
3038
|
+
this._checkForBrokenPassThrough();
|
|
3039
|
+
return this;
|
|
3040
|
+
}
|
|
3041
|
+
/**
|
|
3042
|
+
* @private
|
|
3043
|
+
*/
|
|
3044
|
+
_checkForBrokenPassThrough() {
|
|
3045
|
+
if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
|
|
3046
|
+
throw new Error(
|
|
3047
|
+
`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
|
|
3048
|
+
);
|
|
3049
|
+
}
|
|
3050
|
+
}
|
|
3051
|
+
/**
|
|
3052
|
+
* Whether to store option values as properties on command object,
|
|
3053
|
+
* or store separately (specify false). In both cases the option values can be accessed using .opts().
|
|
3054
|
+
*
|
|
3055
|
+
* @param {boolean} [storeAsProperties=true]
|
|
3056
|
+
* @return {Command} `this` command for chaining
|
|
3057
|
+
*/
|
|
3058
|
+
storeOptionsAsProperties(storeAsProperties = true) {
|
|
3059
|
+
if (this.options.length) {
|
|
3060
|
+
throw new Error("call .storeOptionsAsProperties() before adding options");
|
|
3061
|
+
}
|
|
3062
|
+
if (Object.keys(this._optionValues).length) {
|
|
3063
|
+
throw new Error(
|
|
3064
|
+
"call .storeOptionsAsProperties() before setting option values"
|
|
3065
|
+
);
|
|
3066
|
+
}
|
|
3067
|
+
this._storeOptionsAsProperties = !!storeAsProperties;
|
|
3068
|
+
return this;
|
|
3069
|
+
}
|
|
3070
|
+
/**
|
|
3071
|
+
* Retrieve option value.
|
|
3072
|
+
*
|
|
3073
|
+
* @param {string} key
|
|
3074
|
+
* @return {object} value
|
|
3075
|
+
*/
|
|
3076
|
+
getOptionValue(key) {
|
|
3077
|
+
if (this._storeOptionsAsProperties) {
|
|
3078
|
+
return this[key];
|
|
3079
|
+
}
|
|
3080
|
+
return this._optionValues[key];
|
|
3081
|
+
}
|
|
3082
|
+
/**
|
|
3083
|
+
* Store option value.
|
|
3084
|
+
*
|
|
3085
|
+
* @param {string} key
|
|
3086
|
+
* @param {object} value
|
|
3087
|
+
* @return {Command} `this` command for chaining
|
|
3088
|
+
*/
|
|
3089
|
+
setOptionValue(key, value) {
|
|
3090
|
+
return this.setOptionValueWithSource(key, value, void 0);
|
|
3091
|
+
}
|
|
3092
|
+
/**
|
|
3093
|
+
* Store option value and where the value came from.
|
|
3094
|
+
*
|
|
3095
|
+
* @param {string} key
|
|
3096
|
+
* @param {object} value
|
|
3097
|
+
* @param {string} source - expected values are default/config/env/cli/implied
|
|
3098
|
+
* @return {Command} `this` command for chaining
|
|
3099
|
+
*/
|
|
3100
|
+
setOptionValueWithSource(key, value, source) {
|
|
3101
|
+
if (this._storeOptionsAsProperties) {
|
|
3102
|
+
this[key] = value;
|
|
3103
|
+
} else {
|
|
3104
|
+
this._optionValues[key] = value;
|
|
3105
|
+
}
|
|
3106
|
+
this._optionValueSources[key] = source;
|
|
3107
|
+
return this;
|
|
3108
|
+
}
|
|
3109
|
+
/**
|
|
3110
|
+
* Get source of option value.
|
|
3111
|
+
* Expected values are default | config | env | cli | implied
|
|
3112
|
+
*
|
|
3113
|
+
* @param {string} key
|
|
3114
|
+
* @return {string}
|
|
3115
|
+
*/
|
|
3116
|
+
getOptionValueSource(key) {
|
|
3117
|
+
return this._optionValueSources[key];
|
|
3118
|
+
}
|
|
3119
|
+
/**
|
|
3120
|
+
* Get source of option value. See also .optsWithGlobals().
|
|
3121
|
+
* Expected values are default | config | env | cli | implied
|
|
3122
|
+
*
|
|
3123
|
+
* @param {string} key
|
|
3124
|
+
* @return {string}
|
|
3125
|
+
*/
|
|
3126
|
+
getOptionValueSourceWithGlobals(key) {
|
|
3127
|
+
let source;
|
|
3128
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
3129
|
+
if (cmd.getOptionValueSource(key) !== void 0) {
|
|
3130
|
+
source = cmd.getOptionValueSource(key);
|
|
3131
|
+
}
|
|
3132
|
+
});
|
|
3133
|
+
return source;
|
|
3134
|
+
}
|
|
3135
|
+
/**
|
|
3136
|
+
* Get user arguments from implied or explicit arguments.
|
|
3137
|
+
* Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
|
|
3138
|
+
*
|
|
3139
|
+
* @private
|
|
3140
|
+
*/
|
|
3141
|
+
_prepareUserArgs(argv, parseOptions) {
|
|
3142
|
+
if (argv !== void 0 && !Array.isArray(argv)) {
|
|
3143
|
+
throw new Error("first parameter to parse must be array or undefined");
|
|
3144
|
+
}
|
|
3145
|
+
parseOptions = parseOptions || {};
|
|
3146
|
+
if (argv === void 0 && parseOptions.from === void 0) {
|
|
3147
|
+
if (process2.versions?.electron) {
|
|
3148
|
+
parseOptions.from = "electron";
|
|
3149
|
+
}
|
|
3150
|
+
const execArgv = process2.execArgv ?? [];
|
|
3151
|
+
if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
|
|
3152
|
+
parseOptions.from = "eval";
|
|
3153
|
+
}
|
|
3154
|
+
}
|
|
3155
|
+
if (argv === void 0) {
|
|
3156
|
+
argv = process2.argv;
|
|
3157
|
+
}
|
|
3158
|
+
this.rawArgs = argv.slice();
|
|
3159
|
+
let userArgs;
|
|
3160
|
+
switch (parseOptions.from) {
|
|
3161
|
+
case void 0:
|
|
3162
|
+
case "node":
|
|
3163
|
+
this._scriptPath = argv[1];
|
|
3164
|
+
userArgs = argv.slice(2);
|
|
3165
|
+
break;
|
|
3166
|
+
case "electron":
|
|
3167
|
+
if (process2.defaultApp) {
|
|
3168
|
+
this._scriptPath = argv[1];
|
|
3169
|
+
userArgs = argv.slice(2);
|
|
3170
|
+
} else {
|
|
3171
|
+
userArgs = argv.slice(1);
|
|
3172
|
+
}
|
|
3173
|
+
break;
|
|
3174
|
+
case "user":
|
|
3175
|
+
userArgs = argv.slice(0);
|
|
3176
|
+
break;
|
|
3177
|
+
case "eval":
|
|
3178
|
+
userArgs = argv.slice(1);
|
|
3179
|
+
break;
|
|
3180
|
+
default:
|
|
3181
|
+
throw new Error(
|
|
3182
|
+
`unexpected parse option { from: '${parseOptions.from}' }`
|
|
3183
|
+
);
|
|
3184
|
+
}
|
|
3185
|
+
if (!this._name && this._scriptPath)
|
|
3186
|
+
this.nameFromFilename(this._scriptPath);
|
|
3187
|
+
this._name = this._name || "program";
|
|
3188
|
+
return userArgs;
|
|
3189
|
+
}
|
|
3190
|
+
/**
|
|
3191
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
3192
|
+
*
|
|
3193
|
+
* Use parseAsync instead of parse if any of your action handlers are async.
|
|
3194
|
+
*
|
|
3195
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
3196
|
+
*
|
|
3197
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
3198
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
3199
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
3200
|
+
* - `'user'`: just user arguments
|
|
3201
|
+
*
|
|
3202
|
+
* @example
|
|
3203
|
+
* program.parse(); // parse process.argv and auto-detect electron and special node flags
|
|
3204
|
+
* program.parse(process.argv); // assume argv[0] is app and argv[1] is script
|
|
3205
|
+
* program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
3206
|
+
*
|
|
3207
|
+
* @param {string[]} [argv] - optional, defaults to process.argv
|
|
3208
|
+
* @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
|
|
3209
|
+
* @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
|
|
3210
|
+
* @return {Command} `this` command for chaining
|
|
3211
|
+
*/
|
|
3212
|
+
parse(argv, parseOptions) {
|
|
3213
|
+
this._prepareForParse();
|
|
3214
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
3215
|
+
this._parseCommand([], userArgs);
|
|
3216
|
+
return this;
|
|
3217
|
+
}
|
|
3218
|
+
/**
|
|
3219
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
3220
|
+
*
|
|
3221
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
3222
|
+
*
|
|
3223
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
3224
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
3225
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
3226
|
+
* - `'user'`: just user arguments
|
|
3227
|
+
*
|
|
3228
|
+
* @example
|
|
3229
|
+
* await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
|
|
3230
|
+
* await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
|
|
3231
|
+
* await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
3232
|
+
*
|
|
3233
|
+
* @param {string[]} [argv]
|
|
3234
|
+
* @param {object} [parseOptions]
|
|
3235
|
+
* @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
|
|
3236
|
+
* @return {Promise}
|
|
3237
|
+
*/
|
|
3238
|
+
async parseAsync(argv, parseOptions) {
|
|
3239
|
+
this._prepareForParse();
|
|
3240
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
3241
|
+
await this._parseCommand([], userArgs);
|
|
3242
|
+
return this;
|
|
3243
|
+
}
|
|
3244
|
+
_prepareForParse() {
|
|
3245
|
+
if (this._savedState === null) {
|
|
3246
|
+
this.options.filter(
|
|
3247
|
+
(option) => option.negate && option.defaultValue === void 0 && this.getOptionValue(option.attributeName()) === void 0
|
|
3248
|
+
).forEach((option) => {
|
|
3249
|
+
const positiveLongFlag = option.long.replace(/^--no-/, "--");
|
|
3250
|
+
if (!this._findOption(positiveLongFlag)) {
|
|
3251
|
+
this.setOptionValueWithSource(
|
|
3252
|
+
option.attributeName(),
|
|
3253
|
+
true,
|
|
3254
|
+
"default"
|
|
3255
|
+
);
|
|
3256
|
+
}
|
|
3257
|
+
});
|
|
3258
|
+
this.saveStateBeforeParse();
|
|
3259
|
+
} else {
|
|
3260
|
+
this.restoreStateBeforeParse();
|
|
3261
|
+
}
|
|
3262
|
+
}
|
|
3263
|
+
/**
|
|
3264
|
+
* Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
|
|
3265
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
3266
|
+
*
|
|
3267
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state saved.
|
|
3268
|
+
*/
|
|
3269
|
+
saveStateBeforeParse() {
|
|
3270
|
+
this._savedState = {
|
|
3271
|
+
// name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
|
|
3272
|
+
_name: this._name,
|
|
3273
|
+
// option values before parse have default values (including false for negated options)
|
|
3274
|
+
// shallow clones
|
|
3275
|
+
_optionValues: { ...this._optionValues },
|
|
3276
|
+
_optionValueSources: { ...this._optionValueSources }
|
|
3277
|
+
};
|
|
3278
|
+
}
|
|
3279
|
+
/**
|
|
3280
|
+
* Restore state before parse for calls after the first.
|
|
3281
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
3282
|
+
*
|
|
3283
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state restored.
|
|
3284
|
+
*/
|
|
3285
|
+
restoreStateBeforeParse() {
|
|
3286
|
+
if (this._storeOptionsAsProperties)
|
|
3287
|
+
throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
3288
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);
|
|
3289
|
+
this._name = this._savedState._name;
|
|
3290
|
+
this._scriptPath = null;
|
|
3291
|
+
this.rawArgs = [];
|
|
3292
|
+
this._optionValues = { ...this._savedState._optionValues };
|
|
3293
|
+
this._optionValueSources = { ...this._savedState._optionValueSources };
|
|
3294
|
+
this.args = [];
|
|
3295
|
+
this.processedArgs = [];
|
|
3296
|
+
}
|
|
3297
|
+
/**
|
|
3298
|
+
* Throw if expected executable is missing. Add lots of help for author.
|
|
3299
|
+
*
|
|
3300
|
+
* @param {string} executableFile
|
|
3301
|
+
* @param {string} executableDir
|
|
3302
|
+
* @param {string} subcommandName
|
|
3303
|
+
*/
|
|
3304
|
+
_checkForMissingExecutable(executableFile, executableDir, subcommandName) {
|
|
3305
|
+
if (fs.existsSync(executableFile)) return;
|
|
3306
|
+
const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
|
|
3307
|
+
const executableMissing = `'${executableFile}' does not exist
|
|
3308
|
+
- if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
3309
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
3310
|
+
- ${executableDirMessage}`;
|
|
3311
|
+
throw new Error(executableMissing);
|
|
3312
|
+
}
|
|
3313
|
+
/**
|
|
3314
|
+
* Execute a sub-command executable.
|
|
3315
|
+
*
|
|
3316
|
+
* @private
|
|
3317
|
+
*/
|
|
3318
|
+
_executeSubCommand(subcommand, args) {
|
|
3319
|
+
args = args.slice();
|
|
3320
|
+
const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
|
|
3321
|
+
function findFile(baseDir, baseName) {
|
|
3322
|
+
const localBin = path.resolve(baseDir, baseName);
|
|
3323
|
+
if (fs.existsSync(localBin)) return localBin;
|
|
3324
|
+
if (sourceExt.includes(path.extname(baseName))) return void 0;
|
|
3325
|
+
const foundExt = sourceExt.find(
|
|
3326
|
+
(ext) => fs.existsSync(`${localBin}${ext}`)
|
|
3327
|
+
);
|
|
3328
|
+
if (foundExt) return `${localBin}${foundExt}`;
|
|
3329
|
+
return void 0;
|
|
3330
|
+
}
|
|
3331
|
+
this._checkForMissingMandatoryOptions();
|
|
3332
|
+
this._checkForConflictingOptions();
|
|
3333
|
+
let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
|
|
3334
|
+
let executableDir = this._executableDir || "";
|
|
3335
|
+
if (this._scriptPath) {
|
|
3336
|
+
let resolvedScriptPath;
|
|
3337
|
+
try {
|
|
3338
|
+
resolvedScriptPath = fs.realpathSync(this._scriptPath);
|
|
3339
|
+
} catch {
|
|
3340
|
+
resolvedScriptPath = this._scriptPath;
|
|
3341
|
+
}
|
|
3342
|
+
executableDir = path.resolve(
|
|
3343
|
+
path.dirname(resolvedScriptPath),
|
|
3344
|
+
executableDir
|
|
3345
|
+
);
|
|
3346
|
+
}
|
|
3347
|
+
if (executableDir) {
|
|
3348
|
+
let localFile = findFile(executableDir, executableFile);
|
|
3349
|
+
if (!localFile && !subcommand._executableFile && this._scriptPath) {
|
|
3350
|
+
const legacyName = path.basename(
|
|
3351
|
+
this._scriptPath,
|
|
3352
|
+
path.extname(this._scriptPath)
|
|
3353
|
+
);
|
|
3354
|
+
if (legacyName !== this._name) {
|
|
3355
|
+
localFile = findFile(
|
|
3356
|
+
executableDir,
|
|
3357
|
+
`${legacyName}-${subcommand._name}`
|
|
3358
|
+
);
|
|
3359
|
+
}
|
|
3360
|
+
}
|
|
3361
|
+
executableFile = localFile || executableFile;
|
|
3362
|
+
}
|
|
3363
|
+
const launchWithNode = sourceExt.includes(path.extname(executableFile));
|
|
3364
|
+
let proc;
|
|
3365
|
+
if (process2.platform !== "win32") {
|
|
3366
|
+
if (launchWithNode) {
|
|
3367
|
+
args.unshift(executableFile);
|
|
3368
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
3369
|
+
proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
|
|
3370
|
+
} else {
|
|
3371
|
+
proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
|
|
3372
|
+
}
|
|
3373
|
+
} else {
|
|
3374
|
+
this._checkForMissingExecutable(
|
|
3375
|
+
executableFile,
|
|
3376
|
+
executableDir,
|
|
3377
|
+
subcommand._name
|
|
3378
|
+
);
|
|
3379
|
+
args.unshift(executableFile);
|
|
3380
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
3381
|
+
proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
|
|
3382
|
+
}
|
|
3383
|
+
if (!proc.killed) {
|
|
3384
|
+
const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
|
|
3385
|
+
signals.forEach((signal) => {
|
|
3386
|
+
process2.on(signal, () => {
|
|
3387
|
+
if (proc.killed === false && proc.exitCode === null) {
|
|
3388
|
+
proc.kill(signal);
|
|
3389
|
+
}
|
|
3390
|
+
});
|
|
3391
|
+
});
|
|
3392
|
+
}
|
|
3393
|
+
const exitCallback = this._exitCallback;
|
|
3394
|
+
proc.on("close", (code) => {
|
|
3395
|
+
code = code ?? 1;
|
|
3396
|
+
if (!exitCallback) {
|
|
3397
|
+
process2.exit(code);
|
|
3398
|
+
} else {
|
|
3399
|
+
exitCallback(
|
|
3400
|
+
new CommanderError(
|
|
3401
|
+
code,
|
|
3402
|
+
"commander.executeSubCommandAsync",
|
|
3403
|
+
"(close)"
|
|
3404
|
+
)
|
|
3405
|
+
);
|
|
3406
|
+
}
|
|
3407
|
+
});
|
|
3408
|
+
proc.on("error", (err) => {
|
|
3409
|
+
if (err.code === "ENOENT") {
|
|
3410
|
+
this._checkForMissingExecutable(
|
|
3411
|
+
executableFile,
|
|
3412
|
+
executableDir,
|
|
3413
|
+
subcommand._name
|
|
3414
|
+
);
|
|
3415
|
+
} else if (err.code === "EACCES") {
|
|
3416
|
+
throw new Error(`'${executableFile}' not executable`);
|
|
3417
|
+
}
|
|
3418
|
+
if (!exitCallback) {
|
|
3419
|
+
process2.exit(1);
|
|
3420
|
+
} else {
|
|
3421
|
+
const wrappedError = new CommanderError(
|
|
3422
|
+
1,
|
|
3423
|
+
"commander.executeSubCommandAsync",
|
|
3424
|
+
"(error)"
|
|
3425
|
+
);
|
|
3426
|
+
wrappedError.nestedError = err;
|
|
3427
|
+
exitCallback(wrappedError);
|
|
3428
|
+
}
|
|
3429
|
+
});
|
|
3430
|
+
this.runningCommand = proc;
|
|
3431
|
+
}
|
|
3432
|
+
/**
|
|
3433
|
+
* @private
|
|
3434
|
+
*/
|
|
3435
|
+
_dispatchSubcommand(commandName, operands, unknown) {
|
|
3436
|
+
const subCommand = this._findCommand(commandName);
|
|
3437
|
+
if (!subCommand) this.help({ error: true });
|
|
3438
|
+
subCommand._prepareForParse();
|
|
3439
|
+
let promiseChain;
|
|
3440
|
+
promiseChain = this._chainOrCallSubCommandHook(
|
|
3441
|
+
promiseChain,
|
|
3442
|
+
subCommand,
|
|
3443
|
+
"preSubcommand"
|
|
3444
|
+
);
|
|
3445
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
3446
|
+
if (subCommand._executableHandler) {
|
|
3447
|
+
this._executeSubCommand(subCommand, operands.concat(unknown));
|
|
3448
|
+
} else {
|
|
3449
|
+
return subCommand._parseCommand(operands, unknown);
|
|
3450
|
+
}
|
|
3451
|
+
});
|
|
3452
|
+
return promiseChain;
|
|
3453
|
+
}
|
|
3454
|
+
/**
|
|
3455
|
+
* Invoke help directly if possible, or dispatch if necessary.
|
|
3456
|
+
* e.g. help foo
|
|
3457
|
+
*
|
|
3458
|
+
* @private
|
|
3459
|
+
*/
|
|
3460
|
+
_dispatchHelpCommand(subcommandName) {
|
|
3461
|
+
if (!subcommandName) {
|
|
3462
|
+
this.help();
|
|
3463
|
+
}
|
|
3464
|
+
const subCommand = this._findCommand(subcommandName);
|
|
3465
|
+
if (subCommand && !subCommand._executableHandler) {
|
|
3466
|
+
subCommand.help();
|
|
3467
|
+
}
|
|
3468
|
+
return this._dispatchSubcommand(
|
|
3469
|
+
subcommandName,
|
|
3470
|
+
[],
|
|
3471
|
+
[this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
|
|
3472
|
+
);
|
|
3473
|
+
}
|
|
3474
|
+
/**
|
|
3475
|
+
* Check this.args against expected this.registeredArguments.
|
|
3476
|
+
*
|
|
3477
|
+
* @private
|
|
3478
|
+
*/
|
|
3479
|
+
_checkNumberOfArguments() {
|
|
3480
|
+
this.registeredArguments.forEach((arg, i) => {
|
|
3481
|
+
if (arg.required && this.args[i] == null) {
|
|
3482
|
+
this.missingArgument(arg.name());
|
|
3483
|
+
}
|
|
3484
|
+
});
|
|
3485
|
+
if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
|
|
3486
|
+
return;
|
|
3487
|
+
}
|
|
3488
|
+
if (this.args.length > this.registeredArguments.length) {
|
|
3489
|
+
this._excessArguments(this.args);
|
|
3490
|
+
}
|
|
3491
|
+
}
|
|
3492
|
+
/**
|
|
3493
|
+
* Process this.args using this.registeredArguments and save as this.processedArgs!
|
|
3494
|
+
*
|
|
3495
|
+
* @private
|
|
3496
|
+
*/
|
|
3497
|
+
_processArguments() {
|
|
3498
|
+
const myParseArg = (argument, value, previous) => {
|
|
3499
|
+
let parsedValue = value;
|
|
3500
|
+
if (value !== null && argument.parseArg) {
|
|
3501
|
+
const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
|
|
3502
|
+
parsedValue = this._callParseArg(
|
|
3503
|
+
argument,
|
|
3504
|
+
value,
|
|
3505
|
+
previous,
|
|
3506
|
+
invalidValueMessage
|
|
3507
|
+
);
|
|
3508
|
+
}
|
|
3509
|
+
return parsedValue;
|
|
3510
|
+
};
|
|
3511
|
+
this._checkNumberOfArguments();
|
|
3512
|
+
const processedArgs = [];
|
|
3513
|
+
this.registeredArguments.forEach((declaredArg, index) => {
|
|
3514
|
+
let value = declaredArg.defaultValue;
|
|
3515
|
+
if (declaredArg.variadic) {
|
|
3516
|
+
if (index < this.args.length) {
|
|
3517
|
+
value = this.args.slice(index);
|
|
3518
|
+
if (declaredArg.parseArg) {
|
|
3519
|
+
value = value.reduce((processed, v) => {
|
|
3520
|
+
return myParseArg(declaredArg, v, processed);
|
|
3521
|
+
}, declaredArg.defaultValue);
|
|
3522
|
+
}
|
|
3523
|
+
} else if (value === void 0) {
|
|
3524
|
+
value = [];
|
|
3525
|
+
}
|
|
3526
|
+
} else if (index < this.args.length) {
|
|
3527
|
+
value = this.args[index];
|
|
3528
|
+
if (declaredArg.parseArg) {
|
|
3529
|
+
value = myParseArg(declaredArg, value, declaredArg.defaultValue);
|
|
3530
|
+
}
|
|
3531
|
+
}
|
|
3532
|
+
processedArgs[index] = value;
|
|
3533
|
+
});
|
|
3534
|
+
this.processedArgs = processedArgs;
|
|
3535
|
+
}
|
|
3536
|
+
/**
|
|
3537
|
+
* Once we have a promise we chain, but call synchronously until then.
|
|
3538
|
+
*
|
|
3539
|
+
* @param {(Promise|undefined)} promise
|
|
3540
|
+
* @param {Function} fn
|
|
3541
|
+
* @return {(Promise|undefined)}
|
|
3542
|
+
* @private
|
|
3543
|
+
*/
|
|
3544
|
+
_chainOrCall(promise, fn) {
|
|
3545
|
+
if (promise?.then && typeof promise.then === "function") {
|
|
3546
|
+
return promise.then(() => fn());
|
|
3547
|
+
}
|
|
3548
|
+
return fn();
|
|
3549
|
+
}
|
|
3550
|
+
/**
|
|
3551
|
+
*
|
|
3552
|
+
* @param {(Promise|undefined)} promise
|
|
3553
|
+
* @param {string} event
|
|
3554
|
+
* @return {(Promise|undefined)}
|
|
3555
|
+
* @private
|
|
3556
|
+
*/
|
|
3557
|
+
_chainOrCallHooks(promise, event) {
|
|
3558
|
+
let result = promise;
|
|
3559
|
+
const hooks = [];
|
|
3560
|
+
this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
|
|
3561
|
+
hookedCommand._lifeCycleHooks[event].forEach((callback) => {
|
|
3562
|
+
hooks.push({ hookedCommand, callback });
|
|
3563
|
+
});
|
|
3564
|
+
});
|
|
3565
|
+
if (event === "postAction") {
|
|
3566
|
+
hooks.reverse();
|
|
3567
|
+
}
|
|
3568
|
+
hooks.forEach((hookDetail) => {
|
|
3569
|
+
result = this._chainOrCall(result, () => {
|
|
3570
|
+
return hookDetail.callback(hookDetail.hookedCommand, this);
|
|
3571
|
+
});
|
|
3572
|
+
});
|
|
3573
|
+
return result;
|
|
3574
|
+
}
|
|
3575
|
+
/**
|
|
3576
|
+
*
|
|
3577
|
+
* @param {(Promise|undefined)} promise
|
|
3578
|
+
* @param {Command} subCommand
|
|
3579
|
+
* @param {string} event
|
|
3580
|
+
* @return {(Promise|undefined)}
|
|
3581
|
+
* @private
|
|
3582
|
+
*/
|
|
3583
|
+
_chainOrCallSubCommandHook(promise, subCommand, event) {
|
|
3584
|
+
let result = promise;
|
|
3585
|
+
if (this._lifeCycleHooks[event] !== void 0) {
|
|
3586
|
+
this._lifeCycleHooks[event].forEach((hook) => {
|
|
3587
|
+
result = this._chainOrCall(result, () => {
|
|
3588
|
+
return hook(this, subCommand);
|
|
3589
|
+
});
|
|
3590
|
+
});
|
|
3591
|
+
}
|
|
3592
|
+
return result;
|
|
3593
|
+
}
|
|
3594
|
+
/**
|
|
3595
|
+
* Process arguments in context of this command.
|
|
3596
|
+
* Returns action result, in case it is a promise.
|
|
3597
|
+
*
|
|
3598
|
+
* @private
|
|
3599
|
+
*/
|
|
3600
|
+
_parseCommand(operands, unknown) {
|
|
3601
|
+
const parsed = this.parseOptions(unknown);
|
|
3602
|
+
this._parseOptionsEnv();
|
|
3603
|
+
this._parseOptionsImplied();
|
|
3604
|
+
operands = operands.concat(parsed.operands);
|
|
3605
|
+
unknown = parsed.unknown;
|
|
3606
|
+
this.args = operands.concat(unknown);
|
|
3607
|
+
if (operands && this._findCommand(operands[0])) {
|
|
3608
|
+
return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
|
|
3609
|
+
}
|
|
3610
|
+
if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
|
|
3611
|
+
return this._dispatchHelpCommand(operands[1]);
|
|
3612
|
+
}
|
|
3613
|
+
if (this._defaultCommandName) {
|
|
3614
|
+
this._outputHelpIfRequested(unknown);
|
|
3615
|
+
return this._dispatchSubcommand(
|
|
3616
|
+
this._defaultCommandName,
|
|
3617
|
+
operands,
|
|
3618
|
+
unknown
|
|
3619
|
+
);
|
|
3620
|
+
}
|
|
3621
|
+
if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
|
|
3622
|
+
this.help({ error: true });
|
|
3623
|
+
}
|
|
3624
|
+
this._outputHelpIfRequested(parsed.unknown);
|
|
3625
|
+
this._checkForMissingMandatoryOptions();
|
|
3626
|
+
this._checkForConflictingOptions();
|
|
3627
|
+
const checkForUnknownOptions = () => {
|
|
3628
|
+
if (parsed.unknown.length > 0) {
|
|
3629
|
+
this.unknownOption(parsed.unknown[0]);
|
|
3630
|
+
}
|
|
3631
|
+
};
|
|
3632
|
+
const commandEvent = `command:${this.name()}`;
|
|
3633
|
+
if (this._actionHandler) {
|
|
3634
|
+
checkForUnknownOptions();
|
|
3635
|
+
this._processArguments();
|
|
3636
|
+
let promiseChain;
|
|
3637
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
|
|
3638
|
+
promiseChain = this._chainOrCall(
|
|
3639
|
+
promiseChain,
|
|
3640
|
+
() => this._actionHandler(this.processedArgs)
|
|
3641
|
+
);
|
|
3642
|
+
if (this.parent) {
|
|
3643
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
3644
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
3645
|
+
});
|
|
3646
|
+
}
|
|
3647
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
|
|
3648
|
+
return promiseChain;
|
|
3649
|
+
}
|
|
3650
|
+
if (this.parent?.listenerCount(commandEvent)) {
|
|
3651
|
+
checkForUnknownOptions();
|
|
3652
|
+
this._processArguments();
|
|
3653
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
3654
|
+
} else if (operands.length) {
|
|
3655
|
+
if (this._findCommand("*")) {
|
|
3656
|
+
return this._dispatchSubcommand("*", operands, unknown);
|
|
3657
|
+
}
|
|
3658
|
+
if (this.listenerCount("command:*")) {
|
|
3659
|
+
this.emit("command:*", operands, unknown);
|
|
3660
|
+
} else if (this.commands.length) {
|
|
3661
|
+
this.unknownCommand();
|
|
3662
|
+
} else {
|
|
3663
|
+
checkForUnknownOptions();
|
|
3664
|
+
this._processArguments();
|
|
3665
|
+
}
|
|
3666
|
+
} else if (this.commands.length) {
|
|
3667
|
+
checkForUnknownOptions();
|
|
3668
|
+
this.help({ error: true });
|
|
3669
|
+
} else {
|
|
3670
|
+
checkForUnknownOptions();
|
|
3671
|
+
this._processArguments();
|
|
3672
|
+
}
|
|
3673
|
+
}
|
|
3674
|
+
/**
|
|
3675
|
+
* Find matching command.
|
|
3676
|
+
*
|
|
3677
|
+
* @private
|
|
3678
|
+
* @return {Command | undefined}
|
|
3679
|
+
*/
|
|
3680
|
+
_findCommand(name2) {
|
|
3681
|
+
if (!name2) return void 0;
|
|
3682
|
+
return this.commands.find(
|
|
3683
|
+
(cmd) => cmd._name === name2 || cmd._aliases.includes(name2)
|
|
3684
|
+
);
|
|
3685
|
+
}
|
|
3686
|
+
/**
|
|
3687
|
+
* Return an option matching `arg` if any.
|
|
3688
|
+
*
|
|
3689
|
+
* @param {string} arg
|
|
3690
|
+
* @return {Option}
|
|
3691
|
+
* @package
|
|
3692
|
+
*/
|
|
3693
|
+
_findOption(arg) {
|
|
3694
|
+
return this.options.find((option) => option.is(arg));
|
|
3695
|
+
}
|
|
3696
|
+
/**
|
|
3697
|
+
* Display an error message if a mandatory option does not have a value.
|
|
3698
|
+
* Called after checking for help flags in leaf subcommand.
|
|
3699
|
+
*
|
|
3700
|
+
* @private
|
|
3701
|
+
*/
|
|
3702
|
+
_checkForMissingMandatoryOptions() {
|
|
3703
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
3704
|
+
cmd.options.forEach((anOption) => {
|
|
3705
|
+
if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
|
|
3706
|
+
cmd.missingMandatoryOptionValue(anOption);
|
|
3707
|
+
}
|
|
3708
|
+
});
|
|
3709
|
+
});
|
|
3710
|
+
}
|
|
3711
|
+
/**
|
|
3712
|
+
* Display an error message if conflicting options are used together in this.
|
|
3713
|
+
*
|
|
3714
|
+
* @private
|
|
3715
|
+
*/
|
|
3716
|
+
_checkForConflictingLocalOptions() {
|
|
3717
|
+
const definedNonDefaultOptions = this.options.filter((option) => {
|
|
3718
|
+
const optionKey = option.attributeName();
|
|
3719
|
+
if (this.getOptionValue(optionKey) === void 0) {
|
|
3720
|
+
return false;
|
|
3721
|
+
}
|
|
3722
|
+
return this.getOptionValueSource(optionKey) !== "default";
|
|
3723
|
+
});
|
|
3724
|
+
const optionsWithConflicting = definedNonDefaultOptions.filter(
|
|
3725
|
+
(option) => option.conflictsWith.length > 0
|
|
3726
|
+
);
|
|
3727
|
+
optionsWithConflicting.forEach((option) => {
|
|
3728
|
+
const conflictingAndDefined = definedNonDefaultOptions.find(
|
|
3729
|
+
(defined) => option.conflictsWith.includes(defined.attributeName())
|
|
3730
|
+
);
|
|
3731
|
+
if (conflictingAndDefined) {
|
|
3732
|
+
this._conflictingOption(option, conflictingAndDefined);
|
|
3733
|
+
}
|
|
3734
|
+
});
|
|
3735
|
+
}
|
|
3736
|
+
/**
|
|
3737
|
+
* Display an error message if conflicting options are used together.
|
|
3738
|
+
* Called after checking for help flags in leaf subcommand.
|
|
3739
|
+
*
|
|
3740
|
+
* @private
|
|
3741
|
+
*/
|
|
3742
|
+
_checkForConflictingOptions() {
|
|
3743
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
3744
|
+
cmd._checkForConflictingLocalOptions();
|
|
3745
|
+
});
|
|
3746
|
+
}
|
|
3747
|
+
/**
|
|
3748
|
+
* Parse options from `argv` removing known options,
|
|
3749
|
+
* and return argv split into operands and unknown arguments.
|
|
3750
|
+
*
|
|
3751
|
+
* Side effects: modifies command by storing options. Does not reset state if called again.
|
|
3752
|
+
*
|
|
3753
|
+
* Examples:
|
|
3754
|
+
*
|
|
3755
|
+
* argv => operands, unknown
|
|
3756
|
+
* --known kkk op => [op], []
|
|
3757
|
+
* op --known kkk => [op], []
|
|
3758
|
+
* sub --unknown uuu op => [sub], [--unknown uuu op]
|
|
3759
|
+
* sub -- --unknown uuu op => [sub --unknown uuu op], []
|
|
3760
|
+
*
|
|
3761
|
+
* @param {string[]} args
|
|
3762
|
+
* @return {{operands: string[], unknown: string[]}}
|
|
3763
|
+
*/
|
|
3764
|
+
parseOptions(args) {
|
|
3765
|
+
const operands = [];
|
|
3766
|
+
const unknown = [];
|
|
3767
|
+
let dest = operands;
|
|
3768
|
+
function maybeOption(arg) {
|
|
3769
|
+
return arg.length > 1 && arg[0] === "-";
|
|
3770
|
+
}
|
|
3771
|
+
const negativeNumberArg = (arg) => {
|
|
3772
|
+
if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
|
|
3773
|
+
return !this._getCommandAndAncestors().some(
|
|
3774
|
+
(cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short))
|
|
3775
|
+
);
|
|
3776
|
+
};
|
|
3777
|
+
let activeVariadicOption = null;
|
|
3778
|
+
let activeGroup = null;
|
|
3779
|
+
let i = 0;
|
|
3780
|
+
while (i < args.length || activeGroup) {
|
|
3781
|
+
const arg = activeGroup ?? args[i++];
|
|
3782
|
+
activeGroup = null;
|
|
3783
|
+
if (arg === "--") {
|
|
3784
|
+
if (dest === unknown) dest.push(arg);
|
|
3785
|
+
dest.push(...args.slice(i));
|
|
3786
|
+
break;
|
|
3787
|
+
}
|
|
3788
|
+
if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
|
|
3789
|
+
this.emit(`option:${activeVariadicOption.name()}`, arg);
|
|
3790
|
+
continue;
|
|
3791
|
+
}
|
|
3792
|
+
activeVariadicOption = null;
|
|
3793
|
+
if (maybeOption(arg)) {
|
|
3794
|
+
const option = this._findOption(arg);
|
|
3795
|
+
if (option) {
|
|
3796
|
+
if (option.required) {
|
|
3797
|
+
const value = args[i++];
|
|
3798
|
+
if (value === void 0) this.optionMissingArgument(option);
|
|
3799
|
+
this.emit(`option:${option.name()}`, value);
|
|
3800
|
+
} else if (option.optional) {
|
|
3801
|
+
let value = null;
|
|
3802
|
+
if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
|
|
3803
|
+
value = args[i++];
|
|
3804
|
+
}
|
|
3805
|
+
this.emit(`option:${option.name()}`, value);
|
|
3806
|
+
} else {
|
|
3807
|
+
this.emit(`option:${option.name()}`);
|
|
3808
|
+
}
|
|
3809
|
+
activeVariadicOption = option.variadic ? option : null;
|
|
3810
|
+
continue;
|
|
3811
|
+
}
|
|
3812
|
+
}
|
|
3813
|
+
if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
|
|
3814
|
+
const option = this._findOption(`-${arg[1]}`);
|
|
3815
|
+
if (option) {
|
|
3816
|
+
if (option.required || option.optional && this._combineFlagAndOptionalValue) {
|
|
3817
|
+
this.emit(`option:${option.name()}`, arg.slice(2));
|
|
3818
|
+
} else {
|
|
3819
|
+
this.emit(`option:${option.name()}`);
|
|
3820
|
+
activeGroup = `-${arg.slice(2)}`;
|
|
3821
|
+
}
|
|
3822
|
+
continue;
|
|
3823
|
+
}
|
|
3824
|
+
}
|
|
3825
|
+
if (/^--[^=]+=/.test(arg)) {
|
|
3826
|
+
const index = arg.indexOf("=");
|
|
3827
|
+
const option = this._findOption(arg.slice(0, index));
|
|
3828
|
+
if (option && (option.required || option.optional)) {
|
|
3829
|
+
this.emit(`option:${option.name()}`, arg.slice(index + 1));
|
|
3830
|
+
continue;
|
|
3831
|
+
}
|
|
3832
|
+
}
|
|
3833
|
+
if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
|
|
3834
|
+
dest = unknown;
|
|
3835
|
+
}
|
|
3836
|
+
if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
|
|
3837
|
+
if (this._findCommand(arg)) {
|
|
3838
|
+
operands.push(arg);
|
|
3839
|
+
unknown.push(...args.slice(i));
|
|
3840
|
+
break;
|
|
3841
|
+
} else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
|
|
3842
|
+
operands.push(arg, ...args.slice(i));
|
|
3843
|
+
break;
|
|
3844
|
+
} else if (this._defaultCommandName) {
|
|
3845
|
+
unknown.push(arg, ...args.slice(i));
|
|
3846
|
+
break;
|
|
3847
|
+
}
|
|
3848
|
+
}
|
|
3849
|
+
if (this._passThroughOptions) {
|
|
3850
|
+
dest.push(arg, ...args.slice(i));
|
|
3851
|
+
break;
|
|
3852
|
+
}
|
|
3853
|
+
dest.push(arg);
|
|
3854
|
+
}
|
|
3855
|
+
return { operands, unknown };
|
|
3856
|
+
}
|
|
3857
|
+
/**
|
|
3858
|
+
* Return an object containing local option values as key-value pairs.
|
|
3859
|
+
*
|
|
3860
|
+
* @return {object}
|
|
3861
|
+
*/
|
|
3862
|
+
opts() {
|
|
3863
|
+
if (this._storeOptionsAsProperties) {
|
|
3864
|
+
const result = {};
|
|
3865
|
+
const len = this.options.length;
|
|
3866
|
+
for (let i = 0; i < len; i++) {
|
|
3867
|
+
const key = this.options[i].attributeName();
|
|
3868
|
+
result[key] = key === this._versionOptionName ? this._version : this[key];
|
|
3869
|
+
}
|
|
3870
|
+
return result;
|
|
3871
|
+
}
|
|
3872
|
+
return this._optionValues;
|
|
3873
|
+
}
|
|
3874
|
+
/**
|
|
3875
|
+
* Return an object containing merged local and global option values as key-value pairs.
|
|
3876
|
+
*
|
|
3877
|
+
* @return {object}
|
|
3878
|
+
*/
|
|
3879
|
+
optsWithGlobals() {
|
|
3880
|
+
return this._getCommandAndAncestors().reduce(
|
|
3881
|
+
(combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
|
|
3882
|
+
{}
|
|
3883
|
+
);
|
|
3884
|
+
}
|
|
3885
|
+
/**
|
|
3886
|
+
* Display error message and exit (or call exitOverride).
|
|
3887
|
+
*
|
|
3888
|
+
* @param {string} message
|
|
3889
|
+
* @param {object} [errorOptions]
|
|
3890
|
+
* @param {string} [errorOptions.code] - an id string representing the error
|
|
3891
|
+
* @param {number} [errorOptions.exitCode] - used with process.exit
|
|
3892
|
+
*/
|
|
3893
|
+
error(message3, errorOptions) {
|
|
3894
|
+
this._outputConfiguration.outputError(
|
|
3895
|
+
`${message3}
|
|
3896
|
+
`,
|
|
3897
|
+
this._outputConfiguration.writeErr
|
|
3898
|
+
);
|
|
3899
|
+
if (typeof this._showHelpAfterError === "string") {
|
|
3900
|
+
this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
3901
|
+
`);
|
|
3902
|
+
} else if (this._showHelpAfterError) {
|
|
3903
|
+
this._outputConfiguration.writeErr("\n");
|
|
3904
|
+
this.outputHelp({ error: true });
|
|
3905
|
+
}
|
|
3906
|
+
const config = errorOptions || {};
|
|
3907
|
+
const exitCode = config.exitCode || 1;
|
|
3908
|
+
const code = config.code || "commander.error";
|
|
3909
|
+
this._exit(exitCode, code, message3);
|
|
3910
|
+
}
|
|
3911
|
+
/**
|
|
3912
|
+
* Apply any option related environment variables, if option does
|
|
3913
|
+
* not have a value from cli or client code.
|
|
3914
|
+
*
|
|
3915
|
+
* @private
|
|
3916
|
+
*/
|
|
3917
|
+
_parseOptionsEnv() {
|
|
3918
|
+
this.options.forEach((option) => {
|
|
3919
|
+
if (option.envVar && option.envVar in process2.env) {
|
|
3920
|
+
const optionKey = option.attributeName();
|
|
3921
|
+
if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
|
|
3922
|
+
this.getOptionValueSource(optionKey)
|
|
3923
|
+
)) {
|
|
3924
|
+
if (option.required || option.optional) {
|
|
3925
|
+
this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
|
|
3926
|
+
} else {
|
|
3927
|
+
this.emit(`optionEnv:${option.name()}`);
|
|
3928
|
+
}
|
|
3929
|
+
}
|
|
3930
|
+
}
|
|
3931
|
+
});
|
|
3932
|
+
}
|
|
3933
|
+
/**
|
|
3934
|
+
* Apply any implied option values, if option is undefined or default value.
|
|
3935
|
+
*
|
|
3936
|
+
* @private
|
|
3937
|
+
*/
|
|
3938
|
+
_parseOptionsImplied() {
|
|
3939
|
+
const dualHelper = new DualOptions(this.options);
|
|
3940
|
+
const hasCustomOptionValue = (optionKey) => {
|
|
3941
|
+
return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
|
|
3942
|
+
};
|
|
3943
|
+
this.options.filter(
|
|
3944
|
+
(option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
|
|
3945
|
+
this.getOptionValue(option.attributeName()),
|
|
3946
|
+
option
|
|
3947
|
+
)
|
|
3948
|
+
).forEach((option) => {
|
|
3949
|
+
Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
|
|
3950
|
+
this.setOptionValueWithSource(
|
|
3951
|
+
impliedKey,
|
|
3952
|
+
option.implied[impliedKey],
|
|
3953
|
+
"implied"
|
|
3954
|
+
);
|
|
3955
|
+
});
|
|
3956
|
+
});
|
|
3957
|
+
}
|
|
3958
|
+
/**
|
|
3959
|
+
* Argument `name` is missing.
|
|
3960
|
+
*
|
|
3961
|
+
* @param {string} name
|
|
3962
|
+
* @private
|
|
3963
|
+
*/
|
|
3964
|
+
missingArgument(name2) {
|
|
3965
|
+
const message3 = `error: missing required argument '${name2}'`;
|
|
3966
|
+
this.error(message3, { code: "commander.missingArgument" });
|
|
3967
|
+
}
|
|
3968
|
+
/**
|
|
3969
|
+
* `Option` is missing an argument.
|
|
3970
|
+
*
|
|
3971
|
+
* @param {Option} option
|
|
3972
|
+
* @private
|
|
3973
|
+
*/
|
|
3974
|
+
optionMissingArgument(option) {
|
|
3975
|
+
const message3 = `error: option '${option.flags}' argument missing`;
|
|
3976
|
+
this.error(message3, { code: "commander.optionMissingArgument" });
|
|
3977
|
+
}
|
|
3978
|
+
/**
|
|
3979
|
+
* `Option` does not have a value, and is a mandatory option.
|
|
3980
|
+
*
|
|
3981
|
+
* @param {Option} option
|
|
3982
|
+
* @private
|
|
3983
|
+
*/
|
|
3984
|
+
missingMandatoryOptionValue(option) {
|
|
3985
|
+
const message3 = `error: required option '${option.flags}' not specified`;
|
|
3986
|
+
this.error(message3, { code: "commander.missingMandatoryOptionValue" });
|
|
3987
|
+
}
|
|
3988
|
+
/**
|
|
3989
|
+
* `Option` conflicts with another option.
|
|
3990
|
+
*
|
|
3991
|
+
* @param {Option} option
|
|
3992
|
+
* @param {Option} conflictingOption
|
|
3993
|
+
* @private
|
|
3994
|
+
*/
|
|
3995
|
+
_conflictingOption(option, conflictingOption) {
|
|
3996
|
+
const findBestOptionFromValue = (option2) => {
|
|
3997
|
+
const optionKey = option2.attributeName();
|
|
3998
|
+
const optionValue = this.getOptionValue(optionKey);
|
|
3999
|
+
const negativeOption = this.options.find(
|
|
4000
|
+
(target) => target.negate && optionKey === target.attributeName()
|
|
4001
|
+
);
|
|
4002
|
+
const positiveOption = this.options.find(
|
|
4003
|
+
(target) => !target.negate && optionKey === target.attributeName()
|
|
4004
|
+
);
|
|
4005
|
+
if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
|
|
4006
|
+
return negativeOption;
|
|
4007
|
+
}
|
|
4008
|
+
return positiveOption || option2;
|
|
4009
|
+
};
|
|
4010
|
+
const getErrorMessage = (option2) => {
|
|
4011
|
+
const bestOption = findBestOptionFromValue(option2);
|
|
4012
|
+
const optionKey = bestOption.attributeName();
|
|
4013
|
+
const source = this.getOptionValueSource(optionKey);
|
|
4014
|
+
if (source === "env") {
|
|
4015
|
+
return `environment variable '${bestOption.envVar}'`;
|
|
4016
|
+
}
|
|
4017
|
+
return `option '${bestOption.flags}'`;
|
|
4018
|
+
};
|
|
4019
|
+
const message3 = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
|
|
4020
|
+
this.error(message3, { code: "commander.conflictingOption" });
|
|
4021
|
+
}
|
|
4022
|
+
/**
|
|
4023
|
+
* Unknown option `flag`.
|
|
4024
|
+
*
|
|
4025
|
+
* @param {string} flag
|
|
4026
|
+
* @private
|
|
4027
|
+
*/
|
|
4028
|
+
unknownOption(flag) {
|
|
4029
|
+
if (this._allowUnknownOption) return;
|
|
4030
|
+
let suggestion = "";
|
|
4031
|
+
if (flag.startsWith("--") && this._showSuggestionAfterError) {
|
|
4032
|
+
let candidateFlags = [];
|
|
4033
|
+
let command = this;
|
|
4034
|
+
do {
|
|
4035
|
+
const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
|
|
4036
|
+
candidateFlags = candidateFlags.concat(moreFlags);
|
|
4037
|
+
command = command.parent;
|
|
4038
|
+
} while (command && !command._enablePositionalOptions);
|
|
4039
|
+
suggestion = suggestSimilar(flag, candidateFlags);
|
|
4040
|
+
}
|
|
4041
|
+
const message3 = `error: unknown option '${flag}'${suggestion}`;
|
|
4042
|
+
this.error(message3, { code: "commander.unknownOption" });
|
|
4043
|
+
}
|
|
4044
|
+
/**
|
|
4045
|
+
* Excess arguments, more than expected.
|
|
4046
|
+
*
|
|
4047
|
+
* @param {string[]} receivedArgs
|
|
4048
|
+
* @private
|
|
4049
|
+
*/
|
|
4050
|
+
_excessArguments(receivedArgs) {
|
|
4051
|
+
if (this._allowExcessArguments) return;
|
|
4052
|
+
const expected = this.registeredArguments.length;
|
|
4053
|
+
const s = expected === 1 ? "" : "s";
|
|
4054
|
+
const received = receivedArgs.length;
|
|
4055
|
+
const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
|
|
4056
|
+
const details = receivedArgs.join(", ");
|
|
4057
|
+
const message3 = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${received}: ${details}.`;
|
|
4058
|
+
this.error(message3, { code: "commander.excessArguments" });
|
|
4059
|
+
}
|
|
4060
|
+
/**
|
|
4061
|
+
* Unknown command.
|
|
4062
|
+
*
|
|
4063
|
+
* @private
|
|
4064
|
+
*/
|
|
4065
|
+
unknownCommand() {
|
|
4066
|
+
const unknownName = this.args[0];
|
|
4067
|
+
let suggestion = "";
|
|
4068
|
+
if (this._showSuggestionAfterError) {
|
|
4069
|
+
const candidateNames = [];
|
|
4070
|
+
this.createHelp().visibleCommands(this).forEach((command) => {
|
|
4071
|
+
candidateNames.push(command.name());
|
|
4072
|
+
if (command.alias()) candidateNames.push(command.alias());
|
|
4073
|
+
});
|
|
4074
|
+
suggestion = suggestSimilar(unknownName, candidateNames);
|
|
4075
|
+
}
|
|
4076
|
+
const message3 = `error: unknown command '${unknownName}'${suggestion}`;
|
|
4077
|
+
this.error(message3, { code: "commander.unknownCommand" });
|
|
4078
|
+
}
|
|
4079
|
+
/**
|
|
4080
|
+
* Get or set the program version.
|
|
4081
|
+
*
|
|
4082
|
+
* This method auto-registers the "-V, --version" option which will print the version number.
|
|
4083
|
+
*
|
|
4084
|
+
* You can optionally supply the flags and description to override the defaults.
|
|
4085
|
+
*
|
|
4086
|
+
* @param {string} [str]
|
|
4087
|
+
* @param {string} [flags]
|
|
4088
|
+
* @param {string} [description]
|
|
4089
|
+
* @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
|
|
4090
|
+
*/
|
|
4091
|
+
version(str2, flags, description) {
|
|
4092
|
+
if (str2 === void 0) return this._version;
|
|
4093
|
+
this._version = str2;
|
|
4094
|
+
flags = flags || "-V, --version";
|
|
4095
|
+
description = description || "output the version number";
|
|
4096
|
+
const versionOption = this.createOption(flags, description);
|
|
4097
|
+
this._versionOptionName = versionOption.attributeName();
|
|
4098
|
+
this._registerOption(versionOption);
|
|
4099
|
+
this.on("option:" + versionOption.name(), () => {
|
|
4100
|
+
this._outputConfiguration.writeOut(`${str2}
|
|
4101
|
+
`);
|
|
4102
|
+
this._exit(0, "commander.version", str2);
|
|
4103
|
+
});
|
|
4104
|
+
return this;
|
|
4105
|
+
}
|
|
4106
|
+
/**
|
|
4107
|
+
* Set the description.
|
|
4108
|
+
*
|
|
4109
|
+
* @param {string} [str]
|
|
4110
|
+
* @param {object} [argsDescription]
|
|
4111
|
+
* @return {(string|Command)}
|
|
4112
|
+
*/
|
|
4113
|
+
description(str2, argsDescription) {
|
|
4114
|
+
if (str2 === void 0 && argsDescription === void 0)
|
|
4115
|
+
return this._description;
|
|
4116
|
+
this._description = str2;
|
|
4117
|
+
if (argsDescription) {
|
|
4118
|
+
this._argsDescription = argsDescription;
|
|
4119
|
+
}
|
|
4120
|
+
return this;
|
|
4121
|
+
}
|
|
4122
|
+
/**
|
|
4123
|
+
* Set the summary. Used when listed as subcommand of parent.
|
|
4124
|
+
*
|
|
4125
|
+
* @param {string} [str]
|
|
4126
|
+
* @return {(string|Command)}
|
|
4127
|
+
*/
|
|
4128
|
+
summary(str2) {
|
|
4129
|
+
if (str2 === void 0) return this._summary;
|
|
4130
|
+
this._summary = str2;
|
|
4131
|
+
return this;
|
|
4132
|
+
}
|
|
4133
|
+
/**
|
|
4134
|
+
* Set an alias for the command.
|
|
4135
|
+
*
|
|
4136
|
+
* You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
|
|
4137
|
+
*
|
|
4138
|
+
* @param {string} [alias]
|
|
4139
|
+
* @return {(string|Command)}
|
|
4140
|
+
*/
|
|
4141
|
+
alias(alias) {
|
|
4142
|
+
if (alias === void 0) return this._aliases[0];
|
|
4143
|
+
let command = this;
|
|
4144
|
+
if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
|
|
4145
|
+
command = this.commands[this.commands.length - 1];
|
|
4146
|
+
}
|
|
4147
|
+
if (alias === command._name)
|
|
4148
|
+
throw new Error("Command alias can't be the same as its name");
|
|
4149
|
+
const matchingCommand = this.parent?._findCommand(alias);
|
|
4150
|
+
if (matchingCommand) {
|
|
4151
|
+
const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
|
|
4152
|
+
throw new Error(
|
|
4153
|
+
`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
|
|
4154
|
+
);
|
|
4155
|
+
}
|
|
4156
|
+
command._aliases.push(alias);
|
|
4157
|
+
return this;
|
|
4158
|
+
}
|
|
4159
|
+
/**
|
|
4160
|
+
* Set aliases for the command.
|
|
4161
|
+
*
|
|
4162
|
+
* Only the first alias is shown in the auto-generated help.
|
|
4163
|
+
*
|
|
4164
|
+
* @param {string[]} [aliases]
|
|
4165
|
+
* @return {(string[]|Command)}
|
|
4166
|
+
*/
|
|
4167
|
+
aliases(aliases) {
|
|
4168
|
+
if (aliases === void 0) return this._aliases;
|
|
4169
|
+
aliases.forEach((alias) => this.alias(alias));
|
|
4170
|
+
return this;
|
|
4171
|
+
}
|
|
4172
|
+
/**
|
|
4173
|
+
* Set / get the command usage `str`.
|
|
4174
|
+
*
|
|
4175
|
+
* @param {string} [str]
|
|
4176
|
+
* @return {(string|Command)}
|
|
4177
|
+
*/
|
|
4178
|
+
usage(str2) {
|
|
4179
|
+
if (str2 === void 0) {
|
|
4180
|
+
if (this._usage) return this._usage;
|
|
4181
|
+
const args = this.registeredArguments.map((arg) => {
|
|
4182
|
+
return humanReadableArgName(arg);
|
|
839
4183
|
});
|
|
840
|
-
|
|
4184
|
+
return [].concat(
|
|
4185
|
+
this.options.length || this._helpOption !== null ? "[options]" : [],
|
|
4186
|
+
this.commands.length ? "[command]" : [],
|
|
4187
|
+
this.registeredArguments.length ? args : []
|
|
4188
|
+
).join(" ");
|
|
841
4189
|
}
|
|
842
|
-
|
|
4190
|
+
this._usage = str2;
|
|
4191
|
+
return this;
|
|
843
4192
|
}
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
4193
|
+
/**
|
|
4194
|
+
* Get or set the name of the command.
|
|
4195
|
+
*
|
|
4196
|
+
* @param {string} [str]
|
|
4197
|
+
* @return {(string|Command)}
|
|
4198
|
+
*/
|
|
4199
|
+
name(str2) {
|
|
4200
|
+
if (str2 === void 0) return this._name;
|
|
4201
|
+
this._name = str2;
|
|
4202
|
+
return this;
|
|
4203
|
+
}
|
|
4204
|
+
/**
|
|
4205
|
+
* Set/get the help group heading for this subcommand in parent command's help.
|
|
4206
|
+
*
|
|
4207
|
+
* @param {string} [heading]
|
|
4208
|
+
* @return {Command | string}
|
|
4209
|
+
*/
|
|
4210
|
+
helpGroup(heading) {
|
|
4211
|
+
if (heading === void 0) return this._helpGroupHeading ?? "";
|
|
4212
|
+
this._helpGroupHeading = heading;
|
|
4213
|
+
return this;
|
|
4214
|
+
}
|
|
4215
|
+
/**
|
|
4216
|
+
* Set/get the default help group heading for subcommands added to this command.
|
|
4217
|
+
* (This does not override a group set directly on the subcommand using .helpGroup().)
|
|
4218
|
+
*
|
|
4219
|
+
* @example
|
|
4220
|
+
* program.commandsGroup('Development Commands:);
|
|
4221
|
+
* program.command('watch')...
|
|
4222
|
+
* program.command('lint')...
|
|
4223
|
+
* ...
|
|
4224
|
+
*
|
|
4225
|
+
* @param {string} [heading]
|
|
4226
|
+
* @returns {Command | string}
|
|
4227
|
+
*/
|
|
4228
|
+
commandsGroup(heading) {
|
|
4229
|
+
if (heading === void 0) return this._defaultCommandGroup ?? "";
|
|
4230
|
+
this._defaultCommandGroup = heading;
|
|
4231
|
+
return this;
|
|
4232
|
+
}
|
|
4233
|
+
/**
|
|
4234
|
+
* Set/get the default help group heading for options added to this command.
|
|
4235
|
+
* (This does not override a group set directly on the option using .helpGroup().)
|
|
4236
|
+
*
|
|
4237
|
+
* @example
|
|
4238
|
+
* program
|
|
4239
|
+
* .optionsGroup('Development Options:')
|
|
4240
|
+
* .option('-d, --debug', 'output extra debugging')
|
|
4241
|
+
* .option('-p, --profile', 'output profiling information')
|
|
4242
|
+
*
|
|
4243
|
+
* @param {string} [heading]
|
|
4244
|
+
* @returns {Command | string}
|
|
4245
|
+
*/
|
|
4246
|
+
optionsGroup(heading) {
|
|
4247
|
+
if (heading === void 0) return this._defaultOptionGroup ?? "";
|
|
4248
|
+
this._defaultOptionGroup = heading;
|
|
4249
|
+
return this;
|
|
4250
|
+
}
|
|
4251
|
+
/**
|
|
4252
|
+
* @param {Option} option
|
|
4253
|
+
* @private
|
|
4254
|
+
*/
|
|
4255
|
+
_initOptionGroup(option) {
|
|
4256
|
+
if (this._defaultOptionGroup && !option.helpGroupHeading)
|
|
4257
|
+
option.helpGroup(this._defaultOptionGroup);
|
|
4258
|
+
}
|
|
4259
|
+
/**
|
|
4260
|
+
* @param {Command} cmd
|
|
4261
|
+
* @private
|
|
4262
|
+
*/
|
|
4263
|
+
_initCommandGroup(cmd) {
|
|
4264
|
+
if (this._defaultCommandGroup && !cmd.helpGroup())
|
|
4265
|
+
cmd.helpGroup(this._defaultCommandGroup);
|
|
4266
|
+
}
|
|
4267
|
+
/**
|
|
4268
|
+
* Set the name of the command from script filename, such as process.argv[1],
|
|
4269
|
+
* or import.meta.filename.
|
|
4270
|
+
*
|
|
4271
|
+
* (Used internally and public although not documented in README.)
|
|
4272
|
+
*
|
|
4273
|
+
* @example
|
|
4274
|
+
* program.nameFromFilename(import.meta.filename);
|
|
4275
|
+
*
|
|
4276
|
+
* @param {string} filename
|
|
4277
|
+
* @return {Command}
|
|
4278
|
+
*/
|
|
4279
|
+
nameFromFilename(filename) {
|
|
4280
|
+
this._name = path.basename(filename, path.extname(filename));
|
|
4281
|
+
return this;
|
|
4282
|
+
}
|
|
4283
|
+
/**
|
|
4284
|
+
* Get or set the directory for searching for executable subcommands of this command.
|
|
4285
|
+
*
|
|
4286
|
+
* @example
|
|
4287
|
+
* program.executableDir(import.meta.dirname);
|
|
4288
|
+
* // or
|
|
4289
|
+
* program.executableDir('subcommands');
|
|
4290
|
+
*
|
|
4291
|
+
* @param {string} [path]
|
|
4292
|
+
* @return {(string|null|Command)}
|
|
4293
|
+
*/
|
|
4294
|
+
executableDir(path2) {
|
|
4295
|
+
if (path2 === void 0) return this._executableDir;
|
|
4296
|
+
this._executableDir = path2;
|
|
4297
|
+
return this;
|
|
4298
|
+
}
|
|
4299
|
+
/**
|
|
4300
|
+
* Return program help documentation.
|
|
4301
|
+
*
|
|
4302
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
|
|
4303
|
+
* @return {string}
|
|
4304
|
+
*/
|
|
4305
|
+
helpInformation(contextOptions) {
|
|
4306
|
+
const helper = this.createHelp();
|
|
4307
|
+
const context2 = this._getOutputContext(contextOptions);
|
|
4308
|
+
helper.prepareContext({
|
|
4309
|
+
error: context2.error,
|
|
4310
|
+
helpWidth: context2.helpWidth,
|
|
4311
|
+
outputHasColors: context2.hasColors
|
|
4312
|
+
});
|
|
4313
|
+
const text2 = helper.formatHelp(this, helper);
|
|
4314
|
+
if (context2.hasColors) return text2;
|
|
4315
|
+
return this._outputConfiguration.stripColor(text2);
|
|
4316
|
+
}
|
|
4317
|
+
/**
|
|
4318
|
+
* @typedef HelpContext
|
|
4319
|
+
* @type {object}
|
|
4320
|
+
* @property {boolean} error
|
|
4321
|
+
* @property {number} helpWidth
|
|
4322
|
+
* @property {boolean} hasColors
|
|
4323
|
+
* @property {function} write - includes stripColor if needed
|
|
4324
|
+
*
|
|
4325
|
+
* @returns {HelpContext}
|
|
4326
|
+
* @private
|
|
4327
|
+
*/
|
|
4328
|
+
_getOutputContext(contextOptions) {
|
|
4329
|
+
contextOptions = contextOptions || {};
|
|
4330
|
+
const error = !!contextOptions.error;
|
|
4331
|
+
let baseWrite;
|
|
4332
|
+
let hasColors;
|
|
4333
|
+
let helpWidth;
|
|
4334
|
+
if (error) {
|
|
4335
|
+
baseWrite = (str2) => this._outputConfiguration.writeErr(str2);
|
|
4336
|
+
hasColors = this._outputConfiguration.getErrHasColors();
|
|
4337
|
+
helpWidth = this._outputConfiguration.getErrHelpWidth();
|
|
4338
|
+
} else {
|
|
4339
|
+
baseWrite = (str2) => this._outputConfiguration.writeOut(str2);
|
|
4340
|
+
hasColors = this._outputConfiguration.getOutHasColors();
|
|
4341
|
+
helpWidth = this._outputConfiguration.getOutHelpWidth();
|
|
853
4342
|
}
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
if (table2.has(runId)) return;
|
|
858
|
-
const workspace = join2(opts.configDir, "workspaces", runId);
|
|
859
|
-
const run = {
|
|
860
|
-
runId,
|
|
861
|
-
workspace,
|
|
862
|
-
canceled: false,
|
|
863
|
-
timedOut: false,
|
|
864
|
-
settled: false,
|
|
865
|
-
keyFingerprint: assignment.run_key.slice(0, 14),
|
|
866
|
-
batcher: new LogBatcher((chunk) => client2.appendRunLog(runId, { chunk }).then(() => {
|
|
867
|
-
}), {
|
|
868
|
-
onError: (err) => log(`log append for run ${runId} failed: ${message(err)}`)
|
|
869
|
-
})
|
|
4343
|
+
const write = (str2) => {
|
|
4344
|
+
if (!hasColors) str2 = this._outputConfiguration.stripColor(str2);
|
|
4345
|
+
return baseWrite(str2);
|
|
870
4346
|
};
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
4347
|
+
return { error, write, hasColors, helpWidth };
|
|
4348
|
+
}
|
|
4349
|
+
/**
|
|
4350
|
+
* Output help information for this command.
|
|
4351
|
+
*
|
|
4352
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
4353
|
+
*
|
|
4354
|
+
* @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
4355
|
+
*/
|
|
4356
|
+
outputHelp(contextOptions) {
|
|
4357
|
+
let deprecatedCallback;
|
|
4358
|
+
if (typeof contextOptions === "function") {
|
|
4359
|
+
deprecatedCallback = contextOptions;
|
|
4360
|
+
contextOptions = void 0;
|
|
4361
|
+
}
|
|
4362
|
+
const outputContext = this._getOutputContext(contextOptions);
|
|
4363
|
+
const eventContext = {
|
|
4364
|
+
error: outputContext.error,
|
|
4365
|
+
write: outputContext.write,
|
|
4366
|
+
command: this
|
|
4367
|
+
};
|
|
4368
|
+
this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
|
|
4369
|
+
this.emit("beforeHelp", eventContext);
|
|
4370
|
+
let helpInformation = this.helpInformation({ error: outputContext.error });
|
|
4371
|
+
if (deprecatedCallback) {
|
|
4372
|
+
helpInformation = deprecatedCallback(helpInformation);
|
|
4373
|
+
if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
|
|
4374
|
+
throw new Error("outputHelp callback must return a string or a Buffer");
|
|
885
4375
|
}
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
4376
|
+
}
|
|
4377
|
+
outputContext.write(helpInformation);
|
|
4378
|
+
if (this._getHelpOption()?.long) {
|
|
4379
|
+
this.emit(this._getHelpOption().long);
|
|
4380
|
+
}
|
|
4381
|
+
this.emit("afterHelp", eventContext);
|
|
4382
|
+
this._getCommandAndAncestors().forEach(
|
|
4383
|
+
(command) => command.emit("afterAllHelp", eventContext)
|
|
4384
|
+
);
|
|
4385
|
+
}
|
|
4386
|
+
/**
|
|
4387
|
+
* You can pass in flags and a description to customise the built-in help option.
|
|
4388
|
+
* Pass in false to disable the built-in help option.
|
|
4389
|
+
*
|
|
4390
|
+
* @example
|
|
4391
|
+
* program.helpOption('-?, --help' 'show help'); // customise
|
|
4392
|
+
* program.helpOption(false); // disable
|
|
4393
|
+
*
|
|
4394
|
+
* @param {(string | boolean)} flags
|
|
4395
|
+
* @param {string} [description]
|
|
4396
|
+
* @return {Command} `this` command for chaining
|
|
4397
|
+
*/
|
|
4398
|
+
helpOption(flags, description) {
|
|
4399
|
+
if (typeof flags === "boolean") {
|
|
4400
|
+
if (flags) {
|
|
4401
|
+
if (this._helpOption === null) this._helpOption = void 0;
|
|
4402
|
+
if (this._defaultOptionGroup) {
|
|
4403
|
+
this._initOptionGroup(this._getHelpOption());
|
|
899
4404
|
}
|
|
4405
|
+
} else {
|
|
4406
|
+
this._helpOption = null;
|
|
900
4407
|
}
|
|
901
|
-
|
|
902
|
-
const invocation = buildHarnessInvocation(
|
|
903
|
-
{ harness: opts.harness, command: opts.command },
|
|
904
|
-
{
|
|
905
|
-
workspace,
|
|
906
|
-
promptFile: join2(workspace, "prompt.md"),
|
|
907
|
-
prompt: assignment.prompt,
|
|
908
|
-
model: assignment.run.model
|
|
909
|
-
}
|
|
910
|
-
);
|
|
911
|
-
const child = spawn(invocation.file, invocation.args, {
|
|
912
|
-
cwd: workspace,
|
|
913
|
-
env: { ...process.env, TINES_API_KEY: assignment.run_key, TINES_API_URL: opts.url },
|
|
914
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
915
|
-
detached: true
|
|
916
|
-
});
|
|
917
|
-
run.child = child;
|
|
918
|
-
run.spawnedAt = Date.now();
|
|
919
|
-
table2.persist();
|
|
920
|
-
log(`run ${runId}: launched ${invocation.file} (pid ${child.pid})`);
|
|
921
|
-
child.stdout?.on("data", (data) => run.batcher.append(data.toString("utf8")));
|
|
922
|
-
child.stderr?.on("data", (data) => run.batcher.append(data.toString("utf8")));
|
|
923
|
-
run.timeout = setTimeout(
|
|
924
|
-
() => {
|
|
925
|
-
if (run.settled) return;
|
|
926
|
-
log(`run ${runId} hit its ${assignment.timeout_minutes}m timeout; killing`);
|
|
927
|
-
run.timedOut = true;
|
|
928
|
-
if (child.pid) killTree(child.pid, "SIGTERM");
|
|
929
|
-
if (child.pid) setTimeout(() => killTree(child.pid, "SIGKILL"), 5e3).unref?.();
|
|
930
|
-
},
|
|
931
|
-
assignment.timeout_minutes * 6e4
|
|
932
|
-
);
|
|
933
|
-
child.on("error", (err) => {
|
|
934
|
-
void table2.finishAndCleanup(run, "failed", `failed to launch harness: ${message(err)}`);
|
|
935
|
-
});
|
|
936
|
-
child.on("exit", (code, signal) => {
|
|
937
|
-
if (run.timedOut) {
|
|
938
|
-
void table2.finishAndCleanup(
|
|
939
|
-
run,
|
|
940
|
-
"failed",
|
|
941
|
-
`run exceeded the ${assignment.timeout_minutes}m timeout; harness killed`
|
|
942
|
-
);
|
|
943
|
-
} else if (code === 0) {
|
|
944
|
-
void table2.finishAndCleanup(run, "completed");
|
|
945
|
-
} else {
|
|
946
|
-
void table2.finishAndCleanup(
|
|
947
|
-
run,
|
|
948
|
-
"failed",
|
|
949
|
-
signal ? `harness killed by ${signal}` : `harness exited with code ${code}`
|
|
950
|
-
);
|
|
951
|
-
}
|
|
952
|
-
});
|
|
953
|
-
} catch (err) {
|
|
954
|
-
void table2.finishAndCleanup(run, "failed", `workspace setup failed: ${message(err)}`);
|
|
4408
|
+
return this;
|
|
955
4409
|
}
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
shuttingDown = true;
|
|
960
|
-
log("shutting down; failing in-flight runs");
|
|
961
|
-
await Promise.all(
|
|
962
|
-
table2.values().map(async (run) => {
|
|
963
|
-
if (run.child?.pid) killTree(run.child.pid, "SIGTERM");
|
|
964
|
-
await table2.finishAndCleanup(run, "failed", "daemon shut down");
|
|
965
|
-
})
|
|
4410
|
+
this._helpOption = this.createOption(
|
|
4411
|
+
flags ?? "-h, --help",
|
|
4412
|
+
description ?? "display help for command"
|
|
966
4413
|
);
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
4414
|
+
if (flags || description) this._initOptionGroup(this._helpOption);
|
|
4415
|
+
return this;
|
|
4416
|
+
}
|
|
4417
|
+
/**
|
|
4418
|
+
* Lazy create help option.
|
|
4419
|
+
* Returns null if has been disabled with .helpOption(false).
|
|
4420
|
+
*
|
|
4421
|
+
* @returns {(Option | null)} the help option
|
|
4422
|
+
* @package
|
|
4423
|
+
*/
|
|
4424
|
+
_getHelpOption() {
|
|
4425
|
+
if (this._helpOption === void 0) {
|
|
4426
|
+
this.helpOption(void 0, void 0);
|
|
4427
|
+
}
|
|
4428
|
+
return this._helpOption;
|
|
4429
|
+
}
|
|
4430
|
+
/**
|
|
4431
|
+
* Supply your own option to use for the built-in help option.
|
|
4432
|
+
* This is an alternative to using helpOption() to customise the flags and description etc.
|
|
4433
|
+
*
|
|
4434
|
+
* @param {Option} option
|
|
4435
|
+
* @return {Command} `this` command for chaining
|
|
4436
|
+
*/
|
|
4437
|
+
addHelpOption(option) {
|
|
4438
|
+
this._helpOption = option;
|
|
4439
|
+
this._initOptionGroup(option);
|
|
4440
|
+
return this;
|
|
4441
|
+
}
|
|
4442
|
+
/**
|
|
4443
|
+
* Output help information and exit.
|
|
4444
|
+
*
|
|
4445
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
4446
|
+
*
|
|
4447
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
4448
|
+
*/
|
|
4449
|
+
help(contextOptions) {
|
|
4450
|
+
this.outputHelp(contextOptions);
|
|
4451
|
+
let exitCode = Number(process2.exitCode ?? 0);
|
|
4452
|
+
if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
|
|
4453
|
+
exitCode = 1;
|
|
4454
|
+
}
|
|
4455
|
+
this._exit(exitCode, "commander.help", "(outputHelp)");
|
|
4456
|
+
}
|
|
4457
|
+
/**
|
|
4458
|
+
* // Do a little typing to coordinate emit and listener for the help text events.
|
|
4459
|
+
* @typedef HelpTextEventContext
|
|
4460
|
+
* @type {object}
|
|
4461
|
+
* @property {boolean} error
|
|
4462
|
+
* @property {Command} command
|
|
4463
|
+
* @property {function} write
|
|
4464
|
+
*/
|
|
4465
|
+
/**
|
|
4466
|
+
* Add additional text to be displayed with the built-in help.
|
|
4467
|
+
*
|
|
4468
|
+
* Position is 'before' or 'after' to affect just this command,
|
|
4469
|
+
* and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
|
|
4470
|
+
*
|
|
4471
|
+
* @param {string} position - before or after built-in help
|
|
4472
|
+
* @param {(string | Function)} text - string to add, or a function returning a string
|
|
4473
|
+
* @return {Command} `this` command for chaining
|
|
4474
|
+
*/
|
|
4475
|
+
addHelpText(position, text2) {
|
|
4476
|
+
const allowedValues = ["beforeAll", "before", "after", "afterAll"];
|
|
4477
|
+
if (!allowedValues.includes(position)) {
|
|
4478
|
+
throw new Error(`Unexpected value for position to addHelpText.
|
|
4479
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
4480
|
+
}
|
|
4481
|
+
const helpEvent = `${position}Help`;
|
|
4482
|
+
this.on(helpEvent, (context2) => {
|
|
4483
|
+
let helpStr;
|
|
4484
|
+
if (typeof text2 === "function") {
|
|
4485
|
+
helpStr = text2({ error: context2.error, command: context2.command });
|
|
4486
|
+
} else {
|
|
4487
|
+
helpStr = text2;
|
|
990
4488
|
}
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
if (run.child?.pid) killTree(run.child.pid, "SIGKILL");
|
|
995
|
-
rmSync(run.workspace, { recursive: true, force: true });
|
|
996
|
-
}
|
|
997
|
-
saveDaemonState(statePath, []);
|
|
998
|
-
clearRunnerCredentials(opts.configDir, opts.url, opts.name);
|
|
999
|
-
throw new Error(
|
|
1000
|
-
`the supervisor rejected this runner's token (was it rotated?) \u2014 the stored token was dropped; restart with the new token via \`tines runners rotate-token ${opts.name}\` on this machine, or with TINES_API_KEY set to re-register`
|
|
1001
|
-
);
|
|
4489
|
+
if (helpStr) {
|
|
4490
|
+
context2.write(`${helpStr}
|
|
4491
|
+
`);
|
|
1002
4492
|
}
|
|
1003
|
-
|
|
1004
|
-
|
|
4493
|
+
});
|
|
4494
|
+
return this;
|
|
4495
|
+
}
|
|
4496
|
+
/**
|
|
4497
|
+
* Output help information if help flags specified
|
|
4498
|
+
*
|
|
4499
|
+
* @param {Array} args - array of options to search for help flags
|
|
4500
|
+
* @private
|
|
4501
|
+
*/
|
|
4502
|
+
_outputHelpIfRequested(args) {
|
|
4503
|
+
const helpOption = this._getHelpOption();
|
|
4504
|
+
const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
|
|
4505
|
+
if (helpRequested) {
|
|
4506
|
+
this.outputHelp();
|
|
4507
|
+
this._exit(0, "commander.helpDisplayed", "(outputHelp)");
|
|
1005
4508
|
}
|
|
1006
|
-
const backoff = Math.min(
|
|
1007
|
-
opts.pollIntervalMs * 2 ** Math.min(failures, 3),
|
|
1008
|
-
Math.max(6e4, opts.pollIntervalMs * 5)
|
|
1009
|
-
);
|
|
1010
|
-
await sleep(failures > 0 ? backoff : opts.pollIntervalMs);
|
|
1011
4509
|
}
|
|
1012
|
-
}
|
|
1013
|
-
function
|
|
1014
|
-
return
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
4510
|
+
};
|
|
4511
|
+
function incrementNodeInspectorPort(args) {
|
|
4512
|
+
return args.map((arg) => {
|
|
4513
|
+
if (!arg.startsWith("--inspect")) {
|
|
4514
|
+
return arg;
|
|
4515
|
+
}
|
|
4516
|
+
let debugOption;
|
|
4517
|
+
let debugHost = "127.0.0.1";
|
|
4518
|
+
let debugPort = "9229";
|
|
4519
|
+
let match;
|
|
4520
|
+
if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
|
|
4521
|
+
debugOption = match[1];
|
|
4522
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
|
|
4523
|
+
debugOption = match[1];
|
|
4524
|
+
if (/^\d+$/.test(match[3])) {
|
|
4525
|
+
debugPort = match[3];
|
|
4526
|
+
} else {
|
|
4527
|
+
debugHost = match[3];
|
|
4528
|
+
}
|
|
4529
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
|
|
4530
|
+
debugOption = match[1];
|
|
4531
|
+
debugHost = match[3];
|
|
4532
|
+
debugPort = match[4];
|
|
4533
|
+
}
|
|
4534
|
+
if (debugOption && debugPort !== "0") {
|
|
4535
|
+
return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
|
|
4536
|
+
}
|
|
4537
|
+
return arg;
|
|
1023
4538
|
});
|
|
1024
4539
|
}
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
if (
|
|
1029
|
-
command.help();
|
|
4540
|
+
function useColor() {
|
|
4541
|
+
if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
|
|
4542
|
+
return false;
|
|
4543
|
+
if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
|
|
1030
4544
|
return true;
|
|
1031
|
-
|
|
1032
|
-
return false;
|
|
4545
|
+
return void 0;
|
|
1033
4546
|
}
|
|
1034
4547
|
|
|
4548
|
+
// ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/index.js
|
|
4549
|
+
var program = new Command();
|
|
4550
|
+
|
|
1035
4551
|
// src/index.ts
|
|
1036
|
-
import { Command } from "commander";
|
|
1037
4552
|
var DEFAULT_URL = "http://localhost:5173";
|
|
1038
4553
|
function withCommon(cmd, { baseUrlFlag = true } = {}) {
|
|
1039
4554
|
if (baseUrlFlag) {
|
|
@@ -1058,20 +4573,20 @@ function resolveApiKey(opts) {
|
|
|
1058
4573
|
function client(opts) {
|
|
1059
4574
|
return createApiClient({ baseUrl: resolveUrl(opts), apiKey: resolveApiKey(opts) });
|
|
1060
4575
|
}
|
|
1061
|
-
function die(
|
|
1062
|
-
console.error(`error: ${
|
|
4576
|
+
function die(message3) {
|
|
4577
|
+
console.error(`error: ${message3}`);
|
|
1063
4578
|
process.exit(1);
|
|
1064
4579
|
}
|
|
1065
4580
|
function reportError(err) {
|
|
1066
4581
|
if (err instanceof ApiError) {
|
|
1067
|
-
let
|
|
4582
|
+
let message3 = `${err.message} (${err.code})`;
|
|
1068
4583
|
const allowed = err.details?.allowed_transitions;
|
|
1069
4584
|
if (Array.isArray(allowed)) {
|
|
1070
4585
|
const actions = allowed.map((t) => {
|
|
1071
4586
|
const at = t;
|
|
1072
4587
|
return at.to_state ? `"${at.name}" \u2192 ${at.to_state.name}` : `"${at.name}"`;
|
|
1073
4588
|
});
|
|
1074
|
-
|
|
4589
|
+
message3 += actions.length > 0 ? `
|
|
1075
4590
|
allowed actions: ${actions.join(", ")}` : "\nallowed actions: none (terminal state)";
|
|
1076
4591
|
}
|
|
1077
4592
|
const unmet = err.details?.unmet;
|
|
@@ -1079,13 +4594,13 @@ allowed actions: ${actions.join(", ")}` : "\nallowed actions: none (terminal sta
|
|
|
1079
4594
|
for (const raw of unmet) {
|
|
1080
4595
|
const r = raw;
|
|
1081
4596
|
const spec = [r.type, r.content_type].filter(Boolean).join(", ");
|
|
1082
|
-
|
|
4597
|
+
message3 += `
|
|
1083
4598
|
requires artifact "${r.artifact}"${spec ? ` (${spec})` : ""}: ${r.status ?? "unmet"}${r.description ? ` \u2014 ${r.description}` : ""}`;
|
|
1084
|
-
if (r.fix)
|
|
4599
|
+
if (r.fix) message3 += `
|
|
1085
4600
|
fix: ${r.fix}`;
|
|
1086
4601
|
}
|
|
1087
4602
|
}
|
|
1088
|
-
die(
|
|
4603
|
+
die(message3);
|
|
1089
4604
|
}
|
|
1090
4605
|
die(err instanceof Error ? err.message : String(err));
|
|
1091
4606
|
}
|
|
@@ -1128,14 +4643,14 @@ function readJsonBody(inline, file) {
|
|
|
1128
4643
|
if (file !== void 0 && file !== "-") {
|
|
1129
4644
|
let raw;
|
|
1130
4645
|
try {
|
|
1131
|
-
raw =
|
|
4646
|
+
raw = readFileSync4(file, "utf8");
|
|
1132
4647
|
} catch (err) {
|
|
1133
4648
|
die(`cannot read ${file}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1134
4649
|
}
|
|
1135
4650
|
return parseJsonObject(raw, file);
|
|
1136
4651
|
}
|
|
1137
4652
|
if (file === "-" || !process.stdin.isTTY) {
|
|
1138
|
-
const raw =
|
|
4653
|
+
const raw = readFileSync4(0, "utf8");
|
|
1139
4654
|
if (raw.trim() === "") {
|
|
1140
4655
|
if (file === "-") die("no JSON on stdin");
|
|
1141
4656
|
return void 0;
|
|
@@ -1270,14 +4785,14 @@ function parseFileSpec(spec) {
|
|
|
1270
4785
|
if (sep < 1 || sep === spec.length - 1) {
|
|
1271
4786
|
die(`--file must look like <path>=@<local-file>, got "${spec}"`);
|
|
1272
4787
|
}
|
|
1273
|
-
const
|
|
4788
|
+
const path2 = spec.slice(0, sep);
|
|
1274
4789
|
const source = spec.slice(sep + 1);
|
|
1275
4790
|
if (!source.startsWith("@")) {
|
|
1276
|
-
die(`skill file content always comes from a local file: --file ${
|
|
4791
|
+
die(`skill file content always comes from a local file: --file ${path2}=@<local-file>`);
|
|
1277
4792
|
}
|
|
1278
4793
|
const file = source.slice(1);
|
|
1279
4794
|
try {
|
|
1280
|
-
return { path, content:
|
|
4795
|
+
return { path: path2, content: readFileSync4(file, "utf8") };
|
|
1281
4796
|
} catch (err) {
|
|
1282
4797
|
die(`cannot read ${file}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1283
4798
|
}
|
|
@@ -1475,21 +4990,21 @@ warning: ${w}`);
|
|
|
1475
4990
|
function cliVersion() {
|
|
1476
4991
|
try {
|
|
1477
4992
|
const manifest = new URL("../package.json", import.meta.url);
|
|
1478
|
-
return JSON.parse(
|
|
4993
|
+
return JSON.parse(readFileSync4(manifest, "utf8")).version ?? "0.0.0-unknown";
|
|
1479
4994
|
} catch {
|
|
1480
4995
|
return "0.0.0-unknown";
|
|
1481
4996
|
}
|
|
1482
4997
|
}
|
|
1483
|
-
var
|
|
1484
|
-
|
|
1485
|
-
withCommon(
|
|
4998
|
+
var program2 = new Command();
|
|
4999
|
+
program2.name("tines").description("CLI for Tines").version(cliVersion()).enablePositionalOptions();
|
|
5000
|
+
withCommon(program2.command("time").description("Fetch the current time from the Tines API")).action(
|
|
1486
5001
|
async (opts) => {
|
|
1487
5002
|
const result = await client(opts).getTime();
|
|
1488
5003
|
if (opts.json) printJson(result);
|
|
1489
5004
|
else console.log(`Server time: ${result.time} (unix ${result.unix})`);
|
|
1490
5005
|
}
|
|
1491
5006
|
);
|
|
1492
|
-
var projects =
|
|
5007
|
+
var projects = program2.command("projects").description("Manage projects");
|
|
1493
5008
|
withList(projects.command("list").description("List projects")).action(async (opts) => {
|
|
1494
5009
|
const res = await client(opts).listProjects({ limit: opts.limit, cursor: opts.cursor });
|
|
1495
5010
|
printList(res, opts, (items) => {
|
|
@@ -1567,7 +5082,7 @@ withCommon(
|
|
|
1567
5082
|
await api.deleteProject(project.id);
|
|
1568
5083
|
console.log(`deleted project "${project.name}" (${project.id})`);
|
|
1569
5084
|
});
|
|
1570
|
-
var workflows =
|
|
5085
|
+
var workflows = program2.command("workflows").description("Manage the workflow library");
|
|
1571
5086
|
withList(workflows.command("list").description("List the workflow library")).action(
|
|
1572
5087
|
async (opts) => {
|
|
1573
5088
|
const res = await client(opts).listWorkflows({ limit: opts.limit, cursor: opts.cursor });
|
|
@@ -1640,7 +5155,7 @@ withCommon(
|
|
|
1640
5155
|
await api.deleteWorkflow(wf.id);
|
|
1641
5156
|
console.log(`deleted workflow "${wf.name}" (${wf.id})`);
|
|
1642
5157
|
});
|
|
1643
|
-
var issues =
|
|
5158
|
+
var issues = program2.command("issues").description("Work with issues");
|
|
1644
5159
|
withList(
|
|
1645
5160
|
issues.command("list").description("List issues across projects (hides done issues unless --all)").option("-p, --project <name>", "filter by project name or id").option("-s, --state <name>", "filter by state name or id").option("-c, --category <cat>", "filter by state category").option("-w, --workflow <id-or-name>", "filter by workflow").option("-a, --all", "include issues in done states").option("--ready", "only issues that are actionable now (not done, not a duplicate, no open blockers)").option("-q, --search <text>", "search titles and descriptions")
|
|
1646
5161
|
).action(
|
|
@@ -1840,20 +5355,20 @@ skills: ${context2.skills.map((s) => s.name).join(", ")}`);
|
|
|
1840
5355
|
`refusing to write: checkout-directory conflict${context2.conflicts.length === 1 ? "" : "s"} among the effective repos (${context2.conflicts.map((c) => `"${c.dir}": ${c.item_ids.join(", ")}`).join("; ")}); rename or re-dir the items first`
|
|
1841
5356
|
);
|
|
1842
5357
|
}
|
|
1843
|
-
if (
|
|
5358
|
+
if (existsSync3(opts.out) && readdirSync(opts.out).length > 0 && !opts.force) {
|
|
1844
5359
|
die(`refusing to write into non-empty directory ${opts.out} (pass --force to override)`);
|
|
1845
5360
|
}
|
|
1846
|
-
|
|
1847
|
-
writeFileSync3(
|
|
5361
|
+
mkdirSync4(opts.out, { recursive: true });
|
|
5362
|
+
writeFileSync3(join4(opts.out, "prompt.md"), context2.prompt.text ? `${context2.prompt.text}
|
|
1848
5363
|
` : "");
|
|
1849
5364
|
for (const skill of context2.skills) {
|
|
1850
5365
|
for (const file of skill.files) {
|
|
1851
|
-
const target =
|
|
1852
|
-
|
|
5366
|
+
const target = join4(opts.out, "skills", skill.name, file.path);
|
|
5367
|
+
mkdirSync4(dirname4(target), { recursive: true });
|
|
1853
5368
|
writeFileSync3(target, file.content);
|
|
1854
5369
|
}
|
|
1855
5370
|
}
|
|
1856
|
-
writeFileSync3(
|
|
5371
|
+
writeFileSync3(join4(opts.out, "repos.json"), `${JSON.stringify(context2.repos, null, 2)}
|
|
1857
5372
|
`);
|
|
1858
5373
|
console.log(
|
|
1859
5374
|
`wrote ${opts.out}/prompt.md, ${context2.skills.length} skill${context2.skills.length === 1 ? "" : "s"}, repos.json (${context2.repos.length} repo${context2.repos.length === 1 ? "" : "s"})`
|
|
@@ -1905,13 +5420,13 @@ var MIME_BY_EXT = {
|
|
|
1905
5420
|
mp4: "video/mp4",
|
|
1906
5421
|
webm: "video/webm"
|
|
1907
5422
|
};
|
|
1908
|
-
function sniffContentType(
|
|
1909
|
-
const ext =
|
|
5423
|
+
function sniffContentType(path2) {
|
|
5424
|
+
const ext = path2.match(/\.([A-Za-z0-9]+)$/)?.[1]?.toLowerCase();
|
|
1910
5425
|
return ext && MIME_BY_EXT[ext] || "application/octet-stream";
|
|
1911
5426
|
}
|
|
1912
5427
|
function prRefLabel(v) {
|
|
1913
|
-
const
|
|
1914
|
-
return `${
|
|
5428
|
+
const path2 = (v.pr_repo_url ?? "").replace(/^https:\/\/github\.com\//, "");
|
|
5429
|
+
return `${path2}#${v.pr_number}`;
|
|
1915
5430
|
}
|
|
1916
5431
|
function artifactSummary(a) {
|
|
1917
5432
|
const cv = a.current_version;
|
|
@@ -1932,11 +5447,11 @@ function walkFolder(dir) {
|
|
|
1932
5447
|
const files = [];
|
|
1933
5448
|
const walk = (abs, rel) => {
|
|
1934
5449
|
for (const entry of readdirSync(abs, { withFileTypes: true })) {
|
|
1935
|
-
const nextAbs =
|
|
5450
|
+
const nextAbs = join4(abs, entry.name);
|
|
1936
5451
|
const nextRel = rel ? `${rel}/${entry.name}` : entry.name;
|
|
1937
5452
|
if (entry.isDirectory()) walk(nextAbs, nextRel);
|
|
1938
5453
|
else if (entry.isFile()) {
|
|
1939
|
-
files.push({ path: nextRel, contentType: sniffContentType(entry.name), bytes:
|
|
5454
|
+
files.push({ path: nextRel, contentType: sniffContentType(entry.name), bytes: readFileSync4(nextAbs) });
|
|
1940
5455
|
}
|
|
1941
5456
|
}
|
|
1942
5457
|
};
|
|
@@ -2011,7 +5526,7 @@ withCommon(
|
|
|
2011
5526
|
const issue = await resolveIssue(api, ref);
|
|
2012
5527
|
let artifact;
|
|
2013
5528
|
if (opts.folder !== void 0) {
|
|
2014
|
-
if (!
|
|
5529
|
+
if (!existsSync3(opts.folder) || !statSync(opts.folder).isDirectory()) {
|
|
2015
5530
|
die(`--folder needs a directory, got "${opts.folder}"`);
|
|
2016
5531
|
}
|
|
2017
5532
|
const files = walkFolder(opts.folder);
|
|
@@ -2023,7 +5538,7 @@ withCommon(
|
|
|
2023
5538
|
} else if (opts.file !== void 0) {
|
|
2024
5539
|
let bytes;
|
|
2025
5540
|
try {
|
|
2026
|
-
bytes =
|
|
5541
|
+
bytes = readFileSync4(opts.file);
|
|
2027
5542
|
} catch (err) {
|
|
2028
5543
|
die(`cannot read ${opts.file}: ${err instanceof Error ? err.message : String(err)}`);
|
|
2029
5544
|
}
|
|
@@ -2100,7 +5615,7 @@ withCommon(
|
|
|
2100
5615
|
if (opts.out === void 0) {
|
|
2101
5616
|
die(`artifact "${name2}" is a folder \u2014 pass --out <dir> to write its tree`);
|
|
2102
5617
|
}
|
|
2103
|
-
if (
|
|
5618
|
+
if (existsSync3(opts.out) && !statSync(opts.out).isDirectory()) {
|
|
2104
5619
|
die(`--out for a folder must be a directory, and "${opts.out}" is a file`);
|
|
2105
5620
|
}
|
|
2106
5621
|
const files = version.files ?? [];
|
|
@@ -2110,8 +5625,8 @@ withCommon(
|
|
|
2110
5625
|
version: opts.version,
|
|
2111
5626
|
path: file.path
|
|
2112
5627
|
});
|
|
2113
|
-
const target2 =
|
|
2114
|
-
|
|
5628
|
+
const target2 = join4(opts.out, file.path);
|
|
5629
|
+
mkdirSync4(dirname4(target2), { recursive: true });
|
|
2115
5630
|
writeFileSync3(target2, Buffer.from(content2.bytes));
|
|
2116
5631
|
total += content2.bytes.byteLength;
|
|
2117
5632
|
}
|
|
@@ -2123,8 +5638,8 @@ withCommon(
|
|
|
2123
5638
|
const bytes = Buffer.from(content.bytes);
|
|
2124
5639
|
if (opts.out !== void 0) {
|
|
2125
5640
|
let target2 = opts.out;
|
|
2126
|
-
if (
|
|
2127
|
-
target2 =
|
|
5641
|
+
if (existsSync3(target2) && statSync(target2).isDirectory()) {
|
|
5642
|
+
target2 = join4(target2, version.filename ?? name2);
|
|
2128
5643
|
}
|
|
2129
5644
|
writeFileSync3(target2, bytes);
|
|
2130
5645
|
return console.log(`wrote ${target2} (${bytes.byteLength} bytes, ${content.content_type})`);
|
|
@@ -2232,7 +5747,7 @@ matched rule: ${ex.matched_rule.scope_label}`);
|
|
|
2232
5747
|
);
|
|
2233
5748
|
}
|
|
2234
5749
|
}
|
|
2235
|
-
var context =
|
|
5750
|
+
var context = program2.command("context").description("Manage context items (prompts, skills, repo pointers) scoped to projects, states, and issues");
|
|
2236
5751
|
var SCOPE_FLAGS_HELP = `
|
|
2237
5752
|
Scope flags (combinable \u2014 an item applies where ALL of its set dimensions match):
|
|
2238
5753
|
--project <name> only for issues in this project
|
|
@@ -2339,16 +5854,16 @@ withCommon(
|
|
|
2339
5854
|
if (current.kind !== "skill") die(`--file/--remove-file only apply to skills (this is a ${current.kind})`);
|
|
2340
5855
|
if (body.expected_version === void 0) body.expected_version = current.version;
|
|
2341
5856
|
const files = new Map((current.files ?? []).map((f) => [f.path, f.content]));
|
|
2342
|
-
for (const
|
|
2343
|
-
if (!files.delete(
|
|
2344
|
-
die(`no file "${
|
|
5857
|
+
for (const path2 of opts.removeFile) {
|
|
5858
|
+
if (!files.delete(path2)) {
|
|
5859
|
+
die(`no file "${path2}" in skill "${current.name}" (have: ${[...files.keys()].join(", ") || "none"})`);
|
|
2345
5860
|
}
|
|
2346
5861
|
}
|
|
2347
5862
|
for (const spec of opts.file) {
|
|
2348
5863
|
const f = parseFileSpec(spec);
|
|
2349
5864
|
files.set(f.path, f.content);
|
|
2350
5865
|
}
|
|
2351
|
-
body.files = [...files.entries()].map(([
|
|
5866
|
+
body.files = [...files.entries()].map(([path2, content]) => ({ path: path2, content }));
|
|
2352
5867
|
}
|
|
2353
5868
|
if (opts.url !== void 0) body.repo_url = opts.url;
|
|
2354
5869
|
if (opts.branch !== void 0) body.repo_branch = opts.branch === "" ? null : opts.branch;
|
|
@@ -2392,7 +5907,7 @@ withCommon(
|
|
|
2392
5907
|
`seeded global "${AGENT_GUIDELINES_NAME}" (${created.id}) \u2014 it now opens every launch prompt; edit it freely`
|
|
2393
5908
|
);
|
|
2394
5909
|
});
|
|
2395
|
-
var journal =
|
|
5910
|
+
var journal = program2.command("journal").description("An issue's stage journal: shared notes for its project + the stage your run was launched in");
|
|
2396
5911
|
var STATE_FLAG_HELP = "target this state's journal instead of your run's launch stage (options go BEFORE <ref>)";
|
|
2397
5912
|
async function journalItemAt(api, scope) {
|
|
2398
5913
|
const { items } = await api.listContext({
|
|
@@ -2506,7 +6021,7 @@ withCommon(
|
|
|
2506
6021
|
if (opts.json) return printJson(updated);
|
|
2507
6022
|
console.log(`rewrote the ${scope.label} journal (now v${updated.version})`);
|
|
2508
6023
|
});
|
|
2509
|
-
var schedules =
|
|
6024
|
+
var schedules = program2.command("schedules").description("Manage scheduled tasks (addressed as <project>/<name>)");
|
|
2510
6025
|
function scheduleRef(s) {
|
|
2511
6026
|
return `${s.project_name}/${s.name}`;
|
|
2512
6027
|
}
|
|
@@ -2675,7 +6190,7 @@ function runnerStatusLabel(runner) {
|
|
|
2675
6190
|
if (runner.status === "paused") return "paused";
|
|
2676
6191
|
return runner.online ? "online" : "offline";
|
|
2677
6192
|
}
|
|
2678
|
-
var runners =
|
|
6193
|
+
var runners = program2.command("runners").description("Manage the runner registry");
|
|
2679
6194
|
withCommon(runners.command("list").description("List runners")).action(async (opts) => {
|
|
2680
6195
|
const res = await client(opts).listRunners();
|
|
2681
6196
|
if (opts.json) return printJson(res);
|
|
@@ -2875,9 +6390,12 @@ withCommon(
|
|
|
2875
6390
|
console.log("drop it into the daemon machine's config \u2014 its next poll gets a 401 until it adopts the new token.");
|
|
2876
6391
|
}
|
|
2877
6392
|
});
|
|
2878
|
-
var runnerCmd =
|
|
6393
|
+
var runnerCmd = program2.command("runner").description("The local runner daemon");
|
|
2879
6394
|
withCommon(
|
|
2880
|
-
runnerCmd.command("daemon").description("Run the local runner daemon: register/reconnect, poll for assigned runs, execute them").option("--name <name>", "runner name, unique per user (default: this hostname)").option("--harness <harness>", "claude-code | codex | custom", "claude-code").option("--command <template>", "custom harness command template ({prompt_file}, {workspace}, {model})").option("--max-concurrent <n>", "maximum simultaneous runs", (v) => Number.parseInt(v, 10), 1).option("--poll-interval <seconds>", "seconds between polls", (v) => Number.parseInt(v, 10), 15)
|
|
6395
|
+
runnerCmd.command("daemon").description("Run the local runner daemon: register/reconnect, poll for assigned runs, execute them").option("--name <name>", "runner name, unique per user (default: this hostname)").option("--harness <harness>", "claude-code | codex | custom", "claude-code").option("--command <template>", "custom harness command template ({prompt_file}, {workspace}, {model})").option("--max-concurrent <n>", "maximum simultaneous runs", (v) => Number.parseInt(v, 10), 1).option("--poll-interval <seconds>", "seconds between polls", (v) => Number.parseInt(v, 10), 15).option(
|
|
6396
|
+
"--no-cli-refresh",
|
|
6397
|
+
"do not install/refresh the agent-facing tines CLI from npm (harnesses use the ambient PATH)"
|
|
6398
|
+
)
|
|
2881
6399
|
).action(
|
|
2882
6400
|
async (opts) => {
|
|
2883
6401
|
const harness = opts.harness.replaceAll("-", "_");
|
|
@@ -2902,11 +6420,12 @@ withCommon(
|
|
|
2902
6420
|
command: opts.command,
|
|
2903
6421
|
maxConcurrent: opts.maxConcurrent,
|
|
2904
6422
|
pollIntervalMs: opts.pollInterval * 1e3,
|
|
2905
|
-
configDir: defaultConfigDir()
|
|
6423
|
+
configDir: defaultConfigDir(),
|
|
6424
|
+
cliRefresh: opts.cliRefresh
|
|
2906
6425
|
});
|
|
2907
6426
|
}
|
|
2908
6427
|
);
|
|
2909
|
-
var runsCmd =
|
|
6428
|
+
var runsCmd = program2.command("runs").description("Agent runs: attempts at issues by runners");
|
|
2910
6429
|
function runRow(run) {
|
|
2911
6430
|
return [
|
|
2912
6431
|
run.id,
|
|
@@ -2983,7 +6502,7 @@ withCommon(
|
|
|
2983
6502
|
`canceled ${run.id}${run.issue_ref ? ` on ${issueRef(run.issue_ref)}` : ""} (was on ${run.runner_name})`
|
|
2984
6503
|
);
|
|
2985
6504
|
});
|
|
2986
|
-
var routing =
|
|
6505
|
+
var routing = program2.command("routing").description("Scoped routing rules: which runner takes which issues (most specific scope wins)");
|
|
2987
6506
|
async function resolveRoutingScope(api, opts) {
|
|
2988
6507
|
const projectId = opts.project !== void 0 ? (await resolveProject(api, opts.project)).id : null;
|
|
2989
6508
|
const stateId = opts.state !== void 0 ? (await resolveStateFlag(api, opts.state)).state.id : null;
|
|
@@ -3042,7 +6561,7 @@ withCommon(
|
|
|
3042
6561
|
await api.deleteRoutingRule(existing.id);
|
|
3043
6562
|
console.log(`cleared the ${existing.scope.label} rule`);
|
|
3044
6563
|
});
|
|
3045
|
-
var supervisor =
|
|
6564
|
+
var supervisor = program2.command("supervisor").description("The automation kill switch, quota policy, and attempt limit");
|
|
3046
6565
|
function quotaLabel(quota2, stateName) {
|
|
3047
6566
|
if (quota2.type === "global_cap") return `global cap: at most ${quota2.limit} concurrent runs`;
|
|
3048
6567
|
const overrides = Object.entries(quota2.overrides).map(
|
|
@@ -3140,7 +6659,7 @@ withCommon(
|
|
|
3140
6659
|
}
|
|
3141
6660
|
console.log(quotaLabel(settings.quota, (id) => stateNames.get(id) ?? id));
|
|
3142
6661
|
});
|
|
3143
|
-
var events =
|
|
6662
|
+
var events = program2.command("events").description("Read the activity log");
|
|
3144
6663
|
withList(
|
|
3145
6664
|
events.command("list").description("List activity events, newest first").option("-i, --issue <ref>", "filter to one issue (<project>/<number>)").option("-p, --project <name>", "filter by project name or id").option("-t, --type <type>", "filter by event type (e.g. issue.transitioned)")
|
|
3146
6665
|
).action(async (opts) => {
|
|
@@ -3162,7 +6681,7 @@ withList(
|
|
|
3162
6681
|
});
|
|
3163
6682
|
});
|
|
3164
6683
|
try {
|
|
3165
|
-
await
|
|
6684
|
+
await program2.parseAsync();
|
|
3166
6685
|
} catch (err) {
|
|
3167
6686
|
reportError(err);
|
|
3168
6687
|
}
|