Sub topic 5
Options and flags
This chapter covers the named arguments of a command-line program: options that carry a value and flags that do not. It assumes you can write a #[derive(Parser)] struct as in the previous chapters, that you know Option<T> and Vec<T>, and that you have a project with clap = { version = "4", features = ["derive"] }.
Options versus flags
A positional argument is identified by its place on the command line. An option is identified by a name, and it takes a value: --filter todo. A flag is also identified by a name, but it takes no value. Its presence alone carries the meaning: --verbose.
In derive mode you pick between them with the field's type and an optional action. Every named argument is declared with #[arg(...)].
| Field type | Attribute | Kind | When absent |
|---|---|---|---|
| `bool` | none | flag | `false` |
| `u8` | `action = ArgAction::Count` | counted flag | `0` |
| `Option<T>` | none | optional option | `None` |
| `T` | none | required option | parse error |
| `Vec<T>` | none | repeatable option | empty vector |
Without short or long, a field is a positional argument. The attribute is what makes it a named argument.
A complete example
use clap::{ArgAction, Parser};
use std::path::PathBuf;
/// Print lines of a file that contain a pattern.
#[derive(Parser, Debug)]
#[command(version, about)]
struct Cli {
/// File to search
path: PathBuf,
/// Only print lines containing this text
#[arg(short, long)]
filter: Option<String>,
/// Ignore upper and lower case when matching
#[arg(short = 'i', long)]
ignore_case: bool,
/// Increase output detail (-v, -vv)
#[arg(short, long, action = ArgAction::Count)]
verbose: u8,
/// Skip lines containing this text; may be repeated
#[arg(short = 'e', long = "exclude")]
excludes: Vec<String>,
}
fn main() {
let cli = Cli::parse();
println!("{cli:?}");
}Run it with a mix of forms:
cargo run -- notes.txt -f todo -vv -i -e draft --exclude oldThe output is:
Cli { path: "notes.txt", filter: Some("todo"), ignore_case: true, verbose: 2, excludes: ["draft", "old"] }Each field type produced a different kind of argument. filter is an optional value, ignore_case is a flag, verbose was counted twice, and excludes collected two occurrences in order.
How names are derived
Clap builds names from the field name:
longwith no value uses the field name with underscores turned into hyphens.ignore_casebecomes--ignore-case.shortwith no value uses the first character of the field name.filterbecomes-f.short = 'i'andlong = "exclude"set the name explicitly. Use them when the derived name is wrong, as withexcludes, where--excludeswould read badly.
A field can have a long name only, a short name only, or both. Prefer a long name for every argument, because long names are readable in scripts. Add a short name only for options people type often.
What the parser accepts
Clap follows the usual Unix conventions, so you write no code for any of these forms:
| Input | Meaning |
|---|---|
| `--filter todo` | long option, value as next token |
| `--filter=todo` | long option, value joined by `=` |
| `-f todo` | short option, value as next token |
| `-ftodo` | short option, value attached |
| `-f=todo` | short option, value after `=` |
| `-vvi` | three short flags in one token |
| `--` | end of options; everything after is positional |
The diagram shows how clap classifies each token.
The -- separator matters when a positional value starts with a hyphen. To search a file literally named -notes.txt, run cargo run -- -- -notes.txt. The first -- ends Cargo's own arguments, and the second ends clap's options.
Counting and repeating
A plain bool flag appearing twice is an error. When repetition is meaningful, choose an action that says so:
ArgAction::Countincrements a number each time the flag appears. Useu8for the field.-vvand-v -vboth give2. Use the count as a level, for example0for warnings,1for info and2for debug.Vec<T>appends each occurrence of an option, asexcludesdid above.
Two other flag actions come up less often. ArgAction::SetTrue is what a bool field already uses. ArgAction::SetFalse makes a flag that turns a true default off, as in --no-color.
Several values after one option
By default, one occurrence of an option takes one value. To accept a list after a single occurrence, set num_args:
use clap::Parser;
#[derive(Parser, Debug)]
struct Cli {
/// One or more input files
#[arg(long, num_args = 1..)]
files: Vec<String>,
/// Output file
#[arg(long)]
out: Option<String>,
}
fn main() {
println!("{:?}", Cli::parse());
}--files a.txt b.txt --out result.txt works because --out ends the list.
Required options and missing values
A field of type String, u16 or any other type that is not wrapped in Option and has no default is required. Clap rejects the command if it is missing:
use clap::Parser;
#[derive(Parser, Debug)]
struct Cli {
/// Where to write the result
#[arg(short, long)]
output: String,
}
fn main() {
println!("{:?}", Cli::parse());
}Running this with no arguments prints an error that begins error: the following required arguments were not provided: and names --output <OUTPUT>. It then prints a usage line and exits with code 2. Giving --output with nothing after it is a separate error: clap reports that a value is required.
A required option is a design smell. If every invocation must supply --output, it is probably a positional argument. Reserve options for settings that have a sensible default or a meaningful "not given" state, which is what Option<T> expresses. Defaults are covered in a later chapter.
Values that start with a hyphen
Clap treats a token that starts with - as an option, so this fails:
cargo run -- --offset -5Clap reports that -5 is an unexpected argument. There are two fixes:
- Write
--offset=-5. The=form always takes the rest of the token as the value. - Add
allow_negative_numbers = trueto the argument. Clap then accepts-5as a value, though only for things that look like numbers.
For arbitrary hyphen-leading text, allow_hyphen_values = true accepts any token as the value. Use it sparingly, because a mistyped option name then becomes a silent value.
Name collisions
Clap checks names when it builds the command, and a duplicate is a programming error, not a user error. Two situations cause it.
- Two fields derive the same short name.
filterandformatboth default to-f. - A field takes a short name that clap already reserves. Clap adds
-h/--helpand, withversion,-V/--version. A field namedhostwith#[arg(short)]collides with-h.
In a debug build, either case panics at startup with a message such as Short option names must be unique for each argument, but '-h' is in use by both 'host' and 'help'. Fix it by choosing a different letter, for example short = 'H'.
Exercises
Exercise
A struct has the fields #[arg(short, long)] input: String and #[arg(short, long)] interval: u32. What happens when you run the program in a debug build, and how do you fix it?
Show answer
Both fields derive the short name -i, so clap panics at startup with a message that the short option is in use by both input and interval. Give one of them an explicit short name, for example #[arg(short = 'n', long)] interval: u32, or drop the short name from one field.
Exercise
You want --tag to be repeatable and collect all values in order, so that --tag a --tag b gives ["a", "b"]. What field type do you use, and what value does the field hold when --tag is never given?
Show answer
Use Vec<String> (or another Vec<T>) with #[arg(long)]. When --tag is never given, the field holds an empty vector, not an error and not None.
Exercise
Given #[arg(short, long, action = ArgAction::Count)] verbose: u8, what value does verbose have for the arguments -vv --verbose, and what is it with no arguments?
Show answer
It is 3 for -vv --verbose, because each occurrence adds one and the short and long forms count together. With no arguments it is 0.