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
impl Arg
§Basic API
Sourcepub fn new(id: impl Into<Id>) -> Arg
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
- Positional, see
Arg::shortorArg::longturn it into an option - Accept a single value, see
Arg::actionto override this
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?
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
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}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}Sourcepub fn id(self, id: impl Into<Id>) -> Arg
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.
Sourcepub fn short(self, s: impl IntoResettable<char>) -> Arg
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?
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
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}Sourcepub fn long(self, l: impl IntoResettable<Str>) -> Arg
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?
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
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}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}Sourcepub fn alias(self, name: impl IntoResettable<Str>) -> Arg
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");Sourcepub fn short_alias(self, name: impl IntoResettable<char>) -> Arg
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");Sourcepub fn aliases(self, names: impl IntoIterator<Item = impl Into<Str>>) -> Arg
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);Sourcepub fn short_aliases(self, names: impl IntoIterator<Item = char>) -> Arg
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);Sourcepub fn visible_alias(self, name: impl IntoResettable<Str>) -> Arg
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");Sourcepub fn visible_short_alias(self, name: impl IntoResettable<char>) -> Arg
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");Sourcepub fn visible_aliases(
self,
names: impl IntoIterator<Item = impl Into<Str>>,
) -> Arg
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);Sourcepub fn visible_short_aliases(self, names: impl IntoIterator<Item = char>) -> Arg
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);Sourcepub fn index(self, idx: impl IntoResettable<usize>) -> Arg
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 argumentSourcepub fn trailing_var_arg(self, yes: bool) -> Arg
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"]);Sourcepub fn last(self, yes: bool) -> Arg
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?
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}Sourcepub fn required(self, yes: bool) -> Arg
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?
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}Sourcepub fn requires(self, arg_id: impl IntoResettable<Id>) -> Arg
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 requiredSetting 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);Sourcepub fn exclusive(self, yes: bool) -> Arg
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?
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}Sourcepub fn global(self, yes: bool) -> Arg
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§impl Arg
§Value Handling
impl Arg
§Value Handling
Sourcepub fn action(self, action: impl IntoResettable<ArgAction>) -> Arg
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?
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
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}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}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}Sourcepub fn value_parser(self, parser: impl IntoResettable<ValueParser>) -> Arg
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:
value_parser!(T)for auto-selecting a value parser for a given type- Or range expressions like
0..=1as a shorthand forRangedI64ValueParser
- Or range expressions like
Fn(&str) -> Result<T, E>[&str]andPossibleValuesParserfor static enumerated valuesBoolishValueParser, andFalseyValueParserfor alternativeboolimplementationsNonEmptyStringValueParserfor basic validation for strings- or any other
TypedValueParserimplementation
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?
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
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}Sourcepub fn num_args(self, qty: impl IntoResettable<ValueRange>) -> Arg
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 valueor--option value - Using an equals and no space such as
-o=valueor--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_terminatorif set
Alternatively,
- Use a delimiter between values with
Arg::value_delimiter - Require a flag occurrence per value with
ArgAction::Append - Require positional arguments to appear after
--withArg::last
§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?
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
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}Sourcepub fn value_name(self, name: impl IntoResettable<Str>) -> Arg
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)
§Examples
Arg::new("cfg")
.long("config")
.value_name("FILE")let m = Command::new("prog")
.arg(Arg::new("config")
.long("config")
.value_name("FILE")
.help("Some help text"))
.get_matches_from(vec![
"prog", "--help"
]);Running the above program produces the following output
valnames
Usage: valnames [OPTIONS]
Options:
--config <FILE> Some help text
-h, --help Print help information
-V, --version Print version informationSourcepub fn value_names(self, names: impl IntoIterator<Item = impl Into<Str>>) -> Arg
pub fn value_names(self, names: impl IntoIterator<Item = impl Into<Str>>) -> Arg
Placeholders for the argument’s values in the help message / usage.
These names are cosmetic only, used for help and usage strings only. The names are not
used to access arguments. The values of the arguments are accessed in numeric order (i.e.
if you specify two names one and two one will be the first matched value, two will
be the second).
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.
TIP: It may help to use Arg::next_line_help(true) if there are long, or
multiple value names in order to not throw off the help text alignment of all options.
NOTE: implicitly sets Arg::action(ArgAction::Set) and Arg::num_args(1..).
§Examples
Arg::new("speed")
.short('s')
.value_names(["fast", "slow"]);let m = Command::new("prog")
.arg(Arg::new("io")
.long("io-files")
.value_names(["INFILE", "OUTFILE"]))
.get_matches_from(vec![
"prog", "--help"
]);Running the above program produces the following output
valnames
Usage: valnames [OPTIONS]
Options:
-h, --help Print help information
--io-files <INFILE> <OUTFILE> Some help text
-V, --version Print version informationSourcepub fn value_hint(self, value_hint: impl IntoResettable<ValueHint>) -> Arg
pub fn value_hint(self, value_hint: impl IntoResettable<ValueHint>) -> Arg
Provide the shell a hint about how to complete this argument.
See ValueHint for more information.
NOTE: implicitly sets Arg::action(ArgAction::Set).
For example, to take a username as argument:
Arg::new("user")
.short('u')
.long("user")
.value_hint(ValueHint::Username);To take a full command line and its arguments (for example, when writing a command wrapper):
Command::new("prog")
.trailing_var_arg(true)
.arg(
Arg::new("command")
.action(ArgAction::Set)
.num_args(1..)
.value_hint(ValueHint::CommandWithArguments)
);Sourcepub fn ignore_case(self, yes: bool) -> Arg
pub fn ignore_case(self, yes: bool) -> Arg
Match values against PossibleValuesParser without matching case.
When other arguments are conditionally required based on the
value of a case-insensitive argument, the equality check done
by Arg::required_if_eq, Arg::required_if_eq_any, or
Arg::required_if_eq_all is case-insensitive.
NOTE: Setting this requires taking values
NOTE: To do unicode case folding, enable the unicode feature flag.
§Examples
let m = Command::new("pv")
.arg(Arg::new("option")
.long("option")
.action(ArgAction::Set)
.ignore_case(true)
.value_parser(["test123"]))
.get_matches_from(vec![
"pv", "--option", "TeSt123",
]);
assert!(m.get_one::<String>("option").unwrap().eq_ignore_ascii_case("test123"));This setting also works when multiple values can be defined:
let m = Command::new("pv")
.arg(Arg::new("option")
.short('o')
.long("option")
.action(ArgAction::Set)
.ignore_case(true)
.num_args(1..)
.value_parser(["test123", "test321"]))
.get_matches_from(vec![
"pv", "--option", "TeSt123", "teST123", "tESt321"
]);
let matched_vals = m.get_many::<String>("option").unwrap().collect::<Vec<_>>();
assert_eq!(&*matched_vals, &["TeSt123", "teST123", "tESt321"]);Sourcepub fn allow_hyphen_values(self, yes: bool) -> Arg
pub fn allow_hyphen_values(self, yes: bool) -> Arg
Allows values which start with a leading hyphen (-)
To limit values to just numbers, see
allow_negative_numbers.
See also trailing_var_arg.
NOTE: Setting this requires taking values
WARNING: Prior arguments with allow_hyphen_values(true) get precedence over known
flags but known flags get precedence over the next possible positional argument with
allow_hyphen_values(true). When combined with Arg::num_args(..),
Arg::value_terminator is one way to ensure processing stops.
WARNING: Take caution when using this setting combined with another argument using
Arg::num_args, as this becomes ambiguous $ prog --arg -- -- val. All
three --, --, val will be values when the user may have thought the second -- would
constitute the normal, “Only positional args follow” idiom.
§Examples
let m = Command::new("prog")
.arg(Arg::new("pat")
.action(ArgAction::Set)
.allow_hyphen_values(true)
.long("pattern"))
.get_matches_from(vec![
"prog", "--pattern", "-file"
]);
assert_eq!(m.get_one::<String>("pat").unwrap(), "-file");Not setting Arg::allow_hyphen_values(true) and supplying a value which starts with a
hyphen is an error.
let res = Command::new("prog")
.arg(Arg::new("pat")
.action(ArgAction::Set)
.long("pattern"))
.try_get_matches_from(vec![
"prog", "--pattern", "-file"
]);
assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);Sourcepub fn allow_negative_numbers(self, yes: bool) -> Arg
pub fn allow_negative_numbers(self, yes: bool) -> Arg
Allows negative numbers to pass as values.
This is similar to Arg::allow_hyphen_values except that it only allows numbers,
all other undefined leading hyphens will fail to parse.
NOTE: Setting this requires taking values
§Examples
let res = Command::new("myprog")
.arg(Arg::new("num").allow_negative_numbers(true))
.try_get_matches_from(vec![
"myprog", "-20"
]);
assert!(res.is_ok());
let m = res.unwrap();
assert_eq!(m.get_one::<String>("num").unwrap(), "-20");Sourcepub fn require_equals(self, yes: bool) -> Arg
pub fn require_equals(self, yes: bool) -> Arg
Requires that options use the --option=val syntax
i.e. an equals between the option and associated value.
NOTE: Setting this requires taking values
§Examples
Setting require_equals requires that the option have an equals sign between
it and the associated value.
let res = Command::new("prog")
.arg(Arg::new("cfg")
.action(ArgAction::Set)
.require_equals(true)
.long("config"))
.try_get_matches_from(vec![
"prog", "--config=file.conf"
]);
assert!(res.is_ok());Setting require_equals and not supplying the equals will cause an
error.
let res = Command::new("prog")
.arg(Arg::new("cfg")
.action(ArgAction::Set)
.require_equals(true)
.long("config"))
.try_get_matches_from(vec![
"prog", "--config", "file.conf"
]);
assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::NoEquals);Examples found in repository?
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}Sourcepub fn value_delimiter(self, d: impl IntoResettable<char>) -> Arg
pub fn value_delimiter(self, d: impl IntoResettable<char>) -> Arg
Allow grouping of multiple values via a delimiter.
i.e. allow values (val1,val2,val3) to be parsed as three values (val1, val2,
and val3) instead of one value (val1,val2,val3).
See also Command::dont_delimit_trailing_values.
§Examples
let m = Command::new("prog")
.arg(Arg::new("config")
.short('c')
.long("config")
.value_delimiter(','))
.get_matches_from(vec![
"prog", "--config=val1,val2,val3"
]);
assert_eq!(m.get_many::<String>("config").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"])Sourcepub fn value_terminator(self, term: impl IntoResettable<Str>) -> Arg
pub fn value_terminator(self, term: impl IntoResettable<Str>) -> Arg
Sentinel to stop parsing multiple values of a given argument.
By default when
one sets num_args(1..) on an argument, clap will continue parsing values for that
argument until it reaches another valid argument, or one of the other more specific settings
for multiple values is used (such as num_args).
NOTE: This setting only applies to options and positional arguments
NOTE: When the terminator is passed in on the command line, it is not stored as one of the values
§Examples
Arg::new("vals")
.action(ArgAction::Set)
.num_args(1..)
.value_terminator(";")The following example uses two arguments, a sequence of commands, and the location in which to perform them
let m = Command::new("prog")
.arg(Arg::new("cmds")
.action(ArgAction::Set)
.num_args(1..)
.allow_hyphen_values(true)
.value_terminator(";"))
.arg(Arg::new("location"))
.get_matches_from(vec![
"prog", "find", "-type", "f", "-name", "special", ";", "/home/clap"
]);
let cmds: Vec<_> = m.get_many::<String>("cmds").unwrap().collect();
assert_eq!(&cmds, &["find", "-type", "f", "-name", "special"]);
assert_eq!(m.get_one::<String>("location").unwrap(), "/home/clap");Sourcepub fn raw(self, yes: bool) -> Arg
pub fn raw(self, yes: bool) -> Arg
Consume all following arguments.
Do not parse them individually, but rather pass them in entirety.
It is worth noting that setting this requires all values to come after a -- to indicate
they should all be captured. For example:
--foo something -- -v -v -v -b -b -b --baz -q -u -xWill result in everything after -- to be considered one raw argument. This behavior
may not be exactly what you are expecting and using Arg::trailing_var_arg
may be more appropriate.
NOTE: Implicitly sets Arg::action(ArgAction::Set), Arg::num_args(1..),
Arg::allow_hyphen_values(true), and Arg::last(true) when set to true.
Sourcepub fn default_value(self, val: impl IntoResettable<OsStr>) -> Arg
pub fn default_value(self, val: impl IntoResettable<OsStr>) -> Arg
Value for the argument when not present.
Like with command-line values, this will be split by Arg::value_delimiter.
NOTE: If the user does not use this argument at runtime ArgMatches::contains_id will
still return true. If you wish to determine whether the argument was used at runtime or
not, consider ArgMatches::value_source.
NOTE: This setting is perfectly compatible with Arg::default_value_if but slightly
different. Arg::default_value only takes effect when the user has not provided this arg
at runtime. Arg::default_value_if however only takes effect when the user has not provided
a value at runtime and these other conditions are met as well. If you have set
Arg::default_value and Arg::default_value_if, and the user did not provide this arg
at runtime, nor were the conditions met for Arg::default_value_if, the Arg::default_value
will be applied.
§Examples
First we use the default value without providing any value at runtime.
let m = Command::new("prog")
.arg(Arg::new("opt")
.long("myopt")
.default_value("myval"))
.get_matches_from(vec![
"prog"
]);
assert_eq!(m.get_one::<String>("opt").unwrap(), "myval");
assert!(m.contains_id("opt"));
assert_eq!(m.value_source("opt"), Some(ValueSource::DefaultValue));Next we provide a value at runtime to override the default.
let m = Command::new("prog")
.arg(Arg::new("opt")
.long("myopt")
.default_value("myval"))
.get_matches_from(vec![
"prog", "--myopt=non_default"
]);
assert_eq!(m.get_one::<String>("opt").unwrap(), "non_default");
assert!(m.contains_id("opt"));
assert_eq!(m.value_source("opt"), Some(ValueSource::CommandLine));Examples found in repository?
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}Sourcepub fn default_values(
self,
vals: impl IntoIterator<Item = impl Into<OsStr>>,
) -> Arg
pub fn default_values( self, vals: impl IntoIterator<Item = impl Into<OsStr>>, ) -> Arg
Value for the argument when not present.
See Arg::default_value.
Sourcepub fn default_missing_value(self, val: impl IntoResettable<OsStr>) -> Arg
pub fn default_missing_value(self, val: impl IntoResettable<OsStr>) -> Arg
Value for the argument when the flag is present but no value is specified.
This configuration option is often used to give the user a shortcut and allow them to
efficiently specify an option argument without requiring an explicitly value. The --color
argument is a common example. By supplying a default, such as default_missing_value("always"),
the user can quickly just add --color to the command line to produce the desired color output.
Like with command-line values, this will be split by Arg::value_delimiter.
NOTE: using this configuration option requires the use of the
.num_args(0..N) and the
.require_equals(true) configuration option. These are required in
order to unambiguously determine what, if any, value was supplied for the argument.
§Examples
For POSIX style --color:
fn cli() -> Command {
Command::new("prog")
.arg(Arg::new("color").long("color")
.value_name("WHEN")
.value_parser(["always", "auto", "never"])
.default_value("auto")
.num_args(0..=1)
.require_equals(true)
.default_missing_value("always")
.help("Specify WHEN to colorize output.")
)
}
// first, we'll provide no arguments
let m = cli().get_matches_from(vec![
"prog"
]);
assert_eq!(m.get_one::<String>("color").unwrap(), "auto");
assert_eq!(m.value_source("color"), Some(ValueSource::DefaultValue));
// next, we'll provide a runtime value to override the default (as usually done).
let m = cli().get_matches_from(vec![
"prog", "--color=never"
]);
assert_eq!(m.get_one::<String>("color").unwrap(), "never");
assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine));
// finally, we will use the shortcut and only provide the argument without a value.
let m = cli().get_matches_from(vec![
"prog", "--color"
]);
assert_eq!(m.get_one::<String>("color").unwrap(), "always");
assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine));For bool literals:
fn cli() -> Command {
Command::new("prog")
.arg(Arg::new("create").long("create")
.value_name("BOOL")
.value_parser(value_parser!(bool))
.num_args(0..=1)
.require_equals(true)
.default_missing_value("true")
)
}
// first, we'll provide no arguments
let m = cli().get_matches_from(vec![
"prog"
]);
assert_eq!(m.get_one::<bool>("create").copied(), None);
// next, we'll provide a runtime value to override the default (as usually done).
let m = cli().get_matches_from(vec![
"prog", "--create=false"
]);
assert_eq!(m.get_one::<bool>("create").copied(), Some(false));
assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine));
// finally, we will use the shortcut and only provide the argument without a value.
let m = cli().get_matches_from(vec![
"prog", "--create"
]);
assert_eq!(m.get_one::<bool>("create").copied(), Some(true));
assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine));Examples found in repository?
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
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}Sourcepub fn default_missing_value_os(self, val: impl Into<OsStr>) -> Arg
pub fn default_missing_value_os(self, val: impl Into<OsStr>) -> Arg
Value for the argument when the flag is present but no value is specified.
Sourcepub fn default_missing_values(
self,
vals: impl IntoIterator<Item = impl Into<OsStr>>,
) -> Arg
pub fn default_missing_values( self, vals: impl IntoIterator<Item = impl Into<OsStr>>, ) -> Arg
Value for the argument when the flag is present but no value is specified.
Sourcepub fn default_missing_values_os(
self,
vals: impl IntoIterator<Item = impl Into<OsStr>>,
) -> Arg
pub fn default_missing_values_os( self, vals: impl IntoIterator<Item = impl Into<OsStr>>, ) -> Arg
Value for the argument when the flag is present but no value is specified.
Sourcepub fn env(self, name: impl IntoResettable<OsStr>) -> Arg
Available on crate feature env only.
pub fn env(self, name: impl IntoResettable<OsStr>) -> Arg
env only.Read from name environment variable when argument is not present.
If it is not present in the environment, then default rules will apply.
If user sets the argument in the environment:
- When
Arg::action(ArgAction::Set)is not set, the flag is considered raised. - When
Arg::action(ArgAction::Set)is set,ArgMatches::get_onewill return value of the environment variable.
If user doesn’t set the argument in the environment:
- When
Arg::action(ArgAction::Set)is not set, the flag is considered off. - When
Arg::action(ArgAction::Set)is set,ArgMatches::get_onewill return the default specified.
Like with command-line values, this will be split by Arg::value_delimiter.
§Examples
In this example, we show the variable coming from the environment:
env::set_var("MY_FLAG", "env");
let m = Command::new("prog")
.arg(Arg::new("flag")
.long("flag")
.env("MY_FLAG")
.action(ArgAction::Set))
.get_matches_from(vec![
"prog"
]);
assert_eq!(m.get_one::<String>("flag").unwrap(), "env");In this example, because prog is a flag that accepts an optional, case-insensitive
boolean literal.
Note that the value parser controls how flags are parsed. In this case we’ve selected
FalseyValueParser. A false literal is n, no,
f, false, off or 0. An absent environment variable will also be considered as
false. Anything else will considered as true.
env::set_var("TRUE_FLAG", "true");
env::set_var("FALSE_FLAG", "0");
let m = Command::new("prog")
.arg(Arg::new("true_flag")
.long("true_flag")
.action(ArgAction::SetTrue)
.value_parser(FalseyValueParser::new())
.env("TRUE_FLAG"))
.arg(Arg::new("false_flag")
.long("false_flag")
.action(ArgAction::SetTrue)
.value_parser(FalseyValueParser::new())
.env("FALSE_FLAG"))
.arg(Arg::new("absent_flag")
.long("absent_flag")
.action(ArgAction::SetTrue)
.value_parser(FalseyValueParser::new())
.env("ABSENT_FLAG"))
.get_matches_from(vec![
"prog"
]);
assert!(m.get_flag("true_flag"));
assert!(!m.get_flag("false_flag"));
assert!(!m.get_flag("absent_flag"));In this example, we show the variable coming from an option on the CLI:
env::set_var("MY_FLAG", "env");
let m = Command::new("prog")
.arg(Arg::new("flag")
.long("flag")
.env("MY_FLAG")
.action(ArgAction::Set))
.get_matches_from(vec![
"prog", "--flag", "opt"
]);
assert_eq!(m.get_one::<String>("flag").unwrap(), "opt");In this example, we show the variable coming from the environment even with the presence of a default:
env::set_var("MY_FLAG", "env");
let m = Command::new("prog")
.arg(Arg::new("flag")
.long("flag")
.env("MY_FLAG")
.action(ArgAction::Set)
.default_value("default"))
.get_matches_from(vec![
"prog"
]);
assert_eq!(m.get_one::<String>("flag").unwrap(), "env");In this example, we show the use of multiple values in a single environment variable:
env::set_var("MY_FLAG_MULTI", "env1,env2");
let m = Command::new("prog")
.arg(Arg::new("flag")
.long("flag")
.env("MY_FLAG_MULTI")
.action(ArgAction::Set)
.num_args(1..)
.value_delimiter(','))
.get_matches_from(vec![
"prog"
]);
assert_eq!(m.get_many::<String>("flag").unwrap().collect::<Vec<_>>(), vec!["env1", "env2"]);Source§impl Arg
§Help
impl Arg
§Help
Sourcepub fn help(self, h: impl IntoResettable<StyledStr>) -> Arg
pub fn help(self, h: impl IntoResettable<StyledStr>) -> Arg
Sets the description of the argument for short help (-h).
Typically, this is a short (one line) description of the arg.
If Arg::long_help is not specified, this message will be displayed for --help.
NOTE: Only Arg::help is used in completion script generation in order to be concise
§Examples
Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to include a newline in the help text and have the following text be properly aligned with all the other help text.
Setting help displays a short message to the side of the argument when the user passes
-h or --help (by default).
let m = Command::new("prog")
.arg(Arg::new("cfg")
.long("config")
.help("Some help text describing the --config arg"))
.get_matches_from(vec![
"prog", "--help"
]);The above example displays
helptest
Usage: helptest [OPTIONS]
Options:
--config Some help text describing the --config arg
-h, --help Print help information
-V, --version Print version informationExamples found in repository?
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
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}Sourcepub fn long_help(self, h: impl IntoResettable<StyledStr>) -> Arg
pub fn long_help(self, h: impl IntoResettable<StyledStr>) -> Arg
Sets the description of the argument for long help (--help).
Typically this a more detailed (multi-line) message that describes the arg.
If Arg::help is not specified, this message will be displayed for -h.
NOTE: Only Arg::help is used in completion script generation in order to be concise
§Examples
Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to include a newline in the help text and have the following text be properly aligned with all the other help text.
Setting help displays a short message to the side of the argument when the user passes
-h or --help (by default).
let m = Command::new("prog")
.arg(Arg::new("cfg")
.long("config")
.long_help(
"The config file used by the myprog must be in JSON format
with only valid keys and may not contain other nonsense
that cannot be read by this program. Obviously I'm going on
and on, so I'll stop now."))
.get_matches_from(vec![
"prog", "--help"
]);The above example displays
prog
Usage: prog [OPTIONS]
Options:
--config
The config file used by the myprog must be in JSON format
with only valid keys and may not contain other nonsense
that cannot be read by this program. Obviously I'm going on
and on, so I'll stop now.
-h, --help
Print help information
-V, --version
Print version informationSourcepub fn display_order(self, ord: impl IntoResettable<usize>) -> Arg
pub fn display_order(self, ord: impl IntoResettable<usize>) -> Arg
Allows custom ordering of args within the help message.
Args with a lower value will be displayed first in the help message.
Those with the same display order will be sorted.
Args are automatically assigned a display order based on the order they are added to the
Command.
Overriding this is helpful when the order arguments are added in isn’t the same as the
display order, whether in one-off cases or to automatically sort arguments.
To change, see Command::next_display_order.
NOTE: This setting is ignored for positional arguments which are always displayed in index order.
§Examples
let m = Command::new("prog")
.arg(Arg::new("boat")
.short('b')
.long("boat")
.action(ArgAction::Set)
.display_order(0) // Sort
.help("Some help and text"))
.arg(Arg::new("airplane")
.short('a')
.long("airplane")
.action(ArgAction::Set)
.display_order(0) // Sort
.help("I should be first!"))
.arg(Arg::new("custom-help")
.short('?')
.action(ArgAction::Help)
.display_order(100) // Don't sort
.help("Alt help"))
.get_matches_from(vec![
"prog", "--help"
]);The above example displays the following help message
cust-ord
Usage: cust-ord [OPTIONS]
Options:
-a, --airplane <airplane> I should be first!
-b, --boat <boar> Some help and text
-h, --help Print help information
-? Alt helpSourcepub fn help_heading(self, heading: impl IntoResettable<Str>) -> Arg
pub fn help_heading(self, heading: impl IntoResettable<Str>) -> Arg
Override the --help section this appears in.
For more on the default help heading, see
Command::next_help_heading.
Sourcepub fn next_line_help(self, yes: bool) -> Arg
pub fn next_line_help(self, yes: bool) -> Arg
Render the help on the line after the argument.
This can be helpful for arguments with very long or complex help messages. This can also be helpful for arguments with very long flag names, or many/long value names.
NOTE: To apply this setting to all arguments and subcommands, consider using
crate::Command::next_line_help
§Examples
let m = Command::new("prog")
.arg(Arg::new("opt")
.long("long-option-flag")
.short('o')
.action(ArgAction::Set)
.next_line_help(true)
.value_names(["value1", "value2"])
.help("Some really long help and complex\n\
help that makes more sense to be\n\
on a line after the option"))
.get_matches_from(vec![
"prog", "--help"
]);The above example displays the following help message
nlh
Usage: nlh [OPTIONS]
Options:
-h, --help Print help information
-V, --version Print version information
-o, --long-option-flag <value1> <value2>
Some really long help and complex
help that makes more sense to be
on a line after the optionSourcepub fn hide(self, yes: bool) -> Arg
pub fn hide(self, yes: bool) -> Arg
Do not display the argument in help message.
NOTE: This does not hide the argument from usage strings on error
§Examples
Setting Hidden will hide the argument when displaying help text
let m = Command::new("prog")
.arg(Arg::new("cfg")
.long("config")
.hide(true)
.help("Some help text describing the --config arg"))
.get_matches_from(vec![
"prog", "--help"
]);The above example displays
helptest
Usage: helptest [OPTIONS]
Options:
-h, --help Print help information
-V, --version Print version informationSourcepub fn hide_possible_values(self, yes: bool) -> Arg
pub fn hide_possible_values(self, yes: bool) -> Arg
Do not display the possible values in the help message.
This is useful for args with many values, or ones which are explained elsewhere in the help text.
To set this for all arguments, see
Command::hide_possible_values.
NOTE: Setting this requires taking values
§Examples
let m = Command::new("prog")
.arg(Arg::new("mode")
.long("mode")
.value_parser(["fast", "slow"])
.action(ArgAction::Set)
.hide_possible_values(true));If we were to run the above program with --help the [values: fast, slow] portion of
the help text would be omitted.
Sourcepub fn hide_default_value(self, yes: bool) -> Arg
pub fn hide_default_value(self, yes: bool) -> Arg
Do not display the default value of the argument in the help message.
This is useful when default behavior of an arg is explained elsewhere in the help text.
NOTE: Setting this requires taking values
§Examples
let m = Command::new("connect")
.arg(Arg::new("host")
.long("host")
.default_value("localhost")
.action(ArgAction::Set)
.hide_default_value(true));
If we were to run the above program with --help the [default: localhost] portion of
the help text would be omitted.
Sourcepub fn hide_env(self, yes: bool) -> Arg
Available on crate feature env only.
pub fn hide_env(self, yes: bool) -> Arg
env only.Do not display in help the environment variable name.
This is useful when the variable option is explained elsewhere in the help text.
§Examples
let m = Command::new("prog")
.arg(Arg::new("mode")
.long("mode")
.env("MODE")
.action(ArgAction::Set)
.hide_env(true));If we were to run the above program with --help the [env: MODE] portion of the help
text would be omitted.
Sourcepub fn hide_env_values(self, yes: bool) -> Arg
Available on crate feature env only.
pub fn hide_env_values(self, yes: bool) -> Arg
env only.Do not display in help any values inside the associated ENV variables for the argument.
This is useful when ENV vars contain sensitive values.
§Examples
let m = Command::new("connect")
.arg(Arg::new("host")
.long("host")
.env("CONNECT")
.action(ArgAction::Set)
.hide_env_values(true));
If we were to run the above program with $ CONNECT=super_secret connect --help the
[default: CONNECT=super_secret] portion of the help text would be omitted.
Sourcepub fn hide_short_help(self, yes: bool) -> Arg
pub fn hide_short_help(self, yes: bool) -> Arg
Hides an argument from short help (-h).
NOTE: This does not hide the argument from usage strings on error
NOTE: Setting this option will cause next-line-help output style to be used
when long help (--help) is called.
§Examples
Arg::new("debug")
.hide_short_help(true);Setting hide_short_help(true) will hide the argument when displaying short help text
let m = Command::new("prog")
.arg(Arg::new("cfg")
.long("config")
.hide_short_help(true)
.help("Some help text describing the --config arg"))
.get_matches_from(vec![
"prog", "-h"
]);The above example displays
helptest
Usage: helptest [OPTIONS]
Options:
-h, --help Print help information
-V, --version Print version informationHowever, when –help is called
let m = Command::new("prog")
.arg(Arg::new("cfg")
.long("config")
.hide_short_help(true)
.help("Some help text describing the --config arg"))
.get_matches_from(vec![
"prog", "--help"
]);Then the following would be displayed
helptest
Usage: helptest [OPTIONS]
Options:
--config Some help text describing the --config arg
-h, --help Print help information
-V, --version Print version informationSourcepub fn hide_long_help(self, yes: bool) -> Arg
pub fn hide_long_help(self, yes: bool) -> Arg
Hides an argument from long help (--help).
NOTE: This does not hide the argument from usage strings on error
NOTE: Setting this option will cause next-line-help output style to be used
when long help (--help) is called.
§Examples
Setting hide_long_help(true) will hide the argument when displaying long help text
let m = Command::new("prog")
.arg(Arg::new("cfg")
.long("config")
.hide_long_help(true)
.help("Some help text describing the --config arg"))
.get_matches_from(vec![
"prog", "--help"
]);The above example displays
helptest
Usage: helptest [OPTIONS]
Options:
-h, --help Print help information
-V, --version Print version informationHowever, when -h is called
let m = Command::new("prog")
.arg(Arg::new("cfg")
.long("config")
.hide_long_help(true)
.help("Some help text describing the --config arg"))
.get_matches_from(vec![
"prog", "-h"
]);Then the following would be displayed
helptest
Usage: helptest [OPTIONS]
OPTIONS:
--config Some help text describing the --config arg
-h, --help Print help information
-V, --version Print version informationSource§impl Arg
§Advanced Argument Relations
impl Arg
§Advanced Argument Relations
Sourcepub fn group(self, group_id: impl IntoResettable<Id>) -> Arg
pub fn group(self, group_id: impl IntoResettable<Id>) -> Arg
The name of the ArgGroup the argument belongs to.
§Examples
Arg::new("debug")
.long("debug")
.action(ArgAction::SetTrue)
.group("mode")Multiple arguments can be a member of a single group and then the group checked as if it was one of said arguments.
let m = Command::new("prog")
.arg(Arg::new("debug")
.long("debug")
.action(ArgAction::SetTrue)
.group("mode"))
.arg(Arg::new("verbose")
.long("verbose")
.action(ArgAction::SetTrue)
.group("mode"))
.get_matches_from(vec![
"prog", "--debug"
]);
assert!(m.contains_id("mode"));Sourcepub fn groups(self, group_ids: impl IntoIterator<Item = impl Into<Id>>) -> Arg
pub fn groups(self, group_ids: impl IntoIterator<Item = impl Into<Id>>) -> Arg
The names of ArgGroup’s the argument belongs to.
§Examples
Arg::new("debug")
.long("debug")
.action(ArgAction::SetTrue)
.groups(["mode", "verbosity"])Arguments can be members of multiple groups and then the group checked as if it was one of said arguments.
let m = Command::new("prog")
.arg(Arg::new("debug")
.long("debug")
.action(ArgAction::SetTrue)
.groups(["mode", "verbosity"]))
.arg(Arg::new("verbose")
.long("verbose")
.action(ArgAction::SetTrue)
.groups(["mode", "verbosity"]))
.get_matches_from(vec![
"prog", "--debug"
]);
assert!(m.contains_id("mode"));
assert!(m.contains_id("verbosity"));Sourcepub fn default_value_if(
self,
arg_id: impl Into<Id>,
predicate: impl Into<ArgPredicate>,
default: impl IntoResettable<OsStr>,
) -> Arg
pub fn default_value_if( self, arg_id: impl Into<Id>, predicate: impl Into<ArgPredicate>, default: impl IntoResettable<OsStr>, ) -> Arg
Specifies the value of the argument if arg has been used at runtime.
If default is set to None, default_value will be removed.
Like with command-line values, this will be split by Arg::value_delimiter.
NOTE: This setting is perfectly compatible with Arg::default_value but slightly
different. Arg::default_value only takes effect when the user has not provided this arg
at runtime. This setting however only takes effect when the user has not provided a value at
runtime and these other conditions are met as well. If you have set Arg::default_value
and Arg::default_value_if, and the user did not provide this arg at runtime, nor were
the conditions met for Arg::default_value_if, the Arg::default_value will be applied.
§Examples
First we use the default value only if another arg is present at runtime.
let m = Command::new("prog")
.arg(Arg::new("flag")
.long("flag")
.action(ArgAction::SetTrue))
.arg(Arg::new("other")
.long("other")
.default_value_if("flag", ArgPredicate::IsPresent, Some("default")))
.get_matches_from(vec![
"prog", "--flag"
]);
assert_eq!(m.get_one::<String>("other").unwrap(), "default");Next we run the same test, but without providing --flag.
let m = Command::new("prog")
.arg(Arg::new("flag")
.long("flag")
.action(ArgAction::SetTrue))
.arg(Arg::new("other")
.long("other")
.default_value_if("flag", "true", Some("default")))
.get_matches_from(vec![
"prog"
]);
assert_eq!(m.get_one::<String>("other"), None);Now lets only use the default value if --opt contains the value special.
let m = Command::new("prog")
.arg(Arg::new("opt")
.action(ArgAction::Set)
.long("opt"))
.arg(Arg::new("other")
.long("other")
.default_value_if("opt", "special", Some("default")))
.get_matches_from(vec![
"prog", "--opt", "special"
]);
assert_eq!(m.get_one::<String>("other").unwrap(), "default");We can run the same test and provide any value other than special and we won’t get a
default value.
let m = Command::new("prog")
.arg(Arg::new("opt")
.action(ArgAction::Set)
.long("opt"))
.arg(Arg::new("other")
.long("other")
.default_value_if("opt", "special", Some("default")))
.get_matches_from(vec![
"prog", "--opt", "hahaha"
]);
assert_eq!(m.get_one::<String>("other"), None);If we want to unset the default value for an Arg based on the presence or value of some other Arg.
let m = Command::new("prog")
.arg(Arg::new("flag")
.long("flag")
.action(ArgAction::SetTrue))
.arg(Arg::new("other")
.long("other")
.default_value("default")
.default_value_if("flag", "true", None))
.get_matches_from(vec![
"prog", "--flag"
]);
assert_eq!(m.get_one::<String>("other"), None);Sourcepub fn default_values_if(
self,
arg_id: impl Into<Id>,
predicate: impl Into<ArgPredicate>,
defaults: impl IntoIterator<Item = impl Into<OsStr>>,
) -> Arg
pub fn default_values_if( self, arg_id: impl Into<Id>, predicate: impl Into<ArgPredicate>, defaults: impl IntoIterator<Item = impl Into<OsStr>>, ) -> Arg
Specifies the values of the argument if arg has been used at runtime.
§Examples
use clap_builder::arg;
use clap_builder::Command;
use clap_builder::Arg;
let r = Command::new("df")
.arg(arg!(--opt <FILE> "some arg"))
.arg(
Arg::new("args")
.long("args")
.num_args(2)
.default_values_if("opt", "value", ["df1","df2"]),
)
.try_get_matches_from(vec!["", "--opt", "value"]);
let m = r.unwrap();
assert_eq!(
m.get_many::<String>("args").unwrap().collect::<Vec<_>>(),
["df1", "df2"]
);Sourcepub fn default_value_ifs(
self,
ifs: impl IntoIterator<Item = (impl Into<Id>, impl Into<ArgPredicate>, impl IntoResettable<OsStr>)>,
) -> Arg
pub fn default_value_ifs( self, ifs: impl IntoIterator<Item = (impl Into<Id>, impl Into<ArgPredicate>, impl IntoResettable<OsStr>)>, ) -> Arg
Specifies multiple values and conditions in the same manner as Arg::default_value_if.
The method takes a slice of tuples in the (arg, predicate, default) format.
Like with command-line values, this will be split by Arg::value_delimiter.
NOTE: The conditions are stored in order and evaluated in the same order. I.e. the first if multiple conditions are true, the first one found will be applied and the ultimate value.
§Examples
First we use the default value only if another arg is present at runtime.
let m = Command::new("prog")
.arg(Arg::new("flag")
.long("flag")
.action(ArgAction::SetTrue))
.arg(Arg::new("opt")
.long("opt")
.action(ArgAction::Set))
.arg(Arg::new("other")
.long("other")
.default_value_ifs([
("flag", "true", Some("default")),
("opt", "channal", Some("chan")),
]))
.get_matches_from(vec![
"prog", "--opt", "channal"
]);
assert_eq!(m.get_one::<String>("other").unwrap(), "chan");Next we run the same test, but without providing --flag.
let m = Command::new("prog")
.arg(Arg::new("flag")
.long("flag")
.action(ArgAction::SetTrue))
.arg(Arg::new("other")
.long("other")
.default_value_ifs([
("flag", "true", Some("default")),
("opt", "channal", Some("chan")),
]))
.get_matches_from(vec![
"prog"
]);
assert_eq!(m.get_one::<String>("other"), None);We can also see that these values are applied in order, and if more than one condition is true, only the first evaluated “wins”
let m = Command::new("prog")
.arg(Arg::new("flag")
.long("flag")
.action(ArgAction::SetTrue))
.arg(Arg::new("opt")
.long("opt")
.action(ArgAction::Set))
.arg(Arg::new("other")
.long("other")
.default_value_ifs([
("flag", ArgPredicate::IsPresent, Some("default")),
("opt", ArgPredicate::Equals("channal".into()), Some("chan")),
]))
.get_matches_from(vec![
"prog", "--opt", "channal", "--flag"
]);
assert_eq!(m.get_one::<String>("other").unwrap(), "default");