Files
hose-use/src/cli/runner.ts
T

180 lines
6.4 KiB
TypeScript

import { VERSION_INFO, formatVersionLabel } from "../version.js";
import { parseArgs, stringOption, booleanOption, outputOptions, isJsonRequested } from "./parser.js";
import { printHelp, printJson, redactSensitiveText } from "./printer.js";
import { resolveCommandMetadata } from "./command-metadata.js";
import { classifyCliError } from "./errors.js";
import { initCorpRuntime } from "./helpers.js";
import { findCommandByArea, isStandingCommand } from "./registry.js";
import type { CliParsedArgs, CliResult, CliRunOptions } from "./types.js";
let runQueue = Promise.resolve<any>(undefined);
export function runCli(
rawArgs: string[],
options: CliRunOptions = {}
): Promise<CliResult> {
if (isStandingCommand(rawArgs)) {
return dispatchCli(rawArgs, options);
}
const run = runQueue.then(() => runCliOnce(rawArgs, options));
runQueue = run.then(
() => undefined,
() => undefined
);
return run;
}
async function runCliOnce(
rawArgs: string[],
options: CliRunOptions = {}
): Promise<CliResult> {
const stdoutChunks: string[] = [];
const stderrChunks: string[] = [];
const machineJson = isJsonRequested(rawArgs);
const originalLog = console.log;
const originalError = console.error;
console.log = (...values: unknown[]) => {
const line = values.map((v) => (typeof v === "string" ? v : String(v))).join(" ");
(machineJson ? stderrChunks : stdoutChunks).push(line);
};
console.error = (...values: unknown[]) => {
stderrChunks.push(values.map((v) => (typeof v === "string" ? v : String(v))).join(" "));
};
try {
const result = await dispatchCli(rawArgs, options);
const extraStdout = stdoutChunks.length ? `${stdoutChunks.join("\n")}\n` : "";
const extraStderr = stderrChunks.length ? `${stderrChunks.join("\n")}\n` : "";
const bodyStdout = result.preserveSensitiveStdout
? result.stdout || ""
: redactSensitiveText(result.stdout || "");
return {
stdout: redactSensitiveText(extraStdout) + bodyStdout,
stderr: redactSensitiveText(extraStderr + (result.stderr || "")),
exitCode: result.exitCode,
preserveSensitiveStdout: result.preserveSensitiveStdout,
};
} finally {
console.log = originalLog;
console.error = originalError;
}
}
function isHelpRequested(parsed: CliParsedArgs): boolean {
const normArea = (parsed.area || "").replace(/^-+/, "").toLowerCase();
if (normArea === "help" || normArea === "h" || normArea === "?" || parsed.action === "help") return true;
for (const [key, val] of Object.entries(parsed.options)) {
const normKey = key.replace(/^-+/, "").toLowerCase();
if (normKey === "help" || normKey === "h" || normKey === "?") {
if (val === true || val === "true" || val === "") return true;
}
}
return false;
}
function isVersionRequested(parsed: CliParsedArgs): boolean {
const normArea = (parsed.area || "").replace(/^-+/, "").toLowerCase();
if (normArea === "version" || normArea === "v") return true;
for (const [key, val] of Object.entries(parsed.options)) {
const normKey = key.replace(/^-+/, "").toLowerCase();
const localFlags = resolveCommandMetadata(parsed.area)?.metadata.flags;
if (key === "v" && localFlags?.v) continue;
if (key === "version" && localFlags?.version === "value" && typeof val !== "boolean") continue;
if (normKey === "version" || normKey === "v") {
if (val === true || val === "true" || val === "") return true;
}
}
return false;
}
function resolveHelpTarget(parsed: CliParsedArgs): string[] {
if (["help", "h", "?"].includes((parsed.area || "").toLowerCase())) {
return [parsed.action, parsed.args[0]].filter((value): value is string => Boolean(value));
}
return [parsed.area, parsed.action === "help" ? parsed.args[0] : parsed.action].filter((value): value is string => Boolean(value));
}
async function dispatchCli(rawArgs: string[], options: CliRunOptions = {}): Promise<CliResult> {
try {
return await dispatchParsedCli(rawArgs, options);
} catch (error) {
return cliErrorResult(error, isJsonRequested(rawArgs));
}
}
export function cliErrorResult(error: unknown, jsonMode: boolean): CliResult {
const message = redactSensitiveText(error instanceof Error ? error.message : String(error));
const classification = classifyCliError(error);
return {
stdout: jsonMode ? JSON.stringify({ error: true, message, exitCode: classification.exitCode, ...(classification.nextAction ? { nextAction: classification.nextAction } : {}) }, null, 2) : "",
stderr: jsonMode ? "" : `[ERROR] ${message}${classification.nextAction ? `\n下一步: ${classification.nextAction}` : ""}\n`,
exitCode: classification.exitCode,
};
}
async function dispatchParsedCli(
rawArgs: string[],
options: CliRunOptions = {}
): Promise<CliResult> {
const parsed = parseArgs(rawArgs);
const jsonMode = booleanOption(parsed.options, ["json", "j"]);
if (isHelpRequested(parsed)) {
const help = printHelp(resolveHelpTarget(parsed));
return {
stdout: jsonMode ? printJson({ help }) : `${help}\n`,
stderr: "",
exitCode: 0,
};
}
if (isVersionRequested(parsed)) {
return {
stdout: jsonMode ? printJson(VERSION_INFO) : `${formatVersionLabel("hose-use")}\n`,
stderr: "",
exitCode: 0,
};
}
const corpIdOption = stringOption(parsed.options, ["corp"]);
const statelessOption = booleanOption(parsed.options, ["stateless"]);
const statefulOption = booleanOption(parsed.options, ["stateful"]);
const outputOpts = outputOptions(parsed.options);
const dryRun = booleanOption(parsed.options, ["dry-run", "dryRun", "dryrun"]);
const confirmed = booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"]);
const runtime = initCorpRuntime({
corpId: corpIdOption,
stateless: statelessOption,
stateful: statefulOption,
jsonMode,
dryRun,
confirmed,
outputOptions: outputOpts,
appRoot: options.appRoot,
entryFile: options.entryFile,
launcher: options.launcher,
});
runtime.writeStdout = options.writeStdout;
try {
if (!parsed.area) {
return { stdout: printHelp(resolveHelpTarget(parsed)) + "\n", stderr: "", exitCode: 0 };
}
const commandDef = findCommandByArea(parsed.area);
if (!commandDef) {
return {
stdout: "",
stderr: `未知命令域: ${parsed.area}。运行 hose-use --help 查看帮助\n`,
exitCode: 1,
};
}
return await commandDef.handler(parsed, runtime, options);
} catch (error) {
return cliErrorResult(error, jsonMode);
}
}