Sub topic 5
Options and flags
This chapter assumes you can build a Cargo project with clap 4 and the derive feature enabled. You should also know how #[derive(Parser)] turns a struct into a parser, and how positional arguments work.
Options, flags, and counters
A positional argument is identified by where it appears. An option or a flag is identified by its name. In a derived parser, a field with #[arg(...)] becomes one of these, and the field's type decides which.
- An option takes a value, such as
--filter error. UseOption<T>when it is optional. - A flag takes no value. Its presence means true. Use
bool. - A counter is a flag that can repeat, such as
-vand-vv. Useu8withArgAction::Count.
use clap::{ArgAction, Parser};
use std::path::PathBuf;
/// Print lines of a file that contain a pattern.
#[derive(Parser, Debug)]
struct Cli {
/// File to search
path: PathBuf,
/// Only print lines containing this text
#[arg(short, long)]
filter: Option<String>,
/// Ignore upper and lower case
#[arg(short, long)]
ignore_case: bool,
/// Increase output detail (-v, -vv)
#[arg(short, long, action = ArgAction::Count)]
verbose: u8,
}
fn main() {
let cli = Cli::parse();
println!("{cli:?}");
}Short and long names
#[arg(short)] adds a one-letter name taken from the first letter of the field. #[arg(long)] adds a long name taken from the whole field name, with underscores turned into hyphens. The field ignore_case becomes --ignore-case.
You can also give explicit names: #[arg(short = 'I', long = "no-case")].
Two fields can't share a short name. Here filter and force would both claim -f. clap reports this as a panic in debug builds, and the chapter on testing shows how to catch it early. Fix it by choosing a letter for one field, such as #[arg(short = 'F')].
How the command line is read
The parser accepts several spellings of the same input:
| You type | Meaning |
|---|---|
| `--filter error` | long option, value after a space |
| `--filter=error` | long option, value after `=` |
| `-f error` | short option, value after a space |
| `-ferror` | short option, value attached |
| `-iv` | two short flags combined |
| `-vv` | counter set to 2 |
Given -iv, ignore_case becomes true and verbose becomes 1. Given -vv, verbose becomes 2.
Flag actions
A bool field uses ArgAction::SetTrue by default, so you rarely write it. Two other actions are common.
ArgAction::Countcounts how many times the flag appears. The field must be an integer type.ArgAction::Appendlets an option repeat and collects the values into aVec<T>. For example,#[arg(short, long)] include: Vec<String>accepts--include a --include b.
use clap::Parser;
#[derive(Parser, Debug)]
struct Cli {
/// Pattern to include (repeatable)
#[arg(short, long)]
include: Vec<String>,
}
fn main() {
let cli = Cli::parse();
println!("{:?}", cli.include);
}Running app -i a -i b prints ["a", "b"]. Without any -i, the vector is empty.
Common errors
- A flag that never turns on. If you declare
verbose: Option<bool>, clap treats it as an option that needs a value. Use plainboolfor flags. - A counter that won't compile.
Countneeds an integer field. Aboolfield withCountis rejected. - A value that starts with a hyphen.
--offset -5is read as a new option. Write--offset=-5, or declare the field withallow_negative_numbers = true. - Short name clash. Described above. Run
Cli::command().debug_assert()in a test to find it.
Exercise
Write the struct fields for a --output option that is optional and takes a path, a -q flag that suppresses output, and a -v flag that can repeat. Which input sets verbose to 3?
Show answer
#[arg(short, long)] output: Option<PathBuf>, #[arg(short, long)] quiet: bool, and #[arg(short, long, action = ArgAction::Count)] verbose: u8. The inputs -vvv and -v -v -v both set verbose to 3. Note that quiet and verbose would both claim -q and -v only if their first letters matched, so here each has its own letter.