Sub topic 10
Conflicts, requirements, and groups
Some command lines are valid argument by argument but invalid as a whole. --quiet --verbose makes no sense, and --compress means nothing without --output. This chapter covers how clap enforces these rules before your program logic runs. It assumes you can already define a derived Parser with options and flags, and that you know Option<T> fields are optional.
Why declare rules instead of checking in `main`
You could write if cli.quiet && cli.verbose { ... } yourself. Declaring the rule in the definition has three advantages:
- clap prints a standard error that names the arguments involved and exits with code 2.
- The
--helpusage line reflects required groups, so users see the rules. - The rules live next to the arguments they constrain, and tests can check them without a process.
Use manual checks only for rules clap cannot express, such as "the end date must be after the start date".
Conflicts and requirements
conflicts_with says two arguments cannot appear together. requires says one argument needs another. In the derive API, the string you pass is the argument's id, which is the field name.
use clap::Parser;
use std::path::PathBuf;
#[derive(Parser, Debug)]
struct Cli {
/// Write results to this file
#[arg(long)]
output: Option<PathBuf>,
/// Compress the output file (needs --output)
#[arg(long, requires = "output")]
compress: bool,
/// Suppress all output
#[arg(long, conflicts_with = "verbose")]
quiet: bool,
/// Print extra output
#[arg(long)]
verbose: bool,
}
fn main() {
let cli = Cli::parse();
println!("{cli:?}");
}Both rules apply in both directions where it makes sense. You declared the conflict only on quiet, but --verbose --quiet fails the same way. requires is one-directional: --output alone is fine, but --compress alone fails.
Here is a typical failure:
$ app --compress
error: the following required arguments were not provided:
--output <OUTPUT>
Usage: app --output <OUTPUT> --compressThe exact wording differs between clap versions, so do not match on it in tests. Match on the error kind instead, as shown later.
Other relationship attributes
Each attribute below goes inside #[arg(...)].
| Attribute | Meaning |
|---|---|
| `conflicts_with = "a"` | Cannot be used together with `a`. |
| `conflicts_with_all = ["a", "b"]` | Cannot be used with any of the listed arguments. |
| `requires = "a"` | If this is present, `a` must be present too. |
| `requires_all = ["a", "b"]` | If this is present, all listed arguments must be present. |
| `required_unless_present = "a"` | Required, unless `a` is given. |
| `required_if_eq("mode", "file")` | Required when `mode` has the value `file`. |
| `overrides_with = "a"` | If both are given, the last one wins and there is no error. |
overrides_with suits flag pairs such as --color and --no-color. A user can alias a default in a shell and still override it on the command line. A conflict would reject that.
Groups: "exactly one of these"
A group is a named set of arguments with a rule about how many may appear. In the derive API you make a group by putting the arguments in their own struct that derives Args. Then you embed it with #[command(flatten)] and configure it with #[group(...)].
use clap::{Args, Parser};
use std::path::PathBuf;
#[derive(Parser, Debug)]
struct Cli {
#[command(flatten)]
source: Source,
/// Number of retries
#[arg(long, default_value_t = 3)]
retries: u8,
}
#[derive(Args, Debug)]
#[group(required = true, multiple = false)]
struct Source {
/// Read from a local file
#[arg(long)]
file: Option<PathBuf>,
/// Download from a URL
#[arg(long)]
url: Option<String>,
}
fn main() {
let cli = Cli::parse();
match (&cli.source.file, &cli.source.url) {
(Some(path), None) => println!("file: {}", path.display()),
(None, Some(url)) => println!("url: {url}"),
_ => unreachable!("clap guarantees exactly one source"),
}
}The two settings combine into four behaviors:
| `required` | `multiple` | Rule |
|---|---|---|
| `true` | `false` | Exactly one member must be given. |
| `true` | `true` | At least one member must be given. |
| `false` | `false` | At most one member may be given. |
| `false` | `true` | No restriction. |
The defaults are required = false and multiple = true, so a plain flattened struct adds no rules.
The unreachable! is safe here because the group rule guarantees one Some. The type system does not know this, though. If you want the compiler to enforce "exactly one", use a subcommand or an enum instead. Groups are for when the choices are flags and the rest of the CLI is shared.
Choosing a constraint
Testing constraints
Constraint errors have specific ErrorKind values, so tests can check rules without matching message text. This program has a group like the one above and tests for each failure mode.
use clap::{Args, Parser};
#[derive(Parser, Debug)]
struct Cli {
#[command(flatten)]
source: Source,
#[arg(long, requires = "url")]
insecure: bool,
}
#[derive(Args, Debug)]
#[group(required = true, multiple = false)]
struct Source {
#[arg(long)]
file: Option<String>,
#[arg(long)]
url: Option<String>,
}
fn main() {
let cli = Cli::parse();
println!("{cli:?}");
}
#[cfg(test)]
mod tests {
use super::*;
use clap::error::ErrorKind;
use clap::CommandFactory;
#[test]
fn definition_is_valid() {
Cli::command().debug_assert();
}
#[test]
fn one_source_is_accepted() {
assert!(Cli::try_parse_from(["app", "--file", "a.txt"]).is_ok());
}
#[test]
fn two_sources_conflict() {
let err = Cli::try_parse_from(["app", "--file", "a", "--url", "b"]).unwrap_err();
assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
}
#[test]
fn missing_source_is_reported() {
let err = Cli::try_parse_from(["app"]).unwrap_err();
assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument);
}
#[test]
fn insecure_needs_url() {
let err = Cli::try_parse_from(["app", "--file", "a", "--insecure"]).unwrap_err();
assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument);
}
}Note that a missing required group and an unmet requires both produce MissingRequiredArgument. A conflict, whether from conflicts_with or from a group with multiple = false, produces ArgumentConflict.
Common mistakes
- Typos in ids.
requires = "outptu"refers to an argument that does not exist. clap checks this in debug builds, but the check is a panic fromdebug_assertor from the first parse. Keep thedebug_asserttest in your suite so it fails in CI, not on a user's machine. - Using the long flag name instead of the id. The id is the field name (
output_dir), not the flag spelling (output-dir). Renaming the field changes the id. - Mixing defaults with constraints. An argument with
default_value_talways has a value, which makes "was it given?" rules hard to reason about. PreferOption<T>for arguments that take part in conflicts and requirements. Apply the default in your own code. - Encoding too much in flags. If you have three groups and a pile of
requires_ifattributes, the flags are probably acting as modes. Move each mode to a subcommand, which is the next chapter's topic.
Exercise
A tool takes --json and --csv, and the user must choose exactly one. It also takes --pretty, which only applies to JSON output. Write the argument definitions for the format group and for --pretty. Which ErrorKind does app --json --csv produce, and which does app --csv --pretty produce?
Show answer
Put the formats in an Args struct: #[derive(Args)] #[group(required = true, multiple = false)] struct Format { #[arg(long)] json: bool, #[arg(long)] csv: bool }, flatten it into Cli with #[command(flatten)], and declare #[arg(long, requires = "json")] pretty: bool. app --json --csv produces ErrorKind::ArgumentConflict, because the group allows only one member. app --csv --pretty produces ErrorKind::MissingRequiredArgument, because --pretty requires --json, which was not given.