rust-cli-builder
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/output formats, and distribution strategy before writing any code.
What this skill does
# Rust CLI Tool Builder
## When to use
Use this skill when you need to:
- Scaffold a new Rust CLI tool from scratch with clap
- Add subcommands to an existing CLI application
- Implement config file loading (TOML/JSON/YAML)
- Set up proper error handling with anyhow/thiserror
- Add colored and formatted terminal output
- Structure a CLI project for distribution via cargo install or GitHub releases
## Phase 1: Explore (Plan Mode)
Enter plan mode. Before writing any code, explore the existing project:
### If extending an existing project
- Find `Cargo.toml` and check current dependencies (clap version, serde, tokio, etc.)
- Locate the CLI entry point (`src/main.rs` or `src/cli.rs`)
- Check if clap is using derive macros or builder pattern
- Identify existing subcommand structure
- Look for existing error types, config structs, and output formatting
- Check if there's a `src/lib.rs` separating library logic from CLI
### If starting from scratch
- Check the workspace for any existing Rust projects or workspace `Cargo.toml`
- Look for a `.cargo/config.toml` with custom settings
- Check for `rust-toolchain.toml` to know the target Rust edition
## Phase 2: Interview (AskUserQuestion)
Use AskUserQuestion to clarify requirements. Ask in rounds.
### Round 1: Tool purpose and commands
```
Question: "What kind of CLI tool are you building?"
Header: "Tool type"
Options:
- "Single command (like ripgrep, curl)" — One main action with flags and arguments
- "Multi-command (like git, cargo)" — Multiple subcommands under one binary
- "Interactive REPL (like psql)" — Persistent session with a prompt loop
- "Pipeline tool (like jq, sed)" — Reads stdin, transforms, writes stdout
Question: "What will the tool operate on?"
Header: "Input"
Options:
- "Files/directories" — Read, process, or generate files
- "Network/API" — HTTP requests, TCP connections, API calls
- "System resources" — Processes, hardware info, OS config
- "Data streams (stdin/stdout)" — Pipe-friendly text/binary processing
```
### Round 2: Subcommands (if multi-command)
```
Question: "Describe the subcommands you need (e.g., 'init', 'build', 'deploy')"
Header: "Commands"
Options:
- "2-3 subcommands (I'll describe them)" — Small focused tool
- "4-8 subcommands with groups" — Medium tool, may need command groups
- "I have a rough list, help me design the API" — Collaborative command design
```
### Round 3: Configuration and output
```
Question: "How should the tool be configured?"
Header: "Config"
Options:
- "CLI flags only (Recommended)" — All config via command-line arguments
- "Config file (TOML)" — Load defaults from ~/.config/toolname/config.toml
- "Config file + CLI overrides" — Config file for defaults, flags override specific values
- "Environment variables + flags" — Env vars for secrets, flags for everything else
Question: "What output format does the tool need?"
Header: "Output"
Options:
- "Human-readable (colored text)" — Pretty terminal output with colors and formatting
- "Machine-readable (JSON)" — Structured output for piping to other tools
- "Both (--format flag)" — Default human, --json or --format=json for machines
- "Minimal (exit codes only)" — Success/failure via exit code, errors to stderr
```
### Round 4: Async and error handling
```
Question: "Does the tool need async operations?"
Header: "Async"
Options:
- "No — synchronous is fine (Recommended)" — File I/O, computation, simple operations
- "Yes — tokio (network I/O)" — HTTP requests, concurrent connections, async file I/O
- "Yes — tokio multi-threaded" — Heavy parallelism, multiple concurrent tasks
Question: "How should errors be presented to users?"
Header: "Errors"
Options:
- "Simple messages (anyhow) (Recommended)" — Human-readable error chains, good for most CLIs
- "Typed errors (thiserror)" — Custom error enum with specific variants for each failure
- "Both (thiserror for lib, anyhow for bin)" — Library code is typed, CLI wraps with anyhow
```
## Phase 3: Plan (ExitPlanMode)
Write a concrete implementation plan covering:
1. **Project structure** — `Cargo.toml` dependencies, `src/` file layout
2. **CLI definition** — clap derive structs for all commands, args, and flags
3. **Config loading** — config file format and merge strategy with CLI args
4. **Core logic** — main functions for each subcommand, separated from CLI layer
5. **Error types** — error enum or anyhow usage, user-facing error messages
6. **Output formatting** — colored output, JSON mode, progress indicators
7. **Tests** — unit tests for core logic, integration tests for CLI behavior
Present via ExitPlanMode for user approval.
## Phase 4: Execute
After approval, implement following this order:
### Step 1: Project setup (Cargo.toml)
```toml
[package]
name = "toolname"
version = "0.1.0"
edition = "2021"
description = "Short description of the tool"
[dependencies]
clap = { version = "4", features = ["derive", "env"] }
serde = { version = "1", features = ["derive"] }
anyhow = "1"
# Add based on interview:
# thiserror = "2" # if typed errors
# tokio = { version = "1", features = ["full"] } # if async
# serde_json = "1" # if JSON output
# toml = "0.8" # if TOML config
# colored = "2" # if colored output
# indicatif = "0.17" # if progress bars
# dirs = "5" # if config file (~/.config/)
```
### Step 2: CLI definition with clap derive
```rust
use clap::{Parser, Subcommand};
/// Short one-line description of the tool
#[derive(Parser, Debug)]
#[command(name = "toolname", version, about, long_about = None)]
pub struct Cli {
/// Increase verbosity (-v, -vv, -vvv)
#[arg(short, long, action = clap::ArgAction::Count, global = true)]
pub verbose: u8,
/// Output format
#[arg(long, default_value = "text", global = true)]
pub format: OutputFormat,
/// Path to config file
#[arg(long, global = true)]
pub config: Option<std::path::PathBuf>,
#[command(subcommand)]
pub command: Commands,
}
#[derive(Subcommand, Debug)]
pub enum Commands {
/// Initialize a new project
Init {
/// Project name
name: String,
/// Template to use
#[arg(short, long, default_value = "default")]
template: String,
},
/// Build the project
Build {
/// Build in release mode
#[arg(short, long)]
release: bool,
/// Target directory
#[arg(short, long)]
output: Option<std::path::PathBuf>,
},
/// Show project status
Status,
}
#[derive(clap::ValueEnum, Clone, Debug)]
pub enum OutputFormat {
Text,
Json,
}
```
### Step 3: Error handling
```rust
// With anyhow (simple approach):
use anyhow::{Context, Result};
fn load_config(path: &Path) -> Result<Config> {
let content = std::fs::read_to_string(path)
.with_context(|| format!("Failed to read config file: {}", path.display()))?;
let config: Config = toml::from_str(&content)
.context("Invalid TOML in config file")?;
Ok(config)
}
// With thiserror (typed approach):
use thiserror::Error;
#[derive(Error, Debug)]
pub enum AppError {
#[error("Config file not found: {path}")]
ConfigNotFound { path: std::path::PathBuf },
#[error("Invalid config: {0}")]
InvalidConfig(#[from] toml::de::Error),
#[error("Network error: {0}")]
Network(#[from] reqwest::Error),
#[error("{0}")]
Custom(String),
}
```
### Step 4: Config file loading
```rust
use serde::Deserialize;
use std::path::{Path, PathBuf};
#[derive(Deserialize, Debug, Default)]
pub struct Config {
pub default_template: Option<String>,
pub output_dir: Option<PathBuf>,
// ... fields from interview
}
impl Config {
pub fn load(explicit_path: Option<&Path>) -> anyhow::Result<Self> {
let path = match explicit_path {
Some(p) => p.to_path_buf(),
None => Self::default_path(),
};
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.