feat: add semantic CLI exit codes

This commit is contained in:
gitea committed 2026-09-11 17:11:51 +08:00
1 parent 45eb83a609
commit a5c0146c8d
5 files changed
+93 -10

No files matched your search

+58
View File
@@ -0,0 +1,58 @@
export type CliExitCode = 1 | 2 | 10 | 11 | 12;
export class CliError extends Error {
readonly exitCode: CliExitCode;
readonly nextAction?: string;
constructor(message: string, exitCode: CliExitCode, nextAction?: string) {
super(message);
this.name = "CliError";
this.exitCode = exitCode;
this.nextAction = nextAction;
}
}
export class PayloadTooLargeError extends CliError {
constructor(message: string, nextAction?: string) {
super(message, 12, nextAction);
this.name = "PayloadTooLargeError";
}
}
export function usageError(message: string, nextAction?: string): CliError {
return new CliError(message, 2, nextAction);
}
export function confirmationRequired(message: string, nextAction: string): CliError {
return new CliError(message, 10, nextAction);
}
export function classifyCliError(error: unknown): {
exitCode: CliExitCode;
nextAction?: string;
} {
if (error instanceof CliError) {
return { exitCode: error.exitCode, nextAction: error.nextAction };
}
const value = error instanceof Error ? error.message : String(error);
const status = responseStatus(error);
if (status === 401 || status === 403 || /(?:^|\s)(?:token|bearer|session) (?:expired|missing|invalid)/i.test(value)) {
return { exitCode: 11, nextAction: "hose-use auth login" };
}
if (/^(?:Usage:|用法:|未知(?:命令|.*子命令)|缺少|请提供|请指定|Invalid|Missing|required)/i.test(value)) {
return { exitCode: 2 };
}
if (/without --(?:yes|confirm)|请显式添加 --yes|需要 --(?:yes|confirm)/i.test(value)) {
return { exitCode: 10 };
}
return { exitCode: 1 };
}
function responseStatus(error: unknown): number | undefined {
if (!error || typeof error !== "object") return undefined;
const response = (error as { response?: unknown }).response;
if (!response || typeof response !== "object") return undefined;
const status = (response as { status?: unknown }).status;
return typeof status === "number" ? status : undefined;
}
+5 -4
View File
@@ -1,5 +1,6 @@
import { booleanOption } from "./parser.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "./types.js";
import { CliError } from "./errors.js";
/**
* All mutating CLI commands use the same two-step contract:
@@ -9,17 +10,17 @@ import type { CliParsedArgs, CliResult, CliRuntime } from "./types.js";
* The parsed-argument fallback keeps command handlers easy to unit-test without
* requiring every hand-built CliRuntime to include the newer fields.
*/
export class MutationConfirmationRequired extends Error {
export class MutationConfirmationRequired extends CliError {
readonly operation: string;
readonly nextAction: string;
constructor(operation: string, nextAction: string) {
super(
`拒绝执行${operation}:该操作会改变数据。请先使用 --dry-run 预览,确认后追加 --yes(或 --confirm)。\n下一步:${nextAction}`
`拒绝执行${operation}:该操作会改变数据。请先使用 --dry-run 预览,确认后追加 --yes(或 --confirm)。`,
10,
nextAction
);
this.name = "MutationConfirmationRequired";
this.operation = operation;
this.nextAction = nextAction;
}
}
+4 -2
View File
@@ -1,6 +1,7 @@
import { writeFileSync } from "node:fs";
import { VERSION } from "../version.js";
import type { OutputOptions } from "./types.js";
import { PayloadTooLargeError } from "./errors.js";
export const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
@@ -15,8 +16,9 @@ export function protectLargeOutput(result: unknown, options: OutputOptions = {})
if (options.allowFull || options.outputFile) return;
const bodyBytes = Buffer.byteLength(JSON.stringify(result), "utf-8");
if (bodyBytes > DEFAULT_OUTPUT_BYTES_LIMIT) {
throw new Error(
`输出体积过大 (${bodyBytes} 字节,超过安全阈值 ${DEFAULT_OUTPUT_BYTES_LIMIT} 字节)。请使用 --output-file <路径> (或 -o <路径>) 转储到本地文件;若确需完整大报文请附加 --full 参数。`
throw new PayloadTooLargeError(
`输出体积过大 (${bodyBytes} 字节,超过安全阈值 ${DEFAULT_OUTPUT_BYTES_LIMIT} 字节)。请使用 --output-file <路径> (或 -o <路径>) 转储到本地文件;若确需完整大报文请附加 --full 参数。`,
"hose-use <command> --json --output-file <path>"
);
}
}
+15
View File
@@ -60,4 +60,19 @@ describe("CLI runner - version and help aliases", () => {
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("未知命令域: unknown-command-xyz");
});
it("returns semantic confirmation exit code and nextAction", async () => {
const result = await runCli([
"rule",
"add",
"办公采购",
"采购时,[必须附采购合同]{硬性}。",
"--json",
]);
expect(result.exitCode).toBe(10);
const data = JSON.parse(result.stdout);
expect(data.exitCode).toBe(10);
expect(data.nextAction).toContain("--yes");
});
});
+11 -4
View File
@@ -1,6 +1,7 @@
import { VERSION } from "../version.js";
import { parseArgs, stringOption, booleanOption, outputOptions } from "./parser.js";
import { printHelp, printJson, redactSensitiveText } from "./printer.js";
import { classifyCliError } from "./errors.js";
import { initCorpRuntime } from "./helpers.js";
import { handleAuthCommand } from "./commands/auth.js";
import { handleCorpsCommand } from "./commands/corps.js";
@@ -279,17 +280,23 @@ async function dispatchCli(
}
} catch (error) {
const errorMsg = redactSensitiveText(error instanceof Error ? error.message : String(error));
const classification = classifyCliError(error);
if (jsonMode) {
return {
stdout: printJson({ error: true, message: errorMsg }),
stdout: JSON.stringify({
error: true,
message: errorMsg,
exitCode: classification.exitCode,
...(classification.nextAction ? { nextAction: classification.nextAction } : {}),
}, null, 2),
stderr: "",
exitCode: 1,
exitCode: classification.exitCode,
};
}
return {
stdout: "",
stderr: `[ERROR] ${errorMsg}\n`,
exitCode: 1,
stderr: `[ERROR] ${errorMsg}${classification.nextAction ? `\n下一步: ${classification.nextAction}` : ""}\n`,
exitCode: classification.exitCode,
};
}
}