Sub topic 11
Subcommands and global arguments
This chapter assumes you can define a #[derive(Parser)] struct with positional arguments, options, and flags. It also assumes you know how ValueEnum restricts a value. Here you will split one program into several commands, as git add and git commit do, and share options across them.
What a subcommand is
A subcommand is a word on the command line that selects a mode of the program. Each mode has its own arguments, help text, and validation. In tasks add "Write docs" --priority high, add is the subcommand. "Write docs" and --priority belong only to add.
clap models this with two derives:
Parsergoes on the top-level struct.Subcommandgoes on an enum. Each variant is one command, and the variant's fields are that command's arguments.
The top-level struct points at the enum with #[command(subcommand)].
A first multi-command tool
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);
}
}
}Some details of how clap reads this definition:
- Doc comments on variants become the one-line descriptions in the
--helpcommand list. - Variant names become kebab-case command names.
Commands::ListAllwould be invoked aslist-all. Override the name with#[command(name = "ls")]. - A field of type
Commandsmakes the subcommand required. If the user omits it, clap prints an error and exits with code 2. - Variant fields follow the same rules as fields on a
Parserstruct.Stringis a required positional,boolis a flag, andOption<T>is optional.
Try it:
cargo run -- add "Write docs" --priority high
cargo run -- list --all --verbose
cargo run -- add --helpThe first command prints add "Write docs" with priority High. The second prints list (all = true, verbose = true). The third shows help for add only, with its own usage line and options.
Global arguments
Normally an option belongs to the command level where you declare it. --verbose declared on Cli is accepted only before the subcommand name, so tasks list --verbose would fail with an unexpected-argument error.
Marking it global = true changes that. clap propagates the argument to every subcommand, at any depth. Both of these now work and produce the same result:
cargo run -- --verbose list
cargo run -- list --verboseGlobal arguments have two properties to keep in mind:
- The value lives on the top-level struct. Even when the user writes
list --verbose, you readcli.verbose, not a field on theListvariant. Do not redeclare the argument inside a variant. - The flag also appears in each subcommand's help. This is how users discover that it is accepted there.
Good candidates for global = true are options that apply to the whole program: --verbose, --config <PATH>, --color, and --quiet. Options that matter to only one command should stay on that command.
Sharing arguments with `Args` structs
Inline fields in an enum variant work for small commands. As a command grows, move its arguments into a struct that derives Args. The variant then holds that struct as a single tuple field. This keeps match arms short and lets you pass the whole argument set to a function.
use clap::{Args, Parser, Subcommand};
#[derive(Parser, Debug)]
#[command(name = "tasks", version, arg_required_else_help = true)]
struct Cli {
/// Print extra detail for any subcommand
#[arg(long, global = true)]
verbose: bool,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug)]
enum Commands {
/// Add a task
Add(AddArgs),
/// List tasks
#[command(alias = "ls")]
List(ListArgs),
/// Manage tags on a task
#[command(subcommand)]
Tag(TagCommands),
}
#[derive(Args, Debug)]
struct AddArgs {
/// Task title
title: String,
}
#[derive(Args, Debug)]
struct ListArgs {
/// Include finished tasks
#[arg(short, long)]
all: bool,
}
#[derive(Subcommand, Debug)]
enum TagCommands {
/// Attach a tag to a task
Add { id: u32, tag: String },
/// Remove a tag from a task
Remove { id: u32, tag: String },
}
fn main() {
let cli = Cli::parse();
let verbose = cli.verbose;
match cli.command {
Commands::Add(args) => println!("add {:?} (verbose = {verbose})", args.title),
Commands::List(args) => println!("list all = {}", args.all),
Commands::Tag(TagCommands::Add { id, tag }) => println!("tag #{id} with {tag}"),
Commands::Tag(TagCommands::Remove { id, tag }) => println!("untag #{id}: {tag}"),
}
}This example shows three more features:
- Aliases.
#[command(alias = "ls")]makestasks lswork. The alias is hidden in help. Usevisible_aliasto list it. - Nested subcommands.
Tagholds anotherSubcommandenum, sotasks tag add 3 urgentworks. Mark the variant with#[command(subcommand)]. Nesting can go as deep as you need, but each level adds typing for the user, so two levels is usually the practical limit. - Showing help when run bare.
arg_required_else_help = truemakestaskswith no arguments print the help text instead of a "subcommand required" error. Set it on a nested enum's parent variant with#[command(subcommand, arg_required_else_help = true)]if you wanttasks tagto do the same.
Use #[command(flatten)] on a field to reuse one Args struct in several commands. For example, a ConnectionArgs struct with --host and --port can be flattened into both Push and Pull. The fields appear as if you had written them inline.
Optional subcommands
If a default action makes sense, make the field optional:
#[command(subcommand)]
command: Option<Commands>,When the user gives no subcommand, cli.command is None, and you run the default behavior yourself. For example, tasks alone could behave like tasks list. Do not combine this with arg_required_else_help, which would show help before you get the chance.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `unexpected argument '--verbose' found` after the subcommand name | The option is declared on `Cli` without `global = true` | Add `global = true` |
| `cli.verbose` is always `false` even though the user passed `list --verbose` | A second `verbose` field was declared inside the variant, and you read the top-level one | Declare it once, on the top-level struct |
| `error: 'tasks' requires a subcommand but one was not provided` | The field is `Commands`, not `Option<Commands>` | Make it optional, or keep the error and let users read help |
| A subcommand is named `list-all`, not `listall` or `list_all` | clap converts variant names to kebab-case | Set `#[command(name = "...")]` |
| Compile error about a missing `Args` or `Subcommand` implementation | A tuple variant's inner type lacks the derive | Derive `Args` for structs and `Subcommand` for enums |
If a user mistypes a command, such as tasks ad, clap reports the unrecognized subcommand, suggests a close match, and exits with code 2. You get this behavior without writing any code.
Design guidance
- Keep global arguments few. Each one appears in every subcommand's help and constrains every command that gets added later.
- Name subcommands as verbs (
add,list,remove). Keep names short, because users type them often. - Prefer
Argsstructs once a command has more than two or three fields. A function that takes&AddArgsis easier to call from tests than one with a long parameter list. - Do the actual work outside
main. A later chapter covers keeping parsing separate from program logic. Thematchoncli.commandis the natural boundary: each arm should call one function.
Exercise
You declare #[arg(long, global = true)] verbose: bool on Cli. A user runs tasks add "Write docs" --verbose. Where do you read the flag's value in your code, and what happens if you instead declare --verbose on Cli without global = true and run the same command?
Show answer
Read it from the top-level struct as cli.verbose, even though the user typed it after add. Without global = true, the option is accepted only before the subcommand name, so clap rejects tasks add "Write docs" --verbose with an unexpected-argument error and exits with code 2.
Exercise
Add a Remove command to the Args-based example that takes a numeric id and has the alias rm. Which two pieces of code do you add, and what does the match in main need?
Show answer
Add a Remove(RemoveArgs) variant to Commands with #[command(alias = "rm")], and a #[derive(Args, Debug)] struct RemoveArgs { id: u32 }. The match in main needs a new arm, such as Commands::Remove(args) => println!("remove #{}", args.id). The compiler requires it because match must cover every variant.