关于 building-clis
building-clis 是面向开发者的命令行界面构建技能,介绍 Python、Go 和 Rust 中的框架与实现模式。内容涵盖参数解析、配置、输出、Shell 补全及发布打包。
主要功能
- 01Python、Go、Rust 框架选型
- 02参数、选项与标志设计
- 03子命令与配置管理
- 04人类及机器可读输出
- 05交互提示与进度指示器
- 06Shell 补全和应用打包
适用场景
- 01为现有项目添加命令行功能
- 02构建基础设施管理工具
- 03实现 API 客户端命令行工具
- 04为自动化工具设计参数和配置
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ ancoleman/ ai-design-components --skill building-clis安装后在 Claude Code 中输入/building-clis确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
outputs.yamlexamples/go/cobra_basic.gocobra_subcommands.gocobra_viper.goexamples/python/test_cli.pytyper_basic.pytyper_config.pytyper_progress.pytyper_subcommands.pyexamples/rust/clap_builder.rsclap_derive.rsclap_subcommands.rsreferences/argument-patterns.mdconfiguration-management.mddistribution.mdframework-selection.mdoutput-formatting.mdshell-completion.mdsubcommand-design.md详细介绍
构建 CLI
使用现代框架在 Python、Go 和 Rust 中构建专业的命令行界面,支持可靠的参数解析、配置管理和 Shell 集成。
何时使用此技能
在以下情况下使用此技能:
- 构建开发者工具或自动化 CLI
- 创建基础设施管理工具(部署、监控)
- 实现 API 客户端命令行工具
- 为现有项目添加 CLI 功能
- 打包实用工具以供分发(PyPI、Homebrew、二进制发行版)
常见触发场景:“创建 CLI 工具”“构建命令行界面”“添加 CLI 参数”“解析命令行选项”“生成 Shell 补全”
框架选择
快速决策指南
Python 项目:
- Typer(推荐):现代、类型安全的 CLI,样板代码极少
- Click:成熟灵活,适用于复杂命令层级的 CLI
Go 项目:
- Cobra(推荐):企业级工具的行业标准(Kubernetes、Docker、GitHub CLI)
- urfave/cli:适用于简单 CLI 的轻量级替代方案
Rust 项目:
- clap v4(推荐):类型安全,提供 derive API,或提供具备运行时灵活性的 builder API
如需详细了解框架比较和选择标准,请参阅 references/framework-selection.md。
核心模式
参数、选项与标志
位置参数:
- 主要输入,根据位置识别
- 用于必需的输入(最多 2-3 个参数)
- 示例:
convert input.jpg output.png
选项:
- 带值的命名参数
- 用于配置和可选输入
- 示例:
--output file.txt、--config app.yaml
标志:
- 布尔选项(存在即为 true)
- 用于开关选项
- 示例:
--verbose、--dry-run、--force
决策矩阵:
| 用例 | 类型 | 示例 |
|---|---|---|
| 主要必需输入 | 位置参数 | git commit -m "message" |
| 可选配置 | 选项 | --config app.yaml |
| 布尔设置 | 标志 | --verbose、--force |
| 多个值 | 可变参数 | files... |
有关全面的解析模式,请参阅 references/argument-patterns.md。
子命令组织
扁平结构(1 层):
app command1 [args]
app command2 [args]
适用于:包含 5-10 个操作的小型 CLI
分组结构(2 层):
app group subcommand [args]
适用于:按逻辑分组的中型 CLI(10-30 个命令)
示例:kubectl get pods、kubectl create deployment
嵌套结构(3 层及以上):
app group subgroup command [args]
适用于:具有深层级结构的大型 CLI(30 个以上命令)
示例:gcloud compute instances create
有关结构设计策略,请参阅 references/subcommand-design.md。
配置管理
标准优先级(从高到低):
- CLI 参数/标志(用户显式输入)
- 环境变量(会话级覆盖)
- 配置文件 - 本地(
./config.yaml) - 配置文件 - 用户级(
~/.config/app/config.yaml) - 配置文件 - 系统级(
/etc/app/config.yaml) - 内置默认值(硬编码)
最佳实践:
- 在
--help中说明优先级 - 执行前验证配置文件
- 提供
--print-config以显示生效的配置 - 使用 XDG Base Directory(
~/.config/app/)存放配置文件
有关各种语言的实现模式,请参阅 references/configuration-management.md。
输出格式
格式选择:
| 用例 | 格式 | 时机 |
|---|---|---|
| 人工阅读 | 彩色文本、表格 | 默认交互模式 |
| 机器处理 | JSON、YAML | --output json、管道传输 |
| 日志/调试 | 纯文本 | --verbose、stderr |
| 进度跟踪 | 进度条、旋转指示器 | 耗时操作 |
最佳实践:
- 默认使用便于人工阅读的输出
- 提供
--output标志(json、yaml、table) - 日志写入 stderr,数据写入 stdout
- 自动检测 TTY(非交互模式下禁用颜色)
- 使用退出代码:0 = 成功,1 = 错误,2 = 用法错误
有关格式化策略,请参阅 references/output-formatting.md。
特定语言快速入门
使用 Typer 的 Python
安装:
pip install "typer[all]" # Includes rich for colored output
基本示例:
import typer
from typing import Annotated
app = typer.Typer()
@app.command()
def greet(
name: Annotated[str, typer.Argument(help="Name to greet")],
formal: Annotated[bool, typer.Option(help="Use formal greeting")] = False
):
"""Greet someone with a message."""
greeting = "Good day" if formal else "Hello"
typer.echo(f"{greeting}, {name}!")
if __name__ == "__main__":
app()
主要特性:
- 通过类型提示自动验证
- 使用装饰器减少样板代码
- 自动生成帮助文本
- 集成 Rich 实现彩色输出
请参阅 examples/python/,了解包含子命令、配置管理和交互功能的完整可运行示例。
使用 Cobra 的 Go
安装:
go get -u github.com/spf13/cobra@latest
基本示例:
var rootCmd = &cobra.Command{
Use: "greet [name]",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("Hello, %s!\n", args[0])
},
}
rootCmd.Flags().Bool("formal", false, "Use formal greeting")
rootCmd.Execute()
主要特性:
- 符合 POSIX 标准的标志
- 集成 Viper 进行配置管理
- 子命令架构
- 生成 Shell 补全
请参阅 examples/go/,了解包含 Viper 配置和多级子命令的完整可运行示例。
使用 clap 的 Rust
安装(Cargo.toml):
[dependencies]
clap = { version = "4.5", features = ["derive"] }
基本示例(Derive API):
use clap::Parser;
#[derive(Parser)]
#[command(about = "Greet someone")]
struct Cli {
/// Name to greet
name: String,
/// Use formal greeting
#[arg(long)]
formal: bool,
}
fn main() {
let cli = Cli::parse();
let greeting = if cli.formal { "Good day" } else { "Hello" };
println!("{}, {}!", greeting, cli.name);
}
主要特性:
- 编译时类型安全
- Derive API(声明式)或 Builder API(编程式)
- 全面的验证
- 针对性能进行了优化
请参阅 examples/rust/,了解包含子命令和 Builder API 模式的完整可运行示例。
交互功能
进度指示器
Python(rich):
from rich.progress import track
for _ in track(range(100), description="Processing..."):
time.sleep(0.01)
Go(progressbar):
import "github.com/schollz/progressbar/v3"
bar := progressbar.Default(100)
for i := 0; i < 100; i++ {
bar.Add(1)
}
Rust(indicatif):
use indicatif::ProgressBar;
let bar = ProgressBar::new(100);
for _ in 0..100 {
bar.inc(1);
}
提示与确认
Python:
confirm = typer.confirm("Are you sure?")
if not confirm:
raise typer.Abort()
Go:
reader := bufio.NewReader(os.Stdin)
fmt.Print("Are you sure? (y/n): ")
response, _ := reader.ReadString('\n')
Rust:
use dialoguer::Confirm;
if Confirm::new().with_prompt("Are you sure?").interact()? {
// Proceed
}
Shell 补全
生成补全脚本
Python(Typer):
_MYAPP_COMPLETE=bash_source myapp > ~/.myapp-complete.bash
_MYAPP_COMPLETE=zsh_source myapp > ~/.myapp-complete.zsh
Go(Cobra):
rootCmd.AddCommand(&cobra.Command{
Use: "completion [bash|zsh|fish|powershell]",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
switch args[0] {
case "bash":
rootCmd.GenBashCompletion(os.Stdout)
case "zsh":
rootCmd.GenZshCompletion(os.Stdout)
}
},
})
Rust(clap):
use clap_complete::{generate, shells::Bash};
generate(Bash, &mut Cli::command(), "myapp", &mut io::stdout())
有关安装说明,请参阅 references/shell-completion.md。
分发与打包
Python(PyPI)
pyproject.toml:
[project]
name = "myapp"
version = "1.0.0"
scripts = { myapp = "myapp.cli:app" }
发布:
pip install build twine
python -m build
twine upload dist/*
Go(Homebrew)
Formula:
class Myapp < Formula
desc "My CLI application"
url "https://github.com/user/myapp/archive/v1.0.0.tar.gz"
def install
system "go", "build", "-o", bin/"myapp"
end
end
Rust(Cargo)
发布:
cargo login
cargo publish
安装:
cargo install myapp
有关全面的打包策略(包括二进制发布),请参阅 references/distribution.md。
最佳实践
通用 CLI 约定
始终提供:
- 使用
--help和-h显示用法信息 - 使用
--version和-V显示版本 - 清晰的错误消息,并提供可执行的建议
参数处理:
- 使用
--分隔选项和位置参数 - 同时支持短格式(
-v)和长格式(--verbose) - 验证并清理所有用户输入
错误处理:
- 成功时退出代码为 0
- 一般错误时退出代码为 1
- 用法错误时退出代码为 2
- 错误写入 stderr,数据写入 stdout
交互性:
- 检测 TTY(交互输入还是管道输入)
- 提供
--yes/--force,以便自动化时跳过提示 - 操作耗时超过 2 秒时显示进度
配置最佳实践
文件格式:
- 统一使用 YAML、TOML 或 JSON
- 按环境(dev、staging、prod)分别使用不同文件
- 在 CI/CD 中使用
--check-config验证配置
密钥管理:
- 切勿将密钥提交到配置文件中
- 使用环境变量或密钥管理器
- 记录所需的环境变量
优先级:
- CLI 参数 > 环境变量 > 配置文件 > 默认值
- 在帮助文本中说明优先级
- 提供
--print-config以显示生效的配置
与其他技能集成
testing-strategies:
- 使用模拟和固定数据进行 CLI 测试
- 针对端到端工作流的集成测试
- 请参阅 examples/python/test_cli.py
building-ci-pipelines:
- 构建适用于多个平台的二进制文件
- 通过 GitHub Actions 自动发布
- 请参阅 references/distribution.md
api-patterns:
- 构建 API 客户端 CLI
- 身份验证和令牌管理
- 格式化 API 响应
secret-management:
- 安全存储凭据
- 集成环境变量
- 集成 Vault/密钥管理器
参考文件
决策框架:
- framework-selection.md - 如何选择框架
- argument-patterns.md - 参数、选项与标志
- subcommand-design.md - 组织命令层级结构
实现指南:
- configuration-management.md - 配置文件和优先级
- output-formatting.md - 面向人类与机器可读的输出
- shell-completion.md - 生成自动补全
- distribution.md - 打包和发布 CLI
代码示例:
- examples/python/ - Typer 示例(基础、子命令、配置、交互式)
- examples/go/ - Cobra 示例(基础、子命令、Viper 集成)
- examples/rust/ - clap 示例(derive、builder、子命令)
快速参考
框架建议:
- Python:Typer(现代)或 Click(成熟)
- Go:Cobra(企业级)或 urfave/cli(简单)
- Rust:clap v4(derive 或 builder)
常见模式:
- 参数:主要输入(最多 2–3 个)
- 选项:带值的命名参数
- 标志:布尔开关
- 子命令:将相关操作分组
- 配置:CLI 参数 > 环境变量 > 文件 > 默认值
输出规范:
- 默认:人类可读(带颜色、表格)
- 机器:通过
--output标志输出 JSON/YAML - 错误:stderr;数据:stdout
- 退出码:0 = 成功,1 = 错误,2 = 用法错误
分发:
- Python:PyPI(
pip install) - Go:Homebrew、二进制发布
- Rust:Cargo(
cargo install)、二进制发布