Skip to content

Lesson 2 of 9 · 26m

Designing Commands and Flags with clap

Model subcommands, arguments, value constraints, conflicts, and help output so the CLI prevents bad invocations before your logic runs.

A command-line interface is a public API with worse error messages and no compiler on the user side. The first version of tool run --input feels harmless; three releases later you need --config, environment overrides, shell completion, dry runs, and compatibility with scripts written by people you will never meet. clap is where you encode that contract instead of documenting wishes.

Use derive for the shape, not as a substitute for thought

use clap::{Parser, Subcommand};
use std::path::PathBuf;

#[derive(Parser)]
#[command(version, about = "Build and publish release artifacts")]
struct Cli {
    /// Increase diagnostic detail; repeat for trace output
    #[arg(short, long, action = clap::ArgAction::Count)]
    verbose: u8,

    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Build artifacts without uploading them
    Build {
        #[arg(long, default_value = "release")]
        profile: String,
        #[arg(long)]
        target: Option<String>,
    },
    /// Upload a previously built artifact
    Publish {
        #[arg(long, value_name = "FILE")]
        artifact: PathBuf,
        #[arg(long)]
        dry_run: bool,
    },
}

The important design choice is that build and publish are separate verbs. They have different failure modes, permissions, retry semantics, and operational risk. Do not hide them behind a bag of booleans.

Encode impossible states at the parser boundary

If two flags conflict, say so where parsing happens:

#[arg(long, conflicts_with = "json")]
table: bool,
#[arg(long)]
json: bool,

If a value has a small domain, use an enum implementing ValueEnum. If paths must exist, validate before doing work. If a flag requires another flag, use requires. Every invalid combination rejected by clap is a production incident your match statement never has to handle.

Design help for the person paging through it at 2 a.m.

Long help should show examples and units. Put units in value names: --timeout SECONDS, --memory MIB, --output FILE. Keep short flags scarce; -v, -q, -o, and -f have conventional meanings that users carry from other tools.

deployctl publish --artifact dist/app-linux-amd64.tar.gz --dry-run
deployctl build --profile release --target x86_64-unknown-linux-musl

Treat flags as compatibility debt

Renaming a flag is a breaking change. Removing a positional argument is worse because scripts rarely fail loudly until they hit the wrong argument positions. Add new behavior additively. Deprecate with warnings that go to stderr, and keep machine output stable while humans are being migrated.

Field notes

  • Do not use -h for anything except help; muscle memory is stronger than documentation.
  • --yes should never bypass both confirmation and validation. Bypassing confirmation is UX; skipping validation is corruption.
  • Clap can generate completions, but only if command and value metadata are accurate.
  • Repeated flags and comma-separated values behave differently in scripts. Pick one, document it, and parse it deliberately.
  • Hidden flags are acceptable for migration shims; undocumented behavior is not a compatibility strategy.

Was this lesson helpful?

Sign in to rate