name: clap-scaffolder description: 使用派生宏、子命令和现代Rust模式生成基于Clap的Rust CLI应用程序。创建具有适当cargo结构的生产级Rust CLI。 allowed-tools: Read, Write, Edit, Bash, Glob, Grep
Clap脚手架工具
使用Clap、派生宏和最佳实践生成完整的CLI应用程序。
能力
- 使用派生宏生成基于Rust的Clap CLI项目
- 创建具有嵌套枚举的子命令层次结构
- 设置带有类型验证的参数解析
- 配置Shell自动补全生成
- 使用anyhow错误处理实现彩色输出
- 设置cargo工作区和构建配置
使用场景
在以下情况下调用此技能:
- 使用Clap引导新的CLI应用程序
- 创建具有类型安全参数解析的Rust CLI
- 利用派生宏进行声明式命令定义
- 构建快速、原生的跨平台二进制文件
输入参数
| 参数 | 类型 | 必填 | 描述 |
|---|---|---|---|
| projectName | 字符串 | 是 | CLI项目名称(kebab-case格式) |
| description | 字符串 | 是 | CLI的简短描述 |
| commands | 数组 | 否 | 要搭建的命令列表 |
| deriveFeatures | 数组 | 否 | 要启用的Clap派生功能 |
| colorOutput | 布尔值 | 否 | 启用彩色输出(默认:true) |
命令结构
{
"commands": [
{
"name": "run",
"description": "运行应用程序",
"args": [
{ "name": "target", "help": "运行目标", "required": true }
],
"options": [
{ "long": "watch", "short": "w", "help": "监听文件变化" },
{ "long": "port", "short": "p", "value_name": "PORT", "default": "3000" }
]
}
]
}
输出结构
<projectName>/
├── Cargo.toml
├── Cargo.lock
├── README.md
├── .gitignore
├── src/
│ ├── main.rs # 入口点
│ ├── cli.rs # Clap定义
│ ├── commands/
│ │ ├── mod.rs # 命令导出
│ │ └── <command>.rs # 单个命令
│ ├── config.rs # 配置
│ └── error.rs # 错误类型
├── tests/
│ └── cli.rs # CLI集成测试
└── completions/
├── _<projectName> # Zsh自动补全
├── <projectName>.bash # Bash自动补全
└── <projectName>.fish # Fish自动补全
生成的代码模式
CLI定义 (src/cli.rs)
use clap::{Parser, Subcommand, Args};
#[derive(Parser)]
#[command(name = "<projectName>")]
#[command(author, version, about, long_about = None)]
pub struct Cli {
/// 启用详细输出
#[arg(short, long, global = true)]
pub verbose: bool,
/// 配置文件路径
#[arg(short, long, global = true)]
pub config: Option<PathBuf>,
#[command(subcommand)]
pub command: Commands,
}
#[derive(Subcommand)]
pub enum Commands {
/// 运行应用程序
Run(RunArgs),
/// 构建项目
Build(BuildArgs),
/// 生成Shell自动补全
Completions {
/// 要生成自动补全的Shell
#[arg(value_enum)]
shell: clap_complete::Shell,
},
}
#[derive(Args)]
pub struct RunArgs {
/// 运行目标
pub target: String,
/// 监听文件变化
#[arg(short, long)]
pub watch: bool,
/// 使用的端口
#[arg(short, long, default_value = "3000")]
pub port: u16,
}
主入口 (src/main.rs)
use anyhow::Result;
use clap::Parser;
use colored::Colorize;
mod cli;
mod commands;
mod config;
mod error;
use cli::{Cli, Commands};
fn main() -> Result<()> {
let cli = Cli::parse();
// 根据详细程度设置日志
if cli.verbose {
env_logger::Builder::from_env(
env_logger::Env::default().default_filter_or("debug")
).init();
}
match cli.command {
Commands::Run(args) => commands::run::execute(args)?,
Commands::Build(args) => commands::build::execute(args)?,
Commands::Completions { shell } => {
generate_completions(shell);
}
}
Ok(())
}
命令实现
use anyhow::Result;
use colored::Colorize;
use crate::cli::RunArgs;
pub fn execute(args: RunArgs) -> Result<()> {
println!("{} 运行目标: {}", "→".blue(), args.target.green());
if args.watch {
println!("{} 监听模式已启用", "!".yellow());
}
println!("{} 监听端口 {}", "✓".green(), args.port);
Ok(())
}
依赖项
[package]
name = "<projectName>"
version = "0.1.0"
edition = "2021"
[dependencies]
clap = { version = "4.4", features = ["derive", "env"] }
clap_complete = "4.4"
anyhow = "1.0"
thiserror = "1.0"
colored = "2.0"
env_logger = "0.10"
log = "0.4"
[dev-dependencies]
assert_cmd = "2.0"
predicates = "3.0"
工作流程
- 验证输入 - 检查项目名称、命令结构
- 创建目录结构 - 设置Rust项目布局
- 生成Cargo.toml - 配置依赖项和元数据
- 创建CLI定义 - Clap派生结构体
- 生成命令 - 单个命令模块
- 创建实用工具 - 配置、错误处理
- 生成自动补全 - Shell自动补全脚本
- 设置测试 - CLI集成测试
应用的最佳实践
- 派生宏用于声明式定义
- Anyhow用于错误处理
- 彩色输出提供用户反馈
- 环境变量支持
- 内置自动补全生成
- 跨平台兼容
参考
- Clap文档: https://docs.rs/clap/
- Clap GitHub: https://github.com/clap-rs/clap
- Rust CLI书籍: https://rust-cli.github.io/book/
目标流程
- cli-application-bootstrap
- argument-parser-setup
- shell-completion-scripts