Command

Struct Command 

Source
pub struct Command { /* private fields */ }
Expand description

Build a command-line interface.

This includes defining arguments, subcommands, parser behavior, and help output. Once all configuration is complete, the Command::get_matches family of methods starts the runtime-parsing process. These methods then return information about the user supplied arguments (or lack thereof).

When deriving a Parser, you can use CommandFactory::command to access the Command.

§Examples

let m = Command::new("My Program")
    .author("Me, [email protected]")
    .version("1.0.2")
    .about("Explains in brief what the program does")
    .arg(
        Arg::new("in_file")
    )
    .after_help("Longer explanation to appear after the options when \
                 displaying the help information from --help or -h")
    .get_matches();

// Your program logic starts here...

Implementations§

Source§

impl Command

§Basic API

Source

pub fn new(name: impl Into<Str>) -> Command

Creates a new instance of an Command.

It is common, but not required, to use binary name as the name. This name will only be displayed to the user when they request to print version or help and usage information.

See also command! and crate_name!.

§Examples
Command::new("My Program")
Examples found in repository?
examples/multicall-busybox.rs (line 8)
6fn applet_commands() -> [Command; 2] {
7    [
8        Command::new("true").about("does nothing successfully"),
9        Command::new("false").about("does nothing unsuccessfully"),
10    ]
11}
12
13fn main() {
14    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
15        .multicall(true)
16        .subcommand(
17            Command::new("busybox")
18                .arg_required_else_help(true)
19                .subcommand_value_name("APPLET")
20                .subcommand_help_heading("APPLETS")
21                .arg(
22                    Arg::new("install")
23                        .long("install")
24                        .help("Install hardlinks for all subcommands in path")
25                        .exclusive(true)
26                        .action(ArgAction::Set)
27                        .default_missing_value("/usr/local/bin")
28                        .value_parser(value_parser!(PathBuf)),
29                )
30                .subcommands(applet_commands()),
31        )
32        .subcommands(applet_commands());
33
34    let matches = cmd.get_matches();
35    let mut subcommand = matches.subcommand();
36    if let Some(("busybox", cmd)) = subcommand {
37        if cmd.contains_id("install") {
38            unimplemented!("Make hardlinks to the executable here");
39        }
40        subcommand = cmd.subcommand();
41    }
42    match subcommand {
43        Some(("false", _)) => exit(1),
44        Some(("true", _)) => exit(0),
45        _ => unreachable!("parser should ensure only valid subcommand names are used"),
46    }
47}
More examples
Hide additional examples
examples/derive_ref/hand_subcommand.rs (line 55)
54    fn augment_subcommands(cmd: Command) -> Command {
55        cmd.subcommand(AddArgs::augment_args(Command::new("add")))
56            .subcommand(RemoveArgs::augment_args(Command::new("remove")))
57            .subcommand_required(true)
58    }
59    fn augment_subcommands_for_update(cmd: Command) -> Command {
60        cmd.subcommand(AddArgs::augment_args(Command::new("add")))
61            .subcommand(RemoveArgs::augment_args(Command::new("remove")))
62            .subcommand_required(true)
63    }
examples/derive_ref/augment_subcommands.rs (line 12)
11fn main() {
12    let cli = Command::new("Built CLI");
13    // Augment with derived subcommands
14    let cli = Subcommands::augment_subcommands(cli);
15
16    let matches = cli.get_matches();
17    let derived_subcommands = Subcommands::from_arg_matches(&matches)
18        .map_err(|err| err.exit())
19        .unwrap();
20    println!("Derived subcommands: {derived_subcommands:#?}");
21}
examples/tutorial_builder/02_apps.rs (line 4)
3fn main() {
4    let matches = Command::new("MyApp")
5        .version("1.0")
6        .about("Does awesome things")
7        .arg(arg!(--two <VALUE>).required(true))
8        .arg(arg!(--one <VALUE>).required(true))
9        .get_matches();
10
11    println!(
12        "two: {:?}",
13        matches.get_one::<String>("two").expect("required")
14    );
15    println!(
16        "one: {:?}",
17        matches.get_one::<String>("one").expect("required")
18    );
19}
examples/multicall-hostname.rs (line 4)
3fn main() {
4    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
5        .multicall(true)
6        .arg_required_else_help(true)
7        .subcommand_value_name("APPLET")
8        .subcommand_help_heading("APPLETS")
9        .subcommand(Command::new("hostname").about("show hostname part of FQDN"))
10        .subcommand(Command::new("dnsdomainname").about("show domain name part of FQDN"));
11
12    match cmd.get_matches().subcommand_name() {
13        Some("hostname") => println!("www"),
14        Some("dnsdomainname") => println!("example.com"),
15        _ => unreachable!("parser should ensure only valid subcommand names are used"),
16    }
17}
examples/derive_ref/augment_args.rs (line 10)
9fn main() {
10    let cli = Command::new("CLI").arg(arg!(-b - -built).action(clap::ArgAction::SetTrue));
11    // Augment built args with derived args
12    let cli = DerivedArgs::augment_args(cli);
13
14    let matches = cli.get_matches();
15    println!("Value of built: {:?}", matches.get_flag("built"));
16    println!(
17        "Value of derived via ArgMatches: {:?}",
18        matches.get_flag("derived")
19    );
20
21    // Since DerivedArgs implements FromArgMatches, we can extract it from the unstructured ArgMatches.
22    // This is the main benefit of using derived arguments.
23    let derived_matches = DerivedArgs::from_arg_matches(&matches)
24        .map_err(|err| err.exit())
25        .unwrap();
26    println!("Value of derived: {derived_matches:#?}");
27}
Source

pub fn arg(self, a: impl Into<Arg>) -> Command

Adds an argument to the list of valid possibilities.

§Examples
Command::new("myprog")
    // Adding a single "flag" argument with a short and help text, using Arg::new()
    .arg(
        Arg::new("debug")
           .short('d')
           .help("turns on debugging mode")
    )
    // Adding a single "option" argument with a short, a long, and help text using the less
    // verbose Arg::from()
    .arg(
        arg!(-c --config <CONFIG> "Optionally sets a config file to use")
    )
Examples found in repository?
examples/tutorial_builder/02_apps.rs (line 7)
3fn main() {
4    let matches = Command::new("MyApp")
5        .version("1.0")
6        .about("Does awesome things")
7        .arg(arg!(--two <VALUE>).required(true))
8        .arg(arg!(--one <VALUE>).required(true))
9        .get_matches();
10
11    println!(
12        "two: {:?}",
13        matches.get_one::<String>("two").expect("required")
14    );
15    println!(
16        "one: {:?}",
17        matches.get_one::<String>("one").expect("required")
18    );
19}
More examples
Hide additional examples
examples/derive_ref/flatten_hand_args.rs (lines 39-44)
38    fn augment_args(cmd: Command) -> Command {
39        cmd.arg(
40            Arg::new("foo")
41                .short('f')
42                .long("foo")
43                .action(ArgAction::SetTrue),
44        )
45        .arg(
46            Arg::new("bar")
47                .short('b')
48                .long("bar")
49                .action(ArgAction::SetTrue),
50        )
51        .arg(
52            Arg::new("quuz")
53                .short('q')
54                .long("quuz")
55                .action(ArgAction::Set),
56        )
57    }
58    fn augment_args_for_update(cmd: Command) -> Command {
59        cmd.arg(
60            Arg::new("foo")
61                .short('f')
62                .long("foo")
63                .action(ArgAction::SetTrue),
64        )
65        .arg(
66            Arg::new("bar")
67                .short('b')
68                .long("bar")
69                .action(ArgAction::SetTrue),
70        )
71        .arg(
72            Arg::new("quuz")
73                .short('q')
74                .long("quuz")
75                .action(ArgAction::Set),
76        )
77    }
examples/derive_ref/augment_args.rs (line 10)
9fn main() {
10    let cli = Command::new("CLI").arg(arg!(-b - -built).action(clap::ArgAction::SetTrue));
11    // Augment built args with derived args
12    let cli = DerivedArgs::augment_args(cli);
13
14    let matches = cli.get_matches();
15    println!("Value of built: {:?}", matches.get_flag("built"));
16    println!(
17        "Value of derived via ArgMatches: {:?}",
18        matches.get_flag("derived")
19    );
20
21    // Since DerivedArgs implements FromArgMatches, we can extract it from the unstructured ArgMatches.
22    // This is the main benefit of using derived arguments.
23    let derived_matches = DerivedArgs::from_arg_matches(&matches)
24        .map_err(|err| err.exit())
25        .unwrap();
26    println!("Value of derived: {derived_matches:#?}");
27}
examples/multicall-busybox.rs (lines 21-29)
13fn main() {
14    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
15        .multicall(true)
16        .subcommand(
17            Command::new("busybox")
18                .arg_required_else_help(true)
19                .subcommand_value_name("APPLET")
20                .subcommand_help_heading("APPLETS")
21                .arg(
22                    Arg::new("install")
23                        .long("install")
24                        .help("Install hardlinks for all subcommands in path")
25                        .exclusive(true)
26                        .action(ArgAction::Set)
27                        .default_missing_value("/usr/local/bin")
28                        .value_parser(value_parser!(PathBuf)),
29                )
30                .subcommands(applet_commands()),
31        )
32        .subcommands(applet_commands());
33
34    let matches = cmd.get_matches();
35    let mut subcommand = matches.subcommand();
36    if let Some(("busybox", cmd)) = subcommand {
37        if cmd.contains_id("install") {
38            unimplemented!("Make hardlinks to the executable here");
39        }
40        subcommand = cmd.subcommand();
41    }
42    match subcommand {
43        Some(("false", _)) => exit(1),
44        Some(("true", _)) => exit(0),
45        _ => unreachable!("parser should ensure only valid subcommand names are used"),
46    }
47}
examples/git.rs (line 15)
6fn cli() -> Command {
7    Command::new("git")
8        .about("A fictional versioning CLI")
9        .subcommand_required(true)
10        .arg_required_else_help(true)
11        .allow_external_subcommands(true)
12        .subcommand(
13            Command::new("clone")
14                .about("Clones repos")
15                .arg(arg!(<REMOTE> "The remote to clone"))
16                .arg_required_else_help(true),
17        )
18        .subcommand(
19            Command::new("diff")
20                .about("Compare two commits")
21                .arg(arg!(base: [COMMIT]))
22                .arg(arg!(head: [COMMIT]))
23                .arg(arg!(path: [PATH]).last(true))
24                .arg(
25                    arg!(--color <WHEN>)
26                        .value_parser(["always", "auto", "never"])
27                        .num_args(0..=1)
28                        .require_equals(true)
29                        .default_value("auto")
30                        .default_missing_value("always"),
31                ),
32        )
33        .subcommand(
34            Command::new("push")
35                .about("pushes things")
36                .arg(arg!(<REMOTE> "The remote to target"))
37                .arg_required_else_help(true),
38        )
39        .subcommand(
40            Command::new("add")
41                .about("adds things")
42                .arg_required_else_help(true)
43                .arg(arg!(<PATH> ... "Stuff to add").value_parser(clap::value_parser!(PathBuf))),
44        )
45        .subcommand(
46            Command::new("stash")
47                .args_conflicts_with_subcommands(true)
48                .flatten_help(true)
49                .args(push_args())
50                .subcommand(Command::new("push").args(push_args()))
51                .subcommand(Command::new("pop").arg(arg!([STASH])))
52                .subcommand(Command::new("apply").arg(arg!([STASH]))),
53        )
54}
examples/pacman.rs (lines 17-25)
3fn main() {
4    let matches = Command::new("pacman")
5        .about("package manager utility")
6        .version("5.2.1")
7        .subcommand_required(true)
8        .arg_required_else_help(true)
9        // Query subcommand
10        //
11        // Only a few of its arguments are implemented below.
12        .subcommand(
13            Command::new("query")
14                .short_flag('Q')
15                .long_flag("query")
16                .about("Query the package database.")
17                .arg(
18                    Arg::new("search")
19                        .short('s')
20                        .long("search")
21                        .help("search locally installed packages for matching strings")
22                        .conflicts_with("info")
23                        .action(ArgAction::Set)
24                        .num_args(1..),
25                )
26                .arg(
27                    Arg::new("info")
28                        .long("info")
29                        .short('i')
30                        .conflicts_with("search")
31                        .help("view package information")
32                        .action(ArgAction::Set)
33                        .num_args(1..),
34                ),
35        )
36        // Sync subcommand
37        //
38        // Only a few of its arguments are implemented below.
39        .subcommand(
40            Command::new("sync")
41                .short_flag('S')
42                .long_flag("sync")
43                .about("Synchronize packages.")
44                .arg(
45                    Arg::new("search")
46                        .short('s')
47                        .long("search")
48                        .conflicts_with("info")
49                        .action(ArgAction::Set)
50                        .num_args(1..)
51                        .help("search remote repositories for matching strings"),
52                )
53                .arg(
54                    Arg::new("info")
55                        .long("info")
56                        .conflicts_with("search")
57                        .short('i')
58                        .action(ArgAction::SetTrue)
59                        .help("view package information"),
60                )
61                .arg(
62                    Arg::new("package")
63                        .help("packages")
64                        .required_unless_present("search")
65                        .action(ArgAction::Set)
66                        .num_args(1..),
67                ),
68        )
69        .get_matches();
70
71    match matches.subcommand() {
72        Some(("sync", sync_matches)) => {
73            if sync_matches.contains_id("search") {
74                let packages: Vec<_> = sync_matches
75                    .get_many::<String>("search")
76                    .expect("contains_id")
77                    .map(|s| s.as_str())
78                    .collect();
79                let values = packages.join(", ");
80                println!("Searching for {values}...");
81                return;
82            }
83
84            let packages: Vec<_> = sync_matches
85                .get_many::<String>("package")
86                .expect("is present")
87                .map(|s| s.as_str())
88                .collect();
89            let values = packages.join(", ");
90
91            if sync_matches.get_flag("info") {
92                println!("Retrieving info for {values}...");
93            } else {
94                println!("Installing {values}...");
95            }
96        }
97        Some(("query", query_matches)) => {
98            if let Some(packages) = query_matches.get_many::<String>("info") {
99                let comma_sep = packages.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
100                println!("Retrieving info for {comma_sep}...");
101            } else if let Some(queries) = query_matches.get_many::<String>("search") {
102                let comma_sep = queries.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
103                println!("Searching Locally for {comma_sep}...");
104            } else {
105                println!("Displaying all locally installed packages...");
106            }
107        }
108        _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable
109    }
110}
Source

pub fn args(self, args: impl IntoIterator<Item = impl Into<Arg>>) -> Command

Adds multiple arguments to the list of valid possibilities.

§Examples
Command::new("myprog")
    .args([
        arg!(-d --debug "turns on debugging info"),
        Arg::new("input").help("the input file to use")
    ])
Examples found in repository?
examples/git.rs (line 49)
6fn cli() -> Command {
7    Command::new("git")
8        .about("A fictional versioning CLI")
9        .subcommand_required(true)
10        .arg_required_else_help(true)
11        .allow_external_subcommands(true)
12        .subcommand(
13            Command::new("clone")
14                .about("Clones repos")
15                .arg(arg!(<REMOTE> "The remote to clone"))
16                .arg_required_else_help(true),
17        )
18        .subcommand(
19            Command::new("diff")
20                .about("Compare two commits")
21                .arg(arg!(base: [COMMIT]))
22                .arg(arg!(head: [COMMIT]))
23                .arg(arg!(path: [PATH]).last(true))
24                .arg(
25                    arg!(--color <WHEN>)
26                        .value_parser(["always", "auto", "never"])
27                        .num_args(0..=1)
28                        .require_equals(true)
29                        .default_value("auto")
30                        .default_missing_value("always"),
31                ),
32        )
33        .subcommand(
34            Command::new("push")
35                .about("pushes things")
36                .arg(arg!(<REMOTE> "The remote to target"))
37                .arg_required_else_help(true),
38        )
39        .subcommand(
40            Command::new("add")
41                .about("adds things")
42                .arg_required_else_help(true)
43                .arg(arg!(<PATH> ... "Stuff to add").value_parser(clap::value_parser!(PathBuf))),
44        )
45        .subcommand(
46            Command::new("stash")
47                .args_conflicts_with_subcommands(true)
48                .flatten_help(true)
49                .args(push_args())
50                .subcommand(Command::new("push").args(push_args()))
51                .subcommand(Command::new("pop").arg(arg!([STASH])))
52                .subcommand(Command::new("apply").arg(arg!([STASH]))),
53        )
54}
Source

pub fn mut_arg<F>(self, arg_id: impl AsRef<str>, f: F) -> Command
where F: FnOnce(Arg) -> Arg,

Allows one to mutate an Arg after it’s been added to a Command.

§Panics

If the argument is undefined

§Examples

let mut cmd = Command::new("foo")
    .arg(Arg::new("bar")
        .short('b')
        .action(ArgAction::SetTrue))
    .mut_arg("bar", |a| a.short('B'));

let res = cmd.try_get_matches_from_mut(vec!["foo", "-b"]);

// Since we changed `bar`'s short to "B" this should err as there
// is no `-b` anymore, only `-B`

assert!(res.is_err());

let res = cmd.try_get_matches_from_mut(vec!["foo", "-B"]);
assert!(res.is_ok());
Source

pub fn mut_args<F>(self, f: F) -> Command
where F: FnMut(Arg) -> Arg,

Allows one to mutate all Args after they’ve been added to a Command.

This does not affect the built-in --help or --version arguments.

§Examples

let mut cmd = Command::new("foo")
    .arg(Arg::new("bar")
        .long("bar")
        .action(ArgAction::SetTrue))
    .arg(Arg::new("baz")
        .long("baz")
        .action(ArgAction::SetTrue))
    .mut_args(|a| {
        if let Some(l) = a.get_long().map(|l| format!("prefix-{l}")) {
            a.long(l)
        } else {
            a
        }
    });

let res = cmd.try_get_matches_from_mut(vec!["foo", "--bar"]);

// Since we changed `bar`'s long to "prefix-bar" this should err as there
// is no `--bar` anymore, only `--prefix-bar`.

assert!(res.is_err());

let res = cmd.try_get_matches_from_mut(vec!["foo", "--prefix-bar"]);
assert!(res.is_ok());
Source

pub fn mut_group<F>(self, arg_id: impl AsRef<str>, f: F) -> Command
where F: FnOnce(ArgGroup) -> ArgGroup,

Allows one to mutate an ArgGroup after it’s been added to a Command.

§Panics

If the argument is undefined

§Examples

Command::new("foo")
    .arg(arg!(--"set-ver" <ver> "set the version manually").required(false))
    .arg(arg!(--major "auto increase major"))
    .arg(arg!(--minor "auto increase minor"))
    .arg(arg!(--patch "auto increase patch"))
    .group(ArgGroup::new("vers")
         .args(["set-ver", "major", "minor","patch"])
         .required(true))
    .mut_group("vers", |a| a.required(false));
Source

pub fn mut_subcommand<F>(self, name: impl AsRef<str>, f: F) -> Command
where F: FnOnce(Command) -> Command,

Allows one to mutate a Command after it’s been added as a subcommand.

This can be useful for modifying auto-generated arguments of nested subcommands with Command::mut_arg.

§Panics

If the subcommand is undefined

§Examples

let mut cmd = Command::new("foo")
        .subcommand(Command::new("bar"))
        .mut_subcommand("bar", |subcmd| subcmd.disable_help_flag(true));

let res = cmd.try_get_matches_from_mut(vec!["foo", "bar", "--help"]);

// Since we disabled the help flag on the "bar" subcommand, this should err.

assert!(res.is_err());

let res = cmd.try_get_matches_from_mut(vec!["foo", "bar"]);
assert!(res.is_ok());
Source

pub fn mut_subcommands<F>(self, f: F) -> Command
where F: FnMut(Command) -> Command,

Allows one to mutate all Commands after they’ve been added as subcommands.

This does not affect the built-in --help or --version arguments.

§Examples

let mut cmd = Command::new("foo")
    .subcommands([
        Command::new("fetch"),
        Command::new("push"),
    ])
    // Allow title-case subcommands
    .mut_subcommands(|sub| {
        let name = sub.get_name();
        let alias = name.chars().enumerate().map(|(i, c)| {
            if i == 0 {
                c.to_ascii_uppercase()
            } else {
                c
            }
        }).collect::<String>();
        sub.alias(alias)
    });

let res = cmd.try_get_matches_from_mut(vec!["foo", "fetch"]);
assert!(res.is_ok());

let res = cmd.try_get_matches_from_mut(vec!["foo", "Fetch"]);
assert!(res.is_ok());
Source

pub fn group(self, group: impl Into<ArgGroup>) -> Command

Adds an ArgGroup to the application.

ArgGroups are a family of related arguments. By placing them in a logical group, you can build easier requirement and exclusion rules.

Example use cases:

  • Make an entire ArgGroup required, meaning that one (and only one) argument from that group must be present at runtime.
  • Name an ArgGroup as a conflict to another argument. Meaning any of the arguments that belong to that group will cause a failure if present with the conflicting argument.
  • Ensure exclusion between arguments.
  • Extract a value from a group instead of determining exactly which argument was used.
§Examples

The following example demonstrates using an ArgGroup to ensure that one, and only one, of the arguments from the specified group is present at runtime.

Command::new("cmd")
    .arg(arg!(--"set-ver" <ver> "set the version manually").required(false))
    .arg(arg!(--major "auto increase major"))
    .arg(arg!(--minor "auto increase minor"))
    .arg(arg!(--patch "auto increase patch"))
    .group(ArgGroup::new("vers")
         .args(["set-ver", "major", "minor","patch"])
         .required(true))
Source

pub fn groups( self, groups: impl IntoIterator<Item = impl Into<ArgGroup>>, ) -> Command

Adds multiple ArgGroups to the Command at once.

§Examples
Command::new("cmd")
    .arg(arg!(--"set-ver" <ver> "set the version manually").required(false))
    .arg(arg!(--major         "auto increase major"))
    .arg(arg!(--minor         "auto increase minor"))
    .arg(arg!(--patch         "auto increase patch"))
    .arg(arg!(-c <FILE>       "a config file").required(false))
    .arg(arg!(-i <IFACE>      "an interface").required(false))
    .groups([
        ArgGroup::new("vers")
            .args(["set-ver", "major", "minor","patch"])
            .required(true),
        ArgGroup::new("input")
            .args(["c", "i"])
    ])
Source

pub fn subcommand(self, subcmd: impl Into<Command>) -> Command

Adds a subcommand to the list of valid possibilities.

Subcommands are effectively sub-Commands, because they can contain their own arguments, subcommands, version, usage, etc. They also function just like Commands, in that they get their own auto generated help, version, and usage.

A subcommand’s Command::name will be used for:

  • The argument the user passes in
  • Programmatically looking up the subcommand
§Examples
Command::new("myprog")
    .subcommand(Command::new("config")
        .about("Controls configuration features")
        .arg(arg!(<config> "Required configuration file to use")))
Examples found in repository?
examples/derive_ref/hand_subcommand.rs (line 55)
54    fn augment_subcommands(cmd: Command) -> Command {
55        cmd.subcommand(AddArgs::augment_args(Command::new("add")))
56            .subcommand(RemoveArgs::augment_args(Command::new("remove")))
57            .subcommand_required(true)
58    }
59    fn augment_subcommands_for_update(cmd: Command) -> Command {
60        cmd.subcommand(AddArgs::augment_args(Command::new("add")))
61            .subcommand(RemoveArgs::augment_args(Command::new("remove")))
62            .subcommand_required(true)
63    }
More examples
Hide additional examples
examples/multicall-hostname.rs (line 9)
3fn main() {
4    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
5        .multicall(true)
6        .arg_required_else_help(true)
7        .subcommand_value_name("APPLET")
8        .subcommand_help_heading("APPLETS")
9        .subcommand(Command::new("hostname").about("show hostname part of FQDN"))
10        .subcommand(Command::new("dnsdomainname").about("show domain name part of FQDN"));
11
12    match cmd.get_matches().subcommand_name() {
13        Some("hostname") => println!("www"),
14        Some("dnsdomainname") => println!("example.com"),
15        _ => unreachable!("parser should ensure only valid subcommand names are used"),
16    }
17}
examples/repl.rs (lines 71-75)
51fn cli() -> Command {
52    // strip out usage
53    const PARSER_TEMPLATE: &str = "\
54        {all-args}
55    ";
56    // strip out name/version
57    const APPLET_TEMPLATE: &str = "\
58        {about-with-newline}\n\
59        {usage-heading}\n    {usage}\n\
60        \n\
61        {all-args}{after-help}\
62    ";
63
64    Command::new("repl")
65        .multicall(true)
66        .arg_required_else_help(true)
67        .subcommand_required(true)
68        .subcommand_value_name("APPLET")
69        .subcommand_help_heading("APPLETS")
70        .help_template(PARSER_TEMPLATE)
71        .subcommand(
72            Command::new("ping")
73                .about("Get a response")
74                .help_template(APPLET_TEMPLATE),
75        )
76        .subcommand(
77            Command::new("quit")
78                .alias("exit")
79                .about("Quit the REPL")
80                .help_template(APPLET_TEMPLATE),
81        )
82}
examples/multicall-busybox.rs (lines 16-31)
13fn main() {
14    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
15        .multicall(true)
16        .subcommand(
17            Command::new("busybox")
18                .arg_required_else_help(true)
19                .subcommand_value_name("APPLET")
20                .subcommand_help_heading("APPLETS")
21                .arg(
22                    Arg::new("install")
23                        .long("install")
24                        .help("Install hardlinks for all subcommands in path")
25                        .exclusive(true)
26                        .action(ArgAction::Set)
27                        .default_missing_value("/usr/local/bin")
28                        .value_parser(value_parser!(PathBuf)),
29                )
30                .subcommands(applet_commands()),
31        )
32        .subcommands(applet_commands());
33
34    let matches = cmd.get_matches();
35    let mut subcommand = matches.subcommand();
36    if let Some(("busybox", cmd)) = subcommand {
37        if cmd.contains_id("install") {
38            unimplemented!("Make hardlinks to the executable here");
39        }
40        subcommand = cmd.subcommand();
41    }
42    match subcommand {
43        Some(("false", _)) => exit(1),
44        Some(("true", _)) => exit(0),
45        _ => unreachable!("parser should ensure only valid subcommand names are used"),
46    }
47}
examples/git.rs (lines 12-17)
6fn cli() -> Command {
7    Command::new("git")
8        .about("A fictional versioning CLI")
9        .subcommand_required(true)
10        .arg_required_else_help(true)
11        .allow_external_subcommands(true)
12        .subcommand(
13            Command::new("clone")
14                .about("Clones repos")
15                .arg(arg!(<REMOTE> "The remote to clone"))
16                .arg_required_else_help(true),
17        )
18        .subcommand(
19            Command::new("diff")
20                .about("Compare two commits")
21                .arg(arg!(base: [COMMIT]))
22                .arg(arg!(head: [COMMIT]))
23                .arg(arg!(path: [PATH]).last(true))
24                .arg(
25                    arg!(--color <WHEN>)
26                        .value_parser(["always", "auto", "never"])
27                        .num_args(0..=1)
28                        .require_equals(true)
29                        .default_value("auto")
30                        .default_missing_value("always"),
31                ),
32        )
33        .subcommand(
34            Command::new("push")
35                .about("pushes things")
36                .arg(arg!(<REMOTE> "The remote to target"))
37                .arg_required_else_help(true),
38        )
39        .subcommand(
40            Command::new("add")
41                .about("adds things")
42                .arg_required_else_help(true)
43                .arg(arg!(<PATH> ... "Stuff to add").value_parser(clap::value_parser!(PathBuf))),
44        )
45        .subcommand(
46            Command::new("stash")
47                .args_conflicts_with_subcommands(true)
48                .flatten_help(true)
49                .args(push_args())
50                .subcommand(Command::new("push").args(push_args()))
51                .subcommand(Command::new("pop").arg(arg!([STASH])))
52                .subcommand(Command::new("apply").arg(arg!([STASH]))),
53        )
54}
examples/pacman.rs (lines 12-35)
3fn main() {
4    let matches = Command::new("pacman")
5        .about("package manager utility")
6        .version("5.2.1")
7        .subcommand_required(true)
8        .arg_required_else_help(true)
9        // Query subcommand
10        //
11        // Only a few of its arguments are implemented below.
12        .subcommand(
13            Command::new("query")
14                .short_flag('Q')
15                .long_flag("query")
16                .about("Query the package database.")
17                .arg(
18                    Arg::new("search")
19                        .short('s')
20                        .long("search")
21                        .help("search locally installed packages for matching strings")
22                        .conflicts_with("info")
23                        .action(ArgAction::Set)
24                        .num_args(1..),
25                )
26                .arg(
27                    Arg::new("info")
28                        .long("info")
29                        .short('i')
30                        .conflicts_with("search")
31                        .help("view package information")
32                        .action(ArgAction::Set)
33                        .num_args(1..),
34                ),
35        )
36        // Sync subcommand
37        //
38        // Only a few of its arguments are implemented below.
39        .subcommand(
40            Command::new("sync")
41                .short_flag('S')
42                .long_flag("sync")
43                .about("Synchronize packages.")
44                .arg(
45                    Arg::new("search")
46                        .short('s')
47                        .long("search")
48                        .conflicts_with("info")
49                        .action(ArgAction::Set)
50                        .num_args(1..)
51                        .help("search remote repositories for matching strings"),
52                )
53                .arg(
54                    Arg::new("info")
55                        .long("info")
56                        .conflicts_with("search")
57                        .short('i')
58                        .action(ArgAction::SetTrue)
59                        .help("view package information"),
60                )
61                .arg(
62                    Arg::new("package")
63                        .help("packages")
64                        .required_unless_present("search")
65                        .action(ArgAction::Set)
66                        .num_args(1..),
67                ),
68        )
69        .get_matches();
70
71    match matches.subcommand() {
72        Some(("sync", sync_matches)) => {
73            if sync_matches.contains_id("search") {
74                let packages: Vec<_> = sync_matches
75                    .get_many::<String>("search")
76                    .expect("contains_id")
77                    .map(|s| s.as_str())
78                    .collect();
79                let values = packages.join(", ");
80                println!("Searching for {values}...");
81                return;
82            }
83
84            let packages: Vec<_> = sync_matches
85                .get_many::<String>("package")
86                .expect("is present")
87                .map(|s| s.as_str())
88                .collect();
89            let values = packages.join(", ");
90
91            if sync_matches.get_flag("info") {
92                println!("Retrieving info for {values}...");
93            } else {
94                println!("Installing {values}...");
95            }
96        }
97        Some(("query", query_matches)) => {
98            if let Some(packages) = query_matches.get_many::<String>("info") {
99                let comma_sep = packages.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
100                println!("Retrieving info for {comma_sep}...");
101            } else if let Some(queries) = query_matches.get_many::<String>("search") {
102                let comma_sep = queries.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
103                println!("Searching Locally for {comma_sep}...");
104            } else {
105                println!("Displaying all locally installed packages...");
106            }
107        }
108        _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable
109    }
110}
Source

pub fn subcommands( self, subcmds: impl IntoIterator<Item = impl Into<Command>>, ) -> Command

Adds multiple subcommands to the list of valid possibilities.

§Examples
.subcommands( [
       Command::new("config").about("Controls configuration functionality")
                                .arg(Arg::new("config_file")),
       Command::new("debug").about("Controls debug functionality")])
Examples found in repository?
examples/multicall-busybox.rs (line 30)
13fn main() {
14    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
15        .multicall(true)
16        .subcommand(
17            Command::new("busybox")
18                .arg_required_else_help(true)
19                .subcommand_value_name("APPLET")
20                .subcommand_help_heading("APPLETS")
21                .arg(
22                    Arg::new("install")
23                        .long("install")
24                        .help("Install hardlinks for all subcommands in path")
25                        .exclusive(true)
26                        .action(ArgAction::Set)
27                        .default_missing_value("/usr/local/bin")
28                        .value_parser(value_parser!(PathBuf)),
29                )
30                .subcommands(applet_commands()),
31        )
32        .subcommands(applet_commands());
33
34    let matches = cmd.get_matches();
35    let mut subcommand = matches.subcommand();
36    if let Some(("busybox", cmd)) = subcommand {
37        if cmd.contains_id("install") {
38            unimplemented!("Make hardlinks to the executable here");
39        }
40        subcommand = cmd.subcommand();
41    }
42    match subcommand {
43        Some(("false", _)) => exit(1),
44        Some(("true", _)) => exit(0),
45        _ => unreachable!("parser should ensure only valid subcommand names are used"),
46    }
47}
Source

pub fn defer(self, deferred: fn(Command) -> Command) -> Command

Delay initialization for parts of the Command

This is useful for large applications to delay definitions of subcommands until they are being invoked.

§Examples
Command::new("myprog")
    .subcommand(Command::new("config")
        .about("Controls configuration features")
        .defer(|cmd| {
            cmd.arg(arg!(<config> "Required configuration file to use"))
        })
    )
Source

pub fn debug_assert(self)

Catch problems earlier in the development cycle.

Most error states are handled as asserts under the assumption they are programming mistake and not something to handle at runtime. Rather than relying on tests (manual or automated) that exhaustively test your CLI to ensure the asserts are evaluated, this will run those asserts in a way convenient for running as a test.

Note: This will not help with asserts in ArgMatches, those will need exhaustive testing of your CLI.

§Examples
fn cmd() -> Command {
    Command::new("foo")
        .arg(
            Arg::new("bar").short('b').action(ArgAction::SetTrue)
        )
}

#[test]
fn verify_app() {
    cmd().debug_assert();
}

fn main() {
    let m = cmd().get_matches_from(vec!["foo", "-b"]);
    println!("{}", m.get_flag("bar"));
}
Source

pub fn error(&mut self, kind: ErrorKind, message: impl Display) -> Error

Custom error message for post-parsing validation

Note: this will ensure the Command has been sufficiently built for any relevant context, including usage.

§Panics

If contradictory arguments or settings exist (debug builds).

§Examples
let mut cmd = Command::new("myprog");
let err = cmd.error(ErrorKind::InvalidValue, "Some failure case");
Examples found in repository?
examples/tutorial_derive/04_04_custom.rs (lines 46-49)
34fn main() {
35    let cli = Cli::parse();
36
37    // Let's assume the old version 1.2.3
38    let mut major = 1;
39    let mut minor = 2;
40    let mut patch = 3;
41
42    // See if --set-ver was used to set the version manually
43    let version = if let Some(ver) = cli.set_ver.as_deref() {
44        if cli.major || cli.minor || cli.patch {
45            let mut cmd = Cli::command();
46            cmd.error(
47                ErrorKind::ArgumentConflict,
48                "Can't do relative and absolute version change",
49            )
50            .exit();
51        }
52        ver.to_string()
53    } else {
54        // Increment the one requested (in a real program, we'd reset the lower numbers)
55        let (maj, min, pat) = (cli.major, cli.minor, cli.patch);
56        match (maj, min, pat) {
57            (true, false, false) => major += 1,
58            (false, true, false) => minor += 1,
59            (false, false, true) => patch += 1,
60            _ => {
61                let mut cmd = Cli::command();
62                cmd.error(
63                    ErrorKind::ArgumentConflict,
64                    "Can only modify one version field",
65                )
66                .exit();
67            }
68        };
69        format!("{major}.{minor}.{patch}")
70    };
71
72    println!("Version: {version}");
73
74    // Check for usage of -c
75    if let Some(config) = cli.config.as_deref() {
76        let input = cli
77            .input_file
78            .as_deref()
79            // 'or' is preferred to 'or_else' here since `Option::as_deref` is 'const'
80            .or(cli.spec_in.as_deref())
81            .unwrap_or_else(|| {
82                let mut cmd = Cli::command();
83                cmd.error(
84                    ErrorKind::MissingRequiredArgument,
85                    "INPUT_FILE or --spec-in is required when using --config",
86                )
87                .exit()
88            });
89        println!("Doing work using input {input} and config {config}");
90    }
91}
Source

pub fn get_matches(self) -> ArgMatches

Parse env::args_os, exiting on failure.

§Panics

If contradictory arguments or settings exist (debug builds).

§Examples
let matches = Command::new("myprog")
    // Args and options go here...
    .get_matches();
Examples found in repository?
examples/derive_ref/augment_subcommands.rs (line 16)
11fn main() {
12    let cli = Command::new("Built CLI");
13    // Augment with derived subcommands
14    let cli = Subcommands::augment_subcommands(cli);
15
16    let matches = cli.get_matches();
17    let derived_subcommands = Subcommands::from_arg_matches(&matches)
18        .map_err(|err| err.exit())
19        .unwrap();
20    println!("Derived subcommands: {derived_subcommands:#?}");
21}
More examples
Hide additional examples
examples/tutorial_builder/02_apps.rs (line 9)
3fn main() {
4    let matches = Command::new("MyApp")
5        .version("1.0")
6        .about("Does awesome things")
7        .arg(arg!(--two <VALUE>).required(true))
8        .arg(arg!(--one <VALUE>).required(true))
9        .get_matches();
10
11    println!(
12        "two: {:?}",
13        matches.get_one::<String>("two").expect("required")
14    );
15    println!(
16        "one: {:?}",
17        matches.get_one::<String>("one").expect("required")
18    );
19}
examples/multicall-hostname.rs (line 12)
3fn main() {
4    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
5        .multicall(true)
6        .arg_required_else_help(true)
7        .subcommand_value_name("APPLET")
8        .subcommand_help_heading("APPLETS")
9        .subcommand(Command::new("hostname").about("show hostname part of FQDN"))
10        .subcommand(Command::new("dnsdomainname").about("show domain name part of FQDN"));
11
12    match cmd.get_matches().subcommand_name() {
13        Some("hostname") => println!("www"),
14        Some("dnsdomainname") => println!("example.com"),
15        _ => unreachable!("parser should ensure only valid subcommand names are used"),
16    }
17}
examples/derive_ref/augment_args.rs (line 14)
9fn main() {
10    let cli = Command::new("CLI").arg(arg!(-b - -built).action(clap::ArgAction::SetTrue));
11    // Augment built args with derived args
12    let cli = DerivedArgs::augment_args(cli);
13
14    let matches = cli.get_matches();
15    println!("Value of built: {:?}", matches.get_flag("built"));
16    println!(
17        "Value of derived via ArgMatches: {:?}",
18        matches.get_flag("derived")
19    );
20
21    // Since DerivedArgs implements FromArgMatches, we can extract it from the unstructured ArgMatches.
22    // This is the main benefit of using derived arguments.
23    let derived_matches = DerivedArgs::from_arg_matches(&matches)
24        .map_err(|err| err.exit())
25        .unwrap();
26    println!("Value of derived: {derived_matches:#?}");
27}
examples/multicall-busybox.rs (line 34)
13fn main() {
14    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
15        .multicall(true)
16        .subcommand(
17            Command::new("busybox")
18                .arg_required_else_help(true)
19                .subcommand_value_name("APPLET")
20                .subcommand_help_heading("APPLETS")
21                .arg(
22                    Arg::new("install")
23                        .long("install")
24                        .help("Install hardlinks for all subcommands in path")
25                        .exclusive(true)
26                        .action(ArgAction::Set)
27                        .default_missing_value("/usr/local/bin")
28                        .value_parser(value_parser!(PathBuf)),
29                )
30                .subcommands(applet_commands()),
31        )
32        .subcommands(applet_commands());
33
34    let matches = cmd.get_matches();
35    let mut subcommand = matches.subcommand();
36    if let Some(("busybox", cmd)) = subcommand {
37        if cmd.contains_id("install") {
38            unimplemented!("Make hardlinks to the executable here");
39        }
40        subcommand = cmd.subcommand();
41    }
42    match subcommand {
43        Some(("false", _)) => exit(1),
44        Some(("true", _)) => exit(0),
45        _ => unreachable!("parser should ensure only valid subcommand names are used"),
46    }
47}
examples/git.rs (line 61)
60fn main() {
61    let matches = cli().get_matches();
62
63    match matches.subcommand() {
64        Some(("clone", sub_matches)) => {
65            println!(
66                "Cloning {}",
67                sub_matches.get_one::<String>("REMOTE").expect("required")
68            );
69        }
70        Some(("diff", sub_matches)) => {
71            let color = sub_matches
72                .get_one::<String>("color")
73                .map(|s| s.as_str())
74                .expect("defaulted in clap");
75
76            let mut base = sub_matches.get_one::<String>("base").map(|s| s.as_str());
77            let mut head = sub_matches.get_one::<String>("head").map(|s| s.as_str());
78            let mut path = sub_matches.get_one::<String>("path").map(|s| s.as_str());
79            if path.is_none() {
80                path = head;
81                head = None;
82                if path.is_none() {
83                    path = base;
84                    base = None;
85                }
86            }
87            let base = base.unwrap_or("stage");
88            let head = head.unwrap_or("worktree");
89            let path = path.unwrap_or("");
90            println!("Diffing {base}..{head} {path} (color={color})");
91        }
92        Some(("push", sub_matches)) => {
93            println!(
94                "Pushing to {}",
95                sub_matches.get_one::<String>("REMOTE").expect("required")
96            );
97        }
98        Some(("add", sub_matches)) => {
99            let paths = sub_matches
100                .get_many::<PathBuf>("PATH")
101                .into_iter()
102                .flatten()
103                .collect::<Vec<_>>();
104            println!("Adding {paths:?}");
105        }
106        Some(("stash", sub_matches)) => {
107            let stash_command = sub_matches.subcommand().unwrap_or(("push", sub_matches));
108            match stash_command {
109                ("apply", sub_matches) => {
110                    let stash = sub_matches.get_one::<String>("STASH");
111                    println!("Applying {stash:?}");
112                }
113                ("pop", sub_matches) => {
114                    let stash = sub_matches.get_one::<String>("STASH");
115                    println!("Popping {stash:?}");
116                }
117                ("push", sub_matches) => {
118                    let message = sub_matches.get_one::<String>("message");
119                    println!("Pushing {message:?}");
120                }
121                (name, _) => {
122                    unreachable!("Unsupported subcommand `{name}`")
123                }
124            }
125        }
126        Some((ext, sub_matches)) => {
127            let args = sub_matches
128                .get_many::<OsString>("")
129                .into_iter()
130                .flatten()
131                .collect::<Vec<_>>();
132            println!("Calling out to {ext:?} with {args:?}");
133        }
134        _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable!()
135    }
136
137    // Continued program logic goes here...
138}
Source

pub fn get_matches_mut(&mut self) -> ArgMatches

Parse env::args_os, exiting on failure.

Like Command::get_matches but doesn’t consume the Command.

§Panics

If contradictory arguments or settings exist (debug builds).

§Examples
let mut cmd = Command::new("myprog")
    // Args and options go here...
    ;
let matches = cmd.get_matches_mut();
Source

pub fn try_get_matches(self) -> Result<ArgMatches, Error>

Parse env::args_os, returning a clap::Result on failure.

NOTE: This method WILL NOT exit when --help or --version (or short versions) are used. It will return a clap::Error, where the kind is a ErrorKind::DisplayHelp or ErrorKind::DisplayVersion respectively. You must call Error::exit or perform a std::process::exit.

§Panics

If contradictory arguments or settings exist (debug builds).

§Examples
let matches = Command::new("myprog")
    // Args and options go here...
    .try_get_matches()
    .unwrap_or_else(|e| e.exit());
Source

pub fn get_matches_from<I, T>(self, itr: I) -> ArgMatches
where I: IntoIterator<Item = T>, T: Into<OsString> + Clone,

Parse the specified arguments, exiting on failure.

NOTE: The first argument will be parsed as the binary name unless Command::no_binary_name is used.

§Panics

If contradictory arguments or settings exist (debug builds).

§Examples
let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];

let matches = Command::new("myprog")
    // Args and options go here...
    .get_matches_from(arg_vec);
Source

pub fn try_get_matches_from<I, T>(self, itr: I) -> Result<ArgMatches, Error>
where I: IntoIterator<Item = T>, T: Into<OsString> + Clone,

Parse the specified arguments, returning a clap::Result on failure.

NOTE: This method WILL NOT exit when --help or --version (or short versions) are used. It will return a clap::Error, where the kind is a ErrorKind::DisplayHelp or ErrorKind::DisplayVersion respectively. You must call Error::exit or perform a std::process::exit yourself.

NOTE: The first argument will be parsed as the binary name unless Command::no_binary_name is used.

§Panics

If contradictory arguments or settings exist (debug builds).

§Examples
let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];

let matches = Command::new("myprog")
    // Args and options go here...
    .try_get_matches_from(arg_vec)
    .unwrap_or_else(|e| e.exit());
Examples found in repository?
examples/repl.rs (line 32)
29fn respond(line: &str) -> Result<bool, String> {
30    let args = shlex::split(line).ok_or("error: Invalid quoting")?;
31    let matches = cli()
32        .try_get_matches_from(args)
33        .map_err(|e| e.to_string())?;
34    match matches.subcommand() {
35        Some(("ping", _matches)) => {
36            write!(std::io::stdout(), "Pong").map_err(|e| e.to_string())?;
37            std::io::stdout().flush().map_err(|e| e.to_string())?;
38        }
39        Some(("quit", _matches)) => {
40            write!(std::io::stdout(), "Exiting ...").map_err(|e| e.to_string())?;
41            std::io::stdout().flush().map_err(|e| e.to_string())?;
42            return Ok(true);
43        }
44        Some((name, _matches)) => unimplemented!("{name}"),
45        None => unreachable!("subcommand required"),
46    }
47
48    Ok(false)
49}
Source

pub fn try_get_matches_from_mut<I, T>( &mut self, itr: I, ) -> Result<ArgMatches, Error>
where I: IntoIterator<Item = T>, T: Into<OsString> + Clone,

Parse the specified arguments, returning a clap::Result on failure.

Like Command::try_get_matches_from but doesn’t consume the Command.

NOTE: This method WILL NOT exit when --help or --version (or short versions) are used. It will return a clap::Error, where the kind is a ErrorKind::DisplayHelp or ErrorKind::DisplayVersion respectively. You must call Error::exit or perform a std::process::exit yourself.

NOTE: The first argument will be parsed as the binary name unless Command::no_binary_name is used.

§Panics

If contradictory arguments or settings exist (debug builds).

§Examples
let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];

let mut cmd = Command::new("myprog");
    // Args and options go here...
let matches = cmd.try_get_matches_from_mut(arg_vec)
    .unwrap_or_else(|e| e.exit());
Source

pub fn print_help(&mut self) -> Result<(), Error>

Prints the short help message (-h) to io::stdout().

See also Command::print_long_help.

Note: this will ensure the Command has been sufficiently built.

§Panics

If contradictory arguments or settings exist (debug builds).

§Examples
let mut cmd = Command::new("myprog");
cmd.print_help();
Source

pub fn print_long_help(&mut self) -> Result<(), Error>

Prints the long help message (--help) to io::stdout().

See also Command::print_help.

Note: this will ensure the Command has been sufficiently built.

§Panics

If contradictory arguments or settings exist (debug builds).

§Examples
let mut cmd = Command::new("myprog");
cmd.print_long_help();
Source

pub fn render_help(&mut self) -> StyledStr

Render the short help message (-h) to a StyledStr

See also Command::render_long_help.

Note: this will ensure the Command has been sufficiently built.

§Panics

If contradictory arguments or settings exist (debug builds).

§Examples
use std::io;
let mut cmd = Command::new("myprog");
let mut out = io::stdout();
let help = cmd.render_help();
println!("{help}");
Source

pub fn render_long_help(&mut self) -> StyledStr

Render the long help message (--help) to a StyledStr.

See also Command::render_help.

Note: this will ensure the Command has been sufficiently built.

§Panics

If contradictory arguments or settings exist (debug builds).

§Examples
use std::io;
let mut cmd = Command::new("myprog");
let mut out = io::stdout();
let help = cmd.render_long_help();
println!("{help}");
Source

pub fn render_version(&self) -> String

Version message rendered as if the user ran -V.

See also Command::render_long_version.

§Coloring

This function does not try to color the message nor it inserts any ANSI escape codes.

§Examples
use std::io;
let cmd = Command::new("myprog");
println!("{}", cmd.render_version());
Source

pub fn render_long_version(&self) -> String

Version message rendered as if the user ran --version.

See also Command::render_version.

§Coloring

This function does not try to color the message nor it inserts any ANSI escape codes.

§Examples
use std::io;
let cmd = Command::new("myprog");
println!("{}", cmd.render_long_version());
Source

pub fn render_usage(&mut self) -> StyledStr

Usage statement

Note: this will ensure the Command has been sufficiently built.

§Panics

If contradictory arguments or settings exist (debug builds).

§Examples
use std::io;
let mut cmd = Command::new("myprog");
println!("{}", cmd.render_usage());
Source

pub fn add<T>(self, tagged: T) -> Command
where T: CommandExt + Extension,

Available on crate feature unstable-ext only.

Extend Command with CommandExt data

Source§

impl Command

§Application-wide Settings

These settings will apply to the top-level command and all subcommands, by default. Some settings can be overridden in subcommands.

Source

pub fn no_binary_name(self, yes: bool) -> Command

Specifies that the parser should not assume the first argument passed is the binary name.

This is normally the case when using a “daemon” style mode. For shells / REPLs, see Command::multicall.

§Examples
let m = Command::new("myprog")
    .no_binary_name(true)
    .arg(arg!(<cmd> ... "commands to run"))
    .get_matches_from(vec!["command", "set"]);

let cmds: Vec<_> = m.get_many::<String>("cmd").unwrap().collect();
assert_eq!(cmds, ["command", "set"]);
Source

pub fn ignore_errors(self, yes: bool) -> Command

Try not to fail on parse errors, like missing option values.

NOTE: This choice is propagated to all child subcommands.

§Examples
let cmd = Command::new("cmd")
  .ignore_errors(true)
  .arg(arg!(-c --config <FILE> "Sets a custom config file"))
  .arg(arg!(-x --stuff <FILE> "Sets a custom stuff file"))
  .arg(arg!(f: -f "Flag"));

let r = cmd.try_get_matches_from(vec!["cmd", "-c", "file", "-f", "-x"]);

assert!(r.is_ok(), "unexpected error: {r:?}");
let m = r.unwrap();
assert_eq!(m.get_one::<String>("config").unwrap(), "file");
assert!(m.get_flag("f"));
assert_eq!(m.get_one::<String>("stuff"), None);
Source

pub fn args_override_self(self, yes: bool) -> Command

Replace prior occurrences of arguments rather than error

For any argument that would conflict with itself by default (e.g. ArgAction::Set, it will now override itself.

This is the equivalent to saying the foo arg using Arg::overrides_with("foo") for all defined arguments.

NOTE: This choice is propagated to all child subcommands.

Source

pub fn dont_delimit_trailing_values(self, yes: bool) -> Command

Disables the automatic delimiting of values after -- or when Arg::trailing_var_arg was used.

NOTE: The same thing can be done manually by setting the final positional argument to Arg::value_delimiter(None). Using this setting is safer, because it’s easier to locate when making changes.

NOTE: This choice is propagated to all child subcommands.

§Examples
Command::new("myprog")
    .dont_delimit_trailing_values(true)
    .get_matches();
Source

pub fn color(self, color: ColorChoice) -> Command

Available on crate feature color only.

Sets when to color output.

To customize how the output is styled, see Command::styles.

NOTE: This choice is propagated to all child subcommands.

NOTE: Default behaviour is ColorChoice::Auto.

§Examples
Command::new("myprog")
    .color(ColorChoice::Never)
    .get_matches();
Source

pub fn styles(self, styles: Styles) -> Command

Available on crate feature color only.

Sets the Styles for terminal output

NOTE: This choice is propagated to all child subcommands.

NOTE: Default behaviour is Styles::default.

§Examples
const STYLES: styling::Styles = styling::Styles::styled()
    .header(styling::AnsiColor::Green.on_default().bold())
    .usage(styling::AnsiColor::Green.on_default().bold())
    .literal(styling::AnsiColor::Blue.on_default().bold())
    .placeholder(styling::AnsiColor::Cyan.on_default());
Command::new("myprog")
    .styles(STYLES)
    .get_matches();
Source

pub fn term_width(self, width: usize) -> Command

Available on non-crate feature unstable-v5 or crate feature wrap_help only.

Sets the terminal width at which to wrap help messages.

Using 0 will ignore terminal widths and use source formatting.

Defaults to current terminal width when wrap_help feature flag is enabled. If current width cannot be determined, the default is 100.

unstable-v5 feature: Defaults to unbound, being subject to Command::max_term_width.

NOTE: This setting applies globally and not on a per-command basis.

NOTE: This requires the wrap_help feature

§Examples
Command::new("myprog")
    .term_width(80)
Source

pub fn max_term_width(self, width: usize) -> Command

Available on non-crate feature unstable-v5 or crate feature wrap_help only.

Limit the line length for wrapping help when using the current terminal’s width.

This only applies when term_width is unset so that the current terminal’s width will be used. See Command::term_width for more details.

Using 0 will ignore this, always respecting Command::term_width (default).

unstable-v5 feature: Defaults to 100.

NOTE: This setting applies globally and not on a per-command basis.

NOTE: This requires the wrap_help feature

§Examples
Command::new("myprog")
    .max_term_width(100)
Source

pub fn disable_version_flag(self, yes: bool) -> Command

Disables -V and --version flag.

§Examples
let res = Command::new("myprog")
    .version("1.0.0")
    .disable_version_flag(true)
    .try_get_matches_from(vec![
        "myprog", "--version"
    ]);
assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);

You can create a custom version flag with ArgAction::Version

let mut cmd = Command::new("myprog")
    .version("1.0.0")
    // Remove the `-V` short flag
    .disable_version_flag(true)
    .arg(
        Arg::new("version")
            .long("version")
            .action(ArgAction::Version)
            .help("Print version")
    );

let res = cmd.try_get_matches_from_mut(vec![
        "myprog", "-V"
    ]);
assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);

let res = cmd.try_get_matches_from_mut(vec![
        "myprog", "--version"
    ]);
assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::DisplayVersion);
Source

pub fn propagate_version(self, yes: bool) -> Command

Specifies to use the version of the current command for all subcommands.

Defaults to false; subcommands have independent version strings from their parents.

NOTE: This choice is propagated to all child subcommands.

§Examples
Command::new("myprog")
    .version("v1.1")
    .propagate_version(true)
    .subcommand(Command::new("test"))
    .get_matches();
// running `$ myprog test --version` will display
// "myprog-test v1.1"
Source

pub fn next_line_help(self, yes: bool) -> Command

Places the help string for all arguments and subcommands on the line after them.

NOTE: This choice is propagated to all child subcommands.

§Examples
Command::new("myprog")
    .next_line_help(true)
    .get_matches();
Source

pub fn disable_help_flag(self, yes: bool) -> Command

Disables -h and --help flag.

NOTE: This choice is propagated to all child subcommands.

§Examples
let res = Command::new("myprog")
    .disable_help_flag(true)
    .try_get_matches_from(vec![
        "myprog", "-h"
    ]);
assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);

You can create a custom help flag with ArgAction::Help, ArgAction::HelpShort, or ArgAction::HelpLong

let mut cmd = Command::new("myprog")
    // Change help short flag to `?`
    .disable_help_flag(true)
    .arg(
        Arg::new("help")
            .short('?')
            .long("help")
            .action(ArgAction::Help)
            .help("Print help")
    );

let res = cmd.try_get_matches_from_mut(vec![
        "myprog", "-h"
    ]);
assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);

let res = cmd.try_get_matches_from_mut(vec![
        "myprog", "-?"
    ]);
assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::DisplayHelp);
Source

pub fn disable_help_subcommand(self, yes: bool) -> Command

Disables the help subcommand.

NOTE: This choice is propagated to all child subcommands.

§Examples
let res = Command::new("myprog")
    .disable_help_subcommand(true)
    // Normally, creating a subcommand causes a `help` subcommand to automatically
    // be generated as well
    .subcommand(Command::new("test"))
    .try_get_matches_from(vec![
        "myprog", "help"
    ]);
assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::InvalidSubcommand);
Source

pub fn disable_colored_help(self, yes: bool) -> Command

Disables colorized help messages.

NOTE: This choice is propagated to all child subcommands.

§Examples
Command::new("myprog")
    .disable_colored_help(true)
    .get_matches();
Source

pub fn help_expected(self, yes: bool) -> Command

Panic if help descriptions are omitted.

NOTE: When deriving Parser, you could instead check this at compile-time with #![deny(missing_docs)]

NOTE: This choice is propagated to all child subcommands.

§Examples
Command::new("myprog")
    .help_expected(true)
    .arg(
        Arg::new("foo").help("It does foo stuff")
        // As required via `help_expected`, a help message was supplied
     )
§Panics

On debug builds:

Command::new("myapp")
    .help_expected(true)
    .arg(
        Arg::new("foo")
        // Someone forgot to put .about("...") here
        // Since the setting `help_expected` is activated, this will lead to
        // a panic (if you are in debug mode)
    )
Source

pub fn hide_possible_values(self, yes: bool) -> Command

Tells clap not to print possible values when displaying help information.

This can be useful if there are many values, or they are explained elsewhere.

To set this per argument, see Arg::hide_possible_values.

NOTE: This choice is propagated to all child subcommands.

Source

pub fn infer_long_args(self, yes: bool) -> Command

Allow partial matches of long arguments or their aliases.

For example, to match an argument named --test, one could use --t, --te, --tes, and --test.

NOTE: The match must not be ambiguous at all in order to succeed. i.e. to match --te to --test there could not also be another argument or alias --temp because both start with --te

NOTE: This choice is propagated to all child subcommands.

Source

pub fn infer_subcommands(self, yes: bool) -> Command

Allow partial matches of subcommand names and their aliases.

For example, to match a subcommand named test, one could use t, te, tes, and test.

NOTE: The match must not be ambiguous at all in order to succeed. i.e. to match te to test there could not also be a subcommand or alias temp because both start with te

WARNING: This setting can interfere with positional/free arguments, take care when designing CLIs which allow inferred subcommands and have potential positional/free arguments whose values could start with the same characters as subcommands. If this is the case, it’s recommended to use settings such as Command::args_conflicts_with_subcommands in conjunction with this setting.

NOTE: This choice is propagated to all child subcommands.

§Examples
let m = Command::new("prog")
    .infer_subcommands(true)
    .subcommand(Command::new("test"))
    .get_matches_from(vec![
        "prog", "te"
    ]);
assert_eq!(m.subcommand_name(), Some("test"));
Source§

impl Command

§Command-specific Settings

These apply only to the current command and are not inherited by subcommands.

Source

pub fn name(self, name: impl Into<Str>) -> Command

(Re)Sets the program’s name.

See Command::new for more details.

§Examples
let cmd = clap::command!()
    .name("foo");

// continued logic goes here, such as `cmd.get_matches()` etc.
Source

pub fn bin_name(self, name: impl IntoResettable<String>) -> Command

Overrides the runtime-determined name of the binary for help and error messages.

This should only be used when absolutely necessary, such as when the binary name for your application is misleading, or perhaps not how the user should invoke your program.

TIP: When building things such as third party cargo subcommands, this setting should be used!

NOTE: This does not change or set the name of the binary file on disk. It only changes what clap thinks the name is for the purposes of error or help messages.

§Examples
Command::new("My Program")
     .bin_name("my_binary")
Source

pub fn display_name(self, name: impl IntoResettable<String>) -> Command

Overrides the runtime-determined display name of the program for help and error messages.

§Examples
Command::new("My Program")
     .display_name("my_program")
Source

pub fn author(self, author: impl IntoResettable<Str>) -> Command

Sets the author(s) for the help message.

TIP: Use claps convenience macro crate_authors! to automatically set your application’s author(s) to the same thing as your crate at compile time.

NOTE: A custom help_template is needed for author to show up.

§Examples
Command::new("myprog")
     .author("Me, [email protected]")
Source

pub fn about(self, about: impl IntoResettable<StyledStr>) -> Command

Sets the program’s description for the short help (-h).

If Command::long_about is not specified, this message will be displayed for --help.

See also crate_description!.

§Examples
Command::new("myprog")
    .about("Does really amazing things for great people")
Examples found in repository?
examples/multicall-busybox.rs (line 8)
6fn applet_commands() -> [Command; 2] {
7    [
8        Command::new("true").about("does nothing successfully"),
9        Command::new("false").about("does nothing unsuccessfully"),
10    ]
11}
More examples
Hide additional examples
examples/tutorial_builder/02_apps.rs (line 6)
3fn main() {
4    let matches = Command::new("MyApp")
5        .version("1.0")
6        .about("Does awesome things")
7        .arg(arg!(--two <VALUE>).required(true))
8        .arg(arg!(--one <VALUE>).required(true))
9        .get_matches();
10
11    println!(
12        "two: {:?}",
13        matches.get_one::<String>("two").expect("required")
14    );
15    println!(
16        "one: {:?}",
17        matches.get_one::<String>("one").expect("required")
18    );
19}
examples/multicall-hostname.rs (line 9)
3fn main() {
4    let cmd = Command::new(env!("CARGO_CRATE_NAME"))
5        .multicall(true)
6        .arg_required_else_help(true)
7        .subcommand_value_name("APPLET")
8        .subcommand_help_heading("APPLETS")
9        .subcommand(Command::new("hostname").about("show hostname part of FQDN"))
10        .subcommand(Command::new("dnsdomainname").about("show domain name part of FQDN"));
11
12    match cmd.get_matches().subcommand_name() {
13        Some("hostname") => println!("www"),
14        Some("dnsdomainname") => println!("example.com"),
15        _ => unreachable!("parser should ensure only valid subcommand names are used"),
16    }
17}
examples/repl.rs (line 73)
51fn cli() -> Command {
52    // strip out usage
53    const PARSER_TEMPLATE: &str = "\
54        {all-args}
55    ";
56    // strip out name/version
57    const APPLET_TEMPLATE: &str = "\
58        {about-with-newline}\n\
59        {usage-heading}\n    {usage}\n\
60        \n\
61        {all-args}{after-help}\
62    ";
63
64    Command::new("repl")
65        .multicall(true)
66        .arg_required_else_help(true)
67        .subcommand_required(true)
68        .subcommand_value_name("APPLET")
69        .subcommand_help_heading("APPLETS")
70        .help_template(PARSER_TEMPLATE)
71        .subcommand(
72            Command::new("ping")
73                .about("Get a response")
74                .help_template(APPLET_TEMPLATE),
75        )
76        .subcommand(
77            Command::new("quit")
78                .alias("exit")
79                .about("Quit the REPL")
80                .help_template(APPLET_TEMPLATE),
81        )
82}
examples/git.rs (line 8)
6fn cli() -> Command {
7    Command::new("git")
8        .about("A fictional versioning CLI")
9        .subcommand_required(true)
10        .arg_required_else_help(true)
11        .allow_external_subcommands(true)
12        .subcommand(
13            Command::new("clone")
14                .about("Clones repos")
15                .arg(arg!(<REMOTE> "The remote to clone"))
16                .arg_required_else_help(true),
17        )
18        .subcommand(
19            Command::new("diff")
20                .about("Compare two commits")
21                .arg(arg!(base: [COMMIT]))
22                .arg(arg!(head: [COMMIT]))
23                .arg(arg!(path: [PATH]).last(true))
24                .arg(
25                    arg!(--color <WHEN>)
26                        .value_parser(["always", "auto", "never"])
27                        .num_args(0..=1)
28                        .require_equals(true)
29                        .default_value("auto")
30                        .default_missing_value("always"),
31                ),
32        )
33        .subcommand(
34            Command::new("push")
35                .about("pushes things")
36                .arg(arg!(<REMOTE> "The remote to target"))
37                .arg_required_else_help(true),
38        )
39        .subcommand(
40            Command::new("add")
41                .about("adds things")
42                .arg_required_else_help(true)
43                .arg(arg!(<PATH> ... "Stuff to add").value_parser(clap::value_parser!(PathBuf))),
44        )
45        .subcommand(
46            Command::new("stash")
47                .args_conflicts_with_subcommands(true)
48                .flatten_help(true)
49                .args(push_args())
50                .subcommand(Command::new("push").args(push_args()))
51                .subcommand(Command::new("pop").arg(arg!([STASH])))
52                .subcommand(Command::new("apply").arg(arg!([STASH]))),
53        )
54}
examples/pacman.rs (line 5)
3fn main() {
4    let matches = Command::new("pacman")
5        .about("package manager utility")
6        .version("5.2.1")
7        .subcommand_required(true)
8        .arg_required_else_help(true)
9        // Query subcommand
10        //
11        // Only a few of its arguments are implemented below.
12        .subcommand(
13            Command::new("query")
14                .short_flag('Q')
15                .long_flag("query")
16                .about("Query the package database.")
17                .arg(
18                    Arg::new("search")
19                        .short('s')
20                        .long("search")
21                        .help("search locally installed packages for matching strings")
22                        .conflicts_with("info")
23                        .action(ArgAction::Set)
24                        .num_args(1..),
25                )
26                .arg(
27                    Arg::new("info")
28                        .long("info")
29                        .short('i')
30                        .conflicts_with("search")
31                        .help("view package information")
32                        .action(ArgAction::Set)
33                        .num_args(1..),
34                ),
35        )
36        // Sync subcommand
37        //
38        // Only a few of its arguments are implemented below.
39        .subcommand(
40            Command::new("sync")
41                .short_flag('S')
42                .long_flag("sync")
43                .about("Synchronize packages.")
44                .arg(
45                    Arg::new("search")
46                        .short('s')
47                        .long("search")
48                        .conflicts_with("info")
49                        .action(ArgAction::Set)
50                        .num_args(1..)
51                        .help("search remote repositories for matching strings"),
52                )
53                .arg(
54                    Arg::new("info")
55                        .long("info")
56                        .conflicts_with("search")
57                        .short('i')
58                        .action(ArgAction::SetTrue)
59                        .help("view package information"),
60                )
61                .arg(
62                    Arg::new("package")
63                        .help("packages")
64                        .required_unless_present("search")
65                        .action(ArgAction::Set)
66                        .num_args(1..),
67                ),
68        )
69        .get_matches();
70
71    match matches.subcommand() {
72        Some(("sync", sync_matches)) => {
73            if sync_matches.contains_id("search") {
74                let packages: Vec<_> = sync_matches
75                    .get_many::<String>("search")
76                    .expect("contains_id")
77                    .map(|s| s.as_str())
78                    .collect();
79                let values = packages.join(", ");
80                println!("Searching for {values}...");
81                return;
82            }
83
84            let packages: Vec<_> = sync_matches
85                .get_many::<String>("package")
86                .expect("is present")
87                .map(|s| s.as_str())
88                .collect();
89            let values = packages.join(", ");
90
91            if sync_matches.get_flag("info") {
92                println!("Retrieving info for {values}...");
93            } else {
94                println!("Installing {values}...");
95            }
96        }
97        Some(("query", query_matches)) => {
98            if let Some(packages) = query_matches.get_many::<String>("info") {
99                let comma_sep = packages.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
100                println!("Retrieving info for {comma_sep}...");
101            } else if let Some(queries) = query_matches.get_many::<String>("search") {
102                let comma_sep = queries.map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
103                println!("Searching Locally for {comma_sep}...");
104            } else {
105                println!("Displaying all locally installed packages...");
106            }
107        }
108        _ => unreachable!(), // If all subcommands are defined above, anything else is unreachable
109    }
110}
Source

pub fn long_about(self, long_about: impl IntoResettable<StyledStr>) -> Command

Sets the program’s description for the long help (--help).

If not set, Command::about will be used for long help in addition to short help (-h).

NOTE: Only Command::about (short format) is used in completion script generation in order to be concise.

§Examples
Command::new("myprog")
    .long_about(
"Does really amazing things to great people. Now let's talk a little
 more in depth about how this subcommand really works. It may take about
 a few lines of text, but that's ok!")
Source

pub fn after_help(self, help: impl IntoResettable<StyledStr>) ->