88 lines
2.6 KiB
TypeScript
88 lines
2.6 KiB
TypeScript
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:
|
|
* 1. --dry-run only describes the intended change;
|
|
* 2. --yes/--confirm is required before the real operation runs.
|
|
*
|
|
* 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 CliError {
|
|
readonly operation: string;
|
|
|
|
constructor(operation: string, nextAction: string) {
|
|
super(
|
|
`拒绝执行${operation}:该操作会改变数据。请先使用 --dry-run 预览,确认后追加 --yes(或 --confirm)。`,
|
|
10,
|
|
nextAction
|
|
);
|
|
this.name = "MutationConfirmationRequired";
|
|
this.operation = operation;
|
|
}
|
|
}
|
|
|
|
export function isDryRun(parsed: CliParsedArgs, runtime: CliRuntime): boolean {
|
|
return runtime.dryRun === true || booleanOption(parsed.options, ["dry-run", "dryRun", "dryrun"]);
|
|
}
|
|
|
|
export function isConfirmed(parsed: CliParsedArgs, runtime: CliRuntime): boolean {
|
|
return (
|
|
runtime.confirmed === true ||
|
|
booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"])
|
|
);
|
|
}
|
|
|
|
export function requireMutationConfirmation(
|
|
parsed: CliParsedArgs,
|
|
runtime: CliRuntime,
|
|
operation: string,
|
|
nextAction: string
|
|
): void {
|
|
if (isDryRun(parsed, runtime) || isConfirmed(parsed, runtime)) return;
|
|
throw new MutationConfirmationRequired(operation, nextAction);
|
|
}
|
|
|
|
export function mutationPreview(
|
|
parsed: CliParsedArgs,
|
|
runtime: CliRuntime,
|
|
operation: string,
|
|
target: string,
|
|
changes: Record<string, unknown>
|
|
): CliResult {
|
|
const confirmedArgs = parsed.raw.filter((arg) => !["--dry-run", "--dryRun", "--dryrun"].includes(arg));
|
|
const nextAction = `hose-use ${confirmedArgs.join(" ")} --yes`;
|
|
const payload = {
|
|
dryRun: true,
|
|
operation,
|
|
target,
|
|
changes,
|
|
nextAction,
|
|
};
|
|
|
|
if (runtime.jsonMode) {
|
|
return {
|
|
stdout: `${JSON.stringify(payload, null, 2)}\n`,
|
|
stderr: "",
|
|
exitCode: 0,
|
|
};
|
|
}
|
|
|
|
const lines = [
|
|
"[DRY-RUN] 未执行任何写操作。",
|
|
`操作: ${operation}`,
|
|
`目标: ${target}`,
|
|
"变更:",
|
|
...Object.entries(changes).map(([key, value]) => ` ${key}: ${formatPreviewValue(value)}`),
|
|
`下一步: ${nextAction}`,
|
|
];
|
|
return { stdout: `${lines.join("\n")}\n`, stderr: "", exitCode: 0 };
|
|
}
|
|
|
|
function formatPreviewValue(value: unknown): string {
|
|
if (typeof value === "string") return value;
|
|
return JSON.stringify(value);
|
|
}
|