Sub topic 11
Subcommands and global arguments
This chapter assumes you can define a #[derive(Parser)] struct with options and flags, and that you know Rust enums and match. You will build a small task manager whose commands each take different arguments.
Why subcommands
Tools like git and cargo group related actions under one binary: git commit, git push. Each action takes its own arguments, and --help is generated separately for each. In clap, you model this with an enum where each variant is one command and its fields are that command's arguments.
Defining the commands
Derive Subcommand on an enum. Add a field to the top-level Parser struct and mark it #[command(subcommand)].
use clap::{Parser, Subcommand, ValueEnum};
#[derive(Parser)]
#[command(version, about = "A tiny task manager")]
struct Cli {
/// Print extra detail for any subcommand
#[arg(long, global = true)]
verbose: bool,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Add a task
Add {
title: String,
#[arg(long, value_enum, default_value_t = Priority::Normal)]
priority: Priority,
},
/// List tasks
List {
#[arg(short, long)]
all: bool,
},
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum Priority {
Low,
Normal,
High,
}
fn main() {
let cli = Cli::parse();
match cli.command {
Commands::Add { title, priority } => {
println!("add {title:?} with priority {priority:?}");
}
Commands::List { all } => {
println!("list (all = {all}, verbose = {})", cli.verbose);
}
}
}Several things happen here:
- Variant names become lowercase command names:
Addisadd,Listislist. - Doc comments on variants become the one-line descriptions in
--help. - Fields inside a variant work like fields on a
Parserstruct.titleis a required positional argument, andallis a flag with-aand--all. PriorityderivesValueEnum, so--priorityaccepts onlylow,normal, orhigh.
Because command is not an Option, the user must name a subcommand. Running the program with none prints help and exits with an error. Use Option<Commands> if the tool should also work without one.
Global arguments
Normally an argument belongs to the command where it is declared. --verbose sits on the top-level struct, so without global = true it would only be accepted before the subcommand name. With global = true, clap accepts it in either position, and the value is stored on Cli.
tasks --verbose list
tasks list --verbose
tasks add "Write docs" --priority high --verboseAll three forms are valid. The first two give the same result.
Instead of a diagram, use this table to see where each argument lives.
| Argument | Declared on | Accepted where |
|---|---|---|
| `--verbose` | `Cli` with `global = true` | Before or after any subcommand |
| `title`, `--priority` | `Commands::Add` | After `add` only |
| `-a`, `--all` | `Commands::List` | After `list` only |
Common mistakes
- Reading a global from the wrong place. The value is a field on
Cli, not on the variant. In the example,match cli.commandmoves only thecommandfield, socli.verboseis still usable afterward. - Forgetting
#[command(subcommand)]. Without it, clap treats the enum field as a plain value and the derive fails to compile. - Giving a global argument a required value. A global argument must make sense in every subcommand. Prefer flags or arguments with defaults.
Exercise
You want --config <PATH> to work in all of these positions: tool --config a.toml list, tool list --config a.toml. What do you change, and where is the value stored?
Show answer
Declare config: Option<PathBuf> on the top-level Cli struct with #[arg(long, global = true)]. The value is stored on Cli, so you read it as cli.config, not from a subcommand variant.