# clap 4.6.7

> > **Command Line Argument Parser for Rust**

## clap

> **Command Line Argument Parser for Rust**

Quick Links:
- Derive [tutorial][_derive::_tutorial] and [reference][_derive]
- Builder [tutorial][_tutorial] and [reference][Command]
- [Cookbook][_cookbook]
- [CLI Concepts][_concepts]
- [FAQ][_faq]
- [Discussions](https://github.com/clap-rs/clap/discussions)
- [CHANGELOG](https://github.com/clap-rs/clap/blob/v4.6.7/CHANGELOG.md) (includes major version migration
  guides)

### clap › Aspirations

- Out of the box, users get a polished CLI experience
  - Including common argument behavior, help generation, suggested fixes for users, colored output, [shell completions](https://github.com/clap-rs/clap/tree/master/clap_complete), etc
- Flexible enough to port your existing CLI interface
  - However, we won't necessarily streamline support for each use case
- Reasonable parse performance
- Resilient maintainership, including
  - Willing to break compatibility rather than batching up breaking changes in large releases
  - Leverage feature flags to keep to one active branch
  - Being under [WG-CLI](https://github.com/rust-cli/team/) to increase the bus factor
- We follow semver and will wait about 6-9 months between major breaking changes
- We will support the last two minor Rust releases (MSRV, currently 1.74)

While these aspirations can be at odds with fast build times and low binary
size, we will still strive to keep these reasonable for the flexibility you
get.  Check out the
[argparse-benchmarks](https://github.com/rust-cli/argparse-benchmarks-rs) for
CLI parsers optimized for other use cases.

### clap › Example

Run
```console
$ cargo add clap --features derive
```
*(See also [feature flag reference][_features])*

Then define your CLI in `main.rs`:
```rust
# #[cfg(feature = "derive")] {
use clap::Parser;

/// Simple program to greet a person
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
    /// Name of the person to greet
    #[arg(short, long)]
    name: String,

    /// Number of times to greet
    #[arg(short, long, default_value_t = 1)]
    count: u8,
}

fn main() {
    let args = Args::parse();

    for _ in 0..args.count {
        println!("Hello {}!", args.name);
    }
}
# }
```

And try it out:
```console
$ demo --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: demo[EXE] [OPTIONS] --name <NAME>

Options:
  -n, --name <NAME>    Name of the person to greet
  -c, --count <COUNT>  Number of times to greet [default: 1]
  -h, --help           Print help
  -V, --version        Print version

$ demo --name Me
Hello Me!

```
*(version number and `.exe` extension on windows replaced by placeholders)*

See also the derive [tutorial][_derive::_tutorial] and [reference][_derive]

### clap › Related Projects

Augment clap:
- [wild](https://crates.io/crates/wild) for supporting wildcards (`*`) on Windows like you do Linux
- [argfile](https://crates.io/crates/argfile) for loading additional arguments from a file (aka response files)
- [shadow-rs](https://crates.io/crates/shadow-rs) for generating `Command::long_version`
- [clap_mangen](https://crates.io/crates/clap_mangen) for generating man page source (roff)
- [clap_complete](https://crates.io/crates/clap_complete) for shell completion support
- [clap-i18n-richformatter](https://crates.io/crates/clap-i18n-richformatter) for i18n support with `clap::error::RichFormatter`

CLI Helpers
- [clio](https://crates.io/crates/clio) for reading/writing to files specified as arguments
- [clap-verbosity-flag](https://crates.io/crates/clap-verbosity-flag)
- [clap-cargo](https://crates.io/crates/clap-cargo)
- [colorchoice-clap](https://crates.io/crates/colorchoice-clap)

Testing
- [`trycmd`](https://crates.io/crates/trycmd):  Bulk snapshot testing
- [`snapbox`](https://crates.io/crates/snapbox):  Specialized snapshot testing
- [`assert_cmd`](https://crates.io/crates/assert_cmd) and [`assert_fs`](https://crates.io/crates/assert_fs): Customized testing

Documentation:
- [Command-line Apps for Rust](https://rust-cli.github.io/book/index.html) book

## clap::_concepts (module)

### clap::_concepts (module) › CLI Concepts

Note: this will be speaking towards the general case.

### clap::_concepts (module) › Environmental context

When you run a command line application, it is inside a terminal emulator, or terminal.
This handles integration with the rest of your system including user input,
rendering, etc.

The terminal will run inside of itself an interactive shell.
The shell is responsible for showing the prompt, receiving input including the command you are writing,
letting that command take over until completion, and then repeating.
This is called a read-eval-print loop, or REPL.
Typically the shell will take the command you typed and split it into separate arguments,
including handling of quoting, escaping, and globbing.
The parsing and evaluation of the command is shell specific.
The shell will then determine which application to run and then pass the full command-line as
individual arguments to your program.
These arguments are exposed in Rust as [`std::env::args_os`].

Windows is an exception in Shell behavior in that the command is passed as an individual
string, verbatim, and the application must split the arguments.
[`std::env::args_os`] will handle the splitting for you but will not handle globs.

Takeaways:
- Your application will only see quotes that have been escaped within the shell
  - e.g. to receive `message="hello world"`, you may need to type `'message="hello world"'` or `message=\"hello world\"`
- If your applications needs to parse a string into arguments,
  you will need to pick a syntax and do it yourself
  - POSIX's shell syntax is a common choice and available in packages like [shlex](https://docs.rs/shlex)
  - See also our [REPL cookbook entry][crate::_cookbook::repl]
- On Windows, you will need to handle globbing yourself if desired
  - [`wild`](https://docs.rs/wild) can help with that

### clap::_concepts (module) › Argument Parsing

The first argument of [`std::env::args_os`] is the [`Command::bin_name`]
which is usually limited to affecting [`Command::render_usage`].
[`Command::no_binary_name`] and [`Command::multicall`] exist for rare cases when this assumption is not valid.

Command-lines are a context-sensitive grammar,
meaning the interpretation of an argument is based on the arguments that came before.
Arguments come in one of several flavors:
- Values
- Flags
- Subcommands

When examining the next argument,
1. If it starts with a `--`,
   then that is a long Flag and all remaining text up to a `=` or the end is
   matched to a [`Arg::long`], [`Command::long_flag`], or alias.
   - Everything after the `=` is taken as a Value and parsing a new argument is examined.
   - If no `=` is present, then Values will be taken according to [`Arg::num_args`]
   - We generally call a Flag that takes a Value an Option
2. If it starts with a `-`,
   then that is a sequence of short Flags where each character is matched against a [`Arg::short`], [`Command::short_flag`] or
   alias until `=`, the end, or a short Flag takes Values (see [`Arg::num_args`])
3. If its a `--`, that is an escape and all future arguments are considered to be a Value, even if
   they start with `--` or `-`
4. If it matches a [`Command::name`],
   then the argument is a subcommand
5. If there is an [`Arg`] at the next [`Arg::index`],
   then the argument is considered a Positional argument

When a subcommand matches,
all further arguments are parsed by that [`Command`].

There are many settings that tweak this behavior, including:
- [`Arg::last`]: a positional that can only come after `--`
- [`Arg::trailing_var_arg`]: all further arguments are captured as additional Values
- [`Arg::allow_hyphen_values`] and [`Arg::allow_negative_numbers`]: assumes arguments
  starting with `-` are Values and not Flags.
- [`Command::subcommand_precedence_over_arg`]: when an [`Arg::num_args`] takes Values,
  stop if one matches a subCommand
- [`Command::allow_missing_positional`]: in limited cases a [`Arg::index`] may be skipped
- [`Command::allow_external_subcommands`]: treat any unknown argument as a subcommand, capturing
  all remaining arguments.

Takeaways
- Values that start with a `-` either need to be escaped by the user with `--`
  (if a positional),
  or you need to set [`Arg::allow_hyphen_values`] or [`Arg::allow_negative_numbers`]
- [`Arg::num_args`],
  [`ArgAction::Append`] (on a positional),
  [`Arg::trailing_var_arg`],
  and [`Command::allow_external_subcommands`]
  all affect the parser in similar but slightly different ways and which to use depends on your
  application

### clap::_concepts (module) › Value Parsing

When reacting to a Flag (no Value),
[`Arg::default_missing_values`] will be applied.

The Value will be split by [`Arg::value_delimiter`].

The Value will then be stored according to its [`ArgAction`].
For most [`ArgAction`]s,
the Value will be parsed according to [`ValueParser`]
and stored in the [`ArgMatches`].

## clap::_cookbook (module)

### clap::_cookbook (module) › Documentation: Cookbook

Typed arguments: [derive][typed_derive]
- Topics:
  - Custom `parse()`

Custom cargo command: [builder][cargo_example], [derive][cargo_example_derive]
- Topics:
  - Subcommands
  - Cargo plugins
  - custom terminal [styles][crate::Command::styles] (colors)

find-like interface: [builder][find]
- Topics:
  - Position-sensitive flags

git-like interface: [builder][git], [derive][git_derive]
- Topics:
  - Subcommands
  - External subcommands
  - Optional subcommands
  - Default subcommands
  - [`last`][crate::Arg::last]
  - Configurable command aliases

pacman-like interface: [builder][pacman]
- Topics:
  - Flag subcommands
  - Conflicting arguments
  - Visualizing help output changes through snapshot testing

Escaped positionals with `--`: [builder][escaped_positional], [derive][escaped_positional_derive]

Multi-call
- busybox: [builder][multicall_busybox]
  - Topics:
    - Subcommands
- hostname: [builder][multicall_hostname]
  - Topics:
    - Subcommands

repl: [builder][repl], [derive][repl_derive]
- Topics:
  - Read-Eval-Print Loops / Custom command lines

## clap::_cookbook::cargo_example (module)

### clap::_cookbook::cargo_example (module) › Example: cargo subcommand (Builder API)

```rust
fn main() {
    let cmd = clap::Command::new("cargo")
        .bin_name("cargo")
        .styles(CLAP_STYLING)
        .subcommand_required(true)
        .subcommand(
            clap::command!("example").arg(
                clap::arg!(--"manifest-path" <PATH>)
                    .value_parser(clap::value_parser!(std::path::PathBuf)),
            ),
        );
    let matches = cmd.get_matches();
    let matches = match matches.subcommand() {
        Some(("example", matches)) => matches,
        _ => unreachable!("clap should ensure we don't get here"),
    };
    let manifest_path = matches.get_one::<std::path::PathBuf>("manifest-path");
    println!("{manifest_path:?}");
}

// See also `clap_cargo::style::CLAP_STYLING`
pub const CLAP_STYLING: clap::builder::styling::Styles = clap::builder::styling::Styles::styled()
    .header(clap_cargo::style::HEADER)
    .usage(clap_cargo::style::USAGE)
    .literal(clap_cargo::style::LITERAL)
    .placeholder(clap_cargo::style::PLACEHOLDER)
    .error(clap_cargo::style::ERROR)
    .valid(clap_cargo::style::VALID)
    .invalid(clap_cargo::style::INVALID);
```

For more on creating a custom subcommand, see [the cargo
book](https://doc.rust-lang.org/cargo/reference/external-tools.html#custom-subcommands).
The crate [`clap-cargo`](https://github.com/crate-ci/clap-cargo) can help in
mimicking cargo's interface.

The help looks like:
```console
$ cargo-example --help
Usage: cargo <COMMAND>

Commands:
  example  A simple to use, efficient, and full-featured Command Line Argument Parser
  help     Print this message or the help of the given subcommand(s)

Options:
  -h, --help  Print help

$ cargo-example example --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: cargo example [OPTIONS]

Options:
      --manifest-path <PATH>
  -h, --help                  Print help
  -V, --version               Print version

```

Then to directly invoke the command, run:
```console
$ cargo-example example
None

$ cargo-example example --manifest-path Cargo.toml
Some("Cargo.toml")

```

## clap::_cookbook::cargo_example_derive (module)

### clap::_cookbook::cargo_example_derive (module) › Example: cargo subcommand (Derive API)

```rust
use clap::Parser;

#[derive(Parser)] // requires `derive` feature
#[command(name = "cargo")]
#[command(bin_name = "cargo")]
#[command(styles = CLAP_STYLING)]
enum CargoCli {
    ExampleDerive(ExampleDeriveArgs),
}

// See also `clap_cargo::style::CLAP_STYLING`
pub const CLAP_STYLING: clap::builder::styling::Styles = clap::builder::styling::Styles::styled()
    .header(clap_cargo::style::HEADER)
    .usage(clap_cargo::style::USAGE)
    .literal(clap_cargo::style::LITERAL)
    .placeholder(clap_cargo::style::PLACEHOLDER)
    .error(clap_cargo::style::ERROR)
    .valid(clap_cargo::style::VALID)
    .invalid(clap_cargo::style::INVALID);

#[derive(clap::Args)]
#[command(version, about, long_about = None)]
struct ExampleDeriveArgs {
    #[arg(long)]
    manifest_path: Option<std::path::PathBuf>,
}

fn main() {
    let CargoCli::ExampleDerive(args) = CargoCli::parse();
    println!("{:?}", args.manifest_path);
}
```

For more on creating a custom subcommand, see [the cargo
book](https://doc.rust-lang.org/cargo/reference/external-tools.html#custom-subcommands).
The crate [`clap-cargo`](https://github.com/crate-ci/clap-cargo) can help in
mimicking cargo's interface.

The help looks like:
```console
$ cargo-example-derive --help
Usage: cargo <COMMAND>

Commands:
  example-derive  A simple to use, efficient, and full-featured Command Line Argument Parser
  help            Print this message or the help of the given subcommand(s)

Options:
  -h, --help  Print help

$ cargo-example-derive example-derive --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: cargo example-derive [OPTIONS]

Options:
      --manifest-path <MANIFEST_PATH>
  -h, --help                           Print help
  -V, --version                        Print version

```

Then to directly invoke the command, run:
```console
$ cargo-example-derive example-derive
None

$ cargo-example-derive example-derive --manifest-path Cargo.toml
Some("Cargo.toml")

```

## clap::_cookbook::escaped_positional (module)

### clap::_cookbook::escaped_positional (module) › Example (Builder API)

```rust
use clap::{ArgAction, arg, command, value_parser};

fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(arg!(eff: -f).action(ArgAction::SetTrue))
        .arg(arg!(pea: -p <PEAR>).value_parser(value_parser!(String)))
        .arg(
            // Indicates that `slop` is only accessible after `--`.
            arg!(slop: [SLOP])
                .num_args(1..)
                .last(true)
                .value_parser(value_parser!(String)),
        )
        .get_matches();

    // This is what will happen with `myprog -f -p=bob -- sloppy slop slop`...

    // -f used: true
    println!("-f used: {:?}", matches.get_flag("eff"));
    // -p's value: Some("bob")
    println!("-p's value: {:?}", matches.get_one::<String>("pea"));
    // 'slops' values: Some(["sloppy", "slop", "slop"])
    println!(
        "'slops' values: {:?}",
        matches
            .get_many::<String>("slop")
            .map(|vals| vals.collect::<Vec<_>>())
            .unwrap_or_default()
    );

    // Continued program logic goes here...
}
```

**This requires enabling the [`cargo` feature flag][crate::_features].**

You can use `--` to escape further arguments.

Let's see what this looks like in the help:
```console
$ escaped-positional --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: escaped-positional[EXE] [OPTIONS] [-- <SLOP>...]

Arguments:
  [SLOP]...

Options:
  -f
  -p <PEAR>
  -h, --help     Print help
  -V, --version  Print version

```

Here is a baseline without any arguments:
```console
$ escaped-positional
-f used: false
-p's value: None
'slops' values: []

```

Notice that we can't pass positional arguments before `--`:
```console
$ escaped-positional foo bar
? failed
error: unexpected argument 'foo' found

Usage: escaped-positional[EXE] [OPTIONS] [-- <SLOP>...]

For more information, try '--help'.

```

But you can after:
```console
$ escaped-positional -f -p=bob -- sloppy slop slop
-f used: true
-p's value: Some("bob")
'slops' values: ["sloppy", "slop", "slop"]

```

As mentioned, the parser will directly pass everything through:
```console
$ escaped-positional -- -f -p=bob sloppy slop slop
-f used: false
-p's value: None
'slops' values: ["-f", "-p=bob", "sloppy", "slop", "slop"]

```

## clap::_cookbook::escaped_positional_derive (module)

### clap::_cookbook::escaped_positional_derive (module) › Example (Derive API)

```rust
use clap::Parser;

#[derive(Parser)] // requires `derive` feature
#[command(version, about, long_about = None)]
struct Cli {
    #[arg(short = 'f')]
    eff: bool,

    #[arg(short = 'p', value_name = "PEAR")]
    pea: Option<String>,

    #[arg(last = true)]
    slop: Vec<String>,
}

fn main() {
    let args = Cli::parse();

    // This is what will happen with `myprog -f -p=bob -- sloppy slop slop`...
    println!("-f used: {:?}", args.eff); // -f used: true
    println!("-p's value: {:?}", args.pea); // -p's value: Some("bob")
    println!("'slops' values: {:?}", args.slop); // 'slops' values: Some(["sloppy", "slop", "slop"])

    // Continued program logic goes here...
}
```

**This requires enabling the [`derive` feature flag][crate::_features].**

You can use `--` to escape further arguments.

Let's see what this looks like in the help:
```console
$ escaped-positional-derive --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: escaped-positional-derive[EXE] [OPTIONS] [-- <SLOP>...]

Arguments:
  [SLOP]...

Options:
  -f
  -p <PEAR>
  -h, --help     Print help
  -V, --version  Print version

```

Here is a baseline without any arguments:
```console
$ escaped-positional-derive
-f used: false
-p's value: None
'slops' values: []

```

Notice that we can't pass positional arguments before `--`:
```console
$ escaped-positional-derive foo bar
? failed
error: unexpected argument 'foo' found

Usage: escaped-positional-derive[EXE] [OPTIONS] [-- <SLOP>...]

For more information, try '--help'.

```

But you can after:
```console
$ escaped-positional-derive -f -p=bob -- sloppy slop slop
-f used: true
-p's value: Some("bob")
'slops' values: ["sloppy", "slop", "slop"]

```

As mentioned, the parser will directly pass everything through:
```console
$ escaped-positional-derive -- -f -p=bob sloppy slop slop
-f used: false
-p's value: None
'slops' values: ["-f", "-p=bob", "sloppy", "slop", "slop"]

```

## clap::_cookbook::find (module)

### clap::_cookbook::find (module) › Example: find-like CLI (Builder API)

```rust
use std::collections::BTreeMap;

use clap::{Arg, ArgAction, ArgGroup, ArgMatches, Command, command, value_parser};

fn main() {
    let matches = cli().get_matches();
    let values = Value::from_matches(&matches);
    println!("{values:#?}");
}

fn cli() -> Command {
    command!()
        .group(ArgGroup::new("tests").multiple(true))
        .next_help_heading("TESTS")
        .args([
            position_sensitive_flag(Arg::new("empty"))
                .long("empty")
                .action(ArgAction::Append)
                .help("File is empty and is either a regular file or a directory")
                .group("tests"),
            Arg::new("name")
                .long("name")
                .action(ArgAction::Append)
                .help("Base of file name (the path with the leading directories removed) matches shell pattern pattern")
                .group("tests")
        ])
        .group(ArgGroup::new("operators").multiple(true))
        .next_help_heading("OPERATORS")
        .args([
            position_sensitive_flag(Arg::new("or"))
                .short('o')
                .long("or")
                .action(ArgAction::Append)
                .help("expr2 is not evaluate if exp1 is true")
                .group("operators"),
            position_sensitive_flag(Arg::new("and"))
                .short('a')
                .long("and")
                .action(ArgAction::Append)
                .help("Same as `expr1 expr1`")
                .group("operators"),
        ])
}

fn position_sensitive_flag(arg: Arg) -> Arg {
    // Flags don't track the position of each occurrence, so we need to emulate flags with
    // value-less options to get the same result
    arg.num_args(0)
        .value_parser(value_parser!(bool))
        .default_missing_value("true")
        .default_value("false")
}

#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub enum Value {
    Bool(bool),
    String(String),
}

impl Value {
    pub fn from_matches(matches: &ArgMatches) -> Vec<(clap::Id, Self)> {
        let mut values = BTreeMap::new();
        for id in matches.ids() {
            if matches.try_get_many::<clap::Id>(id.as_str()).is_ok() {
                // ignore groups
                continue;
            }
            let value_source = matches
                .value_source(id.as_str())
                .expect("id came from matches");
            if value_source != clap::parser::ValueSource::CommandLine {
                // Any other source just gets tacked on at the end (like default values)
                continue;
            }
            if Self::extract::<String>(matches, id, &mut values) {
                continue;
            }
            if Self::extract::<bool>(matches, id, &mut values) {
                continue;
            }
            unimplemented!("unknown type for {id}: {matches:?}");
        }
        values.into_values().collect::<Vec<_>>()
    }

    fn extract<T: Clone + Into<Self> + Send + Sync + 'static>(
        matches: &ArgMatches,
        id: &clap::Id,
        output: &mut BTreeMap<usize, (clap::Id, Self)>,
    ) -> bool {
        match matches.try_get_many::<T>(id.as_str()) {
            Ok(Some(values)) => {
                for (value, index) in values.zip(
                    matches
                        .indices_of(id.as_str())
                        .expect("id came from matches"),
                ) {
                    output.insert(index, (id.clone(), value.clone().into()));
                }
                true
            }
            Ok(None) => {
                unreachable!("`ids` only reports what is present")
            }
            Err(clap::parser::MatchesError::UnknownArgument { .. }) => {
                unreachable!("id came from matches")
            }
            Err(clap::parser::MatchesError::Downcast { .. }) => false,
            Err(_) => {
                unreachable!("id came from matches")
            }
        }
    }
}

impl From<String> for Value {
    fn from(other: String) -> Self {
        Self::String(other)
    }
}

impl From<bool> for Value {
    fn from(other: bool) -> Self {
        Self::Bool(other)
    }
}
```

`find` is an example of position-sensitive flags

```console
$ find --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: find[EXE] [OPTIONS]

Options:
  -h, --help     Print help
  -V, --version  Print version

TESTS:
      --empty        File is empty and is either a regular file or a directory
      --name <name>  Base of file name (the path with the leading directories removed) matches shell
                     pattern pattern

OPERATORS:
  -o, --or   expr2 is not evaluate if exp1 is true
  -a, --and  Same as `expr1 expr1`

$ find --empty -o --name .keep
[
    (
        "empty",
        Bool(
            true,
        ),
    ),
    (
        "or",
        Bool(
            true,
        ),
    ),
    (
        "name",
        String(
            ".keep",
        ),
    ),
]

$ find --empty -o --name .keep -o --name foo
[
    (
        "empty",
        Bool(
            true,
        ),
    ),
    (
        "or",
        Bool(
            true,
        ),
    ),
    (
        "name",
        String(
            ".keep",
        ),
    ),
    (
        "or",
        Bool(
            true,
        ),
    ),
    (
        "name",
        String(
            "foo",
        ),
    ),
]

```

## clap::_cookbook::git (module)

### clap::_cookbook::git (module) › Example: git-like CLI (Builder API)

```rust
use std::collections::HashMap;
use std::ffi::OsString;
use std::path::PathBuf;

use clap::{ArgMatches, Command, arg};

fn cli() -> Command {
    Command::new("git")
        .about("A fictional versioning CLI")
        .subcommand_required(true)
        .arg_required_else_help(true)
        .allow_external_subcommands(true)
        .subcommand(
            Command::new("clone")
                .about("Clones repos")
                .arg(arg!(<REMOTE> "The remote to clone"))
                .arg_required_else_help(true),
        )
        .subcommand(
            Command::new("diff")
                .about("Compare two commits")
                .arg(arg!(base: [COMMIT]))
                .arg(arg!(head: [COMMIT]))
                .arg(arg!(path: [PATH]).last(true))
                .arg(
                    arg!(--color <WHEN>)
                        .value_parser(["always", "auto", "never"])
                        .num_args(0..=1)
                        .require_equals(true)
                        .default_value("auto")
                        .default_missing_value("always"),
                ),
        )
        .subcommand(
            Command::new("push")
                .about("pushes things")
                .arg(arg!(<REMOTE> "The remote to target"))
                .arg_required_else_help(true),
        )
        .subcommand(
            Command::new("add")
                .about("adds things")
                .arg_required_else_help(true)
                .arg(arg!(<PATH> ... "Stuff to add").value_parser(clap::value_parser!(PathBuf))),
        )
        .subcommand(
            Command::new("stash")
                .args_conflicts_with_subcommands(true)
                .flatten_help(true)
                .args(push_args())
                .subcommand(Command::new("push").args(push_args()))
                .subcommand(Command::new("pop").arg(arg!([STASH])))
                .subcommand(Command::new("apply").arg(arg!([STASH]))),
        )
}

fn push_args() -> Vec<clap::Arg> {
    vec![arg!(-m --message <MESSAGE>)]
}

fn aliases() -> HashMap<&'static str, Vec<&'static str>> {
    HashMap::from([
        ("last", vec!["diff", "HEAD~", "HEAD", "--"]),
        ("stage", vec!["add"]),
    ])
}

fn parse_aliases() -> Result<ArgMatches, clap::Error> {
    let matches = cli().try_get_matches()?;
    expand_aliases(matches, Vec::new())
}

fn expand_aliases(
    matches: ArgMatches,
    mut expanded: Vec<String>,
) -> Result<ArgMatches, clap::Error> {
    let Some((name, sub_matches)) = matches.subcommand() else {
        return Ok(matches);
    };
    if cli().find_subcommand(name).is_some() {
        return Ok(matches);
    }

    let aliases = aliases();
    let Some(alias) = aliases.get(name) else {
        return Ok(matches);
    };
    let mut args = alias.iter().map(OsString::from).collect::<Vec<_>>();
    args.extend(
        sub_matches
            .get_many::<OsString>("")
            .into_iter()
            .flatten()
            .cloned(),
    );
    let matches = cli().no_binary_name(true).try_get_matches_from(args)?;
    let new_name = matches.subcommand_name().expect("subcommand required");
    expanded.push(name.to_owned());
    if expanded.iter().any(|name| name == new_name) {
        return Err(clap::Error::raw(
            clap::error::ErrorKind::InvalidSubcommand,
            format!("recursive alias `{}`", expanded[0]),
        ));
    }

    expand_aliases(matches, expanded)
}

fn main() {
    let matches = parse_aliases().unwrap_or_else(|error| error.exit());

    match matches.subcommand() {
        Some(("clone", sub_matches)) => {
            println!(
                "Cloning {}",
                sub_matches.get_one::<String>("REMOTE").expect("required")
            );
        }
        Some(("diff", sub_matches)) => {
            let color = sub_matches
                .get_one::<String>("color")
                .map(|s| s.as_str())
                .expect("defaulted in clap");

            let mut base = sub_matches.get_one::<String>("base").map(|s| s.as_str());
            let mut head = sub_matches.get_one::<String>("head").map(|s| s.as_str());
            let mut path = sub_matches.get_one::<String>("path").map(|s| s.as_str());
            if path.is_none() {
                path = head;
                head = None;
                if path.is_none() {
                    path = base;
                    base = None;
                }
            }
            let base = base.unwrap_or("stage");
            let head = head.unwrap_or("worktree");
            let path = path.unwrap_or("");
            println!("Diffing {base}..{head} {path} (color={color})");
        }
        Some(("push", sub_matches)) => {
            println!(
                "Pushing to {}",
                sub_matches.get_one::<String>("REMOTE").expect("required")
            );
        }
        Some(("add", sub_matches)) => {
            let paths = sub_matches
                .get_many::<PathBuf>("PATH")
                .into_iter()
                .flatten()
                .collect::<Vec<_>>();
            println!("Adding {paths:?}");
        }
        Some(("stash", sub_matches)) => {
            let stash_command = sub_matches.subcommand().unwrap_or(("push", sub_matches));
            match stash_command {
                ("apply", sub_matches) => {
                    let stash = sub_matches.get_one::<String>("STASH");
                    println!("Applying {stash:?}");
                }
                ("pop", sub_matches) => {
                    let stash = sub_matches.get_one::<String>("STASH");
                    println!("Popping {stash:?}");
                }
                ("push", sub_matches) => {
                    let message = sub_matches.get_one::<String>("message");
                    println!("Pushing {message:?}");
                }
                (name, _) => {
                    unreachable!("Unsupported subcommand `{name}`")
                }
            }
        }
        Some((ext, sub_matches)) => {
            let args = sub_matches
                .get_many::<OsString>("")
                .into_iter()
                .flatten()
                .collect::<Vec<_>>();
            println!("Calling out to {ext:?} with {args:?}");
        }
        _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable!()
    }

    // Continued program logic goes here...
}
```

Git is an example of several common subcommand patterns.

Help:
```console
$ git
? failed
A fictional versioning CLI

Usage: git[EXE] <COMMAND>

Commands:
  clone  Clones repos
  diff   Compare two commits
  push   pushes things
  add    adds things
  stash
  help   Print this message or the help of the given subcommand(s)

Options:
  -h, --help  Print help

$ git help
A fictional versioning CLI

Usage: git[EXE] <COMMAND>

Commands:
  clone  Clones repos
  diff   Compare two commits
  push   pushes things
  add    adds things
  stash
  help   Print this message or the help of the given subcommand(s)

Options:
  -h, --help  Print help

$ git help add
adds things

Usage: git[EXE] add <PATH>...

Arguments:
  <PATH>...  Stuff to add

Options:
  -h, --help  Print help

```

A basic argument:
```console
$ git add
? failed
adds things

Usage: git[EXE] add <PATH>...

Arguments:
  <PATH>...  Stuff to add

Options:
  -h, --help  Print help

$ git add Cargo.toml Cargo.lock
Adding ["Cargo.toml", "Cargo.lock"]

```

Default subcommand:
```console
$ git stash -h
Usage: git[EXE] stash [OPTIONS]
       git[EXE] stash push [OPTIONS]
       git[EXE] stash pop [STASH]
       git[EXE] stash apply [STASH]
       git[EXE] stash help [COMMAND]...

Options:
  -m, --message <MESSAGE>
  -h, --help               Print help

git[EXE] stash push:
  -m, --message <MESSAGE>
  -h, --help               Print help

git[EXE] stash pop:
  -h, --help  Print help
  [STASH]

git[EXE] stash apply:
  -h, --help  Print help
  [STASH]

git[EXE] stash help:
Print this message or the help of the given subcommand(s)
  [COMMAND]...  Print help for the subcommand(s)

$ git stash push -h
Usage: git[EXE] stash push [OPTIONS]

Options:
  -m, --message <MESSAGE>
  -h, --help               Print help

$ git stash pop -h
Usage: git[EXE] stash pop [STASH]

Arguments:
  [STASH]

Options:
  -h, --help  Print help

$ git stash -m "Prototype"
Pushing Some("Prototype")

$ git stash pop
Popping None

$ git stash push -m "Prototype"
Pushing Some("Prototype")

$ git stash pop
Popping None

```

External subcommands:
```console
$ git custom-tool arg1 --foo bar
Calling out to "custom-tool" with ["arg1", "--foo", "bar"]

```

Configurable aliases:
Aliases loaded from application configuration can expand into built-in commands
and arguments. Built-in commands take precedence over configured aliases.

```console
$ git last ./src
Diffing HEAD~..HEAD ./src (color=auto)

$ git stage Cargo.toml Cargo.lock
Adding ["Cargo.toml", "Cargo.lock"]

```

Last argument:
```console
$ git diff --help
Compare two commits

Usage: git[EXE] diff [OPTIONS] [COMMIT] [COMMIT] [-- <PATH>]

Arguments:
  [COMMIT]
  [COMMIT]
  [PATH]

Options:
      --color[=<WHEN>]  [default: auto] [possible values: always, auto, never]
  -h, --help            Print help

$ git diff
Diffing stage..worktree  (color=auto)

$ git diff ./src
Diffing stage..worktree ./src (color=auto)

$ git diff HEAD ./src
Diffing HEAD..worktree ./src (color=auto)

$ git diff HEAD~~ -- HEAD
Diffing HEAD~~..worktree HEAD (color=auto)

$ git diff --color
Diffing stage..worktree  (color=always)

$ git diff --color=never
Diffing stage..worktree  (color=never)

```

## clap::_cookbook::git_derive (module)

### clap::_cookbook::git_derive (module) › Example: git-like CLI (Derive API)

```rust
use std::collections::HashMap;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::path::PathBuf;

use clap::{Args, Parser, Subcommand, ValueEnum};

/// A fictional versioning CLI
#[derive(Debug, Parser)] // requires `derive` feature
#[command(name = "git")]
#[command(about = "A fictional versioning CLI", long_about = None)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Debug, Subcommand)]
enum Commands {
    /// Clones repos
    #[command(arg_required_else_help = true)]
    Clone {
        /// The remote to clone
        remote: String,
    },
    /// Compare two commits
    Diff {
        #[arg(value_name = "COMMIT")]
        base: Option<OsString>,
        #[arg(value_name = "COMMIT")]
        head: Option<OsString>,
        #[arg(last = true)]
        path: Option<OsString>,
        #[arg(
            long,
            require_equals = true,
            value_name = "WHEN",
            num_args = 0..=1,
            default_value_t = ColorWhen::Auto,
            default_missing_value = "always",
            value_enum
        )]
        color: ColorWhen,
    },
    /// pushes things
    #[command(arg_required_else_help = true)]
    Push {
        /// The remote to target
        remote: String,
    },
    /// adds things
    #[command(arg_required_else_help = true)]
    Add {
        /// Stuff to add
        #[arg(required = true)]
        path: Vec<PathBuf>,
    },
    Stash(StashArgs),
    #[command(external_subcommand)]
    External(Vec<OsString>),
}

#[derive(ValueEnum, Copy, Clone, Debug, PartialEq, Eq)]
enum ColorWhen {
    Always,
    Auto,
    Never,
}

impl std::fmt::Display for ColorWhen {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.to_possible_value()
            .expect("no values are skipped")
            .get_name()
            .fmt(f)
    }
}

#[derive(Debug, Args)]
#[command(args_conflicts_with_subcommands = true)]
#[command(flatten_help = true)]
struct StashArgs {
    #[command(subcommand)]
    command: Option<StashCommands>,

    #[command(flatten)]
    push: StashPushArgs,
}

#[derive(Debug, Subcommand)]
enum StashCommands {
    Push(StashPushArgs),
    Pop { stash: Option<String> },
    Apply { stash: Option<String> },
}

#[derive(Debug, Args)]
struct StashPushArgs {
    #[arg(short, long)]
    message: Option<String>,
}

fn aliases() -> HashMap<&'static str, Vec<&'static str>> {
    HashMap::from([
        ("last", vec!["diff", "HEAD~", "HEAD", "--"]),
        ("stage", vec!["add"]),
    ])
}

fn parse_aliases() -> Result<Cli, clap::Error> {
    let args = Cli::try_parse()?;
    expand_aliases(args, Vec::new())
}

fn expand_aliases(args: Cli, mut expanded: Vec<String>) -> Result<Cli, clap::Error> {
    let Commands::External(external_args) = &args.command else {
        return Ok(args);
    };
    let Some(name) = external_args.first().and_then(|name| name.to_str()) else {
        return Ok(args);
    };

    let aliases = aliases();
    let Some(alias) = aliases.get(name) else {
        return Ok(args);
    };
    if expanded.iter().any(|expanded| expanded == name) {
        return Err(clap::Error::raw(
            clap::error::ErrorKind::InvalidSubcommand,
            format!("recursive alias `{}`", expanded[0]),
        ));
    }
    expanded.push(name.to_owned());

    let mut alias_args = vec![OsString::from("git")];
    alias_args.extend(alias.iter().map(OsString::from));
    alias_args.extend(external_args.iter().skip(1).cloned());
    let args = Cli::try_parse_from(alias_args)?;

    expand_aliases(args, expanded)
}

fn main() {
    let args = parse_aliases().unwrap_or_else(|error| error.exit());

    match args.command {
        Commands::Clone { remote } => {
            println!("Cloning {remote}");
        }
        Commands::Diff {
            mut base,
            mut head,
            mut path,
            color,
        } => {
            if path.is_none() {
                path = head;
                head = None;
                if path.is_none() {
                    path = base;
                    base = None;
                }
            }
            let base = base
                .as_deref()
                .map(|s| s.to_str().unwrap())
                .unwrap_or("stage");
            let head = head
                .as_deref()
                .map(|s| s.to_str().unwrap())
                .unwrap_or("worktree");
            let path = path.as_deref().unwrap_or_else(|| OsStr::new(""));
            println!(
                "Diffing {}..{} {} (color={})",
                base,
                head,
                path.to_string_lossy(),
                color
            );
        }
        Commands::Push { remote } => {
            println!("Pushing to {remote}");
        }
        Commands::Add { path } => {
            println!("Adding {path:?}");
        }
        Commands::Stash(stash) => {
            let stash_cmd = stash.command.unwrap_or(StashCommands::Push(stash.push));
            match stash_cmd {
                StashCommands::Push(push) => {
                    println!("Pushing {push:?}");
                }
                StashCommands::Pop { stash } => {
                    println!("Popping {stash:?}");
                }
                StashCommands::Apply { stash } => {
                    println!("Applying {stash:?}");
                }
            }
        }
        Commands::External(args) => {
            println!("Calling out to {:?} with {:?}", args[0], &args[1..]);
        }
    }

    // Continued program logic goes here...
}
```

**This requires enabling the [`derive` feature flag][crate::_features].**

Git is an example of several common subcommand patterns.

Help:
```console
$ git-derive
? failed
A fictional versioning CLI

Usage: git-derive[EXE] <COMMAND>

Commands:
  clone  Clones repos
  diff   Compare two commits
  push   pushes things
  add    adds things
  stash
  help   Print this message or the help of the given subcommand(s)

Options:
  -h, --help  Print help

$ git-derive help
A fictional versioning CLI

Usage: git-derive[EXE] <COMMAND>

Commands:
  clone  Clones repos
  diff   Compare two commits
  push   pushes things
  add    adds things
  stash
  help   Print this message or the help of the given subcommand(s)

Options:
  -h, --help  Print help

$ git-derive help add
adds things

Usage: git-derive[EXE] add <PATH>...

Arguments:
  <PATH>...  Stuff to add

Options:
  -h, --help  Print help

```

A basic argument:
```console
$ git-derive add
? failed
adds things

Usage: git-derive[EXE] add <PATH>...

Arguments:
  <PATH>...  Stuff to add

Options:
  -h, --help  Print help

$ git-derive add Cargo.toml Cargo.lock
Adding ["Cargo.toml", "Cargo.lock"]

```

Default subcommand:
```console
$ git-derive stash -h
Usage: git-derive[EXE] stash [OPTIONS]
       git-derive[EXE] stash push [OPTIONS]
       git-derive[EXE] stash pop [STASH]
       git-derive[EXE] stash apply [STASH]
       git-derive[EXE] stash help [COMMAND]...

Options:
  -m, --message <MESSAGE>
  -h, --help               Print help

git-derive[EXE] stash push:
  -m, --message <MESSAGE>
  -h, --help               Print help

git-derive[EXE] stash pop:
  -h, --help  Print help
  [STASH]

git-derive[EXE] stash apply:
  -h, --help  Print help
  [STASH]

git-derive[EXE] stash help:
Print this message or the help of the given subcommand(s)
  [COMMAND]...  Print help for the subcommand(s)

$ git-derive stash push -h
Usage: git-derive[EXE] stash push [OPTIONS]

Options:
  -m, --message <MESSAGE>
  -h, --help               Print help

$ git-derive stash pop -h
Usage: git-derive[EXE] stash pop [STASH]

Arguments:
  [STASH]

Options:
  -h, --help  Print help

$ git-derive stash -m "Prototype"
Pushing StashPushArgs { message: Some("Prototype") }

$ git-derive stash pop
Popping None

$ git-derive stash push -m "Prototype"
Pushing StashPushArgs { message: Some("Prototype") }

$ git-derive stash pop
Popping None

```

External subcommands:
```console
$ git-derive custom-tool arg1 --foo bar
Calling out to "custom-tool" with ["arg1", "--foo", "bar"]

```

Configurable aliases:
Aliases loaded from application configuration can expand into built-in commands
and arguments. Built-in commands take precedence over configured aliases.

```console
$ git-derive last ./src
Diffing HEAD~..HEAD ./src (color=auto)

$ git-derive stage Cargo.toml Cargo.lock
Adding ["Cargo.toml", "Cargo.lock"]

```

Last argument:
```console
$ git-derive diff --help
Compare two commits

Usage: git-derive[EXE] diff [OPTIONS] [COMMIT] [COMMIT] [-- <PATH>]

Arguments:
  [COMMIT]
  [COMMIT]
  [PATH]

Options:
      --color[=<WHEN>]  [default: auto] [possible values: always, auto, never]
  -h, --help            Print help

$ git-derive diff
Diffing stage..worktree  (color=auto)

$ git-derive diff ./src
Diffing stage..worktree ./src (color=auto)

$ git-derive diff HEAD ./src
Diffing HEAD..worktree ./src (color=auto)

$ git-derive diff HEAD~~ -- HEAD
Diffing HEAD~~..worktree HEAD (color=auto)

$ git-derive diff --color
Diffing stage..worktree  (color=always)

$ git-derive diff --color=never
Diffing stage..worktree  (color=never)

```

## clap::_cookbook::multicall_busybox (module)

### clap::_cookbook::multicall_busybox (module) › Example: busybox-like CLI (Builder API)

```rust
use std::path::PathBuf;
use std::process::exit;

use clap::{Arg, ArgAction, Command, value_parser};

fn applet_commands() -> [Command; 2] {
    [
        Command::new("true").about("does nothing successfully"),
        Command::new("false").about("does nothing unsuccessfully"),
    ]
}

fn main() {
    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
        .multicall(true)
        .subcommand(
            Command::new("busybox")
                .arg_required_else_help(true)
                .subcommand_value_name("APPLET")
                .subcommand_help_heading("APPLETS")
                .arg(
                    Arg::new("install")
                        .long("install")
                        .help("Install hardlinks for all subcommands in path")
                        .exclusive(true)
                        .action(ArgAction::Set)
                        .default_missing_value("/usr/local/bin")
                        .value_parser(value_parser!(PathBuf)),
                )
                .subcommands(applet_commands()),
        )
        .subcommands(applet_commands());

    let matches = cmd.get_matches();
    let mut subcommand = matches.subcommand();
    if let Some(("busybox", cmd)) = subcommand {
        if cmd.contains_id("install") {
            unimplemented!("Make hardlinks to the executable here");
        }
        subcommand = cmd.subcommand();
    }
    match subcommand {
        Some(("false", _)) => exit(1),
        Some(("true", _)) => exit(0),
        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    }
}
```

See the documentation for [`Command::multicall`][crate::Command::multicall] for rationale.

This example omits every command except true and false,
which are the most trivial to implement,
```console
$ busybox true
? 0

$ busybox false
? 1

```
*Note: without the links setup, we can't demonstrate the multicall behavior*

But includes the `--install` option as an example of why it can be useful
for the main program to take arguments that aren't applet subcommands.
```console
$ busybox --install
? failed
...

```

Though users must pass something:
```console
$ busybox
? failed
Usage: busybox [OPTIONS] [APPLET]

APPLETS:
  true   does nothing successfully
  false  does nothing unsuccessfully
  help   Print this message or the help of the given subcommand(s)

Options:
      --install <install>  Install hardlinks for all subcommands in path
  -h, --help               Print help

```

## clap::_cookbook::multicall_hostname (module)

### clap::_cookbook::multicall_hostname (module) › Example: hostname-like CLI (Builder API)

```rust
use clap::Command;

fn main() {
    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
        .multicall(true)
        .arg_required_else_help(true)
        .subcommand_value_name("APPLET")
        .subcommand_help_heading("APPLETS")
        .subcommand(Command::new("hostname").about("show hostname part of FQDN"))
        .subcommand(Command::new("dnsdomainname").about("show domain name part of FQDN"));

    match cmd.get_matches().subcommand_name() {
        Some("hostname") => println!("www"),
        Some("dnsdomainname") => println!("example.com"),
        _ => unreachable!("parser should ensure only valid subcommand names are used"),
    }
}
```

See the documentation for [`Command::multicall`][crate::Command::multicall] for rationale.

This example omits the implementation of displaying address config

```console
$ hostname
www

```
*Note: without the links setup, we can't demonstrate the multicall behavior*

## clap::_cookbook::pacman (module)

### clap::_cookbook::pacman (module) › Example: pacman-like CLI (Builder API)

```rust
use clap::{Arg, ArgAction, Command};

fn cli() -> Command {
    Command::new("pacman")
        .about("package manager utility")
        .version("5.2.1")
        .subcommand_required(true)
        .arg_required_else_help(true)
        // Query subcommand
        //
        // Only a few of its arguments are implemented below.
        .subcommand(
            Command::new("query")
                .short_flag('Q')
                .long_flag("query")
                .about("Query the package database.")
                .arg(
                    Arg::new("search")
                        .short('s')
                        .long("search")
                        .help("search locally installed packages for matching strings")
                        .conflicts_with("info")
                        .action(ArgAction::Set)
                        .num_args(1..),
                )
                .arg(
                    Arg::new("info")
                        .long("info")
                        .short('i')
                        .conflicts_with("search")
                        .help("view package information")
                        .action(ArgAction::Set)
                        .num_args(1..),
                ),
        )
        // Sync subcommand
        //
        // Only a few of its arguments are implemented below.
        .subcommand(
            Command::new("sync")
                .short_flag('S')
                .long_flag("sync")
                .about("Synchronize packages.")
                .arg(
                    Arg::new("search")
                        .short('s')
                        .long("search")
                        .conflicts_with("info")
                        .action(ArgAction::Set)
                        .num_args(1..)
                        .help("search remote repositories for matching strings"),
                )
                .arg(
                    Arg::new("info")
                        .long("info")
                        .conflicts_with("search")
                        .short('i')
                        .action(ArgAction::SetTrue)
                        .help("view package information"),
                )
                .arg(
                    Arg::new("package")
                        .help("packages")
                        .required_unless_present("search")
                        .action(ArgAction::Set)
                        .num_args(1..),
                ),
        )
}

fn main() {
    let matches = cli().get_matches();

    match matches.subcommand() {
        Some(("sync", sync_matches)) => {
            if sync_matches.contains_id("search") {
                let packages: Vec<_> = sync_matches
                    .get_many::<String>("search")
                    .expect("contains_id")
                    .map(|s| s.as_str())
                    .collect();
                let values = packages.join(", ");
                println!("Searching for {values}...");
                return;
            }

            let packages: Vec<_> = sync_matches
                .get_many::<String>("package")
                .expect("is present")
                .map(|s| s.as_str())
                .collect();
            let values = packages.join(", ");

            if sync_matches.get_flag("info") {
                println!("Retrieving info for {values}...");
            } else {
                println!("Installing {values}...");
            }
        }
        Some(("query", query_matches)) => {
            if let Some(packages) = query_matches.get_many::<String>("info") {
                let comma_sep = packages.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
                println!("Retrieving info for {comma_sep}...");
            } else if let Some(queries) = query_matches.get_many::<String>("search") {
                let comma_sep = queries.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
                println!("Searching Locally for {comma_sep}...");
            } else {
                println!("Displaying all locally installed packages...");
            }
        }
        _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable
    }
}

#[cfg(all(test, feature = "help", feature = "usage"))]
mod tests {
    use super::*;

    #[test]
    fn help_output_is_stable() {
        snapbox::assert_data_eq!(
            render_reference(cli()),
            snapbox::file!["snapshots/pacman.txt"].raw()
        );
    }

    fn render_reference(mut command: Command) -> String {
        command = command.term_width(0);
        command.build();

        let mut buffer = String::new();
        write_help(&mut buffer, &mut command, String::new());

        buffer
    }

    fn write_help(buffer: &mut String, cmd: &mut Command, mut path: String) {
        let header = if path.is_empty() { "#" } else { "##" };
        path.push(' ');
        path.push_str(cmd.get_name());

        buffer.push_str(header);
        buffer.push_str(&path);
        buffer.push_str("\n\n");
        buffer.push_str(&cmd.render_long_help().to_string());

        let has_generated_help = !cmd.is_disable_help_subcommand_set();
        for subcommand in cmd.get_subcommands_mut() {
            // Generated `help` nodes proxy other commands.
            if has_generated_help && subcommand.get_name() == "help" {
                continue;
            }

            buffer.push('\n');
            write_help(buffer, subcommand, path.clone());
        }
    }
}
```

[`pacman`](https://wiki.archlinux.org/index.php/pacman) defines subcommands via flags.

Here, `-S` is a short flag subcommand:
```console
$ pacman -S package
Installing package...

```

Here `--sync` is a long flag subcommand:
```console
$ pacman --sync package
Installing package...

```

Now the short flag subcommand (`-S`) with a long flag:
```console
$ pacman -S --search name
Searching for name...

```

And the various forms of short flags that work:
```console
$ pacman -S -s name
Searching for name...

$ pacman -Ss name
Searching for name...

```
*(users can "stack" short subcommands with short flags or with other short flag subcommands)*

In the help, this looks like:
```console
$ pacman -h
package manager utility

Usage: pacman[EXE] <COMMAND>

Commands:
  query, -Q, --query  Query the package database.
  sync, -S, --sync    Synchronize packages.
  help                Print this message or the help of the given subcommand(s)

Options:
  -h, --help     Print help
  -V, --version  Print version

$ pacman -S -h
Synchronize packages.

Usage: pacman[EXE] {sync|--sync|-S} [OPTIONS] [package]...

Arguments:
  [package]...  packages

Options:
  -s, --search <search>...  search remote repositories for matching strings
  -i, --info                view package information
  -h, --help                Print help

```

And errors:
```console
$ pacman -S -s foo -i bar
? failed
error: the argument '--search <search>...' cannot be used with '--info'

Usage: pacman[EXE] {sync|--sync|-S} --search <search>... <package>...

For more information, try '--help'.

```

<div class="warning">

**NOTE:** Keep in mind that subcommands, flags, and long flags are *case sensitive*: `-Q` and `-q` are different flags/subcommands. For example, you can have both `-Q` subcommand and `-q` flag, and they will be properly disambiguated.
Let's make a quick program to illustrate.

</div>

### clap::_cookbook::pacman (module) › Reviewing help output

The test renders every command's long help.
Each Markdown heading contains the complete command path.
Generated `help` subcommands are skipped.
`term_width(0)` prevents terminal-dependent wrapping.

[`snapbox`](https://docs.rs/snapbox) compares this output with a snapshot.
The resulting diff makes CLI changes easy to review.
Set `SNAPSHOTS=overwrite` to accept intentional changes.

## clap::_cookbook::repl (module)

### clap::_cookbook::repl (module) › Example: Command REPL (Builder API)

```rust
use std::io::Write;

use clap::Command;

fn main() -> Result<(), String> {
    loop {
        let line = readline()?;
        let line = line.trim();
        if line.is_empty() {
            continue;
        }

        match respond(line) {
            Ok(quit) => {
                if quit {
                    break;
                }
            }
            Err(err) => {
                write!(std::io::stdout(), "{err}").map_err(|e| e.to_string())?;
                std::io::stdout().flush().map_err(|e| e.to_string())?;
            }
        }
    }

    Ok(())
}

fn respond(line: &str) -> Result<bool, String> {
    let args = shlex::split(line).ok_or("error: Invalid quoting")?;
    let matches = cli()
        .try_get_matches_from(args)
        .map_err(|e| e.to_string())?;
    match matches.subcommand() {
        Some(("ping", _matches)) => {
            write!(std::io::stdout(), "Pong").map_err(|e| e.to_string())?;
            std::io::stdout().flush().map_err(|e| e.to_string())?;
        }
        Some(("quit", _matches)) => {
            write!(std::io::stdout(), "Exiting ...").map_err(|e| e.to_string())?;
            std::io::stdout().flush().map_err(|e| e.to_string())?;
            return Ok(true);
        }
        Some((name, _matches)) => unimplemented!("{name}"),
        None => unreachable!("subcommand required"),
    }

    Ok(false)
}

fn cli() -> Command {
    // strip out usage
    const PARSER_TEMPLATE: &str = "\
        {all-args}
    ";
    // strip out name/version
    const APPLET_TEMPLATE: &str = "\
        {about-with-newline}\n\
        {usage-heading}\n    {usage}\n\
        \n\
        {all-args}{after-help}\
    ";

    Command::new("repl")
        .multicall(true)
        .arg_required_else_help(true)
        .subcommand_required(true)
        .subcommand_value_name("APPLET")
        .subcommand_help_heading("APPLETS")
        .help_template(PARSER_TEMPLATE)
        .subcommand(
            Command::new("ping")
                .about("Get a response")
                .help_template(APPLET_TEMPLATE),
        )
        .subcommand(
            Command::new("quit")
                .alias("exit")
                .about("Quit the REPL")
                .help_template(APPLET_TEMPLATE),
        )
}

fn readline() -> Result<String, String> {
    write!(std::io::stdout(), "$ ").map_err(|e| e.to_string())?;
    std::io::stdout().flush().map_err(|e| e.to_string())?;
    let mut buffer = String::new();
    std::io::stdin()
        .read_line(&mut buffer)
        .map_err(|e| e.to_string())?;
    Ok(buffer)
}
```

## clap::_cookbook::repl_derive (module)

### clap::_cookbook::repl_derive (module) › Example: REPL (Derive API)

```rust
use std::io::Write;

use clap::{Parser, Subcommand};

fn main() -> Result<(), String> {
    loop {
        let line = readline()?;
        let line = line.trim();
        if line.is_empty() {
            continue;
        }

        match respond(line) {
            Ok(quit) => {
                if quit {
                    break;
                }
            }
            Err(err) => {
                write!(std::io::stdout(), "{err}").map_err(|e| e.to_string())?;
                std::io::stdout().flush().map_err(|e| e.to_string())?;
            }
        }
    }

    Ok(())
}

fn respond(line: &str) -> Result<bool, String> {
    let args = shlex::split(line).ok_or("error: Invalid quoting")?;
    let cli = Cli::try_parse_from(args).map_err(|e| e.to_string())?;
    match cli.command {
        Commands::Ping => {
            write!(std::io::stdout(), "Pong").map_err(|e| e.to_string())?;
            std::io::stdout().flush().map_err(|e| e.to_string())?;
        }
        Commands::Exit => {
            write!(std::io::stdout(), "Exiting ...").map_err(|e| e.to_string())?;
            std::io::stdout().flush().map_err(|e| e.to_string())?;
            return Ok(true);
        }
    }
    Ok(false)
}

#[derive(Debug, Parser)]
#[command(multicall = true)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Debug, Subcommand)]
enum Commands {
    Ping,
    Exit,
}

fn readline() -> Result<String, String> {
    write!(std::io::stdout(), "$ ").map_err(|e| e.to_string())?;
    std::io::stdout().flush().map_err(|e| e.to_string())?;
    let mut buffer = String::new();
    std::io::stdin()
        .read_line(&mut buffer)
        .map_err(|e| e.to_string())?;
    Ok(buffer)
}
```

## clap::_cookbook::typed_derive (module)

### clap::_cookbook::typed_derive (module) › Example: Custom Types (Derive API)

**This requires enabling the [`derive` feature flag][crate::_features].**

### clap::_cookbook::typed_derive (module) › Implicit [`Arg::value_parser`][crate::Arg::value_parser]

```rust
use clap::Args;
use clap::ValueEnum;

#[derive(Args, Debug)]
pub(crate) struct ImplicitParsers {
    /// Implicitly using `std::str::FromStr`
    #[arg(short = 'O')]
    optimization: Option<usize>,

    /// Allow invalid UTF-8 paths
    #[arg(short = 'I', value_name = "DIR", value_hint = clap::ValueHint::DirPath)]
    include: Option<std::path::PathBuf>,

    /// Handle IP addresses
    #[arg(long)]
    bind: Option<std::net::IpAddr>,

    /// Allow human-readable durations
    #[arg(long)]
    sleep: Option<jiff::SignedDuration>,

    /// Custom enums
    #[arg(long)]
    bump_level: Option<BumpLevel>,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
#[value(rename_all = "kebab-case")]
pub(crate) enum BumpLevel {
    /// Increase the major version (x.0.0)
    Major,
    /// Increase the minor version (x.y.0)
    Minor,
    /// Increase the patch version (x.y.z)
    Patch,
}

impl std::fmt::Display for BumpLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use clap::ValueEnum;

        self.to_possible_value()
            .expect("no values are skipped")
            .get_name()
            .fmt(f)
    }
}

impl std::str::FromStr for BumpLevel {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        use clap::ValueEnum;

        for variant in Self::value_variants() {
            if variant.to_possible_value().unwrap().matches(s, false) {
                return Ok(*variant);
            }
        }
        Err(format!("Invalid variant: {s}"))
    }
}
```

Help:
```console
$ typed-derive implicit --help
Usage: typed-derive implicit [OPTIONS]

Options:
  -O <OPTIMIZATION>
          Implicitly using `std::str::FromStr`

  -I <DIR>
          Allow invalid UTF-8 paths

      --bind <BIND>
          Handle IP addresses

      --sleep <SLEEP>
          Allow human-readable durations

      --bump-level <BUMP_LEVEL>
          Custom enums

          Possible values:
          - major: Increase the major version (x.0.0)
          - minor: Increase the minor version (x.y.0)
          - patch: Increase the patch version (x.y.z)

  -h, --help
          Print help (see a summary with '-h')

```

Optimization-level (number)
```console
$ typed-derive implicit -O 1
Implicit(ImplicitParsers { optimization: Some(1), include: None, bind: None, sleep: None, bump_level: None })

$ typed-derive implicit -O plaid
? failed
error: invalid value 'plaid' for '-O <OPTIMIZATION>': invalid digit found in string

For more information, try '--help'.

```

Include (path)
```console
$ typed-derive implicit -I../hello
Implicit(ImplicitParsers { optimization: None, include: Some("../hello"), bind: None, sleep: None, bump_level: None })

```

IP Address
```console
$ typed-derive implicit --bind 192.0.0.1
Implicit(ImplicitParsers { optimization: None, include: None, bind: Some(192.0.0.1), sleep: None, bump_level: None })

$ typed-derive implicit --bind localhost
? failed
error: invalid value 'localhost' for '--bind <BIND>': invalid IP address syntax

For more information, try '--help'.

```

Time
```console
$ typed-derive implicit --sleep 10s
Implicit(ImplicitParsers { optimization: None, include: None, bind: None, sleep: Some(10s), bump_level: None })

$ typed-derive implicit --sleep forever
? failed
error: invalid value 'forever' for '--sleep <SLEEP>': failed to parse input in the "friendly" duration format: expected duration to start with a unit value (a decimal integer) after an optional sign, but no integer was found

For more information, try '--help'.

```

Version field
```console
$ typed-derive implicit --bump-level minor
Implicit(ImplicitParsers { optimization: None, include: None, bind: None, sleep: None, bump_level: Some(Minor) })

$ typed-derive implicit --bump-level 10.0.0
? failed
error: invalid value '10.0.0' for '--bump-level <BUMP_LEVEL>'
  [possible values: major, minor, patch]

For more information, try '--help'.

$ typed-derive implicit --bump-level blue
? failed
error: invalid value 'blue' for '--bump-level <BUMP_LEVEL>'
  [possible values: major, minor, patch]

For more information, try '--help'.

```

### clap::_cookbook::typed_derive (module) › Built-in [`TypedValueParser`][crate::builder::TypedValueParser]

```rust
use clap::Args;
use clap::builder::TypedValueParser as _;

use crate::foreign_crate;

#[derive(Args, Debug)]
pub(crate) struct BuiltInParsers {
    /// Support for discrete numbers
    #[arg(
        long,
        default_value_t = 22,
        value_parser = clap::builder::PossibleValuesParser::new(["22", "80"])
            .map(|s| s.parse::<usize>().unwrap()),
    )]
    port: usize,

    /// Support enums from a foreign crate that don't implement `ValueEnum`
    #[arg(
        long,
        default_value_t = foreign_crate::LogLevel::Info,
        value_parser = clap::builder::PossibleValuesParser::new(["trace", "debug", "info", "warn", "error"])
            .map(|s| s.parse::<foreign_crate::LogLevel>().unwrap()),
    )]
    log_level: foreign_crate::LogLevel,
}
```

Help:
```console
$ typed-derive builtin --help
Usage: typed-derive builtin [OPTIONS]

Options:
      --port <PORT>            Support for discrete numbers [default: 22] [possible values: 22, 80]
      --log-level <LOG_LEVEL>  Support enums from a foreign crate that don't implement `ValueEnum` [default: info] [possible values: trace, debug, info, warn, error]
  -h, --help                   Print help

```

Discrete numbers
```console
$ typed-derive builtin --port 22
Builtin(BuiltInParsers { port: 22, log_level: Info })

$ typed-derive builtin --port 80
Builtin(BuiltInParsers { port: 80, log_level: Info })

$ typed-derive builtin --port
? failed
error: a value is required for '--port <PORT>' but none was supplied
  [possible values: 22, 80]

For more information, try '--help'.

$ typed-derive builtin --port 3000
? failed
error: invalid value '3000' for '--port <PORT>'
  [possible values: 22, 80]

For more information, try '--help'.

```

Enums from crates that can't implement `ValueEnum`
```console
$ typed-derive builtin --log-level debug
Builtin(BuiltInParsers { port: 22, log_level: Debug })

$ typed-derive builtin --log-level error
Builtin(BuiltInParsers { port: 22, log_level: Error })

$ typed-derive builtin --log-level
? failed
error: a value is required for '--log-level <LOG_LEVEL>' but none was supplied
  [possible values: trace, debug, info, warn, error]

For more information, try '--help'.

$ typed-derive builtin --log-level critical
? failed
error: invalid value 'critical' for '--log-level <LOG_LEVEL>'
  [possible values: trace, debug, info, warn, error]

For more information, try '--help'.

```

### clap::_cookbook::typed_derive (module) › Custom parser function

```rust
use std::error::Error;

use clap::Args;

#[derive(Args, Debug)]
pub(crate) struct FnParser {
    /// Hand-written parser for tuples
    #[arg(short = 'D', value_name = "KEY=VALUE", value_parser = parse_key_val::<String, i32>)]
    defines: Vec<(String, i32)>,
}

/// Parse a single key-value pair
fn parse_key_val<T, U>(s: &str) -> Result<(T, U), Box<dyn Error + Send + Sync + 'static>>
where
    T: std::str::FromStr,
    T::Err: Error + Send + Sync + 'static,
    U: std::str::FromStr,
    U::Err: Error + Send + Sync + 'static,
{
    let pos = s
        .find('=')
        .ok_or_else(|| format!("invalid KEY=value: no `=` found in `{s}`"))?;
    Ok((s[..pos].parse()?, s[pos + 1..].parse()?))
}
```

Help:
```console
$ typed-derive fn-parser --help
Usage: typed-derive fn-parser [OPTIONS]

Options:
  -D <KEY=VALUE>  Hand-written parser for tuples
  -h, --help      Print help

```

Defines (key-value pairs)
```console
$ typed-derive fn-parser -D Foo=10 -D Alice=30
FnParser(FnParser { defines: [("Foo", 10), ("Alice", 30)] })

$ typed-derive fn-parser -D Foo
? failed
error: invalid value 'Foo' for '-D <KEY=VALUE>': invalid KEY=value: no `=` found in `Foo`

For more information, try '--help'.

$ typed-derive fn-parser -D Foo=Bar
? failed
error: invalid value 'Foo=Bar' for '-D <KEY=VALUE>': invalid digit found in string

For more information, try '--help'.

```

### clap::_cookbook::typed_derive (module) › Custom [`TypedValueParser`][crate::builder::TypedValueParser]

```rust
use clap::Args;

use crate::implicit::BumpLevel;

#[derive(Args, Debug)]
pub(crate) struct CustomParser {
    /// Hand-implement `TypedValueParser`
    #[arg(long)]
    target_version: Option<TargetVersion>,
}

/// Enum or custom value
#[derive(Clone, Debug)]
pub(crate) enum TargetVersion {
    Relative(BumpLevel),
    Absolute(semver::Version),
}

impl std::fmt::Display for TargetVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        match self {
            Self::Relative(bump_level) => {
                write!(f, "{bump_level}")
            }
            Self::Absolute(version) => {
                write!(f, "{version}")
            }
        }
    }
}

impl std::str::FromStr for TargetVersion {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Ok(bump_level) = BumpLevel::from_str(s) {
            Ok(Self::Relative(bump_level))
        } else {
            Ok(Self::Absolute(
                semver::Version::parse(s).map_err(|e| e.to_string())?,
            ))
        }
    }
}

/// Default to `TargetVersionParser` for `TargetVersion`, instead of `FromStr`
impl clap::builder::ValueParserFactory for TargetVersion {
    type Parser = TargetVersionParser;

    fn value_parser() -> Self::Parser {
        TargetVersionParser
    }
}

#[derive(Copy, Clone)]
pub(crate) struct TargetVersionParser;

impl clap::builder::TypedValueParser for TargetVersionParser {
    type Value = TargetVersion;

    fn parse_ref(
        &self,
        cmd: &clap::Command,
        arg: Option<&clap::Arg>,
        value: &std::ffi::OsStr,
    ) -> Result<Self::Value, clap::Error> {
        let inner_parser = <TargetVersion as std::str::FromStr>::from_str;
        inner_parser.parse_ref(cmd, arg, value)
    }

    fn possible_values(
        &self,
    ) -> Option<Box<dyn Iterator<Item = clap::builder::PossibleValue> + '_>> {
        let inner_parser = clap::builder::EnumValueParser::<BumpLevel>::new();
        #[allow(clippy::needless_collect)] // Erasing a lifetime
        inner_parser.possible_values().map(|ps| {
            let ps = ps.collect::<Vec<_>>();
            let ps: Box<dyn Iterator<Item = clap::builder::PossibleValue> + '_> =
                Box::new(ps.into_iter());
            ps
        })
    }
}
```

Help:
```console
$ typed-derive custom --help
Usage: typed-derive custom [OPTIONS]

Options:
      --target-version <TARGET_VERSION>
          Hand-implement `TypedValueParser`

          Possible values:
          - major: Increase the major version (x.0.0)
          - minor: Increase the minor version (x.y.0)
          - patch: Increase the patch version (x.y.z)

  -h, --help
          Print help (see a summary with '-h')

```

Defines (key-value pairs)
```console
$ typed-derive custom --target-version major
Custom(CustomParser { target_version: Some(Relative(Major)) })

$ typed-derive custom --target-version 10.0.0
Custom(CustomParser { target_version: Some(Absolute(Version { major: 10, minor: 0, patch: 0 })) })

$ typed-derive custom --target-version 10
? failed
error: invalid value '10' for '--target-version <TARGET_VERSION>': unexpected end of input while parsing major version number

For more information, try '--help'.

$ typed-derive custom --target-version blue
? failed
error: invalid value 'blue' for '--target-version <TARGET_VERSION>': unexpected character 'b' while parsing major version number

For more information, try '--help'.

```

## clap::_derive (module)

### clap::_derive (module) › Documentation: Derive Reference

1. [Overview](#overview)
2. [Attributes](#attributes)
    1. [Terminology](#terminology)
    2. [Command Attributes](#command-attributes)
    2. [ArgGroup Attributes](#arggroup-attributes)
    3. [Arg Attributes](#arg-attributes)
    4. [ValueEnum Attributes](#valueenum-attributes)
    5. [Possible Value Attributes](#possible-value-attributes)
3. [Field Types](#field-types)
4. [Doc Comments](#doc-comments)
5. [Mixing Builder and Derive APIs](#mixing-builder-and-derive-apis)
6. [Tips](#tips)

### clap::_derive (module) › Overview

To derive `clap` types, you need to enable the [`derive` feature flag][crate::_features].

Example:
```rust
use clap::Parser;

/// Simple program to greet a person
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
    /// Name of the person to greet
    #[arg(short, long)]
    name: String,

    /// Number of times to greet
    #[arg(short, long, default_value_t = 1)]
    count: u8,
}

fn main() {
    let args = Args::parse();

    for _ in 0..args.count {
        println!("Hello {}!", args.name);
    }
}
```

Let's start by breaking down the anatomy of the derive attributes:
```rust
use clap::{Parser, Args, Subcommand, ValueEnum};

/// Doc comment
#[derive(Parser)]
#[command(CMD ATTRIBUTE)]
#[group(GROUP ATTRIBUTE)]
struct Cli {
    /// Doc comment
    #[arg(ARG ATTRIBUTE)]
    field: UserType,

    #[arg(value_enum, ARG ATTRIBUTE...)]
    field: EnumValues,

    #[command(flatten)]
    delegate: Struct,

    #[command(subcommand)]
    command: Command,
}

/// Doc comment
#[derive(Args)]
#[command(PARENT CMD ATTRIBUTE)]
#[group(GROUP ATTRIBUTE)]
struct Struct {
    /// Doc comment
    #[command(ARG ATTRIBUTE)]
    field: UserType,
}

/// Doc comment
#[derive(Subcommand)]
#[command(PARENT CMD ATTRIBUTE)]
enum Command {
    /// Doc comment
    #[command(CMD ATTRIBUTE)]
    Variant1(Struct),

    /// Doc comment
    #[command(CMD ATTRIBUTE)]
    Variant2 {
        /// Doc comment
        #[arg(ARG ATTRIBUTE)]
        field: UserType,
    }
}

/// Doc comment
#[derive(ValueEnum)]
#[value(VALUE ENUM ATTRIBUTE)]
enum EnumValues {
    /// Doc comment
    #[value(POSSIBLE VALUE ATTRIBUTE)]
    Variant1,
}

let cli = Cli::parse();
```

Traits:
- [`Parser`][crate::Parser] parses arguments into a `struct` (arguments) or `enum` (subcommands).
  - [`Args`][crate::Args] allows defining a set of re-usable arguments that get merged into their parent container.
  - [`Subcommand`][crate::Subcommand] defines available subcommands.
  - Subcommand arguments can be defined in a struct-variant or automatically flattened with a tuple-variant.
- [`ValueEnum`][crate::ValueEnum] allows parsing a value directly into an `enum`, erroring on unsupported values.
  - The derive doesn't work on enums that contain non-unit variants, unless they are skipped

*See also the [derive tutorial][crate::_derive::_tutorial] and [cookbook][crate::_cookbook]*

### clap::_derive (module) › Attributes

### clap::_derive (module) › Terminology

**Raw attributes** are forwarded directly to the underlying [`clap` builder][crate::builder].  Any
[`Command`][crate::Command], [`Arg`][crate::Arg], or [`PossibleValue`][crate::builder::PossibleValue] method can be used as an attribute.

Raw attributes come in two different syntaxes:
```rust,ignore
#[arg(
    global = true, // name = arg form, neat for one-arg methods
    required_if_eq("out", "file") // name(arg1, arg2, ...) form.
)]
```

- `method = arg` can only be used for methods which take only one argument.
- `method(arg1, arg2)` can be used with any method.

As long as `method_name` is not one of the magical methods it will be
translated into a mere method call.

**Magic attributes** have post-processing done to them, whether that is
- Providing of defaults
- Special behavior is triggered off of it

Magic attributes are more constrained in the syntax they support, usually just
`<attr> = <value>` though some use `<attr>(<value>)` instead.  See the specific
magic attributes documentation for details.  This allows users to access the
raw behavior of an attribute via `<attr>(<value>)` syntax.

<div class="warning">

**NOTE:** Some attributes are inferred from [Arg Types](#arg-types) and [Doc
Comments](#doc-comments).  Explicit attributes take precedence over inferred
attributes.

</div>

### clap::_derive (module) › Command Attributes

These correspond to a [`Command`][crate::Command] which is used for both top-level parsers and
when defining subcommands.

**Raw attributes:**  Any [`Command` method][crate::Command] can also be used as an attribute,
see [Terminology](#terminology) for syntax.
- e.g. `#[command(arg_required_else_help(true))]` would translate to `cmd.arg_required_else_help(true)`

**Magic attributes:**
- `name  = <expr>`: [`Command::name`][crate::Command::name]
  - When not present: [package `name`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-name-field) (if on [`Parser`][crate::Parser] container), variant name (if on [`Subcommand`][crate::Subcommand] variant)
- `version [= <expr>]`: [`Command::version`][crate::Command::version]
  - When not present: no version set
  - Without `<expr>`: defaults to [crate `version`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field)
- `author [= <expr>]`: [`Command::author`][crate::Command::author]
  - When not present: no author set
  - Without `<expr>`: defaults to [crate `authors`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-authors-field)
  - **NOTE:** A custom [`help_template`][crate::Command::help_template] is needed for author to show up.
- `about [= <expr>]`: [`Command::about`][crate::Command::about]
  - When not present: [Doc comment summary](#doc-comments)
  - Without `<expr>`: [crate `description`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-description-field) ([`Parser`][crate::Parser] container)
    - **TIP:** When a doc comment is also present, you most likely want to add
      `#[arg(long_about = None)]` to clear the doc comment so only [`about`][crate::Command::about]
      gets shown with both `-h` and `--help`.
- `long_about[ = <expr>]`: [`Command::long_about`][crate::Command::long_about]
  - When not present: [Doc comment](#doc-comments) if there is a blank line, else nothing
  - When present without a value: [Doc comment](#doc-comments)
- `verbatim_doc_comment`: Minimizes pre-processing when converting doc comments to [`about`][crate::Command::about] / [`long_about`][crate::Command::long_about]
- `defer = <bool_literal>`: Delay argument construction for an enum's subcommands with
  [`Command::defer`][crate::Command::defer]. Available on [`Parser`][crate::Parser] and
  [`Subcommand`][crate::Subcommand] enum containers.
  - When not present: `false`, or `true` with the `unstable-v5` feature.
  - Subcommand names and attributes on the variants are applied eagerly, so their descriptions
    are available in the parent's help. Arguments and groups in named variants, and the entire
    [`Args::augment_args`][crate::Args::augment_args] call for newtype variants, are deferred.
  - Put metadata needed by the parent's help on the enum variants. Metadata from an `Args`
    container or its flattened fields is applied when the subcommand is built, and can then
    override metadata on the variant.
  - Flattened and nested `Subcommand` enums use their own `defer` setting. The setting is not
    inherited by those enums and does not defer their registration in the parent.
  - Call [`Command::build`][crate::Command::build] before inspecting deferred arguments or
    nested commands. Parsing builds the selected commands automatically.
- `next_display_order`: [`Command::next_display_order`][crate::Command::next_display_order]
- `next_help_heading`: [`Command::next_help_heading`][crate::Command::next_help_heading]
  - When `flatten`ing [`Args`][crate::Args], this is scoped to just the args in this struct and any struct `flatten`ed into it
- `rename_all = <string_literal>`: Override default field / variant name case conversion for [`Command::name`][crate::Command::name] / [`Arg::id`][crate::Arg::id]
  - When not present: `"kebab-case"`
  - Available values: `"camelCase"`, `"kebab-case"`, `"PascalCase"`, `"SCREAMING_SNAKE_CASE"`, `"snake_case"`, `"lower"`, `"UPPER"`, `"verbatim"`
- `rename_all_env = <string_literal>`: Override default field name case conversion for env variables for  [`Arg::env`][crate::Arg::env]
  - When not present: `"SCREAMING_SNAKE_CASE"`
  - Available values: `"camelCase"`, `"kebab-case"`, `"PascalCase"`, `"SCREAMING_SNAKE_CASE"`, `"snake_case"`, `"lower"`, `"UPPER"`, `"verbatim"`

And for [`Subcommand`][crate::Subcommand] variants:
- `skip`: Ignore this variant
- `flatten`: Delegates to the variant for more subcommands (must implement
  [`Subcommand`][crate::Subcommand])
- `subcommand`: Nest subcommands under the current set of subcommands (must implement
  [`Subcommand`][crate::Subcommand])
- `external_subcommand`: [`Command::allow_external_subcommand(true)`][crate::Command::allow_external_subcommands]
  - Variant must be either `Variant(Vec<String>)` or `Variant(Vec<OsString>)`

And for [`Args`][crate::Args] fields:
- `flatten`: Delegates to the field for more arguments (must implement [`Args`][crate::Args])
  - Only [`next_help_heading`][crate::Command::next_help_heading] can be used with `flatten`.  See
    [clap-rs/clap#3269](https://github.com/clap-rs/clap/issues/3269) for why
    arg attributes are not generally supported.
  - **Tip:** Though we do apply a flattened [`Args`][crate::Args]'s Parent Command Attributes, this
    makes reuse harder. Generally prefer putting the cmd attributes on the
    [`Parser`][crate::Parser] or on the flattened field.
- `subcommand`: Delegates definition of subcommands to the field (must implement
  [`Subcommand`][crate::Subcommand])
  - When `Option<T>`, the subcommand becomes optional

See [Configuring the Parser][_tutorial#configuring-the-parser] and
[Subcommands][_tutorial#subcommands] from the tutorial.

### clap::_derive (module) › ArgGroup Attributes

These correspond to the [`ArgGroup`][crate::ArgGroup] which is implicitly created for each
`Args` derive.

**Raw attributes:**  Any [`ArgGroup` method][crate::ArgGroup] can also be used as an attribute, see [Terminology](#terminology) for syntax.
- e.g. `#[group(required = true)]` would translate to `arg_group.required(true)`

**Magic attributes**:
- `id = <expr>`: [`ArgGroup::id`][crate::ArgGroup::id]
  - When not present: struct's name is used
- `skip [= <expr>]`: Ignore this field, filling in with `<expr>`
  - Without `<expr>`: fills the field with `Default::default()`

Note:
- For `struct`s, [`multiple = true`][crate::ArgGroup::multiple] is implied
- `enum` support is tracked at [#2621](https://github.com/clap-rs/clap/issues/2621)

See [Argument Relations][_tutorial#argument-relations] from the tutorial.

### clap::_derive (module) › Arg Attributes

These correspond to a [`Arg`][crate::Arg].
The default state for a field without attributes is to be a positional argument with [behavior
inferred from the field type](#arg-types).
`#[arg(...)]` attributes allow overriding or extending those defaults.

**Raw attributes:**  Any [`Arg` method][crate::Arg] can also be used as an attribute, see [Terminology](#terminology) for syntax.
- e.g. `#[arg(num_args(..=3))]` would translate to `arg.num_args(..=3)`

**Magic attributes**:
- `id = <expr>`: [`Arg::id`][crate::Arg::id]
  - When not present: field's name is used
- `value_parser [= <expr>]`: [`Arg::value_parser`][crate::Arg::value_parser]
  - When not present: will auto-select an implementation based on the field type using
    [`value_parser!`][crate::value_parser!]
- `action [= <expr>]`: [`Arg::action`][crate::Arg::action]
  - When not present: will auto-select an action based on the field type
- `help = <expr>`: [`Arg::help`][crate::Arg::help]
  - When not present: [Doc comment summary](#doc-comments)
- `long_help[ = <expr>]`: [`Arg::long_help`][crate::Arg::long_help]
  - When not present: [Doc comment](#doc-comments) if there is a blank line, else nothing
  - When present without a value: [Doc comment](#doc-comments)
- `verbatim_doc_comment`: Minimizes pre-processing when converting doc comments to [`help`][crate::Arg::help] / [`long_help`][crate::Arg::long_help]
- `short [= <char>]`: [`Arg::short`][crate::Arg::short]
  - When not present: no short set
  - Without `<char>`: defaults to first character in the case-converted field name
- `long [= <str>]`: [`Arg::long`][crate::Arg::long]
  - When not present: no long set
  - Without `<str>`: defaults to the case-converted field name
- `env [= <str>]`: [`Arg::env`][crate::Arg::env] (needs [`env` feature][crate::_features] enabled)
  - When not present: no env set
  - Without `<str>`: defaults to the case-converted field name
- `from_global`: Read a [`Arg::global`][crate::Arg::global] argument (raw attribute), regardless of what subcommand you are in
- `value_enum`: Parse the value using the [`ValueEnum`][crate::ValueEnum]
- `skip [= <expr>]`: Ignore this field, filling in with `<expr>`
  - Without `<expr>`: fills the field with `Default::default()`
- `default_value = <str>`: [`Arg::default_value`][crate::Arg::default_value] and [`Arg::required(false)`][crate::Arg::required]
- `default_value_t [= <expr>]`: [`Arg::default_value`][crate::Arg::default_value] and [`Arg::required(false)`][crate::Arg::required]
  - Requires `std::fmt::Display` that roundtrips correctly with the
    [`Arg::value_parser`][crate::Arg::value_parser] or `#[arg(value_enum)]`
  - Without `<expr>`, relies on `Default::default()`
- `default_values_t = <expr>`: [`Arg::default_values`][crate::Arg::default_values] and [`Arg::required(false)`][crate::Arg::required]
  - Requires field arg to be of type `Vec<T>` and `T` to implement `std::fmt::Display` or `#[arg(value_enum)]`
  - `<expr>` must implement `IntoIterator<T>`
- `default_value_os_t [= <expr>]`: [`Arg::default_value_os`][crate::Arg::default_value_os] and [`Arg::required(false)`][crate::Arg::required]
  - Requires `std::convert::Into<OsString>` or `#[arg(value_enum)]`
  - Without `<expr>`, relies on `Default::default()`
- `default_values_os_t = <expr>`: [`Arg::default_values_os`][crate::Arg::default_values_os] and [`Arg::required(false)`][crate::Arg::required]
  - Requires field arg to be of type `Vec<T>` and `T` to implement `std::convert::Into<OsString>` or `#[arg(value_enum)]`
  - `<expr>` must implement `IntoIterator<T>`

See [Adding Arguments][_tutorial#adding-arguments] and [Validation][_tutorial#validation] from the
tutorial.

### clap::_derive (module) › ValueEnum Attributes

- `rename_all = <string_literal>`: Override default field / variant name case conversion for [`PossibleValue::new`][crate::builder::PossibleValue]
  - When not present: `"kebab-case"`
  - Available values: `"camelCase"`, `"kebab-case"`, `"PascalCase"`, `"SCREAMING_SNAKE_CASE"`, `"snake_case"`, `"lower"`, `"UPPER"`, `"verbatim"`

See [Enumerated values][_tutorial#enumerated-values] from the tutorial.

### clap::_derive (module) › Possible Value Attributes

These correspond to a [`PossibleValue`][crate::builder::PossibleValue].

**Raw attributes:**  Any [`PossibleValue` method][crate::builder::PossibleValue] can also be used as an attribute, see [Terminology](#terminology) for syntax.
- e.g. `#[value(alias("foo"))]` would translate to `pv.alias("foo")`

**Magic attributes**:
- `name = <expr>`: [`PossibleValue::new`][crate::builder::PossibleValue::new]
  - When not present: case-converted field name is used
- `help = <expr>`: [`PossibleValue::help`][crate::builder::PossibleValue::help]
  - When not present: [Doc comment summary](#doc-comments)
- `skip`: Ignore this variant

### clap::_derive (module) › Field Types

`clap` assumes some intent based on the type used.

### clap::_derive (module) › Subcommand Types

| Type                  | Effect              | Implies                                                   |
|-----------------------|---------------------|-----------------------------------------------------------|
| `Option<T>`           | optional subcommand |                                                           |
| `T`                   | required subcommand | `.subcommand_required(true).arg_required_else_help(true)` |

### clap::_derive (module) › Arg Types

| Type                  | Effect                                               | Implies                                                     | Notes |
|-----------------------|------------------------------------------------------|-------------------------------------------------------------|-------|
| `()`                  | user-defined                                         | `.action(ArgAction::Set).required(false)`                   |       |
| `bool`                | flag                                                 | `.action(ArgAction::SetTrue)`                               |       |
| `Option<T>`           | optional argument                                    | `.action(ArgAction::Set).required(false)`                   |       |
| `Option<Option<T>>`   | optional value for optional argument                 | `.action(ArgAction::Set).required(false).num_args(0..=1)`   |       |
| `T`                   | required argument                                    | `.action(ArgAction::Set).required(!has_default)`            |       |
| `Vec<T>`              | `0..` occurrences of argument                        | `.action(ArgAction::Append).required(false)`  |       |
| `Option<Vec<T>>`      | `0..` occurrences of argument                        | `.action(ArgAction::Append).required(false)`  |       |
| `Vec<Vec<T>>`         | `0..` occurrences of argument, grouped by occurrence | `.action(ArgAction::Append).required(false)`  | requires `unstable-v5` |
| `Option<Vec<Vec<T>>>` | `0..` occurrences of argument, grouped by occurrence | `.action(ArgAction::Append).required(false)`  | requires `unstable-v5` |

In addition, [`.value_parser(value_parser!(T))`][crate::value_parser!] is called for each
field in the absence of a [`#[arg(value_parser)]` attribute](#arg-attributes).

Notes:
- For custom type behavior, you can override the implied attributes/settings and/or set additional ones
  - To force any inferred type (like `Vec<T>`) to be treated as `T`, you can refer to the type
    by another means, like using `std::vec::Vec` instead of `Vec`.  For improving this, see
    [#4626](https://github.com/clap-rs/clap/issues/4626).
- `Option<Vec<T>>` and `Option<Vec<Vec<T>>` will be `None` instead of `vec![]` if no arguments are provided.
  - This gives the user some flexibility in designing their argument, like with `num_args(0..)`
- `Vec<Vec<T>>` will need [`Arg::num_args`][crate::Arg::num_args] set to be meaningful

### clap::_derive (module) › Doc Comments

In clap, help messages for the whole binary can be specified
via [`Command::about`][crate::Command::about] and [`Command::long_about`][crate::Command::long_about] while help messages
for individual arguments can be specified via [`Arg::help`][crate::Arg::help] and [`Arg::long_help`][crate::Arg::long_help].

`long_*` variants are used when user calls the program with
`--help` and "short" variants are used with `-h` flag.

```rust
# use clap::Parser;

#[derive(Parser)]
#[command(about = "I am a program and I work, just pass `-h`", long_about = None)]
struct Foo {
    #[arg(short, help = "Pass `-h` and you'll see me!")]
    bar: String,
}
```

For convenience, doc comments can be used instead of raw methods
(this example works exactly like the one above):

```rust
# use clap::Parser;

#[derive(Parser)]
/// I am a program and I work, just pass `-h`
struct Foo {
    /// Pass `-h` and you'll see me!
    bar: String,
}
```

<div class="warning">

**NOTE:** Attributes have priority over doc comments!

**Top level doc comments always generate `Command::about/long_about` calls!**
If you really want to use the `Command::about/long_about` methods (you likely don't),
use the `about` / `long_about` attributes to override the calls generated from
the doc comment.  To clear `long_about`, you can use
`#[command(long_about = None)]`.

</div>

### clap::_derive (module) › Pre-processing

```rust
# use clap::Parser;
#[derive(Parser)]
/// Hi there, I'm Robo!
///
/// I like beeping, stumbling, eating your electricity,
/// and making records of you singing in a shower.
/// Pay up, or I'll upload it to youtube!
struct Robo {
    /// Call my brother SkyNet.
    ///
    /// I am artificial superintelligence. I won't rest
    /// until I'll have destroyed humanity. Enjoy your
    /// pathetic existence, you mere mortals.
    #[arg(long, action)]
    kill_all_humans: bool,
}
```

A doc comment consists of three parts:
- Short summary
- A blank line (whitespace only)
- Detailed description, all the rest

The summary corresponds with `Command::about` / `Arg::help`.  When a blank line is
present, the whole doc comment will be passed to `Command::long_about` /
`Arg::long_help`.  Or in other words, a doc may result in just a `Command::about` /
`Arg::help` or `Command::about` / `Arg::help` and `Command::long_about` /
`Arg::long_help`

In addition, when `verbatim_doc_comment` is not present, `clap` applies some preprocessing, including:

- Strip leading and trailing whitespace from every line, if present.

- Strip leading and trailing blank lines, if present.

- Interpret each group of non-empty lines as a word-wrapped paragraph.

  We replace newlines within paragraphs with spaces to allow the output
  to be re-wrapped to the terminal width.

- Strip any excess blank lines so that there is exactly one per paragraph break.

- If the first paragraph ends in exactly one period,
  remove the trailing period (i.e. strip trailing periods but not trailing ellipses).

Sometimes you don't want this preprocessing to apply, for example the comment contains
some ASCII art or markdown tables, you would need to preserve LFs along with
blank lines and the leading/trailing whitespace. When you pass use the
`verbatim_doc_comment` magic attribute, you  preserve
them.

**Note:** Keep in mind that `verbatim_doc_comment` will *still*
- Remove one leading space from each line, even if this attribute is present,
  to allow for a space between `///` and the content.
- Remove leading and trailing blank lines

### clap::_derive (module) › Mixing Builder and Derive APIs

The builder and derive APIs do not live in isolation. They can work together, which is
especially helpful if some arguments can be specified at compile-time while others must be
specified at runtime.

### clap::_derive (module) › Using derived arguments in a builder application

When using the derive API, you can `#[command(flatten)]` a struct deriving `Args` into a struct
deriving `Args` or `Parser`. This example shows how you can augment a `Command` instance
created using the builder API with `Args` created using the derive API.

It uses the [`Args::augment_args`][crate::Args::augment_args] method to add the arguments to
the `Command` instance.

Crates such as [clap-verbosity-flag](https://github.com/rust-cli/clap-verbosity-flag) provide
structs that implement `Args`. Without the technique shown in this example, it would not be
possible to use such crates with the builder API.

For example:
```rust
use clap::{Args, Command, FromArgMatches as _, arg};

#[derive(Args, Debug)]
struct DerivedArgs {
    #[arg(short, long)]
    derived: bool,
}

fn main() {
    let cli = Command::new("CLI").arg(arg!(-b - -built).action(clap::ArgAction::SetTrue));
    // Augment built args with derived args
    let cli = DerivedArgs::augment_args(cli);

    let matches = cli.get_matches();
    println!("Value of built: {:?}", matches.get_flag("built"));
    println!(
        "Value of derived via ArgMatches: {:?}",
        matches.get_flag("derived")
    );

    // Since DerivedArgs implements FromArgMatches, we can extract it from the unstructured ArgMatches.
    // This is the main benefit of using derived arguments.
    let derived_matches = DerivedArgs::from_arg_matches(&matches)
        .map_err(|err| err.exit())
        .unwrap();
    println!("Value of derived: {derived_matches:#?}");
}
```

### clap::_derive (module) › Using derived subcommands in a builder application

When using the derive API, you can use `#[command(subcommand)]` inside the struct to add
subcommands. The type of the field is usually an enum that derived `Parser`. However, you can
also add the subcommands in that enum to a `Command` instance created with the builder API.

It uses the [`Subcommand::augment_subcommands`][crate::Subcommand::augment_subcommands] method
to add the subcommands to the `Command` instance.

For example:
```rust
use clap::{Command, FromArgMatches as _, Parser, Subcommand as _};

#[derive(Parser, Debug)]
enum Subcommands {
    Derived {
        #[arg(short, long)]
        derived_flag: bool,
    },
}

fn main() {
    let cli = Command::new("Built CLI");
    // Augment with derived subcommands
    let cli = Subcommands::augment_subcommands(cli);

    let matches = cli.get_matches();
    let derived_subcommands = Subcommands::from_arg_matches(&matches)
        .map_err(|err| err.exit())
        .unwrap();
    println!("Derived subcommands: {derived_subcommands:#?}");
}
```

### clap::_derive (module) › Adding hand-implemented subcommands to a derived application

When using the derive API, you can use `#[command(subcommand)]` inside the struct to add
subcommands. The type of the field is usually an enum that derived `Parser`. However, you can
also implement the `Subcommand` trait manually on this enum (or any other type) and it can
still be used inside the struct created with the derive API. The implementation of the
`Subcommand` trait will use the builder API to add the subcommands to the `Command` instance
created behind the scenes for you by the derive API.

Notice how in the previous example we used
[`augment_subcommands`][crate::Subcommand::augment_subcommands] on an enum that derived
`Parser`, whereas now we implement
[`augment_subcommands`][crate::Subcommand::augment_subcommands] ourselves, but the derive API
calls it automatically since we used the `#[command(subcommand)]` attribute.

For example:
```rust
#![allow(dead_code)]
use clap::error::{Error, ErrorKind};
use clap::{ArgMatches, Args as _, Command, FromArgMatches, Parser, Subcommand};

#[derive(Parser, Debug)]
struct AddArgs {
    name: Vec<String>,
}
#[derive(Parser, Debug)]
struct RemoveArgs {
    #[arg(short, long)]
    force: bool,
    name: Vec<String>,
}

#[derive(Debug)]
enum CliSub {
    Add(AddArgs),
    Remove(RemoveArgs),
}

impl FromArgMatches for CliSub {
    fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> {
        match matches.subcommand() {
            Some(("add", args)) => Ok(Self::Add(AddArgs::from_arg_matches(args)?)),
            Some(("remove", args)) => Ok(Self::Remove(RemoveArgs::from_arg_matches(args)?)),
            Some((_, _)) => Err(Error::raw(
                ErrorKind::InvalidSubcommand,
                "Valid subcommands are `add` and `remove`",
            )),
            None => Err(Error::raw(
                ErrorKind::MissingSubcommand,
                "Valid subcommands are `add` and `remove`",
            )),
        }
    }
    fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> {
        match matches.subcommand() {
            Some(("add", args)) => *self = Self::Add(AddArgs::from_arg_matches(args)?),
            Some(("remove", args)) => *self = Self::Remove(RemoveArgs::from_arg_matches(args)?),
            Some((_, _)) => {
                return Err(Error::raw(
                    ErrorKind::InvalidSubcommand,
                    "Valid subcommands are `add` and `remove`",
                ));
            }
            None => (),
        };
        Ok(())
    }
}

impl Subcommand for CliSub {
    fn augment_subcommands(cmd: Command) -> Command {
        cmd.subcommand(AddArgs::augment_args(Command::new("add")))
            .subcommand(RemoveArgs::augment_args(Command::new("remove")))
            .subcommand_required(true)
    }
    fn augment_subcommands_for_update(cmd: Command) -> Command {
        cmd.subcommand(AddArgs::augment_args(Command::new("add")))
            .subcommand(RemoveArgs::augment_args(Command::new("remove")))
            .subcommand_required(true)
    }
    fn has_subcommand(name: &str) -> bool {
        matches!(name, "add" | "remove")
    }
}

#[derive(Parser, Debug)]
struct Cli {
    #[arg(short, long)]
    top_level: bool,
    #[command(subcommand)]
    subcommand: CliSub,
}

fn main() {
    let args = Cli::parse();
    println!("{args:#?}");
}
```

### clap::_derive (module) › Flattening hand-implemented args into a derived application

When using the derive API, you can use `#[command(flatten)]` inside the struct to add arguments as
if they were added directly to the containing struct. The type of the field is usually an
struct that derived `Args`. However, you can also implement the `Args` trait manually on this
struct (or any other type) and it can still be used inside the struct created with the derive
API. The implementation of the `Args` trait will use the builder API to add the arguments to
the `Command` instance created behind the scenes for you by the derive API.

Notice how in the previous example we used [`augment_args`][crate::Args::augment_args] on the
struct that derived `Parser`, whereas now we implement
[`augment_args`][crate::Args::augment_args] ourselves, but the derive API calls it
automatically since we used the `#[command(flatten)]` attribute.

For example:
```rust
use clap::error::Error;
use clap::{Arg, ArgAction, ArgMatches, Args, Command, FromArgMatches, Parser};

#[derive(Debug)]
struct CliArgs {
    foo: bool,
    bar: bool,
    quuz: Option<String>,
}

impl FromArgMatches for CliArgs {
    fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> {
        let mut matches = matches.clone();
        Self::from_arg_matches_mut(&mut matches)
    }
    fn from_arg_matches_mut(matches: &mut ArgMatches) -> Result<Self, Error> {
        Ok(Self {
            foo: matches.get_flag("foo"),
            bar: matches.get_flag("bar"),
            quuz: matches.remove_one::<String>("quuz"),
        })
    }
    fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> {
        let mut matches = matches.clone();
        self.update_from_arg_matches_mut(&mut matches)
    }
    fn update_from_arg_matches_mut(&mut self, matches: &mut ArgMatches) -> Result<(), Error> {
        self.foo |= matches.get_flag("foo");
        self.bar |= matches.get_flag("bar");
        if let Some(quuz) = matches.remove_one::<String>("quuz") {
            self.quuz = Some(quuz);
        }
        Ok(())
    }
}

impl Args for CliArgs {
    fn augment_args(cmd: Command) -> Command {
        cmd.arg(
            Arg::new("foo")
                .short('f')
                .long("foo")
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("bar")
                .short('b')
                .long("bar")
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("quuz")
                .short('q')
                .long("quuz")
                .action(ArgAction::Set),
        )
    }
    fn augment_args_for_update(cmd: Command) -> Command {
        cmd.arg(
            Arg::new("foo")
                .short('f')
                .long("foo")
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("bar")
                .short('b')
                .long("bar")
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("quuz")
                .short('q')
                .long("quuz")
                .action(ArgAction::Set),
        )
    }
}

#[derive(Parser, Debug)]
struct Cli {
    #[arg(short, long)]
    top_level: bool,
    #[command(flatten)]
    more_args: CliArgs,
}

fn main() {
    let args = Cli::parse();
    println!("{args:#?}");
}
```

### clap::_derive (module) › Tips

- To get access to a [`Command`][crate::Command] call
  [`CommandFactory::command`][crate::CommandFactory::command] (implemented when deriving
  [`Parser`][crate::Parser])
- Proactively check for bad [`Command`][crate::Command] configurations by calling
  [`Command::debug_assert`][crate::Command::debug_assert] in a test
  ([example][_tutorial#testing])
- Always remember to [document](#doc-comments) args and commands with `#![deny(missing_docs)]`
  or `#[deny(clippy::missing_docs_in_private_items)]`

## clap::_derive::_tutorial (module)

### clap::_derive::_tutorial (module) › Tutorial for the Derive API

*See the side bar for the Table of Contents*

### clap::_derive::_tutorial (module) › Quick Start

You can create an application declaratively with a `struct` and some
attributes.

First, ensure `clap` is available with the [`derive` feature flag][crate::_features]:
```console
$ cargo add clap --features derive
```

Here is a preview of the type of application you can make:
```rust
use std::path::PathBuf;

use clap::{Parser, Subcommand};

#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    /// Optional name to operate on
    name: Option<String>,

    /// Sets a custom config file
    #[arg(short, long, value_name = "FILE")]
    config: Option<PathBuf>,

    /// Turn debugging information on
    #[arg(short, long, action = clap::ArgAction::Count)]
    debug: u8,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// does testing things
    Test {
        /// lists test values
        #[arg(short, long)]
        list: bool,
    },
}

fn main() {
    let cli = Cli::parse();

    // You can check the value provided by positional arguments, or option arguments
    if let Some(name) = cli.name.as_deref() {
        println!("Value for name: {name}");
    }

    if let Some(config_path) = cli.config.as_deref() {
        println!("Value for config: {}", config_path.display());
    }

    // You can see how many times a particular flag or argument occurred
    // Note, only flags can have multiple occurrences
    match cli.debug {
        0 => println!("Debug mode is off"),
        1 => println!("Debug mode is kind of on"),
        2 => println!("Debug mode is on"),
        _ => println!("Don't be crazy"),
    }

    // You can check for the existence of subcommands, and if found use their
    // matches just as you would the top level cmd
    match &cli.command {
        Some(Commands::Test { list }) => {
            if *list {
                println!("Printing testing lists...");
            } else {
                println!("Not printing testing lists...");
            }
        }
        None => {}
    }

    // Continued program logic goes here...
}
```

```console
$ 01_quick_derive --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 01_quick_derive[EXE] [OPTIONS] [NAME] [COMMAND]

Commands:
  test  does testing things
  help  Print this message or the help of the given subcommand(s)

Arguments:
  [NAME]  Optional name to operate on

Options:
  -c, --config <FILE>  Sets a custom config file
  -d, --debug...       Turn debugging information on
  -h, --help           Print help
  -V, --version        Print version

```

By default, the program does nothing:
```console
$ 01_quick_derive
Debug mode is off

```

But you can mix and match the various features
```console
$ 01_quick_derive -dd test
Debug mode is on
Not printing testing lists...

```

See also
- [FAQ: When should I use the builder vs derive APIs?][crate::_faq#when-should-i-use-the-builder-vs-derive-apis]
- The [cookbook][crate::_cookbook] for more application-focused examples

### clap::_derive::_tutorial (module) › Configuring the Parser

You use derive [`Parser`][crate::Parser] to start building a parser.

```rust
use clap::Parser;

#[derive(Parser)]
#[command(name = "MyApp")]
#[command(version = "1.0")]
#[command(about = "Does awesome things", long_about = None)]
struct Cli {
    #[arg(long)]
    two: String,
    #[arg(long)]
    one: String,
}

fn main() {
    let cli = Cli::parse();

    println!("two: {:?}", cli.two);
    println!("one: {:?}", cli.one);
}
```

```console
$ 02_apps_derive --help
Does awesome things

Usage: 02_apps_derive[EXE] --two <TWO> --one <ONE>

Options:
      --two <TWO>
      --one <ONE>
  -h, --help       Print help
  -V, --version    Print version

$ 02_apps_derive --version
MyApp 1.0

```

You can use [`#[command(version, about)]` attribute defaults][super#command-attributes] on the struct to fill these fields in from your `Cargo.toml` file.

```rust
use clap::Parser;

#[derive(Parser)]
#[command(version, about, long_about = None)] // Read from `Cargo.toml`
struct Cli {
    #[arg(long)]
    two: String,
    #[arg(long)]
    one: String,
}

fn main() {
    let cli = Cli::parse();

    println!("two: {:?}", cli.two);
    println!("one: {:?}", cli.one);
}
```
```console
$ 02_crate_derive --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 02_crate_derive[EXE] --two <TWO> --one <ONE>

Options:
      --two <TWO>
      --one <ONE>
  -h, --help       Print help
  -V, --version    Print version

$ 02_crate_derive --version
clap [..]

```

You can use `#[command]` attributes on the struct to change the application level behavior of clap.  Any [`Command`][crate::Command] builder function can be used as an attribute, like [`Command::next_line_help`].

```rust
use clap::Parser;

#[derive(Parser)]
#[command(version, about, long_about = None)]
#[command(next_line_help = true)]
struct Cli {
    #[arg(long)]
    two: String,
    #[arg(long)]
    one: String,
}

fn main() {
    let cli = Cli::parse();

    println!("two: {:?}", cli.two);
    println!("one: {:?}", cli.one);
}
```
```console
$ 02_app_settings_derive --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 02_app_settings_derive[EXE] --two <TWO> --one <ONE>

Options:
      --two <TWO>

      --one <ONE>

  -h, --help
          Print help
  -V, --version
          Print version

```

### clap::_derive::_tutorial (module) › Adding Arguments

1. [Positionals](#positionals)
2. [Options](#options)
3. [Flags](#flags)
4. [Optional](#optional)
5. [Defaults](#defaults)
6. [Subcommands](#subcommands)

Arguments are inferred from the fields of your struct.

### clap::_derive::_tutorial (module) › Positionals

By default, struct fields define positional arguments:

```rust
use clap::Parser;

#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    name: String,
}

fn main() {
    let cli = Cli::parse();

    println!("name: {:?}", cli.name);
}
```
```console
$ 03_03_positional_derive --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 03_03_positional_derive[EXE] <NAME>

Arguments:
  <NAME>

Options:
  -h, --help     Print help
  -V, --version  Print version

$ 03_03_positional_derive
? 2
error: the following required arguments were not provided:
  <NAME>

Usage: 03_03_positional_derive[EXE] <NAME>

For more information, try '--help'.

$ 03_03_positional_derive bob
name: "bob"

```

Note that the [default `ArgAction` is `Set`][super#arg-types].  To
accept multiple values, override the [action][Arg::action] with [`Append`][crate::ArgAction::Append] via `Vec`:
```rust
use clap::Parser;

#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    name: Vec<String>,
}

fn main() {
    let cli = Cli::parse();

    println!("name: {:?}", cli.name);
}
```
```console
$ 03_03_positional_mult_derive --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 03_03_positional_mult_derive[EXE] [NAME]...

Arguments:
  [NAME]...

Options:
  -h, --help     Print help
  -V, --version  Print version

$ 03_03_positional_mult_derive
name: []

$ 03_03_positional_mult_derive bob
name: ["bob"]

$ 03_03_positional_mult_derive bob john
name: ["bob", "john"]

```

### clap::_derive::_tutorial (module) › Options

You can name your arguments with a flag:
- Intent of the value is clearer
- Order doesn't matter

To specify the flags for an argument, you can use [`#[arg(short = 'n')]`][Arg::short] and/or
[`#[arg(long = "name")]`][Arg::long] attributes on a field.  When no value is given (e.g.
`#[arg(short)]`), the flag is inferred from the field's name.

```rust
use clap::Parser;

#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    #[arg(short, long)]
    name: String,
}

fn main() {
    let cli = Cli::parse();

    println!("name: {:?}", cli.name);
}
```
```console
$ 03_02_option_derive --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 03_02_option_derive[EXE] --name <NAME>

Options:
  -n, --name <NAME>
  -h, --help         Print help
  -V, --version      Print version

$ 03_02_option_derive
? 2
error: the following required arguments were not provided:
  --name <NAME>

Usage: 03_02_option_derive[EXE] --name <NAME>

For more information, try '--help'.

$ 03_02_option_derive --name bob
name: "bob"

$ 03_02_option_derive --name=bob
name: "bob"

$ 03_02_option_derive -n bob
name: "bob"

$ 03_02_option_derive -n=bob
name: "bob"

$ 03_02_option_derive -nbob
name: "bob"

```

Note that the [default `ArgAction` is `Set`][super#arg-types].  To
accept multiple occurrences, override the [action][Arg::action] with [`Append`][crate::ArgAction::Append] via `Vec`:
```rust
use clap::Parser;

#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    #[arg(short, long)]
    name: Vec<String>,
}

fn main() {
    let cli = Cli::parse();

    println!("name: {:?}", cli.name);
}
```
```console
$ 03_02_option_mult_derive --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 03_02_option_mult_derive[EXE] [OPTIONS]

Options:
  -n, --name <NAME>
  -h, --help         Print help
  -V, --version      Print version

$ 03_02_option_mult_derive
name: []

$ 03_02_option_mult_derive --name bob
name: ["bob"]

$ 03_02_option_mult_derive --name bob --name john
name: ["bob", "john"]

$ 03_02_option_mult_derive --name bob --name=john -n tom -n=chris -nsteve
name: ["bob", "john", "tom", "chris", "steve"]

```

### clap::_derive::_tutorial (module) › Flags

Flags can also be switches that can be on/off:

```rust
use clap::Parser;

#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    #[arg(short, long)]
    verbose: bool,
}

fn main() {
    let cli = Cli::parse();

    println!("verbose: {:?}", cli.verbose);
}
```
```console
$ 03_01_flag_bool_derive --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 03_01_flag_bool_derive[EXE] [OPTIONS]

Options:
  -v, --verbose
  -h, --help     Print help
  -V, --version  Print version

$ 03_01_flag_bool_derive
verbose: false

$ 03_01_flag_bool_derive --verbose
verbose: true

$ 03_01_flag_bool_derive --verbose --verbose
? failed
error: the argument '--verbose' cannot be used multiple times

Usage: 03_01_flag_bool_derive[EXE] [OPTIONS]

For more information, try '--help'.

```

Note that the [default `ArgAction` for a `bool` field is
`SetTrue`][super#arg-types].  To accept multiple flags, override the [action][Arg::action] with
[`Count`][crate::ArgAction::Count]:

```rust
use clap::Parser;

#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    #[arg(short, long, action = clap::ArgAction::Count)]
    verbose: u8,
}

fn main() {
    let cli = Cli::parse();

    println!("verbose: {:?}", cli.verbose);
}
```
```console
$ 03_01_flag_count_derive --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 03_01_flag_count_derive[EXE] [OPTIONS]

Options:
  -v, --verbose...
  -h, --help        Print help
  -V, --version     Print version

$ 03_01_flag_count_derive
verbose: 0

$ 03_01_flag_count_derive --verbose
verbose: 1

$ 03_01_flag_count_derive --verbose --verbose
verbose: 2

```

This also shows that any[`Arg`][crate::Args] method may be used as an attribute.

### clap::_derive::_tutorial (module) › Optional

By default, arguments are assumed to be [`required`][crate::Arg::required].
To make an argument optional, wrap the field's type in `Option`:
```rust
use clap::Parser;

#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    name: Option<String>,
}

fn main() {
    let cli = Cli::parse();

    println!("name: {:?}", cli.name);
}
```
```console
$ 03_06_optional_derive --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 03_06_optional_derive[EXE] [NAME]

Arguments:
  [NAME]

Options:
  -h, --help     Print help
  -V, --version  Print version

$ 03_06_optional_derive
name: None

$ 03_06_optional_derive bob
name: Some("bob")

```

### clap::_derive::_tutorial (module) › Defaults

We've previously showed that arguments can be [`required`][crate::Arg::required] or optional.
When optional, you work with a `Option` and can `unwrap_or`.  Alternatively, you can
set [`#[arg(default_value_t)]`][super#arg-attributes].

```rust
use clap::Parser;

#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    #[arg(default_value_t = 2020)]
    port: u16,
}

fn main() {
    let cli = Cli::parse();

    println!("port: {:?}", cli.port);
}
```
```console
$ 03_05_default_values_derive --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 03_05_default_values_derive[EXE] [PORT]

Arguments:
  [PORT]  [default: 2020]

Options:
  -h, --help     Print help
  -V, --version  Print version

$ 03_05_default_values_derive
port: 2020

$ 03_05_default_values_derive 22
port: 22

```

### clap::_derive::_tutorial (module) › Subcommands

Subcommands are derived with `#[derive(Subcommand)]` and be added via
[`#[command(subcommand)]` attribute][super#command-attributes] on the field using that type.
Each instance of a [Subcommand][crate::Subcommand] can have its own version, author(s), Args,
and even its own subcommands.

```rust
use clap::{Parser, Subcommand};

#[derive(Parser)]
#[command(version, about, long_about = None)]
#[command(propagate_version = true)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Adds files to myapp
    Add { name: Option<String> },
}

fn main() {
    let cli = Cli::parse();

    // You can check for the existence of subcommands, and if found use their
    // matches just as you would the top level cmd
    match &cli.command {
        Commands::Add { name } => {
            println!("'myapp add' was used, name is: {name:?}");
        }
    }
}
```
We used a struct-variant to define the `add` subcommand.
Alternatively, you can use a struct for your subcommand's arguments:
```rust
use clap::{Args, Parser, Subcommand};

#[derive(Parser)]
#[command(version, about, long_about = None)]
#[command(propagate_version = true)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Adds files to myapp
    Add(AddArgs),
}

#[derive(Args)]
struct AddArgs {
    name: Option<String>,
}

fn main() {
    let cli = Cli::parse();

    // You can check for the existence of subcommands, and if found use their
    // matches just as you would the top level cmd
    match &cli.command {
        Commands::Add(name) => {
            println!("'myapp add' was used, name is: {:?}", name.name);
        }
    }
}
```

```console
$ 03_04_subcommands_derive help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 03_04_subcommands_derive[EXE] <COMMAND>

Commands:
  add   Adds files to myapp
  help  Print this message or the help of the given subcommand(s)

Options:
  -h, --help     Print help
  -V, --version  Print version

$ 03_04_subcommands_derive help add
Adds files to myapp

Usage: 03_04_subcommands_derive[EXE] add [NAME]

Arguments:
  [NAME]

Options:
  -h, --help     Print help
  -V, --version  Print version

$ 03_04_subcommands_derive add bob
'myapp add' was used, name is: Some("bob")

```

When specifying commands with `command: Commands`, they are [required][crate::Command::subcommand_required].
By default, a missing subcommand will [show help rather than error][crate::Command::arg_required_else_help].
```console
$ 03_04_subcommands_derive
? failed
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 03_04_subcommands_derive[EXE] <COMMAND>

Commands:
  add   Adds files to myapp
  help  Print this message or the help of the given subcommand(s)

Options:
  -h, --help     Print help
  -V, --version  Print version

```
To make a subcommand optional, wrap it in an `Option` (e.g. `command: Option<Commands>`).

Since we specified [`#[command(propagate_version = true)]`][crate::Command::propagate_version],
the `--version` flag is available in all subcommands:
```console
$ 03_04_subcommands_derive --version
clap [..]

$ 03_04_subcommands_derive add --version
clap-add [..]

```

### clap::_derive::_tutorial (module) › Validation

1. [Enumerated values](#enumerated-values)
2. [Validated values](#validated-values)
3. [Argument Relations](#argument-relations)
4. [Custom Validation](#custom-validation)

An appropriate default parser/validator will be selected for the field's type.  See
[`value_parser!`][crate::value_parser!] for more details.

### clap::_derive::_tutorial (module) › Enumerated values

For example, if you have arguments of specific values you want to test for, you can derive
[`ValueEnum`][super#valueenum-attributes]
(any [`PossibleValue`] builder function can be used as a `#[value]` attribute on enum variants).

This allows you specify the valid values for that argument. If the user does not use one of
those specific values, they will receive a graceful exit with error message informing them
of the mistake, and what the possible valid values are

```rust
use clap::{Parser, ValueEnum};

#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    /// What mode to run the program in
    #[arg(value_enum)]
    mode: Mode,
}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
enum Mode {
    /// Run swiftly
    Fast,
    /// Crawl slowly but steadily
    ///
    /// This paragraph is ignored because there is no long help text for possible values.
    Slow,
}

fn main() {
    let cli = Cli::parse();

    match cli.mode {
        Mode::Fast => {
            println!("Hare");
        }
        Mode::Slow => {
            println!("Tortoise");
        }
    }
}
```
```console
$ 04_01_enum_derive --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 04_01_enum_derive[EXE] <MODE>

Arguments:
  <MODE>
          What mode to run the program in

          Possible values:
          - fast: Run swiftly
          - slow: Crawl slowly but steadily

Options:
  -h, --help
          Print help (see a summary with '-h')

  -V, --version
          Print version

$ 04_01_enum_derive -h
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 04_01_enum_derive[EXE] <MODE>

Arguments:
  <MODE>  What mode to run the program in [possible values: fast, slow]

Options:
  -h, --help     Print help (see more with '--help')
  -V, --version  Print version

$ 04_01_enum_derive fast
Hare

$ 04_01_enum_derive slow
Tortoise

$ 04_01_enum_derive medium
? failed
error: invalid value 'medium' for '<MODE>'
  [possible values: fast, slow]

For more information, try '--help'.

```

### clap::_derive::_tutorial (module) › Validated values

More generally, you can validate and parse into any data type with [`Arg::value_parser`].

```rust
use clap::Parser;

#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    /// Network port to use
    #[arg(value_parser = clap::value_parser!(u16).range(1..))]
    port: u16,
}

fn main() {
    let cli = Cli::parse();

    println!("PORT = {}", cli.port);
}
```
```console
$ 04_02_parse_derive --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 04_02_parse_derive[EXE] <PORT>

Arguments:
  <PORT>  Network port to use

Options:
  -h, --help     Print help
  -V, --version  Print version

$ 04_02_parse_derive 22
PORT = 22

$ 04_02_parse_derive foobar
? failed
error: invalid value 'foobar' for '<PORT>': invalid digit found in string

For more information, try '--help'.

$ 04_02_parse_derive 0
? failed
error: invalid value '0' for '<PORT>': 0 is not in 1..=65535

For more information, try '--help'.

```

A [custom parser][TypedValueParser] can be used to improve the error messages or provide additional validation:

```rust
use std::ops::RangeInclusive;

use clap::Parser;

#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    /// Network port to use
    #[arg(value_parser = port_in_range)]
    port: u16,
}

fn main() {
    let cli = Cli::parse();

    println!("PORT = {}", cli.port);
}

const PORT_RANGE: RangeInclusive<usize> = 1..=65535;

fn port_in_range(s: &str) -> Result<u16, String> {
    let port: usize = s
        .parse()
        .map_err(|_| format!("`{s}` isn't a port number"))?;
    if PORT_RANGE.contains(&port) {
        Ok(port as u16)
    } else {
        Err(format!(
            "port not in range {}-{}",
            PORT_RANGE.start(),
            PORT_RANGE.end()
        ))
    }
}
```
```console
$ 04_02_validate_derive --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 04_02_validate_derive[EXE] <PORT>

Arguments:
  <PORT>  Network port to use

Options:
  -h, --help     Print help
  -V, --version  Print version

$ 04_02_validate_derive 22
PORT = 22

$ 04_02_validate_derive foobar
? failed
error: invalid value 'foobar' for '<PORT>': `foobar` isn't a port number

For more information, try '--help'.

$ 04_02_validate_derive 0
? failed
error: invalid value '0' for '<PORT>': port not in range 1-65535

For more information, try '--help'.

```

See [`Arg::value_parser`][crate::Arg::value_parser] for more details.

### clap::_derive::_tutorial (module) › Argument Relations

You can declare dependencies or conflicts between [`Arg`][crate::Arg]s or even
[`ArgGroup`][crate::ArgGroup]s.

[`ArgGroup`][crate::ArgGroup]s  make it easier to declare relations instead of having to list
each individually, or when you want a rule to apply "any but not all" arguments.

Perhaps the most common use of [`ArgGroup`][crate::ArgGroup]s is to require one and *only* one
argument to be present out of a given set. Imagine that you had multiple arguments, and you
want one of them to be required, but making all of them required isn't feasible because perhaps
they conflict with each other.

[`ArgGroup`][crate::ArgGroup]s are automatically created for a `struct` with its
[`ArgGroup::id`][crate::ArgGroup::id] being the struct's name.

```rust
use clap::{Args, Parser};

#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    #[command(flatten)]
    vers: Vers,

    /// some regular input
    #[arg(group = "input")]
    input_file: Option<String>,

    /// some special input argument
    #[arg(long, group = "input")]
    spec_in: Option<String>,

    #[arg(short, requires = "input")]
    config: Option<String>,
}

#[derive(Args)]
#[group(required = true, multiple = false)]
struct Vers {
    /// set version manually
    #[arg(long, value_name = "VER")]
    set_ver: Option<String>,

    /// auto inc major
    #[arg(long)]
    major: bool,

    /// auto inc minor
    #[arg(long)]
    minor: bool,

    /// auto inc patch
    #[arg(long)]
    patch: bool,
}

fn main() {
    let cli = Cli::parse();

    // Let's assume the old version 1.2.3
    let mut major = 1;
    let mut minor = 2;
    let mut patch = 3;

    // See if --set_ver was used to set the version manually
    let vers = &cli.vers;
    let version = if let Some(ver) = vers.set_ver.as_deref() {
        ver.to_owned()
    } else {
        // Increment the one requested (in a real program, we'd reset the lower numbers)
        let (maj, min, pat) = (vers.major, vers.minor, vers.patch);
        match (maj, min, pat) {
            (true, _, _) => major += 1,
            (_, true, _) => minor += 1,
            (_, _, true) => patch += 1,
            _ => unreachable!(),
        };
        format!("{major}.{minor}.{patch}")
    };

    println!("Version: {version}");

    // Check for usage of -c
    if let Some(config) = cli.config.as_deref() {
        let input = cli
            .input_file
            .as_deref()
            .unwrap_or_else(|| cli.spec_in.as_deref().unwrap());
        println!("Doing work using input {input} and config {config}");
    }
}
```
```console
$ 04_03_relations_derive --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 04_03_relations_derive[EXE] [OPTIONS] <--set-ver <VER>|--major|--minor|--patch> [INPUT_FILE]

Arguments:
  [INPUT_FILE]  some regular input

Options:
      --set-ver <VER>      set version manually
      --major              auto inc major
      --minor              auto inc minor
      --patch              auto inc patch
      --spec-in <SPEC_IN>  some special input argument
  -c <CONFIG>
  -h, --help               Print help
  -V, --version            Print version

$ 04_03_relations_derive
? failed
error: the following required arguments were not provided:
  <--set-ver <VER>|--major|--minor|--patch>

Usage: 04_03_relations_derive[EXE] <--set-ver <VER>|--major|--minor|--patch> [INPUT_FILE]

For more information, try '--help'.

$ 04_03_relations_derive --major
Version: 2.2.3

$ 04_03_relations_derive --major --minor
? failed
error: the argument '--major' cannot be used with '--minor'

Usage: 04_03_relations_derive[EXE] <--set-ver <VER>|--major|--minor|--patch> [INPUT_FILE]

For more information, try '--help'.

$ 04_03_relations_derive --major -c config.toml
? failed
error: the following required arguments were not provided:
  <INPUT_FILE|--spec-in <SPEC_IN>>

Usage: 04_03_relations_derive[EXE] -c <CONFIG> <--set-ver <VER>|--major|--minor|--patch> <INPUT_FILE|--spec-in <SPEC_IN>>

For more information, try '--help'.

$ 04_03_relations_derive --major -c config.toml --spec-in input.txt
Version: 2.2.3
Doing work using input input.txt and config config.toml

```

### clap::_derive::_tutorial (module) › Custom Validation

As a last resort, you can create custom errors with the basics of clap's formatting.

```rust
use clap::error::ErrorKind;
use clap::{CommandFactory, Parser};

#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    /// set version manually
    #[arg(long, value_name = "VER")]
    set_ver: Option<String>,

    /// auto inc major
    #[arg(long)]
    major: bool,

    /// auto inc minor
    #[arg(long)]
    minor: bool,

    /// auto inc patch
    #[arg(long)]
    patch: bool,

    /// some regular input
    input_file: Option<String>,

    /// some special input argument
    #[arg(long)]
    spec_in: Option<String>,

    #[arg(short)]
    config: Option<String>,
}

fn main() {
    let cli = Cli::parse();

    // Let's assume the old version 1.2.3
    let mut major = 1;
    let mut minor = 2;
    let mut patch = 3;

    // See if --set-ver was used to set the version manually
    let version = if let Some(ver) = cli.set_ver.as_deref() {
        if cli.major || cli.minor || cli.patch {
            let mut cmd = Cli::command();
            cmd.error(
                ErrorKind::ArgumentConflict,
                "Can't do relative and absolute version change",
            )
            .exit();
        }
        ver.to_owned()
    } else {
        // Increment the one requested (in a real program, we'd reset the lower numbers)
        let (maj, min, pat) = (cli.major, cli.minor, cli.patch);
        match (maj, min, pat) {
            (true, false, false) => major += 1,
            (false, true, false) => minor += 1,
            (false, false, true) => patch += 1,
            _ => {
                let mut cmd = Cli::command();
                cmd.error(
                    ErrorKind::ArgumentConflict,
                    "Can only modify one version field",
                )
                .exit();
            }
        };
        format!("{major}.{minor}.{patch}")
    };

    println!("Version: {version}");

    // Check for usage of -c
    if let Some(config) = cli.config.as_deref() {
        let input = cli
            .input_file
            .as_deref()
            // 'or' is preferred to 'or_else' here since `Option::as_deref` is 'const'
            .or(cli.spec_in.as_deref())
            .unwrap_or_else(|| {
                let mut cmd = Cli::command();
                cmd.error(
                    ErrorKind::MissingRequiredArgument,
                    "INPUT_FILE or --spec-in is required when using --config",
                )
                .exit()
            });
        println!("Doing work using input {input} and config {config}");
    }
}
```
```console
$ 04_04_custom_derive --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 04_04_custom_derive[EXE] [OPTIONS] [INPUT_FILE]

Arguments:
  [INPUT_FILE]  some regular input

Options:
      --set-ver <VER>      set version manually
      --major              auto inc major
      --minor              auto inc minor
      --patch              auto inc patch
      --spec-in <SPEC_IN>  some special input argument
  -c <CONFIG>
  -h, --help               Print help
  -V, --version            Print version

$ 04_04_custom_derive
? failed
error: Can only modify one version field

Usage: clap [OPTIONS] [INPUT_FILE]

For more information, try '--help'.

$ 04_04_custom_derive --major
Version: 2.2.3

$ 04_04_custom_derive --major --minor
? failed
error: Can only modify one version field

Usage: clap [OPTIONS] [INPUT_FILE]

For more information, try '--help'.

$ 04_04_custom_derive --major -c config.toml
? failed
Version: 2.2.3
error: INPUT_FILE or --spec-in is required when using --config

Usage: clap [OPTIONS] [INPUT_FILE]

For more information, try '--help'.

$ 04_04_custom_derive --major -c config.toml --spec-in input.txt
Version: 2.2.3
Doing work using input input.txt and config config.toml

```

### clap::_derive::_tutorial (module) › Testing

clap reports most development errors as `debug_assert!`s.  Rather than checking every
subcommand, you should have a test that calls
[`Command::debug_assert`][crate::Command::debug_assert]:
```rust,no_run
use clap::Parser;

#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    /// Network port to use
    port: u16,
}

fn main() {
    let cli = Cli::parse();

    println!("PORT = {}", cli.port);
}

#[test]
fn verify_cli() {
    use clap::CommandFactory;
    Cli::command().debug_assert();
}
```

### clap::_derive::_tutorial (module) › Next Steps

- [Cookbook][crate::_cookbook] for application-focused examples
- Explore more features in the [Derive reference][super]
  - See also [`Command`], [`Arg`], [`ArgGroup`], and [`PossibleValue`] builder functions which
    can be used as attributes

For support, see [Discussions](https://github.com/clap-rs/clap/discussions)

## clap::_faq (module)

### clap::_faq (module) › Documentation: FAQ

1. [Comparisons](#comparisons)
   1. [How does `clap` compare to structopt?](#how-does-clap-compare-to-structopt)
   2. [What are some reasons to use `clap`? (The Pitch)](#what-are-some-reasons-to-use-clap-the-pitch)
   3. [What are some reasons *not* to use `clap`? (The Anti Pitch)](#what-are-some-reasons-not-to-use-clap-the-anti-pitch)
   4. [Reasons to use `clap`](#reasons-to-use-clap)
2. [How many approaches are there to create a parser?](#how-many-approaches-are-there-to-create-a-parser)
3. [When should I use the builder vs derive APIs?](#when-should-i-use-the-builder-vs-derive-apis)
4. [Why is there a default subcommand of help?](#why-is-there-a-default-subcommand-of-help)

### clap::_faq (module) › Comparisons

First, let me say that these comparisons are highly subjective, and not meant
in a critical or harsh manner. All the argument parsing libraries out there (to
include `clap`) have their own strengths and weaknesses. Sometimes it just
comes down to personal taste when all other factors are equal. When in doubt,
try them all and pick one that you enjoy :). There's plenty of room in the Rust
community for multiple implementations!

For less detailed but more broad comparisons, see
[argparse-benchmarks](https://github.com/rust-cli/argparse-benchmarks-rs).

### clap::_faq (module) › How does `clap` compare to [structopt](https://github.com/TeXitoi/structopt)?

Simple! `clap` *is* `structopt`.  `structopt` started as a derive API built on
top of clap v2.  With clap v3, we've forked structopt and integrated it
directly into clap.  structopt is in
[maintenance mode](https://github.com/TeXitoi/structopt/issues/516#issuecomment-989566094)
with the release of `clap_derive`.

The benefits of integrating `structopt` and `clap` are:
- Easier cross-linking in documentation
- Documentation parity
- Tighter design feedback loop, ensuring all new features are designed with
  derives in mind and easier to change `clap` in response to `structopt` bugs.
- Clearer endorsement of `structopt`

See also
- [`clap` v3 CHANGELOG](https://github.com/clap-rs/clap/blob/v3-master/CHANGELOG.md#300---2021-12-31)
- [`structopt` migration guide](https://github.com/clap-rs/clap/blob/v3-master/CHANGELOG.md#migrate-structopt)

### clap::_faq (module) › What are some reasons to use `clap`? (The Pitch)

`clap` is as fast, and as lightweight as possible while still giving all the features you'd expect from a modern argument parser. In fact, for the amount and type of features `clap` offers it remains about as fast as `getopts`. If you use `clap`, when you just need some simple arguments parsed, you'll find it's a walk in the park. `clap` also makes it possible to represent extremely complex and advanced requirements without too much thought. `clap` aims to be intuitive, easy to use, and fully capable for wide variety use cases and needs.

### clap::_faq (module) › What are some reasons *not* to use `clap`? (The Anti Pitch)

Depending on the style in which you choose to define the valid arguments, `clap` can be very verbose. `clap` also offers so many finetuning knobs and dials, that learning everything can seem overwhelming. I strive to keep the simple cases simple, but when turning all those custom dials it can get complex. `clap` is also opinionated about parsing. Even though so much can be tweaked and tuned with `clap` (and I'm adding more all the time), there are still certain features which `clap` implements in specific ways that may be contrary to some users' use-cases.

### clap::_faq (module) › Reasons to use `clap`

 * You want all the nice CLI features your users may expect, yet you don't want to implement them all yourself. You'd like to focus on your application, not argument parsing.
 * In addition to the point above, you don't want to sacrifice performance to get all those nice features.
 * You have complex requirements/conflicts between your various valid args.
 * You want to use subcommands (although other libraries also support subcommands, they are not nearly as feature rich as those provided by `clap`).
 * You want some sort of custom validation built into the argument parsing process, instead of as part of your application (which allows for earlier failures, better error messages, more cohesive experience, etc.).

### clap::_faq (module) › How many approaches are there to create a parser?

The following APIs are supported:
- [Derive][crate::_derive::_tutorial]
- [Builder][crate::_tutorial]

Previously, we supported:
- [YAML](https://github.com/clap-rs/clap/issues/3087)
- [docopt](http://docopt.org/)-inspired [usage parser](https://github.com/clap-rs/clap/issues/3086)
- [`clap_app!`](https://github.com/clap-rs/clap/issues/2835)

There are also experiments with other APIs:
- [fncmd](https://github.com/yuhr/fncmd): function attribute
- [clap-serde](https://github.com/aobatact/clap-serde): create a `Command` from a deserializer

### clap::_faq (module) › When should I use the builder vs derive APIs?

Our default answer is to use the [Derive API][crate::_derive::_tutorial]:
- Easier to read, write, and modify
- Easier to keep the argument declaration and reading of argument in sync
- Easier to reuse, e.g. [clap-verbosity-flag](https://crates.io/crates/clap-verbosity-flag)

The [Builder API][crate::_tutorial] is a lower-level API that someone might want to use for
- Faster compile times if you aren't already using other procedural macros
- More flexibility, e.g. you can look up the [argument's values][crate::ArgMatches::get_many],
  their [ordering with other arguments][crate::ArgMatches::indices_of], and [what set
  them][crate::ArgMatches::value_source].  The Derive API can only report values and not
  indices of or other data.

You can [interop between Derive and Builder APIs][crate::_derive#mixing-builder-and-derive-apis].

### clap::_faq (module) › Why is there a default subcommand of help?

There is only a default subcommand of `help` when other subcommands have been defined manually. So it's opt-in(ish), being that you only get a `help` subcommand if you're actually using subcommands.

Also, if the user defined a `help` subcommand themselves, the auto-generated one wouldn't be added (meaning it's only generated if the user hasn't defined one themselves).

## clap::_features (module)

### clap::_features (module) › Documentation: Feature Flags

Available [compile-time feature flags](https://doc.rust-lang.org/cargo/reference/features.html#dependency-features)

### clap::_features (module) › Default Features

* `std`: _Not Currently Used._ Placeholder for supporting `no_std` environments in a backwards compatible manner.
* `color`: Turns on terminal styling of help and error messages.  See
  [`Command::styles`][crate::Command::styles] to customize this.
* `help`: Auto-generate help output
* `usage`: Auto-generate usage
* `error-context`: Include contextual information for errors (which arg failed, etc)
* `suggestions`: Turns on the `Did you mean '--myoption'?` feature for when users make typos.

### clap::_features (module) › Optional features

* `deprecated`: Guided experience to prepare for next breaking release (at different stages of development, this may become default)
* `derive`: Enables the custom derive (i.e. `#[derive(Parser)]`). Without this you must use one of the other methods of creating a `clap` CLI listed above.
* `cargo`: Turns on macros that read values from [`CARGO_*` environment variables](https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates).
* `env`: Turns on the usage of environment variables during parsing.
* `unicode`: Turns on support for unicode characters (including emoji) in arguments and help messages.
* ``wrap_help``: Turns on the help text wrapping feature, based on the terminal size.
* `string`: Allow runtime generated strings (e.g. with [`Str`][crate::builder::Str]).

### clap::_features (module) › Experimental features

**Warning:** These may contain breaking changes between minor releases.

* `unstable-v5`: Preview features which will be stable on the v5.0 release

## clap::_tutorial (module)

### clap::_tutorial (module) › Tutorial for the Builder API

*See the side bar for the Table of Contents*

### clap::_tutorial (module) › Quick Start

You can create an application with several arguments using usage strings.

First, ensure `clap` is available:
```console
$ cargo add clap
```

Here is a preview of the type of application you can make:
```rust
use std::path::PathBuf;

use clap::{ArgAction, Command, arg, command, value_parser};

fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(arg!([name] "Optional name to operate on"))
        .arg(
            arg!(
                -c --config <FILE> "Sets a custom config file"
            )
            // We don't have syntax yet for optional options, so manually calling `required`
            .required(false)
            .value_parser(value_parser!(PathBuf)),
        )
        .arg(arg!(
            -d --debug ... "Turn debugging information on"
        ))
        .subcommand(
            Command::new("test")
                .about("does testing things")
                .arg(arg!(-l --list "lists test values").action(ArgAction::SetTrue)),
        )
        .get_matches();

    // You can check the value provided by positional arguments, or option arguments
    if let Some(name) = matches.get_one::<String>("name") {
        println!("Value for name: {name}");
    }

    if let Some(config_path) = matches.get_one::<PathBuf>("config") {
        println!("Value for config: {}", config_path.display());
    }

    // You can see how many times a particular flag or argument occurred
    // Note, only flags can have multiple occurrences
    match matches
        .get_one::<u8>("debug")
        .expect("Counts are defaulted")
    {
        0 => println!("Debug mode is off"),
        1 => println!("Debug mode is kind of on"),
        2 => println!("Debug mode is on"),
        _ => println!("Don't be crazy"),
    }

    // You can check for the existence of subcommands, and if found use their
    // matches just as you would the top level cmd
    if let Some(matches) = matches.subcommand_matches("test") {
        // "$ myapp test" was run
        if matches.get_flag("list") {
            // "$ myapp test -l" was run
            println!("Printing testing lists...");
        } else {
            println!("Not printing testing lists...");
        }
    }

    // Continued program logic goes here...
}
```

```console
$ 01_quick --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 01_quick[EXE] [OPTIONS] [name] [COMMAND]

Commands:
  test  does testing things
  help  Print this message or the help of the given subcommand(s)

Arguments:
  [name]  Optional name to operate on

Options:
  -c, --config <FILE>  Sets a custom config file
  -d, --debug...       Turn debugging information on
  -h, --help           Print help
  -V, --version        Print version

```

By default, the program does nothing:
```console
$ 01_quick
Debug mode is off

```

But you can mix and match the various features
```console
$ 01_quick -dd test
Debug mode is on
Not printing testing lists...

```

See also
- [FAQ: When should I use the builder vs derive APIs?][crate::_faq#when-should-i-use-the-builder-vs-derive-apis]
- The [cookbook][crate::_cookbook] for more application-focused examples

### clap::_tutorial (module) › Configuring the Parser

You use [`Command`][crate::Command] to start building a parser.

```rust
use clap::{Command, arg};

fn main() {
    let matches = Command::new("MyApp")
        .version("1.0")
        .about("Does awesome things")
        .arg(arg!(--two <VALUE>).required(true))
        .arg(arg!(--one <VALUE>).required(true))
        .get_matches();

    println!(
        "two: {:?}",
        matches.get_one::<String>("two").expect("required")
    );
    println!(
        "one: {:?}",
        matches.get_one::<String>("one").expect("required")
    );
}
```

```console
$ 02_apps --help
Does awesome things

Usage: 02_apps[EXE] --two <VALUE> --one <VALUE>

Options:
      --two <VALUE>
      --one <VALUE>
  -h, --help         Print help
  -V, --version      Print version

$ 02_apps --version
MyApp 1.0

```

You can use [`command!()`][crate::command!] to fill these fields in from your `Cargo.toml`
file.  **This requires the [`cargo` feature flag][crate::_features].**

```rust
use clap::{arg, command};

fn main() {
    // requires `cargo` feature, reading name, version, author, and description from `Cargo.toml`
    let matches = command!()
        .arg(arg!(--two <VALUE>).required(true))
        .arg(arg!(--one <VALUE>).required(true))
        .get_matches();

    println!(
        "two: {:?}",
        matches.get_one::<String>("two").expect("required")
    );
    println!(
        "one: {:?}",
        matches.get_one::<String>("one").expect("required")
    );
}
```
```console
$ 02_crate --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 02_crate[EXE] --two <VALUE> --one <VALUE>

Options:
      --two <VALUE>
      --one <VALUE>
  -h, --help         Print help
  -V, --version      Print version

$ 02_crate --version
clap [..]

```

You can use [`Command`][crate::Command] methods to change the application level behavior of
clap, like [`Command::next_line_help`].

```rust
use clap::{ArgAction, arg, command};

fn main() {
    let matches = command!() // requires `cargo` feature
        .next_line_help(true)
        .arg(arg!(--two <VALUE>).required(true).action(ArgAction::Set))
        .arg(arg!(--one <VALUE>).required(true).action(ArgAction::Set))
        .get_matches();

    println!(
        "two: {:?}",
        matches.get_one::<String>("two").expect("required")
    );
    println!(
        "one: {:?}",
        matches.get_one::<String>("one").expect("required")
    );
}
```
```console
$ 02_app_settings --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 02_app_settings[EXE] --two <VALUE> --one <VALUE>

Options:
      --two <VALUE>

      --one <VALUE>

  -h, --help
          Print help
  -V, --version
          Print version

```

### clap::_tutorial (module) › Adding Arguments

1. [Positionals](#positionals)
2. [Options](#options)
3. [Flags](#flags)
4. [Required](#required)
5. [Defaults](#defaults)
6. [Subcommands](#subcommands)


### clap::_tutorial (module) › Positionals

By default, an [`Arg`] defines a positional argument:

```rust
use clap::{Arg, command};

fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(Arg::new("name"))
        .get_matches();

    println!("name: {:?}", matches.get_one::<String>("name"));
}
```
```console
$ 03_03_positional --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 03_03_positional[EXE] [name]

Arguments:
  [name]

Options:
  -h, --help     Print help
  -V, --version  Print version

$ 03_03_positional
name: None

$ 03_03_positional bob
name: Some("bob")

```

Note that the default [`ArgAction`][crate::ArgAction] is [`Set`][crate::ArgAction::Set].  To
accept multiple values, override the [action][Arg::action] with [`Append`][crate::ArgAction::Append]:
```rust
use clap::{Arg, ArgAction, command};

fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(Arg::new("name").action(ArgAction::Append))
        .get_matches();

    let args = matches
        .get_many::<String>("name")
        .unwrap_or_default()
        .map(|v| v.as_str())
        .collect::<Vec<_>>();

    println!("names: {args:?}");
}
```
```console
$ 03_03_positional_mult --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 03_03_positional_mult[EXE] [name]...

Arguments:
  [name]...

Options:
  -h, --help     Print help
  -V, --version  Print version

$ 03_03_positional_mult
names: []

$ 03_03_positional_mult bob
names: ["bob"]

$ 03_03_positional_mult bob john
names: ["bob", "john"]

```

### clap::_tutorial (module) › Options

You can name your arguments with a flag:
- Intent of the value is clearer
- Order doesn't matter

```rust
use clap::{Arg, command};

fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(Arg::new("name").short('n').long("name"))
        .get_matches();

    println!("name: {:?}", matches.get_one::<String>("name"));
}
```
```console
$ 03_02_option --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 03_02_option[EXE] [OPTIONS]

Options:
  -n, --name <name>
  -h, --help         Print help
  -V, --version      Print version

$ 03_02_option
name: None

$ 03_02_option --name bob
name: Some("bob")

$ 03_02_option --name=bob
name: Some("bob")

$ 03_02_option -n bob
name: Some("bob")

$ 03_02_option -n=bob
name: Some("bob")

$ 03_02_option -nbob
name: Some("bob")

```

Note that the default [`ArgAction`][crate::ArgAction] is [`Set`][crate::ArgAction::Set].  To
accept multiple occurrences, override the [action][Arg::action] with [`Append`][crate::ArgAction::Append]:
```rust
use clap::{Arg, ArgAction, command};

fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(
            Arg::new("name")
                .short('n')
                .long("name")
                .action(ArgAction::Append),
        )
        .get_matches();

    let args = matches
        .get_many::<String>("name")
        .unwrap_or_default()
        .map(|v| v.as_str())
        .collect::<Vec<_>>();

    println!("names: {args:?}");
}
```
```console
$ 03_02_option_mult --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 03_02_option_mult[EXE] [OPTIONS]

Options:
  -n, --name <name>
  -h, --help         Print help
  -V, --version      Print version

$ 03_02_option_mult
names: []

$ 03_02_option_mult --name bob
names: ["bob"]

$ 03_02_option_mult --name bob --name john
names: ["bob", "john"]

$ 03_02_option_mult_derive --name bob --name=john -n tom -n=chris -nsteve
name: ["bob", "john", "tom", "chris", "steve"]

```

### clap::_tutorial (module) › Flags

Flags can also be switches that can be on/off:

```rust
use clap::{Arg, ArgAction, command};

fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(
            Arg::new("verbose")
                .short('v')
                .long("verbose")
                .action(ArgAction::SetTrue),
        )
        .get_matches();

    println!("verbose: {:?}", matches.get_flag("verbose"));
}
```
```console
$ 03_01_flag_bool --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 03_01_flag_bool[EXE] [OPTIONS]

Options:
  -v, --verbose
  -h, --help     Print help
  -V, --version  Print version

$ 03_01_flag_bool
verbose: false

$ 03_01_flag_bool --verbose
verbose: true

$ 03_01_flag_bool --verbose --verbose
? failed
error: the argument '--verbose' cannot be used multiple times

Usage: 03_01_flag_bool[EXE] [OPTIONS]

For more information, try '--help'.

```

To accept multiple flags, use [`Count`][crate::ArgAction::Count]:

```rust
use clap::{Arg, ArgAction, command};

fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(
            Arg::new("verbose")
                .short('v')
                .long("verbose")
                .action(ArgAction::Count),
        )
        .get_matches();

    println!("verbose: {:?}", matches.get_count("verbose"));
}
```
```console
$ 03_01_flag_count --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 03_01_flag_count[EXE] [OPTIONS]

Options:
  -v, --verbose...
  -h, --help        Print help
  -V, --version     Print version

$ 03_01_flag_count
verbose: 0

$ 03_01_flag_count --verbose
verbose: 1

$ 03_01_flag_count --verbose --verbose
verbose: 2

```

### clap::_tutorial (module) › Required

By default, an [`Arg`] is optional which can be changed with
[`required`][crate::Arg::required].
```rust
use clap::{Arg, command};

fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(Arg::new("name").required(true))
        .get_matches();

    println!(
        "name: {:?}",
        matches
            .get_one::<String>("name")
            .expect("clap `required` ensures its present")
    );
}
```
```console
$ 03_06_required --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 03_06_required[EXE] <name>

Arguments:
  <name>

Options:
  -h, --help     Print help
  -V, --version  Print version

$ 03_06_required
? 2
error: the following required arguments were not provided:
  <name>

Usage: 03_06_required[EXE] <name>

For more information, try '--help'.

$ 03_06_required bob
name: "bob"

```

### clap::_tutorial (module) › Defaults

We've previously showed that arguments can be [`required`][crate::Arg::required] or optional.
When optional, you work with a `Option` and can `unwrap_or`.  Alternatively, you can set
[`Arg::default_value`][crate::Arg::default_value].

```rust
use clap::{arg, command, value_parser};

fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(
            arg!([PORT])
                .value_parser(value_parser!(u16))
                .default_value("2020"),
        )
        .get_matches();

    println!(
        "port: {:?}",
        matches
            .get_one::<u16>("PORT")
            .expect("default ensures there is always a value")
    );
}
```
```console
$ 03_05_default_values --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 03_05_default_values[EXE] [PORT]

Arguments:
  [PORT]  [default: 2020]

Options:
  -h, --help     Print help
  -V, --version  Print version

$ 03_05_default_values
port: 2020

$ 03_05_default_values 22
port: 22

```

### clap::_tutorial (module) › Subcommands

Subcommands are defined as [`Command`][crate::Command]s that get added via
[`Command::subcommand`][crate::Command::subcommand]. Each instance of a Subcommand can have its
own version, author(s), Args, and even its own subcommands.

```rust
use clap::{Command, arg, command};

fn main() {
    let matches = command!() // requires `cargo` feature
        .propagate_version(true)
        .subcommand_required(true)
        .arg_required_else_help(true)
        .subcommand(
            Command::new("add")
                .about("Adds files to myapp")
                .arg(arg!([NAME])),
        )
        .get_matches();

    match matches.subcommand() {
        Some(("add", sub_matches)) => println!(
            "'myapp add' was used, name is: {:?}",
            sub_matches.get_one::<String>("NAME")
        ),
        _ => unreachable!("Exhausted list of subcommands and subcommand_required prevents `None`"),
    }
}
```
```console
$ 03_04_subcommands help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 03_04_subcommands[EXE] <COMMAND>

Commands:
  add   Adds files to myapp
  help  Print this message or the help of the given subcommand(s)

Options:
  -h, --help     Print help
  -V, --version  Print version

$ 03_04_subcommands help add
Adds files to myapp

Usage: 03_04_subcommands[EXE] add [NAME]

Arguments:
  [NAME]

Options:
  -h, --help     Print help
  -V, --version  Print version

$ 03_04_subcommands add bob
'myapp add' was used, name is: Some("bob")

```

We set
[`Command::arg_required_else_help`][crate::Command::arg_required_else_help] to
show the help, rather than an error, when the
[required subcommand][crate::Command::subcommand_required] is missing:
```console
$ 03_04_subcommands
? failed
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 03_04_subcommands[EXE] <COMMAND>

Commands:
  add   Adds files to myapp
  help  Print this message or the help of the given subcommand(s)

Options:
  -h, --help     Print help
  -V, --version  Print version

```

Since we specified [`Command::propagate_version`][crate::Command::propagate_version], the `--version` flag
is available in all subcommands:
```console
$ 03_04_subcommands --version
clap [..]

$ 03_04_subcommands add --version
clap-add [..]

```

### clap::_tutorial (module) › Validation

1. [Enumerated values](#enumerated-values)
2. [Validated values](#validated-values)
3. [Argument Relations](#argument-relations)
4. [Custom Validation](#custom-validation)

An appropriate default parser/validator will be selected for the field's type.  See
[`value_parser!`][crate::value_parser!] for more details.

### clap::_tutorial (module) › Enumerated values

If you have arguments of specific values you want to test for, you can use the
[`PossibleValuesParser`] or [`Arg::value_parser(["val1",
...])`][crate::Arg::value_parser] for short.

This allows you to specify the valid values for that argument. If the user does not use one of
those specific values, they will receive a graceful exit with error message informing them
of the mistake, and what the possible valid values are

```rust
use clap::{arg, command};

fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(
            arg!(<MODE>)
                .help("What mode to run the program in")
                .value_parser(["fast", "slow"]),
        )
        .get_matches();

    // Note, it's safe to call unwrap() because the arg is required
    match matches
        .get_one::<String>("MODE")
        .expect("'MODE' is required and parsing will fail if its missing")
        .as_str()
    {
        "fast" => {
            println!("Hare");
        }
        "slow" => {
            println!("Tortoise");
        }
        _ => unreachable!(),
    }
}
```
```console
$ 04_01_possible --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 04_01_possible[EXE] <MODE>

Arguments:
  <MODE>  What mode to run the program in [possible values: fast, slow]

Options:
  -h, --help     Print help
  -V, --version  Print version

$ 04_01_possible fast
Hare

$ 04_01_possible slow
Tortoise

$ 04_01_possible medium
? failed
error: invalid value 'medium' for '<MODE>'
  [possible values: fast, slow]

For more information, try '--help'.

```

When enabling the [`derive` feature][crate::_features], you can use
[`ValueEnum`][crate::ValueEnum] to take care of the boiler plate for you, giving the same
results.

```rust
use clap::{ValueEnum, arg, builder::PossibleValue, command, value_parser};

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum Mode {
    Fast,
    Slow,
}

// Can also be derived with feature flag `derive`
impl ValueEnum for Mode {
    fn value_variants<'a>() -> &'a [Self] {
        &[Self::Fast, Self::Slow]
    }

    fn to_possible_value(&self) -> Option<PossibleValue> {
        Some(match self {
            Self::Fast => PossibleValue::new("fast").help("Run swiftly"),
            Self::Slow => PossibleValue::new("slow").help("Crawl slowly but steadily"),
        })
    }
}

impl std::fmt::Display for Mode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.to_possible_value()
            .expect("no values are skipped")
            .get_name()
            .fmt(f)
    }
}

impl std::str::FromStr for Mode {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        for variant in Self::value_variants() {
            if variant.to_possible_value().unwrap().matches(s, false) {
                return Ok(*variant);
            }
        }
        Err(format!("invalid variant: {s}"))
    }
}

fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(
            arg!(<MODE>)
                .help("What mode to run the program in")
                .value_parser(value_parser!(Mode)),
        )
        .get_matches();

    // Note, it's safe to call unwrap() because the arg is required
    match matches
        .get_one::<Mode>("MODE")
        .expect("'MODE' is required and parsing will fail if its missing")
    {
        Mode::Fast => {
            println!("Hare");
        }
        Mode::Slow => {
            println!("Tortoise");
        }
    }
}
```
```console
$ 04_01_enum --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 04_01_enum[EXE] <MODE>

Arguments:
  <MODE>
          What mode to run the program in

          Possible values:
          - fast: Run swiftly
          - slow: Crawl slowly but steadily

Options:
  -h, --help
          Print help (see a summary with '-h')

  -V, --version
          Print version

$ 04_01_enum -h
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 04_01_enum[EXE] <MODE>

Arguments:
  <MODE>  What mode to run the program in [possible values: fast, slow]

Options:
  -h, --help     Print help (see more with '--help')
  -V, --version  Print version

$ 04_01_enum fast
Hare

$ 04_01_enum slow
Tortoise

$ 04_01_enum medium
? failed
error: invalid value 'medium' for '<MODE>'
  [possible values: fast, slow]

For more information, try '--help'.

```

### clap::_tutorial (module) › Validated values

More generally, you can validate and parse into any data type with [`Arg::value_parser`].

```rust
use clap::{arg, command, value_parser};

fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(
            arg!(<PORT>)
                .help("Network port to use")
                .value_parser(value_parser!(u16).range(1..)),
        )
        .get_matches();

    // Note, it's safe to call unwrap() because the arg is required
    let port: u16 = *matches
        .get_one::<u16>("PORT")
        .expect("'PORT' is required and parsing will fail if its missing");
    println!("PORT = {port}");
}
```
```console
$ 04_02_parse --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 04_02_parse[EXE] <PORT>

Arguments:
  <PORT>  Network port to use

Options:
  -h, --help     Print help
  -V, --version  Print version

$ 04_02_parse 22
PORT = 22

$ 04_02_parse foobar
? failed
error: invalid value 'foobar' for '<PORT>': invalid digit found in string

For more information, try '--help'.

$ 04_02_parse_derive 0
? failed
error: invalid value '0' for '<PORT>': 0 is not in 1..=65535

For more information, try '--help'.

```

A [custom parser][TypedValueParser] can be used to improve the error messages or provide additional validation:

```rust
use std::ops::RangeInclusive;

use clap::{arg, command};

fn main() {
    let matches = command!() // requires `cargo` feature
        .arg(
            arg!(<PORT>)
                .help("Network port to use")
                .value_parser(port_in_range),
        )
        .get_matches();

    // Note, it's safe to call unwrap() because the arg is required
    let port: u16 = *matches
        .get_one::<u16>("PORT")
        .expect("'PORT' is required and parsing will fail if its missing");
    println!("PORT = {port}");
}

const PORT_RANGE: RangeInclusive<usize> = 1..=65535;

fn port_in_range(s: &str) -> Result<u16, String> {
    let port: usize = s
        .parse()
        .map_err(|_| format!("`{s}` isn't a port number"))?;
    if PORT_RANGE.contains(&port) {
        Ok(port as u16)
    } else {
        Err(format!(
            "port not in range {}-{}",
            PORT_RANGE.start(),
            PORT_RANGE.end()
        ))
    }
}
```
```console
$ 04_02_validate --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 04_02_validate[EXE] <PORT>

Arguments:
  <PORT>  Network port to use

Options:
  -h, --help     Print help
  -V, --version  Print version

$ 04_02_validate 22
PORT = 22

$ 04_02_validate foobar
? failed
error: invalid value 'foobar' for '<PORT>': `foobar` isn't a port number

For more information, try '--help'.

$ 04_02_validate 0
? failed
error: invalid value '0' for '<PORT>': port not in range 1-65535

For more information, try '--help'.

```

See [`Arg::value_parser`][crate::Arg::value_parser] for more details.

### clap::_tutorial (module) › Argument Relations

You can declare dependencies or conflicts between [`Arg`][crate::Arg]s or even
[`ArgGroup`][crate::ArgGroup]s.

[`ArgGroup`][crate::ArgGroup]s  make it easier to declare relations instead of having to list
each individually, or when you want a rule to apply "any but not all" arguments.

Perhaps the most common use of [`ArgGroup`][crate::ArgGroup]s is to require one and *only* one
argument to be present out of a given set. Imagine that you had multiple arguments, and you
want one of them to be required, but making all of them required isn't feasible because perhaps
they conflict with each other.

```rust
use std::path::PathBuf;

use clap::{ArgAction, ArgGroup, arg, command, value_parser};

fn main() {
    // Create application like normal
    let matches = command!() // requires `cargo` feature
        // Add the version arguments
        .arg(arg!(--"set-ver" <VER> "set version manually"))
        .arg(arg!(--major         "auto inc major").action(ArgAction::SetTrue))
        .arg(arg!(--minor         "auto inc minor").action(ArgAction::SetTrue))
        .arg(arg!(--patch         "auto inc patch").action(ArgAction::SetTrue))
        // Create a group, make it required, and add the above arguments
        .group(
            ArgGroup::new("vers")
                .required(true)
                .args(["set-ver", "major", "minor", "patch"]),
        )
        // Arguments can also be added to a group individually, these two arguments
        // are part of the "input" group which is not required
        .arg(
            arg!([INPUT_FILE] "some regular input")
                .value_parser(value_parser!(PathBuf))
                .group("input"),
        )
        .arg(
            arg!(--"spec-in" <SPEC_IN> "some special input argument")
                .value_parser(value_parser!(PathBuf))
                .group("input"),
        )
        // Now let's assume we have a -c [config] argument which requires one of
        // (but **not** both) the "input" arguments
        .arg(
            arg!(config: -c <CONFIG>)
                .value_parser(value_parser!(PathBuf))
                .requires("input"),
        )
        .get_matches();

    // Let's assume the old version 1.2.3
    let mut major = 1;
    let mut minor = 2;
    let mut patch = 3;

    // See if --set-ver was used to set the version manually
    let version = if let Some(ver) = matches.get_one::<String>("set-ver") {
        ver.to_owned()
    } else {
        // Increment the one requested (in a real program, we'd reset the lower numbers)
        let (maj, min, pat) = (
            matches.get_flag("major"),
            matches.get_flag("minor"),
            matches.get_flag("patch"),
        );
        match (maj, min, pat) {
            (true, _, _) => major += 1,
            (_, true, _) => minor += 1,
            (_, _, true) => patch += 1,
            _ => unreachable!(),
        };
        format!("{major}.{minor}.{patch}")
    };

    println!("Version: {version}");

    // Check for usage of -c
    if matches.contains_id("config") {
        let input = matches
            .get_one::<PathBuf>("INPUT_FILE")
            .unwrap_or_else(|| matches.get_one::<PathBuf>("spec-in").unwrap())
            .display();
        println!(
            "Doing work using input {} and config {}",
            input,
            matches.get_one::<PathBuf>("config").unwrap().display()
        );
    }
}
```
```console
$ 04_03_relations --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 04_03_relations[EXE] [OPTIONS] <--set-ver <VER>|--major|--minor|--patch> [INPUT_FILE]

Arguments:
  [INPUT_FILE]  some regular input

Options:
      --set-ver <VER>      set version manually
      --major              auto inc major
      --minor              auto inc minor
      --patch              auto inc patch
      --spec-in <SPEC_IN>  some special input argument
  -c <CONFIG>
  -h, --help               Print help
  -V, --version            Print version

$ 04_03_relations
? failed
error: the following required arguments were not provided:
  <--set-ver <VER>|--major|--minor|--patch>

Usage: 04_03_relations[EXE] <--set-ver <VER>|--major|--minor|--patch> [INPUT_FILE]

For more information, try '--help'.

$ 04_03_relations --major
Version: 2.2.3

$ 04_03_relations --major --minor
? failed
error: the argument '--major' cannot be used with '--minor'

Usage: 04_03_relations[EXE] <--set-ver <VER>|--major|--minor|--patch> [INPUT_FILE]

For more information, try '--help'.

$ 04_03_relations --major -c config.toml
? failed
error: the following required arguments were not provided:
  <INPUT_FILE|--spec-in <SPEC_IN>>

Usage: 04_03_relations[EXE] -c <CONFIG> <--set-ver <VER>|--major|--minor|--patch> <INPUT_FILE|--spec-in <SPEC_IN>>

For more information, try '--help'.

$ 04_03_relations --major -c config.toml --spec-in input.txt
Version: 2.2.3
Doing work using input input.txt and config config.toml

```

### clap::_tutorial (module) › Custom Validation

As a last resort, you can create custom errors with the basics of clap's formatting.

```rust
use std::path::PathBuf;

use clap::error::ErrorKind;
use clap::{ArgAction, arg, command, value_parser};

fn main() {
    // Create application like normal
    let mut cmd = command!() // requires `cargo` feature
        // Add the version arguments
        .arg(arg!(--"set-ver" <VER> "set version manually"))
        .arg(arg!(--major         "auto inc major").action(ArgAction::SetTrue))
        .arg(arg!(--minor         "auto inc minor").action(ArgAction::SetTrue))
        .arg(arg!(--patch         "auto inc patch").action(ArgAction::SetTrue))
        // Arguments can also be added to a group individually, these two arguments
        // are part of the "input" group which is not required
        .arg(arg!([INPUT_FILE] "some regular input").value_parser(value_parser!(PathBuf)))
        .arg(
            arg!(--"spec-in" <SPEC_IN> "some special input argument")
                .value_parser(value_parser!(PathBuf)),
        )
        // Now let's assume we have a -c [config] argument which requires one of
        // (but **not** both) the "input" arguments
        .arg(arg!(config: -c <CONFIG>).value_parser(value_parser!(PathBuf)));
    let matches = cmd.get_matches_mut();

    // Let's assume the old version 1.2.3
    let mut major = 1;
    let mut minor = 2;
    let mut patch = 3;

    // See if --set-ver was used to set the version manually
    let version = if let Some(ver) = matches.get_one::<String>("set-ver") {
        if matches.get_flag("major") || matches.get_flag("minor") || matches.get_flag("patch") {
            cmd.error(
                ErrorKind::ArgumentConflict,
                "Can't do relative and absolute version change",
            )
            .exit();
        }
        ver.clone()
    } else {
        // Increment the one requested (in a real program, we'd reset the lower numbers)
        let (maj, min, pat) = (
            matches.get_flag("major"),
            matches.get_flag("minor"),
            matches.get_flag("patch"),
        );
        match (maj, min, pat) {
            (true, false, false) => major += 1,
            (false, true, false) => minor += 1,
            (false, false, true) => patch += 1,
            _ => {
                cmd.error(
                    ErrorKind::ArgumentConflict,
                    "Can only modify one version field",
                )
                .exit();
            }
        };
        format!("{major}.{minor}.{patch}")
    };

    println!("Version: {version}");

    // Check for usage of -c
    if matches.contains_id("config") {
        let input = matches
            .get_one::<PathBuf>("INPUT_FILE")
            .or_else(|| matches.get_one::<PathBuf>("spec-in"))
            .unwrap_or_else(|| {
                cmd.error(
                    ErrorKind::MissingRequiredArgument,
                    "INPUT_FILE or --spec-in is required when using --config",
                )
                .exit()
            })
            .display();
        println!(
            "Doing work using input {} and config {}",
            input,
            matches.get_one::<PathBuf>("config").unwrap().display()
        );
    }
}
```
```console
$ 04_04_custom --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 04_04_custom[EXE] [OPTIONS] [INPUT_FILE]

Arguments:
  [INPUT_FILE]  some regular input

Options:
      --set-ver <VER>      set version manually
      --major              auto inc major
      --minor              auto inc minor
      --patch              auto inc patch
      --spec-in <SPEC_IN>  some special input argument
  -c <CONFIG>
  -h, --help               Print help
  -V, --version            Print version

$ 04_04_custom
? failed
error: Can only modify one version field

Usage: 04_04_custom[EXE] [OPTIONS] [INPUT_FILE]

For more information, try '--help'.

$ 04_04_custom --major
Version: 2.2.3

$ 04_04_custom --major --minor
? failed
error: Can only modify one version field

Usage: 04_04_custom[EXE] [OPTIONS] [INPUT_FILE]

For more information, try '--help'.

$ 04_04_custom --major -c config.toml
? failed
Version: 2.2.3
error: INPUT_FILE or --spec-in is required when using --config

Usage: 04_04_custom[EXE] [OPTIONS] [INPUT_FILE]

For more information, try '--help'.

$ 04_04_custom --major -c config.toml --spec-in input.txt
Version: 2.2.3
Doing work using input input.txt and config config.toml

```

### clap::_tutorial (module) › Testing

clap reports most development errors as `debug_assert!`s.  Rather than checking every
subcommand, you should have a test that calls
[`Command::debug_assert`][crate::Command::debug_assert]:
```rust,no_run
use clap::{arg, command, value_parser};

fn main() {
    let matches = cmd().get_matches();

    // Note, it's safe to call unwrap() because the arg is required
    let port: usize = *matches
        .get_one::<usize>("PORT")
        .expect("'PORT' is required and parsing will fail if its missing");
    println!("PORT = {port}");
}

fn cmd() -> clap::Command {
    command!() // requires `cargo` feature
        .arg(
            arg!(<PORT>)
                .help("Network port to use")
                .value_parser(value_parser!(usize)),
        )
}

#[test]
fn verify_cmd() {
    cmd().debug_assert();
}
```

### clap::_tutorial (module) › Next Steps

- [Cookbook][crate::_cookbook] for application-focused examples
- Explore more features in the [API reference][super]

For support, see [Discussions](https://github.com/clap-rs/clap/discussions)

