引言
CLI 的体验由细节决定:命令是否可发现、错误是否可理解、默认行为是否安全、能否融入脚本。好的 CLI 让常见任务零参数完成,让危险操作必须显式确认。
命令结构与帮助
用清晰的动词和名词组织子命令,保持层级浅。帮助文本应回答“这个命令做什么、需要什么、会输出什么”,并提供示例。--help 必须在任何位置可用,退出码为 0。
默认值与错误
默认值应覆盖最常见场景,同时允许通过参数、环境变量和配置文件覆盖,并明确优先级。错误信息要指出哪个参数错了、期望什么、如何修复;用法错误与运行时失败使用不同退出码。stdout 只输出机器可读结果,诊断信息写 stderr。
补全与终端礼仪
为 bash、zsh 和 fish 提供补全脚本,降低记忆成本。检测 TTY 和颜色支持,在管道中关闭动画和颜色。尊重 NO_COLOR 和 CI 环境变量。
结论
优秀的 CLI 把复杂性留给自己,把可预测性留给用户。参数解析、帮助、退出码和输出流是一体化的契约,应像 API 一样测试。
代码示例
import { Command, Argument, Option } from "commander";
const program = new Command()
.name("mytool")
.description("Deploy and manage services")
.version("1.4.0");
program
.command("deploy")
.description("Deploy a service to an environment")
.addArgument(new Argument("<service>").argChoices(["api", "web", "worker"]))
.addOption(new Option("-e, --env <environment>", "target environment").choices(["staging", "production"]).makeOptionMandatory(true))
.addOption(new Option("--dry-run", "print the plan without deploying").default(false))
.addOption(new Option("--image <tag>", "image tag; defaults to latest git sha"))
.action(async (service, opts) => {
const tag = opts.image ?? (await gitSha());
console.log(`Deploying ${service}:${tag} to ${opts.env}${opts.dryRun ? " (dry run)" : ""}`);
});
program.parseAsync(process.argv);
program
.command("logs")
.description("Stream logs for a service (Ctrl-C to stop)")
.argument("<service>", "service name")
.option("-f, --follow", "follow new log lines", true)
.option("--since <duration>", "show logs since a duration (e.g. 30m, 2h)", "15m")
.option("--level <level>", "minimum level to show", "info")
.action(streamLogs);
program.exitOverride(); // throw instead of process.exit, so we can catch
try {
await program.parseAsync(process.argv);
} catch (err: any) {
if (err.code === "commander.helpDisplayed" || err.code === "commander.version") {
process.exit(0);
}
if (err.code === "commander.invalidArgument" || err.code === "commander.invalidOptionArgument") {
console.error(`error: ${err.message}`);
console.error(`run '${program.name()} ${err.command?.name() ?? ""} --help' for usage`);
process.exit(2); // 2: usage error (distinct from 1: runtime error)
}
console.error(`error: ${err.message ?? err}`);
if (process.argv.includes("--debug")) console.error(err.stack);
process.exit(1);
}
// Generate and print the completion script for the user's shell.
program
.command("completion")
.description("Print a shell completion script (source it in your shell rc)")
.argument("<shell>", "shell name", ["bash", "zsh", "fish"])
.action((shell) => {
console.log(generateCompletion(program, shell));
console.error(`\n# Install with: source <(mytool completion ${shell})`);
});
import { cosmiconfig } from "cosmiconfig";
async function loadConfig(explicitPath?: string) {
const explorer = cosmiconfig("mytool", { searchPlaces: [".mytoolrc", ".mytoolrc.json", "package.json"] });
const found = explicitPath ? await explorer.load(explicitPath) : await explorer.search();
return found?.config ?? {};
}
// Merge with precedence: defaults < env < config file < CLI flags.
function resolveConfig(fileConfig: object, cliFlags: object, env: NodeJS.ProcessEnv) {
return deepMerge(defaults, fromEnv(env), fileConfig, cliFlags);
}
interface Plugin {
name: string;
setup(ctx: PluginContext): void | (() => void); // setup returns an optional teardown
}
interface PluginContext {
config: Config;
logger: Logger;
registerCommand: (cmd: Command) => void;
beforeDeploy: (hook: () => Promise<void>) => void;
}
async function loadPlugins(names: string[], ctx: PluginContext): Promise<Plugin[]> {
const teardowns: Array<() => void> = [];
for (const name of names) {
const mod = await import(name);
const plugin: Plugin = mod.default ?? mod;
try {
const teardown = plugin.setup(ctx);
if (teardown) teardowns.push(teardown);
} catch (err) {
ctx.logger.error({ plugin: name, err: toLoggable(err) }, "plugin failed to load; skipping");
}
}
return teardowns;
}