Arg

Struct Arg 

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

The abstract representation of a command line argument. Used to set all the options and relationships that define a valid argument for the program.

There are two methods for constructing Args, using the builder pattern and setting options manually, or using a usage string which is far less verbose but has fewer options. You can also use a combination of the two methods to achieve the best of both worlds.

§Examples

// Using the traditional builder pattern and setting each option manually
let cfg = Arg::new("config")
      .short('c')
      .long("config")
      .action(ArgAction::Set)
      .value_name("FILE")
      .help("Provides a config file to myprog");
// Using a usage string (setting a similar argument to the one above)
let input = arg!(-i --input <FILE> "Provides an input file to the program");

Implementations§

Source§

impl Arg

§Basic API

Source

pub fn new(id: impl Into<Id>) -> Arg

Create a new Arg with a unique name.

The name is used to check whether or not the argument was used at runtime, get values, set relationships with other args, etc..

By default, an Arg is

NOTE: In the case of arguments that take values (i.e. Arg::action(ArgAction::Set)) and positional arguments (i.e. those without a preceding - or --) the name will also be displayed when the user prints the usage/help information of the program.

§Examples
Arg::new("config")
Examples found in repository?
examples/derive_ref/flatten_hand_args.rs (line 40)
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    }
More examples
Hide additional examples
examples/multicall-busybox.rs (line 22)
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/pacman.rs (line 18)
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 id(self, id: impl Into<Id>) -> Arg

Set the identifier used for referencing this argument in the clap API.

See Arg::new for more details.

Source

pub fn short(self, s: impl IntoResettable<char>) -> Arg

Sets the short version of the argument without the preceding -.

By default V and h are used by the auto-generated version and help arguments, respectively. You will need to disable the auto-generated flags (disable_help_flag, disable_version_flag) and define your own.

§Examples

When calling short, use a single valid UTF-8 character which will allow using the argument via a single hyphen (-) such as -c:

let m = Command::new("prog")
    .arg(Arg::new("config")
        .short('c')
        .action(ArgAction::Set))
    .get_matches_from(vec![
        "prog", "-c", "file.toml"
    ]);

assert_eq!(m.get_one::<String>("config").map(String::as_str), Some("file.toml"));

To use -h for your own flag and still have help:

let m = Command::new("prog")
    .disable_help_flag(true)
    .arg(Arg::new("host")
        .short('h')
        .long("host"))
    .arg(Arg::new("help")
        .long("help")
        .global(true)
        .action(ArgAction::Help))
    .get_matches_from(vec![
        "prog", "-h", "wikipedia.org"
    ]);

assert_eq!(m.get_one::<String>("host").map(String::as_str), Some("wikipedia.org"));
Examples found in repository?
examples/derive_ref/flatten_hand_args.rs (line 41)
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    }
More examples
Hide additional examples
examples/pacman.rs (line 19)
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(self, l: impl IntoResettable<Str>) -> Arg

Sets the long version of the argument without the preceding --.

By default version and help are used by the auto-generated version and help arguments, respectively. You may use the word version or help for the long form of your own arguments, in which case clap simply will not assign those to the auto-generated version or help arguments.

NOTE: Any leading - characters will be stripped

§Examples

To set long use a word containing valid UTF-8. If you supply a double leading -- such as --config they will be stripped. Hyphens in the middle of the word, however, will not be stripped (i.e. config-file is allowed).

Setting long allows using the argument via a double hyphen (--) such as --config

let m = Command::new("prog")
    .arg(Arg::new("cfg")
        .long("config")
        .action(ArgAction::Set))
    .get_matches_from(vec![
        "prog", "--config", "file.toml"
    ]);

assert_eq!(m.get_one::<String>("cfg").map(String::as_str), Some("file.toml"));
Examples found in repository?
examples/derive_ref/flatten_hand_args.rs (line 42)
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    }
More examples
Hide additional examples
examples/multicall-busybox.rs (line 23)
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/pacman.rs (line 20)
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 alias(self, name: impl IntoResettable<Str>) -> Arg

Add an alias, which functions as a hidden long flag.

This is more efficient, and easier than creating multiple hidden arguments as one only needs to check for the existence of this command, and not all variants.

§Examples
let m = Command::new("prog")
            .arg(Arg::new("test")
            .long("test")
            .alias("alias")
            .action(ArgAction::Set))
       .get_matches_from(vec![
            "prog", "--alias", "cool"
        ]);
assert_eq!(m.get_one::<String>("test").unwrap(), "cool");
Source

pub fn short_alias(self, name: impl IntoResettable<char>) -> Arg

Add an alias, which functions as a hidden short flag.

This is more efficient, and easier than creating multiple hidden arguments as one only needs to check for the existence of this command, and not all variants.

§Examples
let m = Command::new("prog")
            .arg(Arg::new("test")
            .short('t')
            .short_alias('e')
            .action(ArgAction::Set))
       .get_matches_from(vec![
            "prog", "-e", "cool"
        ]);
assert_eq!(m.get_one::<String>("test").unwrap(), "cool");
Source

pub fn aliases(self, names: impl IntoIterator<Item = impl Into<Str>>) -> Arg

Add aliases, which function as hidden long flags.

This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.

§Examples
let m = Command::new("prog")
            .arg(Arg::new("test")
                    .long("test")
                    .aliases(["do-stuff", "do-tests", "tests"])
                    .action(ArgAction::SetTrue)
                    .help("the file to add")
                    .required(false))
            .get_matches_from(vec![
                "prog", "--do-tests"
            ]);
assert_eq!(m.get_flag("test"), true);
Source

pub fn short_aliases(self, names: impl IntoIterator<Item = char>) -> Arg

Add aliases, which functions as a hidden short flag.

This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.

§Examples
let m = Command::new("prog")
            .arg(Arg::new("test")
                    .short('t')
                    .short_aliases(['e', 's'])
                    .action(ArgAction::SetTrue)
                    .help("the file to add")
                    .required(false))
            .get_matches_from(vec![
                "prog", "-s"
            ]);
assert_eq!(m.get_flag("test"), true);
Source

pub fn visible_alias(self, name: impl IntoResettable<Str>) -> Arg

Add an alias, which functions as a visible long flag.

Like Arg::alias, except that they are visible inside the help message.

§Examples
let m = Command::new("prog")
            .arg(Arg::new("test")
                .visible_alias("something-awesome")
                .long("test")
                .action(ArgAction::Set))
       .get_matches_from(vec![
            "prog", "--something-awesome", "coffee"
        ]);
assert_eq!(m.get_one::<String>("test").unwrap(), "coffee");
Source

pub fn visible_short_alias(self, name: impl IntoResettable<char>) -> Arg

Add an alias, which functions as a visible short flag.

Like Arg::short_alias, except that they are visible inside the help message.

§Examples
let m = Command::new("prog")
            .arg(Arg::new("test")
                .long("test")
                .visible_short_alias('t')
                .action(ArgAction::Set))
       .get_matches_from(vec![
            "prog", "-t", "coffee"
        ]);
assert_eq!(m.get_one::<String>("test").unwrap(), "coffee");
Source

pub fn visible_aliases( self, names: impl IntoIterator<Item = impl Into<Str>>, ) -> Arg

Add aliases, which function as visible long flags.

Like Arg::aliases, except that they are visible inside the help message.

§Examples
let m = Command::new("prog")
            .arg(Arg::new("test")
                .long("test")
                .action(ArgAction::SetTrue)
                .visible_aliases(["something", "awesome", "cool"]))
       .get_matches_from(vec![
            "prog", "--awesome"
        ]);
assert_eq!(m.get_flag("test"), true);
Source

pub fn visible_short_aliases(self, names: impl IntoIterator<Item = char>) -> Arg

Add aliases, which function as visible short flags.

Like Arg::short_aliases, except that they are visible inside the help message.

§Examples
let m = Command::new("prog")
            .arg(Arg::new("test")
                .long("test")
                .action(ArgAction::SetTrue)
                .visible_short_aliases(['t', 'e']))
       .get_matches_from(vec![
            "prog", "-t"
        ]);
assert_eq!(m.get_flag("test"), true);
Source

pub fn index(self, idx: impl IntoResettable<usize>) -> Arg

Specifies the index of a positional argument starting at 1.

NOTE: The index refers to position according to other positional argument. It does not define position in the argument list as a whole.

NOTE: You can optionally leave off the index method, and the index will be assigned in order of evaluation. Utilizing the index method allows for setting indexes out of order

NOTE: This is only meant to be used for positional arguments and shouldn’t to be used with Arg::short or Arg::long.

NOTE: When utilized with Arg::num_args(1..), only the last positional argument may be defined as having a variable number of arguments (i.e. with the highest index)

§Panics

Command will panic! if indexes are skipped (such as defining index(1) and index(3) but not index(2), or a positional argument is defined as multiple and is not the highest index (debug builds)

§Examples
Arg::new("config")
    .index(1)
let m = Command::new("prog")
    .arg(Arg::new("mode")
        .index(1))
    .arg(Arg::new("debug")
        .long("debug")
        .action(ArgAction::SetTrue))
    .get_matches_from(vec![
        "prog", "--debug", "fast"
    ]);

assert!(m.contains_id("mode"));
assert_eq!(m.get_one::<String>("mode").unwrap(), "fast"); // notice index(1) means "first positional"
                                                          // *not* first argument
Source

pub fn trailing_var_arg(self, yes: bool) -> Arg

This is a “var arg” and everything that follows should be captured by it, as if the user had used a --.

NOTE: To start the trailing “var arg” on unknown flags (and not just a positional value), set allow_hyphen_values. Either way, users still have the option to explicitly escape ambiguous arguments with --.

NOTE: Arg::value_delimiter still applies if set.

NOTE: Setting this requires Arg::num_args(..).

§Examples
let m = Command::new("myprog")
    .arg(arg!(<cmd> ... "commands to run").trailing_var_arg(true))
    .get_matches_from(vec!["myprog", "arg1", "-r", "val1"]);

let trail: Vec<_> = m.get_many::<String>("cmd").unwrap().collect();
assert_eq!(trail, ["arg1", "-r", "val1"]);
Source

pub fn last(self, yes: bool) -> Arg

This arg is the last, or final, positional argument (i.e. has the highest index) and is only able to be accessed via the -- syntax (i.e. $ prog args -- last_arg).

Even, if no other arguments are left to parse, if the user omits the -- syntax they will receive an UnknownArgument error. Setting an argument to .last(true) also allows one to access this arg early using the -- syntax. Accessing an arg early, even with the -- syntax is otherwise not possible.

NOTE: This will change the usage string to look like $ prog [OPTIONS] [-- <ARG>] if ARG is marked as .last(true).

NOTE: This setting will imply crate::Command::dont_collapse_args_in_usage because failing to set this can make the usage string very confusing.

NOTE: This setting only applies to positional arguments, and has no effect on OPTIONS

NOTE: Setting this requires taking values

WARNING: Using this setting and having child subcommands is not recommended with the exception of also using crate::Command::args_conflicts_with_subcommands (or crate::Command::subcommand_negates_reqs if the argument marked Last is also marked Arg::required)

§Examples
Arg::new("args")
    .action(ArgAction::Set)
    .last(true)

Setting last ensures the arg has the highest index of all positional args and requires that the -- syntax be used to access it early.

let res = Command::new("prog")
    .arg(Arg::new("first"))
    .arg(Arg::new("second"))
    .arg(Arg::new("third")
        .action(ArgAction::Set)
        .last(true))
    .try_get_matches_from(vec![
        "prog", "one", "--", "three"
    ]);

assert!(res.is_ok());
let m = res.unwrap();
assert_eq!(m.get_one::<String>("third").unwrap(), "three");
assert_eq!(m.get_one::<String>("second"), None);

Even if the positional argument marked Last is the only argument left to parse, failing to use the -- syntax results in an error.

let res = Command::new("prog")
    .arg(Arg::new("first"))
    .arg(Arg::new("second"))
    .arg(Arg::new("third")
        .action(ArgAction::Set)
        .last(true))
    .try_get_matches_from(vec![
        "prog", "one", "two", "three"
    ]);

assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
Examples found in repository?
examples/git.rs (line 23)
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 required(self, yes: bool) -> Arg

Specifies that the argument must be present.

Required by default means it is required, when no other conflicting rules or overrides have been evaluated. Conflicting rules take precedence over being required.

Pro tip: Flags (i.e. not positional, or arguments that take values) shouldn’t be required by default. This is because if a flag were to be required, it should simply be implied. No additional information is required from user. Flags by their very nature are simply boolean on/off switches. The only time a user should be required to use a flag is if the operation is destructive in nature, and the user is essentially proving to you, “Yes, I know what I’m doing.”

§Examples
Arg::new("config")
    .required(true)

Setting required requires that the argument be used at runtime.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .required(true)
        .action(ArgAction::Set)
        .long("config"))
    .try_get_matches_from(vec![
        "prog", "--config", "file.conf",
    ]);

assert!(res.is_ok());

Setting required and then not supplying that argument at runtime is an error.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .required(true)
        .action(ArgAction::Set)
        .long("config"))
    .try_get_matches_from(vec![
        "prog"
    ]);

assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
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}
Source

pub fn requires(self, arg_id: impl IntoResettable<Id>) -> Arg

Sets an argument that is required when this one is present

i.e. when using this argument, the following argument must be present.

NOTE: Conflicting rules and override rules take precedence over being required

§Examples
Arg::new("config")
    .requires("input")

Setting Arg::requires(name) requires that the argument be used at runtime if the defining argument is used. If the defining argument isn’t used, the other argument isn’t required

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .action(ArgAction::Set)
        .requires("input")
        .long("config"))
    .arg(Arg::new("input"))
    .try_get_matches_from(vec![
        "prog"
    ]);

assert!(res.is_ok()); // We didn't use cfg, so input wasn't required

Setting Arg::requires(name) and not supplying that argument is an error.

let res = Command::new("prog")
    .arg(Arg::new("cfg")
        .action(ArgAction::Set)
        .requires("input")
        .long("config"))
    .arg(Arg::new("input"))
    .try_get_matches_from(vec![
        "prog", "--config", "file.conf"
    ]);

assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
Source

pub fn exclusive(self, yes: bool) -> Arg

This argument must be passed alone; it conflicts with all other arguments.

§Examples
Arg::new("config")
    .exclusive(true)

Setting an exclusive argument and having any other arguments present at runtime is an error.

let res = Command::new("prog")
    .arg(Arg::new("exclusive")
        .action(ArgAction::Set)
        .exclusive(true)
        .long("exclusive"))
    .arg(Arg::new("debug")
        .long("debug"))
    .arg(Arg::new("input"))
    .try_get_matches_from(vec![
        "prog", "--exclusive", "file.conf", "file.txt"
    ]);

assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict);
Examples found in repository?
examples/multicall-busybox.rs (line 25)
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 global(self, yes: bool) -> Arg

Specifies that an argument can be matched to all child Subcommands.

NOTE: Global arguments only propagate down, not up (to parent commands), however their values once a user uses them will be propagated back up to parents. In effect, this means one should define all global arguments at the top level, however it doesn’t matter where the user uses the global argument.

§Examples

Assume an application with two subcommands, and you’d like to define a --verbose flag that can be called on any of the subcommands and parent, but you don’t want to clutter the source with three duplicate Arg definitions.

let m = Command::new("prog")
    .arg(Arg::new("verb")
        .long("verbose")
        .short('v')
        .action(ArgAction::SetTrue)
        .global(true))
    .subcommand(Command::new("test"))
    .subcommand(Command::new("do-stuff"))
    .get_matches_from(vec![
        "prog", "do-stuff", "--verbose"
    ]);

assert_eq!(m.subcommand_name(), Some("do-stuff"));
let sub_m = m.subcommand_matches("do-stuff").unwrap();
assert_eq!(sub_m.get_flag("verb"), true);
Source

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

Available on crate feature unstable-ext only.

Extend Arg with ArgExt data

Source§

impl Arg

§Value Handling

Source

pub fn action(self, action: impl IntoResettable<ArgAction>) -> Arg

Specify how to react to an argument when parsing it.

ArgAction controls things like

  • Overwriting previous values with new ones
  • Appending new values to all previous ones
  • Counting how many times a flag occurs

The default action is ArgAction::Set

§Examples
let cmd = Command::new("mycmd")
    .arg(
        Arg::new("flag")
            .long("flag")
            .action(clap::ArgAction::Append)
    );

let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value"]).unwrap();
assert!(matches.contains_id("flag"));
assert_eq!(
    matches.get_many::<String>("flag").unwrap_or_default().map(|v| v.as_str()).collect::<Vec<_>>(),
    vec!["value"]
);
Examples found in repository?
examples/derive_ref/flatten_hand_args.rs (line 43)
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    }
More examples
Hide additional examples
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 (line 26)
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/pacman.rs (line 23)
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 value_parser(self, parser: impl IntoResettable<ValueParser>) -> Arg

Specify the typed behavior of the argument.

This allows parsing and validating a value before storing it into ArgMatches as the given type.

Possible value parsers include:

The default value is ValueParser::string.

let mut cmd = clap::Command::new("raw")
    .arg(
        clap::Arg::new("color")
            .long("color")
            .value_parser(["always", "auto", "never"])
            .default_value("auto")
    )
    .arg(
        clap::Arg::new("hostname")
            .long("hostname")
            .value_parser(clap::builder::NonEmptyStringValueParser::new())
            .action(ArgAction::Set)
            .required(true)
    )
    .arg(
        clap::Arg::new("port")
            .long("port")
            .value_parser(clap::value_parser!(u16).range(3000..))
            .action(ArgAction::Set)
            .required(true)
    );

let m = cmd.try_get_matches_from_mut(
    ["cmd", "--hostname", "rust-lang.org", "--port", "3001"]
).unwrap();

let color: &String = m.get_one("color")
    .expect("default");
assert_eq!(color, "auto");

let hostname: &String = m.get_one("hostname")
    .expect("required");
assert_eq!(hostname, "rust-lang.org");

let port: u16 = *m.get_one("port")
    .expect("required");
assert_eq!(port, 3001);
Examples found in repository?
examples/multicall-busybox.rs (line 28)
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/git.rs (line 26)
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 num_args(self, qty: impl IntoResettable<ValueRange>) -> Arg

Specifies the number of arguments parsed per occurrence

For example, if you had a -f <file> argument where you wanted exactly 3 ‘files’ you would set .num_args(3), and this argument wouldn’t be satisfied unless the user provided 3 and only 3 values.

Users may specify values for arguments in any of the following methods

  • Using a space such as -o value or --option value
  • Using an equals and no space such as -o=value or --option=value
  • Use a short and no space such as -ovalue

WARNING:

Setting a variable number of values (e.g. 1..=10) for an argument without other details can be dangerous in some circumstances. Because multiple values are allowed, --option val1 val2 val3 is perfectly valid. Be careful when designing a CLI where positional arguments or subcommands are also expected as clap will continue parsing values until one of the following happens:

  • It reaches the maximum number of values
  • It reaches a specific number of values
  • It finds another flag or option (i.e. something that starts with a -)
  • It reaches the Arg::value_terminator if set

Alternatively,

§Examples

Option:

let m = Command::new("prog")
    .arg(Arg::new("mode")
        .long("mode")
        .num_args(1))
    .get_matches_from(vec![
        "prog", "--mode", "fast"
    ]);

assert_eq!(m.get_one::<String>("mode").unwrap(), "fast");

Flag/option hybrid (see also default_missing_value)

let cmd = Command::new("prog")
    .arg(Arg::new("mode")
        .long("mode")
        .default_missing_value("slow")
        .default_value("plaid")
        .num_args(0..=1));

let m = cmd.clone()
    .get_matches_from(vec![
        "prog", "--mode", "fast"
    ]);
assert_eq!(m.get_one::<String>("mode").unwrap(), "fast");

let m = cmd.clone()
    .get_matches_from(vec![
        "prog", "--mode",
    ]);
assert_eq!(m.get_one::<String>("mode").unwrap(), "slow");

let m = cmd.clone()
    .get_matches_from(vec![
        "prog",
    ]);
assert_eq!(m.get_one::<String>("mode").unwrap(), "plaid");

Tuples

let cmd = Command::new("prog")
    .arg(Arg::new("file")
        .action(ArgAction::Set)
        .num_args(2)
        .short('F'));

let m = cmd.clone()
    .get_matches_from(vec![
        "prog", "-F", "in-file", "out-file"
    ]);
assert_eq!(
    m.get_many::<String>("file").unwrap_or_default().map(|v| v.as_str()).collect::<Vec<_>>(),
    vec!["in-file", "out-file"]
);

let res = cmd.clone()
    .try_get_matches_from(vec![
        "prog", "-F", "file1"
    ]);
assert_eq!(res.unwrap_err().kind(), ErrorKind::WrongNumberOfValues);

A common mistake is to define an option which allows multiple values and a positional argument.

let cmd = Command::new("prog")
    .arg(Arg::new("file")
        .action(ArgAction::Set)
        .num_args(0..)
        .short('F'))
    .arg(Arg::new("word"));

let m = cmd.clone().get_matches_from(vec![
    "prog", "-F", "file1", "file2", "file3", "word"
]);
let files: Vec<_> = m.get_many::<String>("file").unwrap().collect();
assert_eq!(files, ["file1", "file2", "file3", "word"]); // wait...what?!
assert!(!m.contains_id("word")); // but we clearly used word!

// but this works
let m = cmd.clone().get_matches_from(vec![
    "prog", "word", "-F", "file1", "file2", "file3",
]);
let files: Vec<_> = m.get_many::<String>("file").unwrap().collect();
assert_eq!(files, ["file1", "file2", "file3"]);
assert_eq!(m.get_one::<String>("word").unwrap(), "word");

The problem is clap doesn’t know when to stop parsing values for “file”.

A solution for the example above is to limit how many values with a maximum, or specific number, or to say ArgAction::Append is ok, but multiple values are not.

let m = Command::new("prog")
    .arg(Arg::new("file")
        .action(ArgAction::Append)
        .short('F'))
    .arg(Arg::new("word"))
    .get_matches_from(vec![
        "prog", "-F", "file1", "-F", "file2", "-F", "file3", "word"
    ]);

let files: Vec<_> = m.get_many::<String>("file").unwrap().collect();
assert_eq!(files, ["file1", "file2", "file3"]);
assert_eq!(m.get_one::<String>("word").unwrap(), "word");
Examples found in repository?
examples/git.rs (line 27)
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}
More examples
Hide additional examples
examples/pacman.rs (line 24)
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 value_name(self, name: impl IntoResettable<Str>) -> Arg

Placeholder for the argument’s value in the help message / usage.

This name is cosmetic only; the name is not used to access arguments. This setting can be very helpful when describing the type of input the user should be using, such as FILE, INTERFACE, etc. Although not required, it’s somewhat convention to use all capital letters for the value name.

NOTE: implicitly sets Arg::action(ArgAction::Set)