Build Rust command-line tools that are predictable, scriptable, pleasant in terminals, and easy to ship.
Operating Model
- Discover the existing CLI contract first:
Cargo.toml,src/bin,clapdefinitions, integration tests, snapshots, release scripts, and README examples. - Preserve user-facing command behavior unless the task explicitly asks for a breaking change. If behavior changes, update tests and docs in the same patch.
- Prefer
clapderive for ordinary CLIs. Use the builder API when commands are generated dynamically, hidden/unstable command surfaces need custom construction, or macros make the shape harder to read. - Design command output as an API: human output on stdout, diagnostics on stderr, deterministic
--json/machine output where automation is expected, and stable exit codes. - Keep command handlers thin. Parse into typed arguments, normalize config once, then call library code that tests can exercise without spawning a process.
Reference Map
Open only the section needed for the task:
references/clap-parser-playbook.mdforclapderive/builder design, argument groups, validators, completions, and migration notes.references/terminal-contracts.mdfor stdout/stderr, color, progress, config precedence, error messages, and shell automation rules.references/testing-packaging.mdforassert_cmd,trycmd, snapshots, binaries, completions, manpages,cargo-dist, and release checks.
Defaults
- Use
clap = { features = ["derive", "env"] }when environment variables are part of the contract; otherwise avoid unused features. - Use
caminoorUtf8PathBufonly when UTF-8 paths are an explicit invariant. Otherwise keepPathBuf. - Use
anstream/anstyleorclapstyling for color-aware output; respectNO_COLOR,CLICOLOR, and non-TTY behavior. - Use
tracingfor diagnostics when the CLI has subcommands, network calls, daemon/client modes, or hidden debugging flags. - Use
thiserrorfor domain errors andmietteorcolor-eyreat the presentation boundary only when rich reports add value.
Verification
For CLI changes, prefer the smallest ladder that proves the contract:
cargo fmt --all --check
cargo test --all-targets
cargo clippy --workspace --all-targets --all-features -- -D warnings
Add focused command tests for new flags, output modes, exit codes, config precedence, and examples shown in docs. Snapshot CLI output only after normalizing volatile paths, timestamps, colors, and ordering.