Skip to main content

## Module cargo_example

Source
Available on crate feature `unstable-doc` only.
Expand description

## §Example: cargo subcommand (Builder API)

    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. The crate `clap-cargo` can help in mimicking cargo’s interface.

The help looks like:

    $ 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:

    $ cargo-example example
    None

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