[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6R13GV5TACNGP4GE9CZ0996":3,"skill-same:01M6R13GV5TACNGP4GE9CZ0996":67},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":46,"commitSha":47,"skillDirectory":48,"forksCount":49,"repositoryHtmlUrl":50,"repositoryHomepageUrl":6,"ownerHtmlUrl":51,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":52,"install":53,"resources":66},"01M6R13GV5TACNGP4GE9CZ0996","rust-cli-builder",null,"Plan and build production-ready Rust CLI tools using clap for argument parsing, with subcommands, config file support, colored output, and proper error handling. Uses interview-driven planning to clarify commands, input\u002Foutput formats, and distribution strategy before writing any code.","Mishit18\u002Fclaude-code-templates","Mishit18","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F244127857?v=4","01M6QXBYKWM76HSKYDNWSKKE41","Mishit Sharma","01M6QXBYRJ0CAVM51S1RTEKTZZ",1,"MIT","https:\u002F\u002Fgithub.com\u002FMishit18\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fdevelopment\u002Frust-cli-builder\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"cli","rust","rust cli builder","builder","cli builder","production-ready","writing","argument","command-line","error","line","distribution","ready","command","clarify","plan","devtools","code","support","terminal","2026-11-10 10:12:30",false,"---\nname: rust-cli-builder\ndescription: Plan and build production-ready Rust CLI tools using clap for argument parsing, with subcommands, config file support, colored output, and proper error handling. Uses interview-driven planning to clarify commands, input\u002Foutput formats, and distribution strategy before writing any code.\ntags: [rust, cli, clap, terminal, command-line, devtools]\n---\n\n# Rust CLI Tool Builder\n\n## When to use\n\nUse this skill when you need to:\n\n- Scaffold a new Rust CLI tool from scratch with clap\n- Add subcommands to an existing CLI application\n- Implement config file loading (TOML\u002FJSON\u002FYAML)\n- Set up proper error handling with anyhow\u002Fthiserror\n- Add colored and formatted terminal output\n- Structure a CLI project for distribution via cargo install or GitHub releases\n\n## Phase 1: Explore (Plan Mode)\n\nEnter plan mode. Before writing any code, explore the existing project:\n\n### If extending an existing project\n- Find `Cargo.toml` and check current dependencies (clap version, serde, tokio, etc.)\n- Locate the CLI entry point (`src\u002Fmain.rs` or `src\u002Fcli.rs`)\n- Check if clap is using derive macros or builder pattern\n- Identify existing subcommand structure\n- Look for existing error types, config structs, and output formatting\n- Check if there's a `src\u002Flib.rs` separating library logic from CLI\n\n### If starting from scratch\n- Check the workspace for any existing Rust projects or workspace `Cargo.toml`\n- Look for a `.cargo\u002Fconfig.toml` with custom settings\n- Check for `rust-toolchain.toml` to know the target Rust edition\n\n## Phase 2: Interview (AskUserQuestion)\n\nUse AskUserQuestion to clarify requirements. Ask in rounds.\n\n### Round 1: Tool purpose and commands\n\n```\nQuestion: \"What kind of CLI tool are you building?\"\nHeader: \"Tool type\"\nOptions:\n  - \"Single command (like ripgrep, curl)\" — One main action with flags and arguments\n  - \"Multi-command (like git, cargo)\" — Multiple subcommands under one binary\n  - \"Interactive REPL (like psql)\" — Persistent session with a prompt loop\n  - \"Pipeline tool (like jq, sed)\" — Reads stdin, transforms, writes stdout\n\nQuestion: \"What will the tool operate on?\"\nHeader: \"Input\"\nOptions:\n  - \"Files\u002Fdirectories\" — Read, process, or generate files\n  - \"Network\u002FAPI\" — HTTP requests, TCP connections, API calls\n  - \"System resources\" — Processes, hardware info, OS config\n  - \"Data streams (stdin\u002Fstdout)\" — Pipe-friendly text\u002Fbinary processing\n```\n\n### Round 2: Subcommands (if multi-command)\n\n```\nQuestion: \"Describe the subcommands you need (e.g., 'init', 'build', 'deploy')\"\nHeader: \"Commands\"\nOptions:\n  - \"2-3 subcommands (I'll describe them)\" — Small focused tool\n  - \"4-8 subcommands with groups\" — Medium tool, may need command groups\n  - \"I have a rough list, help me design the API\" — Collaborative command design\n```\n\n### Round 3: Configuration and output\n\n```\nQuestion: \"How should the tool be configured?\"\nHeader: \"Config\"\nOptions:\n  - \"CLI flags only (Recommended)\" — All config via command-line arguments\n  - \"Config file (TOML)\" — Load defaults from ~\u002F.config\u002Ftoolname\u002Fconfig.toml\n  - \"Config file + CLI overrides\" — Config file for defaults, flags override specific values\n  - \"Environment variables + flags\" — Env vars for secrets, flags for everything else\n\nQuestion: \"What output format does the tool need?\"\nHeader: \"Output\"\nOptions:\n  - \"Human-readable (colored text)\" — Pretty terminal output with colors and formatting\n  - \"Machine-readable (JSON)\" — Structured output for piping to other tools\n  - \"Both (--format flag)\" — Default human, --json or --format=json for machines\n  - \"Minimal (exit codes only)\" — Success\u002Ffailure via exit code, errors to stderr\n```\n\n### Round 4: Async and error handling\n\n```\nQuestion: \"Does the tool need async operations?\"\nHeader: \"Async\"\nOptions:\n  - \"No — synchronous is fine (Recommended)\" — File I\u002FO, computation, simple operations\n  - \"Yes — tokio (network I\u002FO)\" — HTTP requests, concurrent connections, async file I\u002FO\n  - \"Yes — tokio multi-threaded\" — Heavy parallelism, multiple concurrent tasks\n\nQuestion: \"How should errors be presented to users?\"\nHeader: \"Errors\"\nOptions:\n  - \"Simple messages (anyhow) (Recommended)\" — Human-readable error chains, good for most CLIs\n  - \"Typed errors (thiserror)\" — Custom error enum with specific variants for each failure\n  - \"Both (thiserror for lib, anyhow for bin)\" — Library code is typed, CLI wraps with anyhow\n```\n\n## Phase 3: Plan (ExitPlanMode)\n\nWrite a concrete implementation plan covering:\n\n1. **Project structure** — `Cargo.toml` dependencies, `src\u002F` file layout\n2. **CLI definition** — clap derive structs for all commands, args, and flags\n3. **Config loading** — config file format and merge strategy with CLI args\n4. **Core logic** — main functions for each subcommand, separated from CLI layer\n5. **Error types** — error enum or anyhow usage, user-facing error messages\n6. **Output formatting** — colored output, JSON mode, progress indicators\n7. **Tests** — unit tests for core logic, integration tests for CLI behavior\n\nPresent via ExitPlanMode for user approval.\n\n## Phase 4: Execute\n\nAfter approval, implement following this order:\n\n### Step 1: Project setup (Cargo.toml)\n\n```toml\n[package]\nname = \"toolname\"\nversion = \"0.1.0\"\nedition = \"2021\"\ndescription = \"Short description of the tool\"\n\n[dependencies]\nclap = { version = \"4\", features = [\"derive\", \"env\"] }\nserde = { version = \"1\", features = [\"derive\"] }\nanyhow = \"1\"\n# Add based on interview:\n# thiserror = \"2\"              # if typed errors\n# tokio = { version = \"1\", features = [\"full\"] }  # if async\n# serde_json = \"1\"             # if JSON output\n# toml = \"0.8\"                 # if TOML config\n# colored = \"2\"                # if colored output\n# indicatif = \"0.17\"           # if progress bars\n# dirs = \"5\"                   # if config file (~\u002F.config\u002F)\n```\n\n### Step 2: CLI definition with clap derive\n\n```rust\nuse clap::{Parser, Subcommand};\n\n\u002F\u002F\u002F Short one-line description of the tool\n#[derive(Parser, Debug)]\n#[command(name = \"toolname\", version, about, long_about = None)]\npub struct Cli {\n    \u002F\u002F\u002F Increase verbosity (-v, -vv, -vvv)\n    #[arg(short, long, action = clap::ArgAction::Count, global = true)]\n    pub verbose: u8,\n\n    \u002F\u002F\u002F Output format\n    #[arg(long, default_value = \"text\", global = true)]\n    pub format: OutputFormat,\n\n    \u002F\u002F\u002F Path to config file\n    #[arg(long, global = true)]\n    pub config: Option\u003Cstd::path::PathBuf>,\n\n    #[command(subcommand)]\n    pub command: Commands,\n}\n\n#[derive(Subcommand, Debug)]\npub enum Commands {\n    \u002F\u002F\u002F Initialize a new project\n    Init {\n        \u002F\u002F\u002F Project name\n        name: String,\n\n        \u002F\u002F\u002F Template to use\n        #[arg(short, long, default_value = \"default\")]\n        template: String,\n    },\n\n    \u002F\u002F\u002F Build the project\n    Build {\n        \u002F\u002F\u002F Build in release mode\n        #[arg(short, long)]\n        release: bool,\n\n        \u002F\u002F\u002F Target directory\n        #[arg(short, long)]\n        output: Option\u003Cstd::path::PathBuf>,\n    },\n\n    \u002F\u002F\u002F Show project status\n    Status,\n}\n\n#[derive(clap::ValueEnum, Clone, Debug)]\npub enum OutputFormat {\n    Text,\n    Json,\n}\n```\n\n### Step 3: Error handling\n\n```rust\n\u002F\u002F With anyhow (simple approach):\nuse anyhow::{Context, Result};\n\nfn load_config(path: &Path) -> Result\u003CConfig> {\n    let content = std::fs::read_to_string(path)\n        .with_context(|| format!(\"Failed to read config file: {}\", path.display()))?;\n    let config: Config = toml::from_str(&content)\n        .context(\"Invalid TOML in config file\")?;\n    Ok(config)\n}\n\n\u002F\u002F With thiserror (typed approach):\nuse thiserror::Error;\n\n#[derive(Error, Debug)]\npub enum AppError {\n    #[error(\"Config file not found: {path}\")]\n    ConfigNotFound { path: std::path::PathBuf },\n\n    #[error(\"Invalid config: {0}\")]\n    InvalidConfig(#[from] toml::de::Error),\n\n    #[error(\"Network error: {0}\")]\n    Network(#[from] reqwest::Error),\n\n    #[error(\"{0}\")]\n    Custom(String),\n}\n```\n\n### Step 4: Config file loading\n\n```rust\nuse serde::Deserialize;\nuse std::path::{Path, PathBuf};\n\n#[derive(Deserialize, Debug, Default)]\npub struct Config {\n    pub default_template: Option\u003CString>,\n    pub output_dir: Option\u003CPathBuf>,\n    \u002F\u002F ... fields from interview\n}\n\nimpl Config {\n    pub fn load(explicit_path: Option\u003C&Path>) -> anyhow::Result\u003CSelf> {\n        let path = match explicit_path {\n            Some(p) => p.to_path_buf(),\n            None => Self::default_path(),\n        };\n\n        if !path.exists() {\n            return Ok(Config::default());\n        }\n\n        let content = std::fs::read_to_string(&path)?;\n        let config: Config = toml::from_str(&content)?;\n        Ok(config)\n    }\n\n    fn default_path() -> PathBuf {\n        dirs::config_dir()\n            .unwrap_or_else(|| PathBuf::from(\".\"))\n            .join(\"toolname\")\n            .join(\"config.toml\")\n    }\n}\n```\n\n### Step 5: Colored output and formatting\n\n```rust\nuse colored::Colorize;\n\npub struct Output {\n    format: OutputFormat,\n    verbose: u8,\n}\n\nimpl Output {\n    pub fn new(format: OutputFormat, verbose: u8) -> Self {\n        Self { format, verbose }\n    }\n\n    pub fn success(&self, msg: &str) {\n        match self.format {\n            OutputFormat::Text => eprintln!(\"{} {}\", \"✓\".green().bold(), msg),\n            OutputFormat::Json => {} \u002F\u002F JSON output goes to stdout only\n        }\n    }\n\n    pub fn error(&self, msg: &str) {\n        match self.format {\n            OutputFormat::Text => eprintln!(\"{} {}\", \"✗\".red().bold(), msg),\n            OutputFormat::Json => {\n                let err = serde_json::json!({\"error\": msg});\n                println!(\"{}\", serde_json::to_string(&err).unwrap());\n            }\n        }\n    }\n\n    pub fn info(&self, msg: &str) {\n        if self.verbose >= 1 {\n            match self.format {\n                OutputFormat::Text => eprintln!(\"{} {}\", \"ℹ\".blue(), msg),\n                OutputFormat::Json => {}\n            }\n        }\n    }\n\n    pub fn data\u003CT: serde::Serialize>(&self, data: &T) {\n        match self.format {\n            OutputFormat::Text => {\n                \u002F\u002F Pretty print for humans — customize per subcommand\n                println!(\"{:#?}\", data);\n            }\n            OutputFormat::Json => {\n                println!(\"{}\", serde_json::to_string_pretty(data).unwrap());\n            }\n        }\n    }\n}\n```\n\n### Step 6: Main entry point\n\n```rust\nuse clap::Parser;\n\nfn main() -> anyhow::Result\u003C()> {\n    let cli = Cli::parse();\n    let config = Config::load(cli.config.as_deref())?;\n    let output = Output::new(cli.format.clone(), cli.verbose);\n\n    match cli.command {\n        Commands::Init { name, template } => {\n            cmd_init(&name, &template, &config, &output)?;\n        }\n        Commands::Build { release, output_dir } => {\n            let dir = output_dir\n                .or(config.output_dir.clone())\n                .unwrap_or_else(|| PathBuf::from(\".\u002Fdist\"));\n            cmd_build(release, &dir, &output)?;\n        }\n        Commands::Status => {\n            cmd_status(&config, &output)?;\n        }\n    }\n\n    Ok(())\n}\n\n\u002F\u002F If async (tokio):\n\u002F\u002F #[tokio::main]\n\u002F\u002F async fn main() -> anyhow::Result\u003C()> { ... }\n```\n\n### Step 7: Subcommand implementations\n\n```rust\nfn cmd_init(name: &str, template: &str, config: &Config, out: &Output) -> anyhow::Result\u003C()> {\n    let template = if template == \"default\" {\n        config.default_template.as_deref().unwrap_or(\"default\")\n    } else {\n        template\n    };\n\n    out.info(&format!(\"Using template: {}\", template));\n\n    let project_dir = Path::new(name);\n    if project_dir.exists() {\n        anyhow::bail!(\"Directory '{}' already exists\", name);\n    }\n\n    std::fs::create_dir_all(project_dir)?;\n    \u002F\u002F ... scaffold project files based on template\n\n    out.success(&format!(\"Created project '{}' with template '{}'\", name, template));\n    Ok(())\n}\n```\n\n### Step 8: Tests\n\n```rust\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn test_config_default() {\n        let config = Config::default();\n        assert!(config.default_template.is_none());\n    }\n\n    #[test]\n    fn test_config_parse_toml() {\n        let toml_str = r#\"\n            default_template = \"react\"\n            output_dir = \".\u002Fbuild\"\n        \"#;\n        let config: Config = toml::from_str(toml_str).unwrap();\n        assert_eq!(config.default_template.unwrap(), \"react\");\n    }\n}\n\n\u002F\u002F Integration tests (tests\u002Fcli.rs):\nuse assert_cmd::Command;\nuse predicates::prelude::*;\n\n#[test]\nfn test_help_flag() {\n    Command::cargo_bin(\"toolname\")\n        .unwrap()\n        .arg(\"--help\")\n        .assert()\n        .success()\n        .stdout(predicate::str::contains(\"Usage:\"));\n}\n\n#[test]\nfn test_version_flag() {\n    Command::cargo_bin(\"toolname\")\n        .unwrap()\n        .arg(\"--version\")\n        .assert()\n        .success();\n}\n\n#[test]\nfn test_init_creates_directory() {\n    let dir = tempfile::tempdir().unwrap();\n    let project_name = dir.path().join(\"test-project\");\n\n    Command::cargo_bin(\"toolname\")\n        .unwrap()\n        .args([\"init\", project_name.to_str().unwrap()])\n        .assert()\n        .success();\n\n    assert!(project_name.exists());\n}\n\n#[test]\nfn test_init_existing_directory_fails() {\n    let dir = tempfile::tempdir().unwrap();\n\n    Command::cargo_bin(\"toolname\")\n        .unwrap()\n        .args([\"init\", dir.path().to_str().unwrap()])\n        .assert()\n        .failure()\n        .stderr(predicate::str::contains(\"already exists\"));\n}\n\n#[test]\nfn test_json_output_format() {\n    Command::cargo_bin(\"toolname\")\n        .unwrap()\n        .args([\"--format\", \"json\", \"status\"])\n        .assert()\n        .success()\n        .stdout(predicate::str::starts_with(\"{\"));\n}\n```\n\n## Project structure reference\n\n```\ntoolname\u002F\n├── Cargo.toml\n├── src\u002F\n│   ├── main.rs          # Entry point, CLI parsing, command dispatch\n│   ├── cli.rs           # Clap derive structs (Cli, Commands, Args)\n│   ├── config.rs        # Config file loading and merging\n│   ├── output.rs        # Output formatting (text\u002FJSON\u002Fcolored)\n│   ├── error.rs         # Error types (if using thiserror)\n│   └── commands\u002F\n│       ├── mod.rs\n│       ├── init.rs      # Init subcommand logic\n│       ├── build.rs     # Build subcommand logic\n│       └── status.rs    # Status subcommand logic\n└── tests\u002F\n    └── cli.rs           # Integration tests with assert_cmd\n```\n\n## Best practices\n\n### Separate CLI from logic\nKeep clap structs and argument parsing in `cli.rs`. Put business logic in `commands\u002F`. This makes the core logic testable without invoking the CLI.\n\n### Use stderr for status, stdout for data\nHuman-readable messages (progress, success, errors) go to `stderr`. Machine-readable data goes to `stdout`. This lets users pipe output cleanly: `toolname status --format json | jq '.items'`.\n\n### Respect NO_COLOR\nCheck the `NO_COLOR` environment variable and disable colors when set:\n```rust\nif std::env::var(\"NO_COLOR\").is_ok() {\n    colored::control::set_override(false);\n}\n```\n\n### Exit codes\nUse meaningful exit codes: 0 for success, 1 for general errors, 2 for usage errors (clap handles this automatically).\n\n### Dev dependencies for testing\n\n```toml\n[dev-dependencies]\nassert_cmd = \"2\"\npredicates = \"3\"\ntempfile = \"3\"\n```\n\n## Checklist before finishing\n\n- [ ] `clap` derive structs have doc comments (they become --help text)\n- [ ] All subcommands have short and long descriptions\n- [ ] Config file has sensible defaults and doesn't error when missing\n- [ ] `--format json` outputs valid, parseable JSON to stdout\n- [ ] Errors show context (file paths, what went wrong, how to fix it)\n- [ ] Integration tests verify CLI behavior end-to-end\n- [ ] `cargo clippy` passes with no warnings\n- [ ] `cargo fmt` has been run\n\n","# Rust CLI Tool Builder\n\n## When to use\n\nUse this skill when you need to:\n\n- Scaffold a new Rust CLI tool from scratch with clap\n- Add subcommands to an existing CLI application\n- Implement config file loading (TOML\u002FJSON\u002FYAML)\n- Set up proper error handling with anyhow\u002Fthiserror\n- Add colored and formatted terminal output\n- Structure a CLI project for distribution via cargo install or GitHub releases\n\n## Phase 1: Explore (Plan Mode)\n\nEnter plan mode. Before writing any code, explore the existing project:\n\n### If extending an existing project\n- Find `Cargo.toml` and check current dependencies (clap version, serde, tokio, etc.)\n- Locate the CLI entry point (`src\u002Fmain.rs` or `src\u002Fcli.rs`)\n- Check if clap is using derive macros or builder pattern\n- Identify existing subcommand structure\n- Look for existing error types, config structs, and output formatting\n- Check if there's a `src\u002Flib.rs` separating library logic from CLI\n\n### If starting from scratch\n- Check the workspace for any existing Rust projects or workspace `Cargo.toml`\n- Look for a `.cargo\u002Fconfig.toml` with custom settings\n- Check for `rust-toolchain.toml` to know the target Rust edition\n\n## Phase 2: Interview (AskUserQuestion)\n\nUse AskUserQuestion to clarify requirements. Ask in rounds.\n\n### Round 1: Tool purpose and commands\n\n```\nQuestion: \"What kind of CLI tool are you building?\"\nHeader: \"Tool type\"\nOptions:\n  - \"Single command (like ripgrep, curl)\" — One main action with flags and arguments\n  - \"Multi-command (like git, cargo)\" — Multiple subcommands under one binary\n  - \"Interactive REPL (like psql)\" — Persistent session with a prompt loop\n  - \"Pipeline tool (like jq, sed)\" — Reads stdin, transforms, writes stdout\n\nQuestion: \"What will the tool operate on?\"\nHeader: \"Input\"\nOptions:\n  - \"Files\u002Fdirectories\" — Read, process, or generate files\n  - \"Network\u002FAPI\" — HTTP requests, TCP connections, API calls\n  - \"System resources\" — Processes, hardware info, OS config\n  - \"Data streams (stdin\u002Fstdout)\" — Pipe-friendly text\u002Fbinary processing\n```\n\n### Round 2: Subcommands (if multi-command)\n\n```\nQuestion: \"Describe the subcommands you need (e.g., 'init', 'build', 'deploy')\"\nHeader: \"Commands\"\nOptions:\n  - \"2-3 subcommands (I'll describe them)\" — Small focused tool\n  - \"4-8 subcommands with groups\" — Medium tool, may need command groups\n  - \"I have a rough list, help me design the API\" — Collaborative command design\n```\n\n### Round 3: Configuration and output\n\n```\nQuestion: \"How should the tool be configured?\"\nHeader: \"Config\"\nOptions:\n  - \"CLI flags only (Recommended)\" — All config via command-line arguments\n  - \"Config file (TOML)\" — Load defaults from ~\u002F.config\u002Ftoolname\u002Fconfig.toml\n  - \"Config file + CLI overrides\" — Config file for defaults, flags override specific values\n  - \"Environment variables + flags\" — Env vars for secrets, flags for everything else\n\nQuestion: \"What output format does the tool need?\"\nHeader: \"Output\"\nOptions:\n  - \"Human-readable (colored text)\" — Pretty terminal output with colors and formatting\n  - \"Machine-readable (JSON)\" — Structured output for piping to other tools\n  - \"Both (--format flag)\" — Default human, --json or --format=json for machines\n  - \"Minimal (exit codes only)\" — Success\u002Ffailure via exit code, errors to stderr\n```\n\n### Round 4: Async and error handling\n\n```\nQuestion: \"Does the tool need async operations?\"\nHeader: \"Async\"\nOptions:\n  - \"No — synchronous is fine (Recommended)\" — File I\u002FO, computation, simple operations\n  - \"Yes — tokio (network I\u002FO)\" — HTTP requests, concurrent connections, async file I\u002FO\n  - \"Yes — tokio multi-threaded\" — Heavy parallelism, multiple concurrent tasks\n\nQuestion: \"How should errors be presented to users?\"\nHeader: \"Errors\"\nOptions:\n  - \"Simple messages (anyhow) (Recommended)\" — Human-readable error chains, good for most CLIs\n  - \"Typed errors (thiserror)\" — Custom error enum with specific variants for each failure\n  - \"Both (thiserror for lib, anyhow for bin)\" — Library code is typed, CLI wraps with anyhow\n```\n\n## Phase 3: Plan (ExitPlanMode)\n\nWrite a concrete implementation plan covering:\n\n1. **Project structure** — `Cargo.toml` dependencies, `src\u002F` file layout\n2. **CLI definition** — clap derive structs for all commands, args, and flags\n3. **Config loading** — config file format and merge strategy with CLI args\n4. **Core logic** — main functions for each subcommand, separated from CLI layer\n5. **Error types** — error enum or anyhow usage, user-facing error messages\n6. **Output formatting** — colored output, JSON mode, progress indicators\n7. **Tests** — unit tests for core logic, integration tests for CLI behavior\n\nPresent via ExitPlanMode for user approval.\n\n## Phase 4: Execute\n\nAfter approval, implement following this order:\n\n### Step 1: Project setup (Cargo.toml)\n\n```toml\n[package]\nname = \"toolname\"\nversion = \"0.1.0\"\nedition = \"2021\"\ndescription = \"Short description of the tool\"\n\n[dependencies]\nclap = { version = \"4\", features = [\"derive\", \"env\"] }\nserde = { version = \"1\", features = [\"derive\"] }\nanyhow = \"1\"\n# Add based on interview:\n# thiserror = \"2\"              # if typed errors\n# tokio = { version = \"1\", features = [\"full\"] }  # if async\n# serde_json = \"1\"             # if JSON output\n# toml = \"0.8\"                 # if TOML config\n# colored = \"2\"                # if colored output\n# indicatif = \"0.17\"           # if progress bars\n# dirs = \"5\"                   # if config file (~\u002F.config\u002F)\n```\n\n### Step 2: CLI definition with clap derive\n\n```rust\nuse clap::{Parser, Subcommand};\n\n\u002F\u002F\u002F Short one-line description of the tool\n#[derive(Parser, Debug)]\n#[command(name = \"toolname\", version, about, long_about = None)]\npub struct Cli {\n    \u002F\u002F\u002F Increase verbosity (-v, -vv, -vvv)\n    #[arg(short, long, action = clap::ArgAction::Count, global = true)]\n    pub verbose: u8,\n\n    \u002F\u002F\u002F Output format\n    #[arg(long, default_value = \"text\", global = true)]\n    pub format: OutputFormat,\n\n    \u002F\u002F\u002F Path to config file\n    #[arg(long, global = true)]\n    pub config: Option\u003Cstd::path::PathBuf>,\n\n    #[command(subcommand)]\n    pub command: Commands,\n}\n\n#[derive(Subcommand, Debug)]\npub enum Commands {\n    \u002F\u002F\u002F Initialize a new project\n    Init {\n        \u002F\u002F\u002F Project name\n        name: String,\n\n        \u002F\u002F\u002F Template to use\n        #[arg(short, long, default_value = \"default\")]\n        template: String,\n    },\n\n    \u002F\u002F\u002F Build the project\n    Build {\n        \u002F\u002F\u002F Build in release mode\n        #[arg(short, long)]\n        release: bool,\n\n        \u002F\u002F\u002F Target directory\n        #[arg(short, long)]\n        output: Option\u003Cstd::path::PathBuf>,\n    },\n\n    \u002F\u002F\u002F Show project status\n    Status,\n}\n\n#[derive(clap::ValueEnum, Clone, Debug)]\npub enum OutputFormat {\n    Text,\n    Json,\n}\n```\n\n### Step 3: Error handling\n\n```rust\n\u002F\u002F With anyhow (simple approach):\nuse anyhow::{Context, Result};\n\nfn load_config(path: &Path) -> Result\u003CConfig> {\n    let content = std::fs::read_to_string(path)\n        .with_context(|| format!(\"Failed to read config file: {}\", path.display()))?;\n    let config: Config = toml::from_str(&content)\n        .context(\"Invalid TOML in config file\")?;\n    Ok(config)\n}\n\n\u002F\u002F With thiserror (typed approach):\nuse thiserror::Error;\n\n#[derive(Error, Debug)]\npub enum AppError {\n    #[error(\"Config file not found: {path}\")]\n    ConfigNotFound { path: std::path::PathBuf },\n\n    #[error(\"Invalid config: {0}\")]\n    InvalidConfig(#[from] toml::de::Error),\n\n    #[error(\"Network error: {0}\")]\n    Network(#[from] reqwest::Error),\n\n    #[error(\"{0}\")]\n    Custom(String),\n}\n```\n\n### Step 4: Config file loading\n\n```rust\nuse serde::Deserialize;\nuse std::path::{Path, PathBuf};\n\n#[derive(Deserialize, Debug, Default)]\npub struct Config {\n    pub default_template: Option\u003CString>,\n    pub output_dir: Option\u003CPathBuf>,\n    \u002F\u002F ... fields from interview\n}\n\nimpl Config {\n    pub fn load(explicit_path: Option\u003C&Path>) -> anyhow::Result\u003CSelf> {\n        let path = match explicit_path {\n            Some(p) => p.to_path_buf(),\n            None => Self::default_path(),\n        };\n\n        if !path.exists() {\n            return Ok(Config::default());\n        }\n\n        let content = std::fs::read_to_string(&path)?;\n        let config: Config = toml::from_str(&content)?;\n        Ok(config)\n    }\n\n    fn default_path() -> PathBuf {\n        dirs::config_dir()\n            .unwrap_or_else(|| PathBuf::from(\".\"))\n            .join(\"toolname\")\n            .join(\"config.toml\")\n    }\n}\n```\n\n### Step 5: Colored output and formatting\n\n```rust\nuse colored::Colorize;\n\npub struct Output {\n    format: OutputFormat,\n    verbose: u8,\n}\n\nimpl Output {\n    pub fn new(format: OutputFormat, verbose: u8) -> Self {\n        Self { format, verbose }\n    }\n\n    pub fn success(&self, msg: &str) {\n        match self.format {\n            OutputFormat::Text => eprintln!(\"{} {}\", \"✓\".green().bold(), msg),\n            OutputFormat::Json => {} \u002F\u002F JSON output goes to stdout only\n        }\n    }\n\n    pub fn error(&self, msg: &str) {\n        match self.format {\n            OutputFormat::Text => eprintln!(\"{} {}\", \"✗\".red().bold(), msg),\n            OutputFormat::Json => {\n                let err = serde_json::json!({\"error\": msg});\n                println!(\"{}\", serde_json::to_string(&err).unwrap());\n            }\n        }\n    }\n\n    pub fn info(&self, msg: &str) {\n        if self.verbose >= 1 {\n            match self.format {\n                OutputFormat::Text => eprintln!(\"{} {}\", \"ℹ\".blue(), msg),\n                OutputFormat::Json => {}\n            }\n        }\n    }\n\n    pub fn data\u003CT: serde::Serialize>(&self, data: &T) {\n        match self.format {\n            OutputFormat::Text => {\n                \u002F\u002F Pretty print for humans — customize per subcommand\n                println!(\"{:#?}\", data);\n            }\n            OutputFormat::Json => {\n                println!(\"{}\", serde_json::to_string_pretty(data).unwrap());\n            }\n        }\n    }\n}\n```\n\n### Step 6: Main entry point\n\n```rust\nuse clap::Parser;\n\nfn main() -> anyhow::Result\u003C()> {\n    let cli = Cli::parse();\n    let config = Config::load(cli.config.as_deref())?;\n    let output = Output::new(cli.format.clone(), cli.verbose);\n\n    match cli.command {\n        Commands::Init { name, template } => {\n            cmd_init(&name, &template, &config, &output)?;\n        }\n        Commands::Build { release, output_dir } => {\n            let dir = output_dir\n                .or(config.output_dir.clone())\n                .unwrap_or_else(|| PathBuf::from(\".\u002Fdist\"));\n            cmd_build(release, &dir, &output)?;\n        }\n        Commands::Status => {\n            cmd_status(&config, &output)?;\n        }\n    }\n\n    Ok(())\n}\n\n\u002F\u002F If async (tokio):\n\u002F\u002F #[tokio::main]\n\u002F\u002F async fn main() -> anyhow::Result\u003C()> { ... }\n```\n\n### Step 7: Subcommand implementations\n\n```rust\nfn cmd_init(name: &str, template: &str, config: &Config, out: &Output) -> anyhow::Result\u003C()> {\n    let template = if template == \"default\" {\n        config.default_template.as_deref().unwrap_or(\"default\")\n    } else {\n        template\n    };\n\n    out.info(&format!(\"Using template: {}\", template));\n\n    let project_dir = Path::new(name);\n    if project_dir.exists() {\n        anyhow::bail!(\"Directory '{}' already exists\", name);\n    }\n\n    std::fs::create_dir_all(project_dir)?;\n    \u002F\u002F ... scaffold project files based on template\n\n    out.success(&format!(\"Created project '{}' with template '{}'\", name, template));\n    Ok(())\n}\n```\n\n### Step 8: Tests\n\n```rust\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn test_config_default() {\n        let config = Config::default();\n        assert!(config.default_template.is_none());\n    }\n\n    #[test]\n    fn test_config_parse_toml() {\n        let toml_str = r#\"\n            default_template = \"react\"\n            output_dir = \".\u002Fbuild\"\n        \"#;\n        let config: Config = toml::from_str(toml_str).unwrap();\n        assert_eq!(config.default_template.unwrap(), \"react\");\n    }\n}\n\n\u002F\u002F Integration tests (tests\u002Fcli.rs):\nuse assert_cmd::Command;\nuse predicates::prelude::*;\n\n#[test]\nfn test_help_flag() {\n    Command::cargo_bin(\"toolname\")\n        .unwrap()\n        .arg(\"--help\")\n        .assert()\n        .success()\n        .stdout(predicate::str::contains(\"Usage:\"));\n}\n\n#[test]\nfn test_version_flag() {\n    Command::cargo_bin(\"toolname\")\n        .unwrap()\n        .arg(\"--version\")\n        .assert()\n        .success();\n}\n\n#[test]\nfn test_init_creates_directory() {\n    let dir = tempfile::tempdir().unwrap();\n    let project_name = dir.path().join(\"test-project\");\n\n    Command::cargo_bin(\"toolname\")\n        .unwrap()\n        .args([\"init\", project_name.to_str().unwrap()])\n        .assert()\n        .success();\n\n    assert!(project_name.exists());\n}\n\n#[test]\nfn test_init_existing_directory_fails() {\n    let dir = tempfile::tempdir().unwrap();\n\n    Command::cargo_bin(\"toolname\")\n        .unwrap()\n        .args([\"init\", dir.path().to_str().unwrap()])\n        .assert()\n        .failure()\n        .stderr(predicate::str::contains(\"already exists\"));\n}\n\n#[test]\nfn test_json_output_format() {\n    Command::cargo_bin(\"toolname\")\n        .unwrap()\n        .args([\"--format\", \"json\", \"status\"])\n        .assert()\n        .success()\n        .stdout(predicate::str::starts_with(\"{\"));\n}\n```\n\n## Project structure reference\n\n```\ntoolname\u002F\n├── Cargo.toml\n├── src\u002F\n│   ├── main.rs          # Entry point, CLI parsing, command dispatch\n│   ├── cli.rs           # Clap derive structs (Cli, Commands, Args)\n│   ├── config.rs        # Config file loading and merging\n│   ├── output.rs        # Output formatting (text\u002FJSON\u002Fcolored)\n│   ├── error.rs         # Error types (if using thiserror)\n│   └── commands\u002F\n│       ├── mod.rs\n│       ├── init.rs      # Init subcommand logic\n│       ├── build.rs     # Build subcommand logic\n│       └── status.rs    # Status subcommand logic\n└── tests\u002F\n    └── cli.rs           # Integration tests with assert_cmd\n```\n\n## Best practices\n\n### Separate CLI from logic\nKeep clap structs and argument parsing in `cli.rs`. Put business logic in `commands\u002F`. This makes the core logic testable without invoking the CLI.\n\n### Use stderr for status, stdout for data\nHuman-readable messages (progress, success, errors) go to `stderr`. Machine-readable data goes to `stdout`. This lets users pipe output cleanly: `toolname status --format json | jq '.items'`.\n\n### Respect NO_COLOR\nCheck the `NO_COLOR` environment variable and disable colors when set:\n```rust\nif std::env::var(\"NO_COLOR\").is_ok() {\n    colored::control::set_override(false);\n}\n```\n\n### Exit codes\nUse meaningful exit codes: 0 for success, 1 for general errors, 2 for usage errors (clap handles this automatically).\n\n### Dev dependencies for testing\n\n```toml\n[dev-dependencies]\nassert_cmd = \"2\"\npredicates = \"3\"\ntempfile = \"3\"\n```\n\n## Checklist before finishing\n\n- [ ] `clap` derive structs have doc comments (they become --help text)\n- [ ] All subcommands have short and long descriptions\n- [ ] Config file has sensible defaults and doesn't error when missing\n- [ ] `--format json` outputs valid, parseable JSON to stdout\n- [ ] Errors show context (file paths, what went wrong, how to fix it)\n- [ ] Integration tests verify CLI behavior end-to-end\n- [ ] `cargo clippy` passes with no warnings\n- [ ] `cargo fmt` has been run\n\n",{"name":5,"tags":44,"description":7},[20,19,45,38,27,35],"clap","main","015422534a7457348a313b6381f0255d3364eb8c","cli-tool\u002Fcomponents\u002Fskills\u002Fdevelopment\u002Frust-cli-builder",0,"https:\u002F\u002Fgithub.com\u002FMishit18\u002Fclaude-code-templates","https:\u002F\u002Fgithub.com\u002FMishit18","2026-11-14 17:36:32",{"source":8,"skillName":5,"commands":54,"prompt":64,"zipAvailable":65},[55,58,61],{"tool":56,"command":57},"npx","npx skills add Mishit18\u002Fclaude-code-templates --skill rust-cli-builder",{"tool":59,"command":60},"bunx","bunx skills add Mishit18\u002Fclaude-code-templates --skill rust-cli-builder",{"tool":62,"command":63},"pnpm","pnpm dlx skills add Mishit18\u002Fclaude-code-templates --skill rust-cli-builder","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMishit18\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fdevelopment\u002Frust-cli-builder\u002FSKILL.md",true,[],[68,97,123,144,170,180],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":72,"licenseFileUrl":73,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":96},"01M6R194Y2CS39V9VPAVRVW1ZV","skill-creation-guide","Guide for creating effective skills. This skill should be used when users want to create a new skill (or update an existing skill) that extends Claude's capabilities with specialized knowledge, workflows, or tool integrations.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FMishit18\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fdevelopment\u002Fskill-creation-guide\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FMishit18\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fdevelopment\u002Fskill-creation-guide\u002FSKILL.md",[],[77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95],"skill creation guide","guide","creation","skill creation","workflows","create","update","capabilities","knowledge","tool","integrations","specialized","new skill","existing skill","users","with","for","Existing","when","2026-11-11 15:11:14",{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":72,"licenseFileUrl":101,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":39},"01M6R4ARN4W2VZRDERDTMN1KP0","web-artifacts-builder","Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn\u002Fui). Use for complex artifacts requiring state management, routing, or shadcn\u002Fui components - not for simple single-file HTML\u002FJSX artifacts.","https:\u002F\u002Fgithub.com\u002FMishit18\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Futilities\u002Fweb-artifacts-builder\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FMishit18\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Futilities\u002Fweb-artifacts-builder\u002FSKILL.md",[],[105,106,107,108,22,109,110,111,112,113,114,115,116,117,118,119,120,121,93,122],"web artifacts builder","web","artifacts","artifacts builder","frontend","css","components","react","routing","state management","state","file","Tailwind","use","single-file","ui components","multi","single",{"skillNo":124,"name":125,"nameZh":6,"description":126,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":72,"licenseFileUrl":127,"sourceHtmlUrl":128,"categories":129,"keywords":130,"publishedAt":39},"01M6R45GXREM5DP8T08MAC788H","webapp-testing","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","https:\u002F\u002Fgithub.com\u002FMishit18\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fsecurity\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FMishit18\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fsecurity\u002Fwebapp-testing\u002FSKILL.md",[],[131,132,133,109,134,135,106,136,137,138,139,140,141,142,143,92,93],"testing","webapp testing","webapp","screenshots","playwright","debugging","toolkit","browser","ui","logs","applications","behavior","local",{"skillNo":145,"name":146,"nameZh":6,"description":147,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":148,"sourceHtmlUrl":149,"categories":150,"keywords":151,"publishedAt":39},"01M6R2GYJ470X8EB7R58V0B68K","think-tank","Run a Virtual Think Tank — a structured multi-persona debate — before planning or making architectural\u002Fdesign\u002Fstrategic decisions. Use this skill whenever the user is about to plan a system, make a technology choice, evaluate trade-offs, decide on an approach, or faces any decision where multiple perspectives would sharpen the outcome. Also trigger when the user says \"think tank\", \"debate this\", \"perspectives on\", \"trade-offs\", \"should I use X or Y\", \"help me decide\", \"before we plan\", or asks for pros\u002Fcons of competing approaches. This skill should run BEFORE any implementation planning begins — it produces a structured analysis that feeds into better plans.","https:\u002F\u002Fgithub.com\u002FMishit18\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fproductivity\u002Fthink-tank\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FMishit18\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fproductivity\u002Fthink-tank\u002FSKILL.md",[],[152,153,154,155,156,157,158,34,159,160,161,162,163,164,165,166,167,168,169,95],"think tank","think","design","run","feeds","analysis","persona","sharpen","virtual","decision","choice","decide","perspectives","outcome","me","debate","make","trade-offs",{"skillNo":171,"name":172,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":72,"licenseFileUrl":173,"sourceHtmlUrl":174,"categories":175,"keywords":176,"publishedAt":39},"01M6R2FSR55AVRFA9YZ8SC2GZG","skill-creator","https:\u002F\u002Fgithub.com\u002FMishit18\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fproductivity\u002Fskill-creator\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FMishit18\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fproductivity\u002Fskill-creator\u002FSKILL.md",[],[177,178,81,82,83,84,85,86,87,88,78,89,90,91,92,93,94,95,179],"skill creator","creator","new",{"skillNo":181,"name":182,"nameZh":6,"description":183,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":184,"categories":185,"keywords":186,"publishedAt":39},"01M6R2FK42ZZ4HJTJVVK9WJBBP","ship-learn-next","Transform learning content (like YouTube transcripts, articles, tutorials) into actionable implementation plans using the Ship-Learn-Next framework. Use when user wants to turn advice, lessons, or educational content into concrete action steps, reps, or a learning quest.","https:\u002F\u002Fgithub.com\u002FMishit18\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fproductivity\u002Fship-learn-next\u002FSKILL.md",[],[187,188,189,190,191,192,193,194,118,195,196,197,198,199,200,201,202,203,204,95],"learn","ship learn next","ship","next","framework","learning","read","write","advice","implementation","youtube","plans","quest","transform","actionable","action","lessons","youtube transcripts"]