1 #[cfg(any(target_os = "windows", target_arch = "wasm32"))]
2 use osstringext::OsStrExt3;
3 #[cfg(feature = "yaml")]
4 use std::collections::BTreeMap;
5 use std::env;
6 use std::ffi::{OsStr, OsString};
7 #[cfg(not(any(target_os = "windows", target_arch = "wasm32")))]
8 use std::os::unix::ffi::OsStrExt;
9 use std::rc::Rc;
10 
11 use map::VecMap;
12 #[cfg(feature = "yaml")]
13 use yaml_rust::Yaml;
14 
15 use args::arg_builder::{Base, Switched, Valued};
16 use args::settings::ArgSettings;
17 use usage_parser::UsageParser;
18 
19 /// The abstract representation of a command line argument. Used to set all the options and
20 /// relationships that define a valid argument for the program.
21 ///
22 /// There are two methods for constructing [`Arg`]s, using the builder pattern and setting options
23 /// manually, or using a usage string which is far less verbose but has fewer options. You can also
24 /// use a combination of the two methods to achieve the best of both worlds.
25 ///
26 /// # Examples
27 ///
28 /// ```rust
29 /// # use clap::Arg;
30 /// // Using the traditional builder pattern and setting each option manually
31 /// let cfg = Arg::with_name("config")
32 ///       .short("c")
33 ///       .long("config")
34 ///       .takes_value(true)
35 ///       .value_name("FILE")
36 ///       .help("Provides a config file to myprog");
37 /// // Using a usage string (setting a similar argument to the one above)
38 /// let input = Arg::from_usage("-i, --input=[FILE] 'Provides an input file to the program'");
39 /// ```
40 /// [`Arg`]: ./struct.Arg.html
41 #[allow(missing_debug_implementations)]
42 #[derive(Default, Clone)]
43 pub struct Arg<'a, 'b>
44 where
45     'a: 'b,
46 {
47     #[doc(hidden)]
48     pub b: Base<'a, 'b>,
49     #[doc(hidden)]
50     pub s: Switched<'b>,
51     #[doc(hidden)]
52     pub v: Valued<'a, 'b>,
53     #[doc(hidden)]
54     pub index: Option<u64>,
55     #[doc(hidden)]
56     pub r_ifs: Option<Vec<(&'a str, &'b str)>>,
57 }
58 
59 impl<'a, 'b> Arg<'a, 'b> {
60     /// Creates a new instance of [`Arg`] using a unique string name. The name will be used to get
61     /// information about whether or not the argument was used at runtime, get values, set
62     /// relationships with other args, etc..
63     ///
64     /// **NOTE:** In the case of arguments that take values (i.e. [`Arg::takes_value(true)`])
65     /// and positional arguments (i.e. those without a preceding `-` or `--`) the name will also
66     /// be displayed when the user prints the usage/help information of the program.
67     ///
68     /// # Examples
69     ///
70     /// ```rust
71     /// # use clap::{App, Arg};
72     /// Arg::with_name("config")
73     /// # ;
74     /// ```
75     /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
76     /// [`Arg`]: ./struct.Arg.html
with_name(n: &'a str) -> Self77     pub fn with_name(n: &'a str) -> Self {
78         Arg {
79             b: Base::new(n),
80             ..Default::default()
81         }
82     }
83 
84     /// Creates a new instance of [`Arg`] from a .yml (YAML) file.
85     ///
86     /// # Examples
87     ///
88     /// ```ignore
89     /// # #[macro_use]
90     /// # extern crate clap;
91     /// # use clap::Arg;
92     /// # fn main() {
93     /// let yml = load_yaml!("arg.yml");
94     /// let arg = Arg::from_yaml(yml);
95     /// # }
96     /// ```
97     /// [`Arg`]: ./struct.Arg.html
98     #[cfg(feature = "yaml")]
from_yaml(y: &BTreeMap<Yaml, Yaml>) -> Arg99     pub fn from_yaml(y: &BTreeMap<Yaml, Yaml>) -> Arg {
100         // We WANT this to panic on error...so expect() is good.
101         let name_yml = y.keys().nth(0).unwrap();
102         let name_str = name_yml.as_str().unwrap();
103         let mut a = Arg::with_name(name_str);
104         let arg_settings = y.get(name_yml).unwrap().as_hash().unwrap();
105 
106         for (k, v) in arg_settings.iter() {
107             a = match k.as_str().unwrap() {
108                 "short" => yaml_to_str!(a, v, short),
109                 "long" => yaml_to_str!(a, v, long),
110                 "aliases" => yaml_vec_or_str!(v, a, alias),
111                 "help" => yaml_to_str!(a, v, help),
112                 "long_help" => yaml_to_str!(a, v, long_help),
113                 "required" => yaml_to_bool!(a, v, required),
114                 "required_if" => yaml_tuple2!(a, v, required_if),
115                 "required_ifs" => yaml_tuple2!(a, v, required_if),
116                 "takes_value" => yaml_to_bool!(a, v, takes_value),
117                 "index" => yaml_to_u64!(a, v, index),
118                 "global" => yaml_to_bool!(a, v, global),
119                 "multiple" => yaml_to_bool!(a, v, multiple),
120                 "hidden" => yaml_to_bool!(a, v, hidden),
121                 "next_line_help" => yaml_to_bool!(a, v, next_line_help),
122                 "empty_values" => yaml_to_bool!(a, v, empty_values),
123                 "group" => yaml_to_str!(a, v, group),
124                 "number_of_values" => yaml_to_u64!(a, v, number_of_values),
125                 "max_values" => yaml_to_u64!(a, v, max_values),
126                 "min_values" => yaml_to_u64!(a, v, min_values),
127                 "value_name" => yaml_to_str!(a, v, value_name),
128                 "use_delimiter" => yaml_to_bool!(a, v, use_delimiter),
129                 "allow_hyphen_values" => yaml_to_bool!(a, v, allow_hyphen_values),
130                 "last" => yaml_to_bool!(a, v, last),
131                 "require_delimiter" => yaml_to_bool!(a, v, require_delimiter),
132                 "value_delimiter" => yaml_to_str!(a, v, value_delimiter),
133                 "required_unless" => yaml_to_str!(a, v, required_unless),
134                 "display_order" => yaml_to_usize!(a, v, display_order),
135                 "default_value" => yaml_to_str!(a, v, default_value),
136                 "default_value_if" => yaml_tuple3!(a, v, default_value_if),
137                 "default_value_ifs" => yaml_tuple3!(a, v, default_value_if),
138                 "env" => yaml_to_str!(a, v, env),
139                 "value_names" => yaml_vec_or_str!(v, a, value_name),
140                 "groups" => yaml_vec_or_str!(v, a, group),
141                 "requires" => yaml_vec_or_str!(v, a, requires),
142                 "requires_if" => yaml_tuple2!(a, v, requires_if),
143                 "requires_ifs" => yaml_tuple2!(a, v, requires_if),
144                 "conflicts_with" => yaml_vec_or_str!(v, a, conflicts_with),
145                 "overrides_with" => yaml_vec_or_str!(v, a, overrides_with),
146                 "possible_values" => yaml_vec_or_str!(v, a, possible_value),
147                 "case_insensitive" => yaml_to_bool!(a, v, case_insensitive),
148                 "required_unless_one" => yaml_vec_or_str!(v, a, required_unless),
149                 "required_unless_all" => {
150                     a = yaml_vec_or_str!(v, a, required_unless);
151                     a.setb(ArgSettings::RequiredUnlessAll);
152                     a
153                 }
154                 s => panic!(
155                     "Unknown Arg setting '{}' in YAML file for arg '{}'",
156                     s, name_str
157                 ),
158             }
159         }
160 
161         a
162     }
163 
164     /// Creates a new instance of [`Arg`] from a usage string. Allows creation of basic settings
165     /// for the [`Arg`]. The syntax is flexible, but there are some rules to follow.
166     ///
167     /// **NOTE**: Not all settings may be set using the usage string method. Some properties are
168     /// only available via the builder pattern.
169     ///
170     /// **NOTE**: Only ASCII values are officially supported in [`Arg::from_usage`] strings. Some
171     /// UTF-8 codepoints may work just fine, but this is not guaranteed.
172     ///
173     /// # Syntax
174     ///
175     /// Usage strings typically following the form:
176     ///
177     /// ```notrust
178     /// [explicit name] [short] [long] [value names] [help string]
179     /// ```
180     ///
181     /// This is not a hard rule as the attributes can appear in other orders. There are also
182     /// several additional sigils which denote additional settings. Below are the details of each
183     /// portion of the string.
184     ///
185     /// ### Explicit Name
186     ///
187     /// This is an optional field, if it's omitted the argument will use one of the additional
188     /// fields as the name using the following priority order:
189     ///
190     ///  * Explicit Name (This always takes precedence when present)
191     ///  * Long
192     ///  * Short
193     ///  * Value Name
194     ///
195     /// `clap` determines explicit names as the first string of characters between either `[]` or
196     /// `<>` where `[]` has the dual notation of meaning the argument is optional, and `<>` meaning
197     /// the argument is required.
198     ///
199     /// Explicit names may be followed by:
200     ///  * The multiple denotation `...`
201     ///
202     /// Example explicit names as follows (`ename` for an optional argument, and `rname` for a
203     /// required argument):
204     ///
205     /// ```notrust
206     /// [ename] -s, --long 'some flag'
207     /// <rname> -r, --longer 'some other flag'
208     /// ```
209     ///
210     /// ### Short
211     ///
212     /// This is set by placing a single character after a leading `-`.
213     ///
214     /// Shorts may be followed by
215     ///  * The multiple denotation `...`
216     ///  * An optional comma `,` which is cosmetic only
217     ///  * Value notation
218     ///
219     /// Example shorts are as follows (`-s`, and `-r`):
220     ///
221     /// ```notrust
222     /// -s, --long 'some flag'
223     /// <rname> -r [val], --longer 'some option'
224     /// ```
225     ///
226     /// ### Long
227     ///
228     /// This is set by placing a word (no spaces) after a leading `--`.
229     ///
230     /// Shorts may be followed by
231     ///  * The multiple denotation `...`
232     ///  * Value notation
233     ///
234     /// Example longs are as follows (`--some`, and `--rapid`):
235     ///
236     /// ```notrust
237     /// -s, --some 'some flag'
238     /// --rapid=[FILE] 'some option'
239     /// ```
240     ///
241     /// ### Values (Value Notation)
242     ///
243     /// This is set by placing a word(s) between `[]` or `<>` optionally after `=` (although this
244     /// is cosmetic only and does not affect functionality). If an explicit name has **not** been
245     /// set, using `<>` will denote a required argument, and `[]` will denote an optional argument
246     ///
247     /// Values may be followed by
248     ///  * The multiple denotation `...`
249     ///  * More Value notation
250     ///
251     /// More than one value will also implicitly set the arguments number of values, i.e. having
252     /// two values, `--option [val1] [val2]` specifies that in order for option to be satisified it
253     /// must receive exactly two values
254     ///
255     /// Example values are as follows (`FILE`, and `SPEED`):
256     ///
257     /// ```notrust
258     /// -s, --some [FILE] 'some option'
259     /// --rapid=<SPEED>... 'some required multiple option'
260     /// ```
261     ///
262     /// ### Help String
263     ///
264     /// The help string is denoted between a pair of single quotes `''` and may contain any
265     /// characters.
266     ///
267     /// Example help strings are as follows:
268     ///
269     /// ```notrust
270     /// -s, --some [FILE] 'some option'
271     /// --rapid=<SPEED>... 'some required multiple option'
272     /// ```
273     ///
274     /// ### Additional Sigils
275     ///
276     /// Multiple notation `...` (three consecutive dots/periods) specifies that this argument may
277     /// be used multiple times. Do not confuse multiple occurrences (`...`) with multiple values.
278     /// `--option val1 val2` is a single occurrence with multiple values. `--flag --flag` is
279     /// multiple occurrences (and then you can obviously have instances of both as well)
280     ///
281     /// # Examples
282     ///
283     /// ```rust
284     /// # use clap::{App, Arg};
285     /// App::new("prog")
286     ///     .args(&[
287     ///         Arg::from_usage("--config <FILE> 'a required file for the configuration and no short'"),
288     ///         Arg::from_usage("-d, --debug... 'turns on debugging information and allows multiples'"),
289     ///         Arg::from_usage("[input] 'an optional input file to use'")
290     /// ])
291     /// # ;
292     /// ```
293     /// [`Arg`]: ./struct.Arg.html
294     /// [`Arg::from_usage`]: ./struct.Arg.html#method.from_usage
from_usage(u: &'a str) -> Self295     pub fn from_usage(u: &'a str) -> Self {
296         let parser = UsageParser::from_usage(u);
297         parser.parse()
298     }
299 
300     /// Sets the short version of the argument without the preceding `-`.
301     ///
302     /// By default `clap` automatically assigns `V` and `h` to the auto-generated `version` and
303     /// `help` arguments respectively. You may use the uppercase `V` or lowercase `h` for your own
304     /// arguments, in which case `clap` simply will not assign those to the auto-generated
305     /// `version` or `help` arguments.
306     ///
307     /// **NOTE:** Any leading `-` characters will be stripped, and only the first
308     /// non `-` character will be used as the [`short`] version
309     ///
310     /// # Examples
311     ///
312     /// To set [`short`] use a single valid UTF-8 code point. If you supply a leading `-` such as
313     /// `-c`, the `-` will be stripped.
314     ///
315     /// ```rust
316     /// # use clap::{App, Arg};
317     /// Arg::with_name("config")
318     ///     .short("c")
319     /// # ;
320     /// ```
321     ///
322     /// Setting [`short`] allows using the argument via a single hyphen (`-`) such as `-c`
323     ///
324     /// ```rust
325     /// # use clap::{App, Arg};
326     /// let m = App::new("prog")
327     ///     .arg(Arg::with_name("config")
328     ///         .short("c"))
329     ///     .get_matches_from(vec![
330     ///         "prog", "-c"
331     ///     ]);
332     ///
333     /// assert!(m.is_present("config"));
334     /// ```
335     /// [`short`]: ./struct.Arg.html#method.short
short<S: AsRef<str>>(mut self, s: S) -> Self336     pub fn short<S: AsRef<str>>(mut self, s: S) -> Self {
337         self.s.short = s.as_ref().trim_left_matches(|c| c == '-').chars().nth(0);
338         self
339     }
340 
341     /// Sets the long version of the argument without the preceding `--`.
342     ///
343     /// By default `clap` automatically assigns `version` and `help` to the auto-generated
344     /// `version` and `help` arguments respectively. You may use the word `version` or `help` for
345     /// the long form of your own arguments, in which case `clap` simply will not assign those to
346     /// the auto-generated `version` or `help` arguments.
347     ///
348     /// **NOTE:** Any leading `-` characters will be stripped
349     ///
350     /// # Examples
351     ///
352     /// To set `long` use a word containing valid UTF-8 codepoints. If you supply a double leading
353     /// `--` such as `--config` they will be stripped. Hyphens in the middle of the word, however,
354     /// will *not* be stripped (i.e. `config-file` is allowed)
355     ///
356     /// ```rust
357     /// # use clap::{App, Arg};
358     /// Arg::with_name("cfg")
359     ///     .long("config")
360     /// # ;
361     /// ```
362     ///
363     /// Setting `long` allows using the argument via a double hyphen (`--`) such as `--config`
364     ///
365     /// ```rust
366     /// # use clap::{App, Arg};
367     /// let m = App::new("prog")
368     ///     .arg(Arg::with_name("cfg")
369     ///         .long("config"))
370     ///     .get_matches_from(vec![
371     ///         "prog", "--config"
372     ///     ]);
373     ///
374     /// assert!(m.is_present("cfg"));
375     /// ```
long(mut self, l: &'b str) -> Self376     pub fn long(mut self, l: &'b str) -> Self {
377         self.s.long = Some(l.trim_left_matches(|c| c == '-'));
378         self
379     }
380 
381     /// Allows adding a [`Arg`] alias, which function as "hidden" arguments that
382     /// automatically dispatch as if this argument was used. This is more efficient, and easier
383     /// than creating multiple hidden arguments as one only needs to check for the existence of
384     /// this command, and not all variants.
385     ///
386     /// # Examples
387     ///
388     /// ```rust
389     /// # use clap::{App, Arg};
390     /// let m = App::new("prog")
391     ///             .arg(Arg::with_name("test")
392     ///             .long("test")
393     ///             .alias("alias")
394     ///             .takes_value(true))
395     ///        .get_matches_from(vec![
396     ///             "prog", "--alias", "cool"
397     ///         ]);
398     /// assert!(m.is_present("test"));
399     /// assert_eq!(m.value_of("test"), Some("cool"));
400     /// ```
401     /// [`Arg`]: ./struct.Arg.html
alias<S: Into<&'b str>>(mut self, name: S) -> Self402     pub fn alias<S: Into<&'b str>>(mut self, name: S) -> Self {
403         if let Some(ref mut als) = self.s.aliases {
404             als.push((name.into(), false));
405         } else {
406             self.s.aliases = Some(vec![(name.into(), false)]);
407         }
408         self
409     }
410 
411     /// Allows adding [`Arg`] aliases, which function as "hidden" arguments that
412     /// automatically dispatch as if this argument was used. This is more efficient, and easier
413     /// than creating multiple hidden subcommands as one only needs to check for the existence of
414     /// this command, and not all variants.
415     ///
416     /// # Examples
417     ///
418     /// ```rust
419     /// # use clap::{App, Arg};
420     /// let m = App::new("prog")
421     ///             .arg(Arg::with_name("test")
422     ///                     .long("test")
423     ///                     .aliases(&["do-stuff", "do-tests", "tests"])
424     ///                     .help("the file to add")
425     ///                     .required(false))
426     ///             .get_matches_from(vec![
427     ///                 "prog", "--do-tests"
428     ///             ]);
429     /// assert!(m.is_present("test"));
430     /// ```
431     /// [`Arg`]: ./struct.Arg.html
aliases(mut self, names: &[&'b str]) -> Self432     pub fn aliases(mut self, names: &[&'b str]) -> Self {
433         if let Some(ref mut als) = self.s.aliases {
434             for n in names {
435                 als.push((n, false));
436             }
437         } else {
438             self.s.aliases = Some(names.iter().map(|n| (*n, false)).collect::<Vec<_>>());
439         }
440         self
441     }
442 
443     /// Allows adding a [`Arg`] alias that functions exactly like those defined with
444     /// [`Arg::alias`], except that they are visible inside the help message.
445     ///
446     /// # Examples
447     ///
448     /// ```rust
449     /// # use clap::{App, Arg};
450     /// let m = App::new("prog")
451     ///             .arg(Arg::with_name("test")
452     ///                 .visible_alias("something-awesome")
453     ///                 .long("test")
454     ///                 .takes_value(true))
455     ///        .get_matches_from(vec![
456     ///             "prog", "--something-awesome", "coffee"
457     ///         ]);
458     /// assert!(m.is_present("test"));
459     /// assert_eq!(m.value_of("test"), Some("coffee"));
460     /// ```
461     /// [`Arg`]: ./struct.Arg.html
462     /// [`App::alias`]: ./struct.Arg.html#method.alias
visible_alias<S: Into<&'b str>>(mut self, name: S) -> Self463     pub fn visible_alias<S: Into<&'b str>>(mut self, name: S) -> Self {
464         if let Some(ref mut als) = self.s.aliases {
465             als.push((name.into(), true));
466         } else {
467             self.s.aliases = Some(vec![(name.into(), true)]);
468         }
469         self
470     }
471 
472     /// Allows adding multiple [`Arg`] aliases that functions exactly like those defined
473     /// with [`Arg::aliases`], except that they are visible inside the help message.
474     ///
475     /// # Examples
476     ///
477     /// ```rust
478     /// # use clap::{App, Arg};
479     /// let m = App::new("prog")
480     ///             .arg(Arg::with_name("test")
481     ///                 .long("test")
482     ///                 .visible_aliases(&["something", "awesome", "cool"]))
483     ///        .get_matches_from(vec![
484     ///             "prog", "--awesome"
485     ///         ]);
486     /// assert!(m.is_present("test"));
487     /// ```
488     /// [`Arg`]: ./struct.Arg.html
489     /// [`App::aliases`]: ./struct.Arg.html#method.aliases
visible_aliases(mut self, names: &[&'b str]) -> Self490     pub fn visible_aliases(mut self, names: &[&'b str]) -> Self {
491         if let Some(ref mut als) = self.s.aliases {
492             for n in names {
493                 als.push((n, true));
494             }
495         } else {
496             self.s.aliases = Some(names.iter().map(|n| (*n, true)).collect::<Vec<_>>());
497         }
498         self
499     }
500 
501     /// Sets the short help text of the argument that will be displayed to the user when they print
502     /// the help information with `-h`. Typically, this is a short (one line) description of the
503     /// arg.
504     ///
505     /// **NOTE:** If only `Arg::help` is provided, and not [`Arg::long_help`] but the user requests
506     /// `--help` clap will still display the contents of `help` appropriately
507     ///
508     /// **NOTE:** Only `Arg::help` is used in completion script generation in order to be concise
509     ///
510     /// # Examples
511     ///
512     /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to
513     /// include a newline in the help text and have the following text be properly aligned with all
514     /// the other help text.
515     ///
516     /// ```rust
517     /// # use clap::{App, Arg};
518     /// Arg::with_name("config")
519     ///     .help("The config file used by the myprog")
520     /// # ;
521     /// ```
522     ///
523     /// Setting `help` displays a short message to the side of the argument when the user passes
524     /// `-h` or `--help` (by default).
525     ///
526     /// ```rust
527     /// # use clap::{App, Arg};
528     /// let m = App::new("prog")
529     ///     .arg(Arg::with_name("cfg")
530     ///         .long("config")
531     ///         .help("Some help text describing the --config arg"))
532     ///     .get_matches_from(vec![
533     ///         "prog", "--help"
534     ///     ]);
535     /// ```
536     ///
537     /// The above example displays
538     ///
539     /// ```notrust
540     /// helptest
541     ///
542     /// USAGE:
543     ///    helptest [FLAGS]
544     ///
545     /// FLAGS:
546     ///     --config     Some help text describing the --config arg
547     /// -h, --help       Prints help information
548     /// -V, --version    Prints version information
549     /// ```
550     /// [`Arg::long_help`]: ./struct.Arg.html#method.long_help
help(mut self, h: &'b str) -> Self551     pub fn help(mut self, h: &'b str) -> Self {
552         self.b.help = Some(h);
553         self
554     }
555 
556     /// Sets the long help text of the argument that will be displayed to the user when they print
557     /// the help information with `--help`. Typically this a more detailed (multi-line) message
558     /// that describes the arg.
559     ///
560     /// **NOTE:** If only `long_help` is provided, and not [`Arg::help`] but the user requests `-h`
561     /// clap will still display the contents of `long_help` appropriately
562     ///
563     /// **NOTE:** Only [`Arg::help`] is used in completion script generation in order to be concise
564     ///
565     /// # Examples
566     ///
567     /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to
568     /// include a newline in the help text and have the following text be properly aligned with all
569     /// the other help text.
570     ///
571     /// ```rust
572     /// # use clap::{App, Arg};
573     /// Arg::with_name("config")
574     ///     .long_help(
575     /// "The config file used by the myprog must be in JSON format
576     /// with only valid keys and may not contain other nonsense
577     /// that cannot be read by this program. Obviously I'm going on
578     /// and on, so I'll stop now.")
579     /// # ;
580     /// ```
581     ///
582     /// Setting `help` displays a short message to the side of the argument when the user passes
583     /// `-h` or `--help` (by default).
584     ///
585     /// ```rust
586     /// # use clap::{App, Arg};
587     /// let m = App::new("prog")
588     ///     .arg(Arg::with_name("cfg")
589     ///         .long("config")
590     ///         .long_help(
591     /// "The config file used by the myprog must be in JSON format
592     /// with only valid keys and may not contain other nonsense
593     /// that cannot be read by this program. Obviously I'm going on
594     /// and on, so I'll stop now."))
595     ///     .get_matches_from(vec![
596     ///         "prog", "--help"
597     ///     ]);
598     /// ```
599     ///
600     /// The above example displays
601     ///
602     /// ```notrust
603     /// helptest
604     ///
605     /// USAGE:
606     ///    helptest [FLAGS]
607     ///
608     /// FLAGS:
609     ///    --config
610     ///         The config file used by the myprog must be in JSON format
611     ///         with only valid keys and may not contain other nonsense
612     ///         that cannot be read by this program. Obviously I'm going on
613     ///         and on, so I'll stop now.
614     ///
615     /// -h, --help
616     ///         Prints help information
617     ///
618     /// -V, --version
619     ///         Prints version information
620     /// ```
621     /// [`Arg::help`]: ./struct.Arg.html#method.help
long_help(mut self, h: &'b str) -> Self622     pub fn long_help(mut self, h: &'b str) -> Self {
623         self.b.long_help = Some(h);
624         self
625     }
626 
627     /// Specifies that this arg is the last, or final, positional argument (i.e. has the highest
628     /// index) and is *only* able to be accessed via the `--` syntax (i.e. `$ prog args --
629     /// last_arg`). Even, if no other arguments are left to parse, if the user omits the `--` syntax
630     /// they will receive an [`UnknownArgument`] error. Setting an argument to `.last(true)` also
631     /// allows one to access this arg early using the `--` syntax. Accessing an arg early, even with
632     /// the `--` syntax is otherwise not possible.
633     ///
634     /// **NOTE:** This will change the usage string to look like `$ prog [FLAGS] [-- <ARG>]` if
635     /// `ARG` is marked as `.last(true)`.
636     ///
637     /// **NOTE:** This setting will imply [`AppSettings::DontCollapseArgsInUsage`] because failing
638     /// to set this can make the usage string very confusing.
639     ///
640     /// **NOTE**: This setting only applies to positional arguments, and has no affect on FLAGS /
641     /// OPTIONS
642     ///
643     /// **CAUTION:** Setting an argument to `.last(true)` *and* having child subcommands is not
644     /// recommended with the exception of *also* using [`AppSettings::ArgsNegateSubcommands`]
645     /// (or [`AppSettings::SubcommandsNegateReqs`] if the argument marked `.last(true)` is also
646     /// marked [`.required(true)`])
647     ///
648     /// # Examples
649     ///
650     /// ```rust
651     /// # use clap::Arg;
652     /// Arg::with_name("args")
653     ///     .last(true)
654     /// # ;
655     /// ```
656     ///
657     /// Setting [`Arg::last(true)`] ensures the arg has the highest [index] of all positional args
658     /// and requires that the `--` syntax be used to access it early.
659     ///
660     /// ```rust
661     /// # use clap::{App, Arg};
662     /// let res = App::new("prog")
663     ///     .arg(Arg::with_name("first"))
664     ///     .arg(Arg::with_name("second"))
665     ///     .arg(Arg::with_name("third").last(true))
666     ///     .get_matches_from_safe(vec![
667     ///         "prog", "one", "--", "three"
668     ///     ]);
669     ///
670     /// assert!(res.is_ok());
671     /// let m = res.unwrap();
672     /// assert_eq!(m.value_of("third"), Some("three"));
673     /// assert!(m.value_of("second").is_none());
674     /// ```
675     ///
676     /// Even if the positional argument marked `.last(true)` is the only argument left to parse,
677     /// failing to use the `--` syntax results in an error.
678     ///
679     /// ```rust
680     /// # use clap::{App, Arg, ErrorKind};
681     /// let res = App::new("prog")
682     ///     .arg(Arg::with_name("first"))
683     ///     .arg(Arg::with_name("second"))
684     ///     .arg(Arg::with_name("third").last(true))
685     ///     .get_matches_from_safe(vec![
686     ///         "prog", "one", "two", "three"
687     ///     ]);
688     ///
689     /// assert!(res.is_err());
690     /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
691     /// ```
692     /// [`Arg::last(true)`]: ./struct.Arg.html#method.last
693     /// [index]: ./struct.Arg.html#method.index
694     /// [`AppSettings::DontCollapseArgsInUsage`]: ./enum.AppSettings.html#variant.DontCollapseArgsInUsage
695     /// [`AppSettings::ArgsNegateSubcommands`]: ./enum.AppSettings.html#variant.ArgsNegateSubcommands
696     /// [`AppSettings::SubcommandsNegateReqs`]: ./enum.AppSettings.html#variant.SubcommandsNegateReqs
697     /// [`.required(true)`]: ./struct.Arg.html#method.required
698     /// [`UnknownArgument`]: ./enum.ErrorKind.html#variant.UnknownArgument
last(self, l: bool) -> Self699     pub fn last(self, l: bool) -> Self {
700         if l {
701             self.set(ArgSettings::Last)
702         } else {
703             self.unset(ArgSettings::Last)
704         }
705     }
706 
707     /// Sets whether or not the argument is required by default. Required by default means it is
708     /// required, when no other conflicting rules have been evaluated. Conflicting rules take
709     /// precedence over being required. **Default:** `false`
710     ///
711     /// **NOTE:** Flags (i.e. not positional, or arguments that take values) cannot be required by
712     /// default. This is simply because if a flag should be required, it should simply be implied
713     /// as no additional information is required from user. Flags by their very nature are simply
714     /// yes/no, or true/false.
715     ///
716     /// # Examples
717     ///
718     /// ```rust
719     /// # use clap::Arg;
720     /// Arg::with_name("config")
721     ///     .required(true)
722     /// # ;
723     /// ```
724     ///
725     /// Setting [`Arg::required(true)`] requires that the argument be used at runtime.
726     ///
727     /// ```rust
728     /// # use clap::{App, Arg};
729     /// let res = App::new("prog")
730     ///     .arg(Arg::with_name("cfg")
731     ///         .required(true)
732     ///         .takes_value(true)
733     ///         .long("config"))
734     ///     .get_matches_from_safe(vec![
735     ///         "prog", "--config", "file.conf"
736     ///     ]);
737     ///
738     /// assert!(res.is_ok());
739     /// ```
740     ///
741     /// Setting [`Arg::required(true)`] and *not* supplying that argument is an error.
742     ///
743     /// ```rust
744     /// # use clap::{App, Arg, ErrorKind};
745     /// let res = App::new("prog")
746     ///     .arg(Arg::with_name("cfg")
747     ///         .required(true)
748     ///         .takes_value(true)
749     ///         .long("config"))
750     ///     .get_matches_from_safe(vec![
751     ///         "prog"
752     ///     ]);
753     ///
754     /// assert!(res.is_err());
755     /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
756     /// ```
757     /// [`Arg::required(true)`]: ./struct.Arg.html#method.required
required(self, r: bool) -> Self758     pub fn required(self, r: bool) -> Self {
759         if r {
760             self.set(ArgSettings::Required)
761         } else {
762             self.unset(ArgSettings::Required)
763         }
764     }
765 
766     /// Requires that options use the `--option=val` syntax (i.e. an equals between the option and
767     /// associated value) **Default:** `false`
768     ///
769     /// **NOTE:** This setting also removes the default of allowing empty values and implies
770     /// [`Arg::empty_values(false)`].
771     ///
772     /// # Examples
773     ///
774     /// ```rust
775     /// # use clap::Arg;
776     /// Arg::with_name("config")
777     ///     .long("config")
778     ///     .takes_value(true)
779     ///     .require_equals(true)
780     /// # ;
781     /// ```
782     ///
783     /// Setting [`Arg::require_equals(true)`] requires that the option have an equals sign between
784     /// it and the associated value.
785     ///
786     /// ```rust
787     /// # use clap::{App, Arg};
788     /// let res = App::new("prog")
789     ///     .arg(Arg::with_name("cfg")
790     ///         .require_equals(true)
791     ///         .takes_value(true)
792     ///         .long("config"))
793     ///     .get_matches_from_safe(vec![
794     ///         "prog", "--config=file.conf"
795     ///     ]);
796     ///
797     /// assert!(res.is_ok());
798     /// ```
799     ///
800     /// Setting [`Arg::require_equals(true)`] and *not* supplying the equals will cause an error
801     /// unless [`Arg::empty_values(true)`] is set.
802     ///
803     /// ```rust
804     /// # use clap::{App, Arg, ErrorKind};
805     /// let res = App::new("prog")
806     ///     .arg(Arg::with_name("cfg")
807     ///         .require_equals(true)
808     ///         .takes_value(true)
809     ///         .long("config"))
810     ///     .get_matches_from_safe(vec![
811     ///         "prog", "--config", "file.conf"
812     ///     ]);
813     ///
814     /// assert!(res.is_err());
815     /// assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue);
816     /// ```
817     /// [`Arg::require_equals(true)`]: ./struct.Arg.html#method.require_equals
818     /// [`Arg::empty_values(true)`]: ./struct.Arg.html#method.empty_values
819     /// [`Arg::empty_values(false)`]: ./struct.Arg.html#method.empty_values
require_equals(mut self, r: bool) -> Self820     pub fn require_equals(mut self, r: bool) -> Self {
821         if r {
822             self.unsetb(ArgSettings::EmptyValues);
823             self.set(ArgSettings::RequireEquals)
824         } else {
825             self.unset(ArgSettings::RequireEquals)
826         }
827     }
828 
829     /// Allows values which start with a leading hyphen (`-`)
830     ///
831     /// **WARNING**: Take caution when using this setting combined with [`Arg::multiple(true)`], as
832     /// this becomes ambiguous `$ prog --arg -- -- val`. All three `--, --, val` will be values
833     /// when the user may have thought the second `--` would constitute the normal, "Only
834     /// positional args follow" idiom. To fix this, consider using [`Arg::number_of_values(1)`]
835     ///
836     /// **WARNING**: When building your CLIs, consider the effects of allowing leading hyphens and
837     /// the user passing in a value that matches a valid short. For example `prog -opt -F` where
838     /// `-F` is supposed to be a value, yet `-F` is *also* a valid short for another arg. Care should
839     /// should be taken when designing these args. This is compounded by the ability to "stack"
840     /// short args. I.e. if `-val` is supposed to be a value, but `-v`, `-a`, and `-l` are all valid
841     /// shorts.
842     ///
843     /// # Examples
844     ///
845     /// ```rust
846     /// # use clap::Arg;
847     /// Arg::with_name("pattern")
848     ///     .allow_hyphen_values(true)
849     /// # ;
850     /// ```
851     ///
852     /// ```rust
853     /// # use clap::{App, Arg};
854     /// let m = App::new("prog")
855     ///     .arg(Arg::with_name("pat")
856     ///         .allow_hyphen_values(true)
857     ///         .takes_value(true)
858     ///         .long("pattern"))
859     ///     .get_matches_from(vec![
860     ///         "prog", "--pattern", "-file"
861     ///     ]);
862     ///
863     /// assert_eq!(m.value_of("pat"), Some("-file"));
864     /// ```
865     ///
866     /// Not setting [`Arg::allow_hyphen_values(true)`] and supplying a value which starts with a
867     /// hyphen is an error.
868     ///
869     /// ```rust
870     /// # use clap::{App, Arg, ErrorKind};
871     /// let res = App::new("prog")
872     ///     .arg(Arg::with_name("pat")
873     ///         .takes_value(true)
874     ///         .long("pattern"))
875     ///     .get_matches_from_safe(vec![
876     ///         "prog", "--pattern", "-file"
877     ///     ]);
878     ///
879     /// assert!(res.is_err());
880     /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
881     /// ```
882     /// [`Arg::allow_hyphen_values(true)`]: ./struct.Arg.html#method.allow_hyphen_values
883     /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
884     /// [`Arg::number_of_values(1)`]: ./struct.Arg.html#method.number_of_values
allow_hyphen_values(self, a: bool) -> Self885     pub fn allow_hyphen_values(self, a: bool) -> Self {
886         if a {
887             self.set(ArgSettings::AllowLeadingHyphen)
888         } else {
889             self.unset(ArgSettings::AllowLeadingHyphen)
890         }
891     }
892     /// Sets an arg that override this arg's required setting. (i.e. this arg will be required
893     /// unless this other argument is present).
894     ///
895     /// **Pro Tip:** Using [`Arg::required_unless`] implies [`Arg::required`] and is therefore not
896     /// mandatory to also set.
897     ///
898     /// # Examples
899     ///
900     /// ```rust
901     /// # use clap::Arg;
902     /// Arg::with_name("config")
903     ///     .required_unless("debug")
904     /// # ;
905     /// ```
906     ///
907     /// Setting [`Arg::required_unless(name)`] requires that the argument be used at runtime
908     /// *unless* `name` is present. In the following example, the required argument is *not*
909     /// provided, but it's not an error because the `unless` arg has been supplied.
910     ///
911     /// ```rust
912     /// # use clap::{App, Arg};
913     /// let res = App::new("prog")
914     ///     .arg(Arg::with_name("cfg")
915     ///         .required_unless("dbg")
916     ///         .takes_value(true)
917     ///         .long("config"))
918     ///     .arg(Arg::with_name("dbg")
919     ///         .long("debug"))
920     ///     .get_matches_from_safe(vec![
921     ///         "prog", "--debug"
922     ///     ]);
923     ///
924     /// assert!(res.is_ok());
925     /// ```
926     ///
927     /// Setting [`Arg::required_unless(name)`] and *not* supplying `name` or this arg is an error.
928     ///
929     /// ```rust
930     /// # use clap::{App, Arg, ErrorKind};
931     /// let res = App::new("prog")
932     ///     .arg(Arg::with_name("cfg")
933     ///         .required_unless("dbg")
934     ///         .takes_value(true)
935     ///         .long("config"))
936     ///     .arg(Arg::with_name("dbg")
937     ///         .long("debug"))
938     ///     .get_matches_from_safe(vec![
939     ///         "prog"
940     ///     ]);
941     ///
942     /// assert!(res.is_err());
943     /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
944     /// ```
945     /// [`Arg::required_unless`]: ./struct.Arg.html#method.required_unless
946     /// [`Arg::required`]: ./struct.Arg.html#method.required
947     /// [`Arg::required_unless(name)`]: ./struct.Arg.html#method.required_unless
required_unless(mut self, name: &'a str) -> Self948     pub fn required_unless(mut self, name: &'a str) -> Self {
949         if let Some(ref mut vec) = self.b.r_unless {
950             vec.push(name);
951         } else {
952             self.b.r_unless = Some(vec![name]);
953         }
954         self.required(true)
955     }
956 
957     /// Sets args that override this arg's required setting. (i.e. this arg will be required unless
958     /// all these other arguments are present).
959     ///
960     /// **NOTE:** If you wish for this argument to only be required if *one of* these args are
961     /// present see [`Arg::required_unless_one`]
962     ///
963     /// # Examples
964     ///
965     /// ```rust
966     /// # use clap::Arg;
967     /// Arg::with_name("config")
968     ///     .required_unless_all(&["cfg", "dbg"])
969     /// # ;
970     /// ```
971     ///
972     /// Setting [`Arg::required_unless_all(names)`] requires that the argument be used at runtime
973     /// *unless* *all* the args in `names` are present. In the following example, the required
974     /// argument is *not* provided, but it's not an error because all the `unless` args have been
975     /// supplied.
976     ///
977     /// ```rust
978     /// # use clap::{App, Arg};
979     /// let res = App::new("prog")
980     ///     .arg(Arg::with_name("cfg")
981     ///         .required_unless_all(&["dbg", "infile"])
982     ///         .takes_value(true)
983     ///         .long("config"))
984     ///     .arg(Arg::with_name("dbg")
985     ///         .long("debug"))
986     ///     .arg(Arg::with_name("infile")
987     ///         .short("i")
988     ///         .takes_value(true))
989     ///     .get_matches_from_safe(vec![
990     ///         "prog", "--debug", "-i", "file"
991     ///     ]);
992     ///
993     /// assert!(res.is_ok());
994     /// ```
995     ///
996     /// Setting [`Arg::required_unless_all(names)`] and *not* supplying *all* of `names` or this
997     /// arg is an error.
998     ///
999     /// ```rust
1000     /// # use clap::{App, Arg, ErrorKind};
1001     /// let res = App::new("prog")
1002     ///     .arg(Arg::with_name("cfg")
1003     ///         .required_unless_all(&["dbg", "infile"])
1004     ///         .takes_value(true)
1005     ///         .long("config"))
1006     ///     .arg(Arg::with_name("dbg")
1007     ///         .long("debug"))
1008     ///     .arg(Arg::with_name("infile")
1009     ///         .short("i")
1010     ///         .takes_value(true))
1011     ///     .get_matches_from_safe(vec![
1012     ///         "prog"
1013     ///     ]);
1014     ///
1015     /// assert!(res.is_err());
1016     /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
1017     /// ```
1018     /// [`Arg::required_unless_one`]: ./struct.Arg.html#method.required_unless_one
1019     /// [`Arg::required_unless_all(names)`]: ./struct.Arg.html#method.required_unless_all
required_unless_all(mut self, names: &[&'a str]) -> Self1020     pub fn required_unless_all(mut self, names: &[&'a str]) -> Self {
1021         if let Some(ref mut vec) = self.b.r_unless {
1022             for s in names {
1023                 vec.push(s);
1024             }
1025         } else {
1026             self.b.r_unless = Some(names.iter().map(|s| *s).collect::<Vec<_>>());
1027         }
1028         self.setb(ArgSettings::RequiredUnlessAll);
1029         self.required(true)
1030     }
1031 
1032     /// Sets args that override this arg's [required] setting. (i.e. this arg will be required
1033     /// unless *at least one of* these other arguments are present).
1034     ///
1035     /// **NOTE:** If you wish for this argument to only be required if *all of* these args are
1036     /// present see [`Arg::required_unless_all`]
1037     ///
1038     /// # Examples
1039     ///
1040     /// ```rust
1041     /// # use clap::Arg;
1042     /// Arg::with_name("config")
1043     ///     .required_unless_all(&["cfg", "dbg"])
1044     /// # ;
1045     /// ```
1046     ///
1047     /// Setting [`Arg::required_unless_one(names)`] requires that the argument be used at runtime
1048     /// *unless* *at least one of* the args in `names` are present. In the following example, the
1049     /// required argument is *not* provided, but it's not an error because one the `unless` args
1050     /// have been supplied.
1051     ///
1052     /// ```rust
1053     /// # use clap::{App, Arg};
1054     /// let res = App::new("prog")
1055     ///     .arg(Arg::with_name("cfg")
1056     ///         .required_unless_one(&["dbg", "infile"])
1057     ///         .takes_value(true)
1058     ///         .long("config"))
1059     ///     .arg(Arg::with_name("dbg")
1060     ///         .long("debug"))
1061     ///     .arg(Arg::with_name("infile")
1062     ///         .short("i")
1063     ///         .takes_value(true))
1064     ///     .get_matches_from_safe(vec![
1065     ///         "prog", "--debug"
1066     ///     ]);
1067     ///
1068     /// assert!(res.is_ok());
1069     /// ```
1070     ///
1071     /// Setting [`Arg::required_unless_one(names)`] and *not* supplying *at least one of* `names`
1072     /// or this arg is an error.
1073     ///
1074     /// ```rust
1075     /// # use clap::{App, Arg, ErrorKind};
1076     /// let res = App::new("prog")
1077     ///     .arg(Arg::with_name("cfg")
1078     ///         .required_unless_one(&["dbg", "infile"])
1079     ///         .takes_value(true)
1080     ///         .long("config"))
1081     ///     .arg(Arg::with_name("dbg")
1082     ///         .long("debug"))
1083     ///     .arg(Arg::with_name("infile")
1084     ///         .short("i")
1085     ///         .takes_value(true))
1086     ///     .get_matches_from_safe(vec![
1087     ///         "prog"
1088     ///     ]);
1089     ///
1090     /// assert!(res.is_err());
1091     /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
1092     /// ```
1093     /// [required]: ./struct.Arg.html#method.required
1094     /// [`Arg::required_unless_one(names)`]: ./struct.Arg.html#method.required_unless_one
1095     /// [`Arg::required_unless_all`]: ./struct.Arg.html#method.required_unless_all
required_unless_one(mut self, names: &[&'a str]) -> Self1096     pub fn required_unless_one(mut self, names: &[&'a str]) -> Self {
1097         if let Some(ref mut vec) = self.b.r_unless {
1098             for s in names {
1099                 vec.push(s);
1100             }
1101         } else {
1102             self.b.r_unless = Some(names.iter().map(|s| *s).collect::<Vec<_>>());
1103         }
1104         self.required(true)
1105     }
1106 
1107     /// Sets a conflicting argument by name. I.e. when using this argument,
1108     /// the following argument can't be present and vice versa.
1109     ///
1110     /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules
1111     /// only need to be set for one of the two arguments, they do not need to be set for each.
1112     ///
1113     /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments
1114     /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need
1115     /// need to also do B.conflicts_with(A))
1116     ///
1117     /// # Examples
1118     ///
1119     /// ```rust
1120     /// # use clap::Arg;
1121     /// Arg::with_name("config")
1122     ///     .conflicts_with("debug")
1123     /// # ;
1124     /// ```
1125     ///
1126     /// Setting conflicting argument, and having both arguments present at runtime is an error.
1127     ///
1128     /// ```rust
1129     /// # use clap::{App, Arg, ErrorKind};
1130     /// let res = App::new("prog")
1131     ///     .arg(Arg::with_name("cfg")
1132     ///         .takes_value(true)
1133     ///         .conflicts_with("debug")
1134     ///         .long("config"))
1135     ///     .arg(Arg::with_name("debug")
1136     ///         .long("debug"))
1137     ///     .get_matches_from_safe(vec![
1138     ///         "prog", "--debug", "--config", "file.conf"
1139     ///     ]);
1140     ///
1141     /// assert!(res.is_err());
1142     /// assert_eq!(res.unwrap_err().kind, ErrorKind::ArgumentConflict);
1143     /// ```
conflicts_with(mut self, name: &'a str) -> Self1144     pub fn conflicts_with(mut self, name: &'a str) -> Self {
1145         if let Some(ref mut vec) = self.b.blacklist {
1146             vec.push(name);
1147         } else {
1148             self.b.blacklist = Some(vec![name]);
1149         }
1150         self
1151     }
1152 
1153     /// The same as [`Arg::conflicts_with`] but allows specifying multiple two-way conlicts per
1154     /// argument.
1155     ///
1156     /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules
1157     /// only need to be set for one of the two arguments, they do not need to be set for each.
1158     ///
1159     /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments
1160     /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need
1161     /// need to also do B.conflicts_with(A))
1162     ///
1163     /// # Examples
1164     ///
1165     /// ```rust
1166     /// # use clap::Arg;
1167     /// Arg::with_name("config")
1168     ///     .conflicts_with_all(&["debug", "input"])
1169     /// # ;
1170     /// ```
1171     ///
1172     /// Setting conflicting argument, and having any of the arguments present at runtime with a
1173     /// conflicting argument is an error.
1174     ///
1175     /// ```rust
1176     /// # use clap::{App, Arg, ErrorKind};
1177     /// let res = App::new("prog")
1178     ///     .arg(Arg::with_name("cfg")
1179     ///         .takes_value(true)
1180     ///         .conflicts_with_all(&["debug", "input"])
1181     ///         .long("config"))
1182     ///     .arg(Arg::with_name("debug")
1183     ///         .long("debug"))
1184     ///     .arg(Arg::with_name("input")
1185     ///         .index(1))
1186     ///     .get_matches_from_safe(vec![
1187     ///         "prog", "--config", "file.conf", "file.txt"
1188     ///     ]);
1189     ///
1190     /// assert!(res.is_err());
1191     /// assert_eq!(res.unwrap_err().kind, ErrorKind::ArgumentConflict);
1192     /// ```
1193     /// [`Arg::conflicts_with`]: ./struct.Arg.html#method.conflicts_with
conflicts_with_all(mut self, names: &[&'a str]) -> Self1194     pub fn conflicts_with_all(mut self, names: &[&'a str]) -> Self {
1195         if let Some(ref mut vec) = self.b.blacklist {
1196             for s in names {
1197                 vec.push(s);
1198             }
1199         } else {
1200             self.b.blacklist = Some(names.iter().map(|s| *s).collect::<Vec<_>>());
1201         }
1202         self
1203     }
1204 
1205     /// Sets a overridable argument by name. I.e. this argument and the following argument
1206     /// will override each other in POSIX style (whichever argument was specified at runtime
1207     /// **last** "wins")
1208     ///
1209     /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any
1210     /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed
1211     ///
1212     /// **WARNING:** Positional arguments cannot override themselves (or we would never be able
1213     /// to advance to the next positional). If a positional agument lists itself as an override,
1214     /// it is simply ignored.
1215     ///
1216     /// # Examples
1217     ///
1218     /// ```rust
1219     /// # use clap::{App, Arg};
1220     /// let m = App::new("prog")
1221     ///     .arg(Arg::from_usage("-f, --flag 'some flag'")
1222     ///         .conflicts_with("debug"))
1223     ///     .arg(Arg::from_usage("-d, --debug 'other flag'"))
1224     ///     .arg(Arg::from_usage("-c, --color 'third flag'")
1225     ///         .overrides_with("flag"))
1226     ///     .get_matches_from(vec![
1227     ///         "prog", "-f", "-d", "-c"]);
1228     ///             //    ^~~~~~~~~~~~^~~~~ flag is overridden by color
1229     ///
1230     /// assert!(m.is_present("color"));
1231     /// assert!(m.is_present("debug")); // even though flag conflicts with debug, it's as if flag
1232     ///                                 // was never used because it was overridden with color
1233     /// assert!(!m.is_present("flag"));
1234     /// ```
1235     /// Care must be taken when using this setting, and having an arg override with itself. This
1236     /// is common practice when supporting things like shell aliases, config files, etc.
1237     /// However, when combined with multiple values, it can get dicy.
1238     /// Here is how clap handles such situations:
1239     ///
1240     /// When a flag overrides itself, it's as if the flag was only ever used once (essentially
1241     /// preventing a "Unexpected multiple usage" error):
1242     ///
1243     /// ```rust
1244     /// # use clap::{App, Arg};
1245     /// let m = App::new("posix")
1246     ///             .arg(Arg::from_usage("--flag  'some flag'").overrides_with("flag"))
1247     ///             .get_matches_from(vec!["posix", "--flag", "--flag"]);
1248     /// assert!(m.is_present("flag"));
1249     /// assert_eq!(m.occurrences_of("flag"), 1);
1250     /// ```
1251     /// Making a arg `multiple(true)` and override itself is essentially meaningless. Therefore
1252     /// clap ignores an override of self if it's a flag and it already accepts multiple occurrences.
1253     ///
1254     /// ```
1255     /// # use clap::{App, Arg};
1256     /// let m = App::new("posix")
1257     ///             .arg(Arg::from_usage("--flag...  'some flag'").overrides_with("flag"))
1258     ///             .get_matches_from(vec!["", "--flag", "--flag", "--flag", "--flag"]);
1259     /// assert!(m.is_present("flag"));
1260     /// assert_eq!(m.occurrences_of("flag"), 4);
1261     /// ```
1262     /// Now notice with options (which *do not* set `multiple(true)`), it's as if only the last
1263     /// occurrence happened.
1264     ///
1265     /// ```
1266     /// # use clap::{App, Arg};
1267     /// let m = App::new("posix")
1268     ///             .arg(Arg::from_usage("--opt [val] 'some option'").overrides_with("opt"))
1269     ///             .get_matches_from(vec!["", "--opt=some", "--opt=other"]);
1270     /// assert!(m.is_present("opt"));
1271     /// assert_eq!(m.occurrences_of("opt"), 1);
1272     /// assert_eq!(m.value_of("opt"), Some("other"));
1273     /// ```
1274     ///
1275     /// Just like flags, options with `multiple(true)` set, will ignore the "override self" setting.
1276     ///
1277     /// ```
1278     /// # use clap::{App, Arg};
1279     /// let m = App::new("posix")
1280     ///             .arg(Arg::from_usage("--opt [val]... 'some option'")
1281     ///                 .overrides_with("opt"))
1282     ///             .get_matches_from(vec!["", "--opt", "first", "over", "--opt", "other", "val"]);
1283     /// assert!(m.is_present("opt"));
1284     /// assert_eq!(m.occurrences_of("opt"), 2);
1285     /// assert_eq!(m.values_of("opt").unwrap().collect::<Vec<_>>(), &["first", "over", "other", "val"]);
1286     /// ```
1287     ///
1288     /// A safe thing to do if you'd like to support an option which supports multiple values, but
1289     /// also is "overridable" by itself, is to use `use_delimiter(false)` and *not* use
1290     /// `multiple(true)` while telling users to seperate values with a comma (i.e. `val1,val2`)
1291     ///
1292     /// ```
1293     /// # use clap::{App, Arg};
1294     /// let m = App::new("posix")
1295     ///             .arg(Arg::from_usage("--opt [val] 'some option'")
1296     ///                 .overrides_with("opt")
1297     ///                 .use_delimiter(false))
1298     ///             .get_matches_from(vec!["", "--opt=some,other", "--opt=one,two"]);
1299     /// assert!(m.is_present("opt"));
1300     /// assert_eq!(m.occurrences_of("opt"), 1);
1301     /// assert_eq!(m.values_of("opt").unwrap().collect::<Vec<_>>(), &["one,two"]);
1302     /// ```
overrides_with(mut self, name: &'a str) -> Self1303     pub fn overrides_with(mut self, name: &'a str) -> Self {
1304         if let Some(ref mut vec) = self.b.overrides {
1305             vec.push(name);
1306         } else {
1307             self.b.overrides = Some(vec![name]);
1308         }
1309         self
1310     }
1311 
1312     /// Sets multiple mutually overridable arguments by name. I.e. this argument and the following
1313     /// argument will override each other in POSIX style (whichever argument was specified at
1314     /// runtime **last** "wins")
1315     ///
1316     /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any
1317     /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed
1318     ///
1319     /// # Examples
1320     ///
1321     /// ```rust
1322     /// # use clap::{App, Arg};
1323     /// let m = App::new("prog")
1324     ///     .arg(Arg::from_usage("-f, --flag 'some flag'")
1325     ///         .conflicts_with("color"))
1326     ///     .arg(Arg::from_usage("-d, --debug 'other flag'"))
1327     ///     .arg(Arg::from_usage("-c, --color 'third flag'")
1328     ///         .overrides_with_all(&["flag", "debug"]))
1329     ///     .get_matches_from(vec![
1330     ///         "prog", "-f", "-d", "-c"]);
1331     ///             //    ^~~~~~^~~~~~~~~ flag and debug are overridden by color
1332     ///
1333     /// assert!(m.is_present("color")); // even though flag conflicts with color, it's as if flag
1334     ///                                 // and debug were never used because they were overridden
1335     ///                                 // with color
1336     /// assert!(!m.is_present("debug"));
1337     /// assert!(!m.is_present("flag"));
1338     /// ```
overrides_with_all(mut self, names: &[&'a str]) -> Self1339     pub fn overrides_with_all(mut self, names: &[&'a str]) -> Self {
1340         if let Some(ref mut vec) = self.b.overrides {
1341             for s in names {
1342                 vec.push(s);
1343             }
1344         } else {
1345             self.b.overrides = Some(names.iter().map(|s| *s).collect::<Vec<_>>());
1346         }
1347         self
1348     }
1349 
1350     /// Sets an argument by name that is required when this one is present I.e. when
1351     /// using this argument, the following argument *must* be present.
1352     ///
1353     /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required
1354     ///
1355     /// # Examples
1356     ///
1357     /// ```rust
1358     /// # use clap::Arg;
1359     /// Arg::with_name("config")
1360     ///     .requires("input")
1361     /// # ;
1362     /// ```
1363     ///
1364     /// Setting [`Arg::requires(name)`] requires that the argument be used at runtime if the
1365     /// defining argument is used. If the defining argument isn't used, the other argument isn't
1366     /// required
1367     ///
1368     /// ```rust
1369     /// # use clap::{App, Arg};
1370     /// let res = App::new("prog")
1371     ///     .arg(Arg::with_name("cfg")
1372     ///         .takes_value(true)
1373     ///         .requires("input")
1374     ///         .long("config"))
1375     ///     .arg(Arg::with_name("input")
1376     ///         .index(1))
1377     ///     .get_matches_from_safe(vec![
1378     ///         "prog"
1379     ///     ]);
1380     ///
1381     /// assert!(res.is_ok()); // We didn't use cfg, so input wasn't required
1382     /// ```
1383     ///
1384     /// Setting [`Arg::requires(name)`] and *not* supplying that argument is an error.
1385     ///
1386     /// ```rust
1387     /// # use clap::{App, Arg, ErrorKind};
1388     /// let res = App::new("prog")
1389     ///     .arg(Arg::with_name("cfg")
1390     ///         .takes_value(true)
1391     ///         .requires("input")
1392     ///         .long("config"))
1393     ///     .arg(Arg::with_name("input")
1394     ///         .index(1))
1395     ///     .get_matches_from_safe(vec![
1396     ///         "prog", "--config", "file.conf"
1397     ///     ]);
1398     ///
1399     /// assert!(res.is_err());
1400     /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
1401     /// ```
1402     /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires
1403     /// [Conflicting]: ./struct.Arg.html#method.conflicts_with
1404     /// [override]: ./struct.Arg.html#method.overrides_with
requires(mut self, name: &'a str) -> Self1405     pub fn requires(mut self, name: &'a str) -> Self {
1406         if let Some(ref mut vec) = self.b.requires {
1407             vec.push((None, name));
1408         } else {
1409             let mut vec = vec![];
1410             vec.push((None, name));
1411             self.b.requires = Some(vec);
1412         }
1413         self
1414     }
1415 
1416     /// Allows a conditional requirement. The requirement will only become valid if this arg's value
1417     /// equals `val`.
1418     ///
1419     /// **NOTE:** If using YAML the values should be laid out as follows
1420     ///
1421     /// ```yaml
1422     /// requires_if:
1423     ///     - [val, arg]
1424     /// ```
1425     ///
1426     /// # Examples
1427     ///
1428     /// ```rust
1429     /// # use clap::Arg;
1430     /// Arg::with_name("config")
1431     ///     .requires_if("val", "arg")
1432     /// # ;
1433     /// ```
1434     ///
1435     /// Setting [`Arg::requires_if(val, arg)`] requires that the `arg` be used at runtime if the
1436     /// defining argument's value is equal to `val`. If the defining argument is anything other than
1437     /// `val`, the other argument isn't required.
1438     ///
1439     /// ```rust
1440     /// # use clap::{App, Arg};
1441     /// let res = App::new("prog")
1442     ///     .arg(Arg::with_name("cfg")
1443     ///         .takes_value(true)
1444     ///         .requires_if("my.cfg", "other")
1445     ///         .long("config"))
1446     ///     .arg(Arg::with_name("other"))
1447     ///     .get_matches_from_safe(vec![
1448     ///         "prog", "--config", "some.cfg"
1449     ///     ]);
1450     ///
1451     /// assert!(res.is_ok()); // We didn't use --config=my.cfg, so other wasn't required
1452     /// ```
1453     ///
1454     /// Setting [`Arg::requires_if(val, arg)`] and setting the value to `val` but *not* supplying
1455     /// `arg` is an error.
1456     ///
1457     /// ```rust
1458     /// # use clap::{App, Arg, ErrorKind};
1459     /// let res = App::new("prog")
1460     ///     .arg(Arg::with_name("cfg")
1461     ///         .takes_value(true)
1462     ///         .requires_if("my.cfg", "input")
1463     ///         .long("config"))
1464     ///     .arg(Arg::with_name("input"))
1465     ///     .get_matches_from_safe(vec![
1466     ///         "prog", "--config", "my.cfg"
1467     ///     ]);
1468     ///
1469     /// assert!(res.is_err());
1470     /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
1471     /// ```
1472     /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires
1473     /// [Conflicting]: ./struct.Arg.html#method.conflicts_with
1474     /// [override]: ./struct.Arg.html#method.overrides_with
requires_if(mut self, val: &'b str, arg: &'a str) -> Self1475     pub fn requires_if(mut self, val: &'b str, arg: &'a str) -> Self {
1476         if let Some(ref mut vec) = self.b.requires {
1477             vec.push((Some(val), arg));
1478         } else {
1479             self.b.requires = Some(vec![(Some(val), arg)]);
1480         }
1481         self
1482     }
1483 
1484     /// Allows multiple conditional requirements. The requirement will only become valid if this arg's value
1485     /// equals `val`.
1486     ///
1487     /// **NOTE:** If using YAML the values should be laid out as follows
1488     ///
1489     /// ```yaml
1490     /// requires_if:
1491     ///     - [val, arg]
1492     ///     - [val2, arg2]
1493     /// ```
1494     ///
1495     /// # Examples
1496     ///
1497     /// ```rust
1498     /// # use clap::Arg;
1499     /// Arg::with_name("config")
1500     ///     .requires_ifs(&[
1501     ///         ("val", "arg"),
1502     ///         ("other_val", "arg2"),
1503     ///     ])
1504     /// # ;
1505     /// ```
1506     ///
1507     /// Setting [`Arg::requires_ifs(&["val", "arg"])`] requires that the `arg` be used at runtime if the
1508     /// defining argument's value is equal to `val`. If the defining argument's value is anything other
1509     /// than `val`, `arg` isn't required.
1510     ///
1511     /// ```rust
1512     /// # use clap::{App, Arg, ErrorKind};
1513     /// let res = App::new("prog")
1514     ///     .arg(Arg::with_name("cfg")
1515     ///         .takes_value(true)
1516     ///         .requires_ifs(&[
1517     ///             ("special.conf", "opt"),
1518     ///             ("other.conf", "other"),
1519     ///         ])
1520     ///         .long("config"))
1521     ///     .arg(Arg::with_name("opt")
1522     ///         .long("option")
1523     ///         .takes_value(true))
1524     ///     .arg(Arg::with_name("other"))
1525     ///     .get_matches_from_safe(vec![
1526     ///         "prog", "--config", "special.conf"
1527     ///     ]);
1528     ///
1529     /// assert!(res.is_err()); // We  used --config=special.conf so --option <val> is required
1530     /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
1531     /// ```
1532     /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires
1533     /// [Conflicting]: ./struct.Arg.html#method.conflicts_with
1534     /// [override]: ./struct.Arg.html#method.overrides_with
requires_ifs(mut self, ifs: &[(&'b str, &'a str)]) -> Self1535     pub fn requires_ifs(mut self, ifs: &[(&'b str, &'a str)]) -> Self {
1536         if let Some(ref mut vec) = self.b.requires {
1537             for &(val, arg) in ifs {
1538                 vec.push((Some(val), arg));
1539             }
1540         } else {
1541             let mut vec = vec![];
1542             for &(val, arg) in ifs {
1543                 vec.push((Some(val), arg));
1544             }
1545             self.b.requires = Some(vec);
1546         }
1547         self
1548     }
1549 
1550     /// Allows specifying that an argument is [required] conditionally. The requirement will only
1551     /// become valid if the specified `arg`'s value equals `val`.
1552     ///
1553     /// **NOTE:** If using YAML the values should be laid out as follows
1554     ///
1555     /// ```yaml
1556     /// required_if:
1557     ///     - [arg, val]
1558     /// ```
1559     ///
1560     /// # Examples
1561     ///
1562     /// ```rust
1563     /// # use clap::Arg;
1564     /// Arg::with_name("config")
1565     ///     .required_if("other_arg", "value")
1566     /// # ;
1567     /// ```
1568     ///
1569     /// Setting [`Arg::required_if(arg, val)`] makes this arg required if the `arg` is used at
1570     /// runtime and it's value is equal to `val`. If the `arg`'s value is anything other than `val`,
1571     /// this argument isn't required.
1572     ///
1573     /// ```rust
1574     /// # use clap::{App, Arg};
1575     /// let res = App::new("prog")
1576     ///     .arg(Arg::with_name("cfg")
1577     ///         .takes_value(true)
1578     ///         .required_if("other", "special")
1579     ///         .long("config"))
1580     ///     .arg(Arg::with_name("other")
1581     ///         .long("other")
1582     ///         .takes_value(true))
1583     ///     .get_matches_from_safe(vec![
1584     ///         "prog", "--other", "not-special"
1585     ///     ]);
1586     ///
1587     /// assert!(res.is_ok()); // We didn't use --other=special, so "cfg" wasn't required
1588     /// ```
1589     ///
1590     /// Setting [`Arg::required_if(arg, val)`] and having `arg` used with a value of `val` but *not*
1591     /// using this arg is an error.
1592     ///
1593     /// ```rust
1594     /// # use clap::{App, Arg, ErrorKind};
1595     /// let res = App::new("prog")
1596     ///     .arg(Arg::with_name("cfg")
1597     ///         .takes_value(true)
1598     ///         .required_if("other", "special")
1599     ///         .long("config"))
1600     ///     .arg(Arg::with_name("other")
1601     ///         .long("other")
1602     ///         .takes_value(true))
1603     ///     .get_matches_from_safe(vec![
1604     ///         "prog", "--other", "special"
1605     ///     ]);
1606     ///
1607     /// assert!(res.is_err());
1608     /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
1609     /// ```
1610     /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires
1611     /// [Conflicting]: ./struct.Arg.html#method.conflicts_with
1612     /// [required]: ./struct.Arg.html#method.required
required_if(mut self, arg: &'a str, val: &'b str) -> Self1613     pub fn required_if(mut self, arg: &'a str, val: &'b str) -> Self {
1614         if let Some(ref mut vec) = self.r_ifs {
1615             vec.push((arg, val));
1616         } else {
1617             self.r_ifs = Some(vec![(arg, val)]);
1618         }
1619         self
1620     }
1621 
1622     /// Allows specifying that an argument is [required] based on multiple conditions. The
1623     /// conditions are set up in a `(arg, val)` style tuple. The requirement will only become valid
1624     /// if one of the specified `arg`'s value equals it's corresponding `val`.
1625     ///
1626     /// **NOTE:** If using YAML the values should be laid out as follows
1627     ///
1628     /// ```yaml
1629     /// required_if:
1630     ///     - [arg, val]
1631     ///     - [arg2, val2]
1632     /// ```
1633     ///
1634     /// # Examples
1635     ///
1636     /// ```rust
1637     /// # use clap::Arg;
1638     /// Arg::with_name("config")
1639     ///     .required_ifs(&[
1640     ///         ("extra", "val"),
1641     ///         ("option", "spec")
1642     ///     ])
1643     /// # ;
1644     /// ```
1645     ///
1646     /// Setting [`Arg::required_ifs(&[(arg, val)])`] makes this arg required if any of the `arg`s
1647     /// are used at runtime and it's corresponding value is equal to `val`. If the `arg`'s value is
1648     /// anything other than `val`, this argument isn't required.
1649     ///
1650     /// ```rust
1651     /// # use clap::{App, Arg};
1652     /// let res = App::new("prog")
1653     ///     .arg(Arg::with_name("cfg")
1654     ///         .required_ifs(&[
1655     ///             ("extra", "val"),
1656     ///             ("option", "spec")
1657     ///         ])
1658     ///         .takes_value(true)
1659     ///         .long("config"))
1660     ///     .arg(Arg::with_name("extra")
1661     ///         .takes_value(true)
1662     ///         .long("extra"))
1663     ///     .arg(Arg::with_name("option")
1664     ///         .takes_value(true)
1665     ///         .long("option"))
1666     ///     .get_matches_from_safe(vec![
1667     ///         "prog", "--option", "other"
1668     ///     ]);
1669     ///
1670     /// assert!(res.is_ok()); // We didn't use --option=spec, or --extra=val so "cfg" isn't required
1671     /// ```
1672     ///
1673     /// Setting [`Arg::required_ifs(&[(arg, val)])`] and having any of the `arg`s used with it's
1674     /// value of `val` but *not* using this arg is an error.
1675     ///
1676     /// ```rust
1677     /// # use clap::{App, Arg, ErrorKind};
1678     /// let res = App::new("prog")
1679     ///     .arg(Arg::with_name("cfg")
1680     ///         .required_ifs(&[
1681     ///             ("extra", "val"),
1682     ///             ("option", "spec")
1683     ///         ])
1684     ///         .takes_value(true)
1685     ///         .long("config"))
1686     ///     .arg(Arg::with_name("extra")
1687     ///         .takes_value(true)
1688     ///         .long("extra"))
1689     ///     .arg(Arg::with_name("option")
1690     ///         .takes_value(true)
1691     ///         .long("option"))
1692     ///     .get_matches_from_safe(vec![
1693     ///         "prog", "--option", "spec"
1694     ///     ]);
1695     ///
1696     /// assert!(res.is_err());
1697     /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
1698     /// ```
1699     /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires
1700     /// [Conflicting]: ./struct.Arg.html#method.conflicts_with
1701     /// [required]: ./struct.Arg.html#method.required
required_ifs(mut self, ifs: &[(&'a str, &'b str)]) -> Self1702     pub fn required_ifs(mut self, ifs: &[(&'a str, &'b str)]) -> Self {
1703         if let Some(ref mut vec) = self.r_ifs {
1704             for r_if in ifs {
1705                 vec.push((r_if.0, r_if.1));
1706             }
1707         } else {
1708             let mut vec = vec![];
1709             for r_if in ifs {
1710                 vec.push((r_if.0, r_if.1));
1711             }
1712             self.r_ifs = Some(vec);
1713         }
1714         self
1715     }
1716 
1717     /// Sets multiple arguments by names that are required when this one is present I.e. when
1718     /// using this argument, the following arguments *must* be present.
1719     ///
1720     /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required
1721     /// by default.
1722     ///
1723     /// # Examples
1724     ///
1725     /// ```rust
1726     /// # use clap::Arg;
1727     /// Arg::with_name("config")
1728     ///     .requires_all(&["input", "output"])
1729     /// # ;
1730     /// ```
1731     ///
1732     /// Setting [`Arg::requires_all(&[arg, arg2])`] requires that all the arguments be used at
1733     /// runtime if the defining argument is used. If the defining argument isn't used, the other
1734     /// argument isn't required
1735     ///
1736     /// ```rust
1737     /// # use clap::{App, Arg};
1738     /// let res = App::new("prog")
1739     ///     .arg(Arg::with_name("cfg")
1740     ///         .takes_value(true)
1741     ///         .requires("input")
1742     ///         .long("config"))
1743     ///     .arg(Arg::with_name("input")
1744     ///         .index(1))
1745     ///     .arg(Arg::with_name("output")
1746     ///         .index(2))
1747     ///     .get_matches_from_safe(vec![
1748     ///         "prog"
1749     ///     ]);
1750     ///
1751     /// assert!(res.is_ok()); // We didn't use cfg, so input and output weren't required
1752     /// ```
1753     ///
1754     /// Setting [`Arg::requires_all(&[arg, arg2])`] and *not* supplying all the arguments is an
1755     /// error.
1756     ///
1757     /// ```rust
1758     /// # use clap::{App, Arg, ErrorKind};
1759     /// let res = App::new("prog")
1760     ///     .arg(Arg::with_name("cfg")
1761     ///         .takes_value(true)
1762     ///         .requires_all(&["input", "output"])
1763     ///         .long("config"))
1764     ///     .arg(Arg::with_name("input")
1765     ///         .index(1))
1766     ///     .arg(Arg::with_name("output")
1767     ///         .index(2))
1768     ///     .get_matches_from_safe(vec![
1769     ///         "prog", "--config", "file.conf", "in.txt"
1770     ///     ]);
1771     ///
1772     /// assert!(res.is_err());
1773     /// // We didn't use output
1774     /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
1775     /// ```
1776     /// [Conflicting]: ./struct.Arg.html#method.conflicts_with
1777     /// [override]: ./struct.Arg.html#method.overrides_with
1778     /// [`Arg::requires_all(&[arg, arg2])`]: ./struct.Arg.html#method.requires_all
requires_all(mut self, names: &[&'a str]) -> Self1779     pub fn requires_all(mut self, names: &[&'a str]) -> Self {
1780         if let Some(ref mut vec) = self.b.requires {
1781             for s in names {
1782                 vec.push((None, s));
1783             }
1784         } else {
1785             let mut vec = vec![];
1786             for s in names {
1787                 vec.push((None, *s));
1788             }
1789             self.b.requires = Some(vec);
1790         }
1791         self
1792     }
1793 
1794     /// Specifies that the argument takes a value at run time.
1795     ///
1796     /// **NOTE:** values for arguments may be specified in any of the following methods
1797     ///
1798     /// * Using a space such as `-o value` or `--option value`
1799     /// * Using an equals and no space such as `-o=value` or `--option=value`
1800     /// * Use a short and no space such as `-ovalue`
1801     ///
1802     /// **NOTE:** By default, args which allow [multiple values] are delimited by commas, meaning
1803     /// `--option=val1,val2,val3` is three values for the `--option` argument. If you wish to
1804     /// change the delimiter to another character you can use [`Arg::value_delimiter(char)`],
1805     /// alternatively you can turn delimiting values **OFF** by using [`Arg::use_delimiter(false)`]
1806     ///
1807     /// # Examples
1808     ///
1809     /// ```rust
1810     /// # use clap::{App, Arg};
1811     /// Arg::with_name("config")
1812     ///     .takes_value(true)
1813     /// # ;
1814     /// ```
1815     ///
1816     /// ```rust
1817     /// # use clap::{App, Arg};
1818     /// let m = App::new("prog")
1819     ///     .arg(Arg::with_name("mode")
1820     ///         .long("mode")
1821     ///         .takes_value(true))
1822     ///     .get_matches_from(vec![
1823     ///         "prog", "--mode", "fast"
1824     ///     ]);
1825     ///
1826     /// assert!(m.is_present("mode"));
1827     /// assert_eq!(m.value_of("mode"), Some("fast"));
1828     /// ```
1829     /// [`Arg::value_delimiter(char)`]: ./struct.Arg.html#method.value_delimiter
1830     /// [`Arg::use_delimiter(false)`]: ./struct.Arg.html#method.use_delimiter
1831     /// [multiple values]: ./struct.Arg.html#method.multiple
takes_value(self, tv: bool) -> Self1832     pub fn takes_value(self, tv: bool) -> Self {
1833         if tv {
1834             self.set(ArgSettings::TakesValue)
1835         } else {
1836             self.unset(ArgSettings::TakesValue)
1837         }
1838     }
1839 
1840     /// Specifies if the possible values of an argument should be displayed in the help text or
1841     /// not. Defaults to `false` (i.e. show possible values)
1842     ///
1843     /// This is useful for args with many values, or ones which are explained elsewhere in the
1844     /// help text.
1845     ///
1846     /// # Examples
1847     ///
1848     /// ```rust
1849     /// # use clap::{App, Arg};
1850     /// Arg::with_name("config")
1851     ///     .hide_possible_values(true)
1852     /// # ;
1853     /// ```
1854     ///
1855     /// ```rust
1856     /// # use clap::{App, Arg};
1857     /// let m = App::new("prog")
1858     ///     .arg(Arg::with_name("mode")
1859     ///         .long("mode")
1860     ///         .possible_values(&["fast", "slow"])
1861     ///         .takes_value(true)
1862     ///         .hide_possible_values(true));
1863     ///
1864     /// ```
1865     ///
1866     /// If we were to run the above program with `--help` the `[values: fast, slow]` portion of
1867     /// the help text would be omitted.
hide_possible_values(self, hide: bool) -> Self1868     pub fn hide_possible_values(self, hide: bool) -> Self {
1869         if hide {
1870             self.set(ArgSettings::HidePossibleValues)
1871         } else {
1872             self.unset(ArgSettings::HidePossibleValues)
1873         }
1874     }
1875 
1876     /// Specifies if the default value of an argument should be displayed in the help text or
1877     /// not. Defaults to `false` (i.e. show default value)
1878     ///
1879     /// This is useful when default behavior of an arg is explained elsewhere in the help text.
1880     ///
1881     /// # Examples
1882     ///
1883     /// ```rust
1884     /// # use clap::{App, Arg};
1885     /// Arg::with_name("config")
1886     ///     .hide_default_value(true)
1887     /// # ;
1888     /// ```
1889     ///
1890     /// ```rust
1891     /// # use clap::{App, Arg};
1892     /// let m = App::new("connect")
1893     ///     .arg(Arg::with_name("host")
1894     ///         .long("host")
1895     ///         .default_value("localhost")
1896     ///         .hide_default_value(true));
1897     ///
1898     /// ```
1899     ///
1900     /// If we were to run the above program with `--help` the `[default: localhost]` portion of
1901     /// the help text would be omitted.
hide_default_value(self, hide: bool) -> Self1902     pub fn hide_default_value(self, hide: bool) -> Self {
1903         if hide {
1904             self.set(ArgSettings::HideDefaultValue)
1905         } else {
1906             self.unset(ArgSettings::HideDefaultValue)
1907         }
1908     }
1909 
1910     /// Specifies the index of a positional argument **starting at** 1.
1911     ///
1912     /// **NOTE:** The index refers to position according to **other positional argument**. It does
1913     /// not define position in the argument list as a whole.
1914     ///
1915     /// **NOTE:** If no [`Arg::short`], or [`Arg::long`] have been defined, you can optionally
1916     /// leave off the `index` method, and the index will be assigned in order of evaluation.
1917     /// Utilizing the `index` method allows for setting indexes out of order
1918     ///
1919     /// **NOTE:** When utilized with [`Arg::multiple(true)`], only the **last** positional argument
1920     /// may be defined as multiple (i.e. with the highest index)
1921     ///
1922     /// # Panics
1923     ///
1924     /// Although not in this method directly, [`App`] will [`panic!`] if indexes are skipped (such
1925     /// as defining `index(1)` and `index(3)` but not `index(2)`, or a positional argument is
1926     /// defined as multiple and is not the highest index
1927     ///
1928     /// # Examples
1929     ///
1930     /// ```rust
1931     /// # use clap::{App, Arg};
1932     /// Arg::with_name("config")
1933     ///     .index(1)
1934     /// # ;
1935     /// ```
1936     ///
1937     /// ```rust
1938     /// # use clap::{App, Arg};
1939     /// let m = App::new("prog")
1940     ///     .arg(Arg::with_name("mode")
1941     ///         .index(1))
1942     ///     .arg(Arg::with_name("debug")
1943     ///         .long("debug"))
1944     ///     .get_matches_from(vec![
1945     ///         "prog", "--debug", "fast"
1946     ///     ]);
1947     ///
1948     /// assert!(m.is_present("mode"));
1949     /// assert_eq!(m.value_of("mode"), Some("fast")); // notice index(1) means "first positional"
1950     ///                                               // *not* first argument
1951     /// ```
1952     /// [`Arg::short`]: ./struct.Arg.html#method.short
1953     /// [`Arg::long`]: ./struct.Arg.html#method.long
1954     /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
1955     /// [`App`]: ./struct.App.html
1956     /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html
index(mut self, idx: u64) -> Self1957     pub fn index(mut self, idx: u64) -> Self {
1958         self.index = Some(idx);
1959         self
1960     }
1961 
1962     /// Specifies that the argument may appear more than once. For flags, this results
1963     /// in the number of occurrences of the flag being recorded. For example `-ddd` or `-d -d -d`
1964     /// would count as three occurrences. For options there is a distinct difference in multiple
1965     /// occurrences vs multiple values.
1966     ///
1967     /// For example, `--opt val1 val2` is one occurrence, but two values. Whereas
1968     /// `--opt val1 --opt val2` is two occurrences.
1969     ///
1970     /// **WARNING:**
1971     ///
1972     /// Setting `multiple(true)` for an [option] with no other details, allows multiple values
1973     /// **and** multiple occurrences because it isn't possible to have more occurrences than values
1974     /// for options. Because multiple values are allowed, `--option val1 val2 val3` is perfectly
1975     /// valid, be careful when designing a CLI where positional arguments are expected after a
1976     /// option which accepts multiple values, as `clap` will continue parsing *values* until it
1977     /// reaches the max or specific number of values defined, or another flag or option.
1978     ///
1979     /// **Pro Tip**:
1980     ///
1981     /// It's possible to define an option which allows multiple occurrences, but only one value per
1982     /// occurrence. To do this use [`Arg::number_of_values(1)`] in coordination with
1983     /// [`Arg::multiple(true)`].
1984     ///
1985     /// **WARNING:**
1986     ///
1987     /// When using args with `multiple(true)` on [options] or [positionals] (i.e. those args that
1988     /// accept values) and [subcommands], one needs to consider the possibility of an argument value
1989     /// being the same as a valid subcommand. By default `clap` will parse the argument in question
1990     /// as a value *only if* a value is possible at that moment. Otherwise it will be parsed as a
1991     /// subcommand. In effect, this means using `multiple(true)` with no additional parameters and
1992     /// a possible value that coincides with a subcommand name, the subcommand cannot be called
1993     /// unless another argument is passed first.
1994     ///
1995     /// As an example, consider a CLI with an option `--ui-paths=<paths>...` and subcommand `signer`
1996     ///
1997     /// The following would be parsed as values to `--ui-paths`.
1998     ///
1999     /// ```notrust
2000     /// $ program --ui-paths path1 path2 signer
2001     /// ```
2002     ///
2003     /// This is because `--ui-paths` accepts multiple values. `clap` will continue parsing values
2004     /// until another argument is reached and it knows `--ui-paths` is done.
2005     ///
2006     /// By adding additional parameters to `--ui-paths` we can solve this issue. Consider adding
2007     /// [`Arg::number_of_values(1)`] as discussed above. The following are all valid, and `signer`
2008     /// is parsed as both a subcommand and a value in the second case.
2009     ///
2010     /// ```notrust
2011     /// $ program --ui-paths path1 signer
2012     /// $ program --ui-paths path1 --ui-paths signer signer
2013     /// ```
2014     ///
2015     /// # Examples
2016     ///
2017     /// ```rust
2018     /// # use clap::{App, Arg};
2019     /// Arg::with_name("debug")
2020     ///     .short("d")
2021     ///     .multiple(true)
2022     /// # ;
2023     /// ```
2024     /// An example with flags
2025     ///
2026     /// ```rust
2027     /// # use clap::{App, Arg};
2028     /// let m = App::new("prog")
2029     ///     .arg(Arg::with_name("verbose")
2030     ///         .multiple(true)
2031     ///         .short("v"))
2032     ///     .get_matches_from(vec![
2033     ///         "prog", "-v", "-v", "-v"    // note, -vvv would have same result
2034     ///     ]);
2035     ///
2036     /// assert!(m.is_present("verbose"));
2037     /// assert_eq!(m.occurrences_of("verbose"), 3);
2038     /// ```
2039     ///
2040     /// An example with options
2041     ///
2042     /// ```rust
2043     /// # use clap::{App, Arg};
2044     /// let m = App::new("prog")
2045     ///     .arg(Arg::with_name("file")
2046     ///         .multiple(true)
2047     ///         .takes_value(true)
2048     ///         .short("F"))
2049     ///     .get_matches_from(vec![
2050     ///         "prog", "-F", "file1", "file2", "file3"
2051     ///     ]);
2052     ///
2053     /// assert!(m.is_present("file"));
2054     /// assert_eq!(m.occurrences_of("file"), 1); // notice only one occurrence
2055     /// let files: Vec<_> = m.values_of("file").unwrap().collect();
2056     /// assert_eq!(files, ["file1", "file2", "file3"]);
2057     /// ```
2058     /// This is functionally equivalent to the example above
2059     ///
2060     /// ```rust
2061     /// # use clap::{App, Arg};
2062     /// let m = App::new("prog")
2063     ///     .arg(Arg::with_name("file")
2064     ///         .multiple(true)
2065     ///         .takes_value(true)
2066     ///         .short("F"))
2067     ///     .get_matches_from(vec![
2068     ///         "prog", "-F", "file1", "-F", "file2", "-F", "file3"
2069     ///     ]);
2070     /// let files: Vec<_> = m.values_of("file").unwrap().collect();
2071     /// assert_eq!(files, ["file1", "file2", "file3"]);
2072     ///
2073     /// assert!(m.is_present("file"));
2074     /// assert_eq!(m.occurrences_of("file"), 3); // Notice 3 occurrences
2075     /// let files: Vec<_> = m.values_of("file").unwrap().collect();
2076     /// assert_eq!(files, ["file1", "file2", "file3"]);
2077     /// ```
2078     ///
2079     /// A common mistake is to define an option which allows multiples, and a positional argument
2080     ///
2081     /// ```rust
2082     /// # use clap::{App, Arg};
2083     /// let m = App::new("prog")
2084     ///     .arg(Arg::with_name("file")
2085     ///         .multiple(true)
2086     ///         .takes_value(true)
2087     ///         .short("F"))
2088     ///     .arg(Arg::with_name("word")
2089     ///         .index(1))
2090     ///     .get_matches_from(vec![
2091     ///         "prog", "-F", "file1", "file2", "file3", "word"
2092     ///     ]);
2093     ///
2094     /// assert!(m.is_present("file"));
2095     /// let files: Vec<_> = m.values_of("file").unwrap().collect();
2096     /// assert_eq!(files, ["file1", "file2", "file3", "word"]); // wait...what?!
2097     /// assert!(!m.is_present("word")); // but we clearly used word!
2098     /// ```
2099     /// The problem is clap doesn't know when to stop parsing values for "files". This is further
2100     /// compounded by if we'd said `word -F file1 file2` it would have worked fine, so it would
2101     /// appear to only fail sometimes...not good!
2102     ///
2103     /// A solution for the example above is to specify that `-F` only accepts one value, but is
2104     /// allowed to appear multiple times
2105     ///
2106     /// ```rust
2107     /// # use clap::{App, Arg};
2108     /// let m = App::new("prog")
2109     ///     .arg(Arg::with_name("file")
2110     ///         .multiple(true)
2111     ///         .takes_value(true)
2112     ///         .number_of_values(1)
2113     ///         .short("F"))
2114     ///     .arg(Arg::with_name("word")
2115     ///         .index(1))
2116     ///     .get_matches_from(vec![
2117     ///         "prog", "-F", "file1", "-F", "file2", "-F", "file3", "word"
2118     ///     ]);
2119     ///
2120     /// assert!(m.is_present("file"));
2121     /// let files: Vec<_> = m.values_of("file").unwrap().collect();
2122     /// assert_eq!(files, ["file1", "file2", "file3"]);
2123     /// assert!(m.is_present("word"));
2124     /// assert_eq!(m.value_of("word"), Some("word"));
2125     /// ```
2126     /// As a final example, notice if we define [`Arg::number_of_values(1)`] and try to run the
2127     /// problem example above, it would have been a runtime error with a pretty message to the
2128     /// user :)
2129     ///
2130     /// ```rust
2131     /// # use clap::{App, Arg, ErrorKind};
2132     /// let res = App::new("prog")
2133     ///     .arg(Arg::with_name("file")
2134     ///         .multiple(true)
2135     ///         .takes_value(true)
2136     ///         .number_of_values(1)
2137     ///         .short("F"))
2138     ///     .arg(Arg::with_name("word")
2139     ///         .index(1))
2140     ///     .get_matches_from_safe(vec![
2141     ///         "prog", "-F", "file1", "file2", "file3", "word"
2142     ///     ]);
2143     ///
2144     /// assert!(res.is_err());
2145     /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
2146     /// ```
2147     /// [option]: ./struct.Arg.html#method.takes_value
2148     /// [options]: ./struct.Arg.html#method.takes_value
2149     /// [subcommands]: ./struct.SubCommand.html
2150     /// [positionals]: ./struct.Arg.html#method.index
2151     /// [`Arg::number_of_values(1)`]: ./struct.Arg.html#method.number_of_values
2152     /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
multiple(self, multi: bool) -> Self2153     pub fn multiple(self, multi: bool) -> Self {
2154         if multi {
2155             self.set(ArgSettings::Multiple)
2156         } else {
2157             self.unset(ArgSettings::Multiple)
2158         }
2159     }
2160 
2161     /// Specifies a value that *stops* parsing multiple values of a give argument. By default when
2162     /// one sets [`multiple(true)`] on an argument, clap will continue parsing values for that
2163     /// argument until it reaches another valid argument, or one of the other more specific settings
2164     /// for multiple values is used (such as [`min_values`], [`max_values`] or
2165     /// [`number_of_values`]).
2166     ///
2167     /// **NOTE:** This setting only applies to [options] and [positional arguments]
2168     ///
2169     /// **NOTE:** When the terminator is passed in on the command line, it is **not** stored as one
2170     /// of the values
2171     ///
2172     /// # Examples
2173     ///
2174     /// ```rust
2175     /// # use clap::{App, Arg};
2176     /// Arg::with_name("vals")
2177     ///     .takes_value(true)
2178     ///     .multiple(true)
2179     ///     .value_terminator(";")
2180     /// # ;
2181     /// ```
2182     /// The following example uses two arguments, a sequence of commands, and the location in which
2183     /// to perform them
2184     ///
2185     /// ```rust
2186     /// # use clap::{App, Arg};
2187     /// let m = App::new("prog")
2188     ///     .arg(Arg::with_name("cmds")
2189     ///         .multiple(true)
2190     ///         .allow_hyphen_values(true)
2191     ///         .value_terminator(";"))
2192     ///     .arg(Arg::with_name("location"))
2193     ///     .get_matches_from(vec![
2194     ///         "prog", "find", "-type", "f", "-name", "special", ";", "/home/clap"
2195     ///     ]);
2196     /// let cmds: Vec<_> = m.values_of("cmds").unwrap().collect();
2197     /// assert_eq!(&cmds, &["find", "-type", "f", "-name", "special"]);
2198     /// assert_eq!(m.value_of("location"), Some("/home/clap"));
2199     /// ```
2200     /// [options]: ./struct.Arg.html#method.takes_value
2201     /// [positional arguments]: ./struct.Arg.html#method.index
2202     /// [`multiple(true)`]: ./struct.Arg.html#method.multiple
2203     /// [`min_values`]: ./struct.Arg.html#method.min_values
2204     /// [`number_of_values`]: ./struct.Arg.html#method.number_of_values
2205     /// [`max_values`]: ./struct.Arg.html#method.max_values
value_terminator(mut self, term: &'b str) -> Self2206     pub fn value_terminator(mut self, term: &'b str) -> Self {
2207         self.setb(ArgSettings::TakesValue);
2208         self.v.terminator = Some(term);
2209         self
2210     }
2211 
2212     /// Specifies that an argument can be matched to all child [`SubCommand`]s.
2213     ///
2214     /// **NOTE:** Global arguments *only* propagate down, **not** up (to parent commands), however
2215     /// their values once a user uses them will be propagated back up to parents. In effect, this
2216     /// means one should *define* all global arguments at the top level, however it doesn't matter
2217     /// where the user *uses* the global argument.
2218     ///
2219     /// # Examples
2220     ///
2221     /// ```rust
2222     /// # use clap::{App, Arg};
2223     /// Arg::with_name("debug")
2224     ///     .short("d")
2225     ///     .global(true)
2226     /// # ;
2227     /// ```
2228     ///
2229     /// For example, assume an application with two subcommands, and you'd like to define a
2230     /// `--verbose` flag that can be called on any of the subcommands and parent, but you don't
2231     /// want to clutter the source with three duplicate [`Arg`] definitions.
2232     ///
2233     /// ```rust
2234     /// # use clap::{App, Arg, SubCommand};
2235     /// let m = App::new("prog")
2236     ///     .arg(Arg::with_name("verb")
2237     ///         .long("verbose")
2238     ///         .short("v")
2239     ///         .global(true))
2240     ///     .subcommand(SubCommand::with_name("test"))
2241     ///     .subcommand(SubCommand::with_name("do-stuff"))
2242     ///     .get_matches_from(vec![
2243     ///         "prog", "do-stuff", "--verbose"
2244     ///     ]);
2245     ///
2246     /// assert_eq!(m.subcommand_name(), Some("do-stuff"));
2247     /// let sub_m = m.subcommand_matches("do-stuff").unwrap();
2248     /// assert!(sub_m.is_present("verb"));
2249     /// ```
2250     /// [`SubCommand`]: ./struct.SubCommand.html
2251     /// [required]: ./struct.Arg.html#method.required
2252     /// [`ArgMatches`]: ./struct.ArgMatches.html
2253     /// [`ArgMatches::is_present("flag")`]: ./struct.ArgMatches.html#method.is_present
2254     /// [`Arg`]: ./struct.Arg.html
global(self, g: bool) -> Self2255     pub fn global(self, g: bool) -> Self {
2256         if g {
2257             self.set(ArgSettings::Global)
2258         } else {
2259             self.unset(ArgSettings::Global)
2260         }
2261     }
2262 
2263     /// Allows an argument to accept explicitly empty values. An empty value must be specified at
2264     /// the command line with an explicit `""`, or `''`
2265     ///
2266     /// **NOTE:** Defaults to `true` (Explicitly empty values are allowed)
2267     ///
2268     /// **NOTE:** Implicitly sets [`Arg::takes_value(true)`] when set to `false`
2269     ///
2270     /// # Examples
2271     ///
2272     /// ```rust
2273     /// # use clap::{App, Arg};
2274     /// Arg::with_name("file")
2275     ///     .long("file")
2276     ///     .empty_values(false)
2277     /// # ;
2278     /// ```
2279     /// The default is to allow empty values, such as `--option ""` would be an empty value. But
2280     /// we can change to make empty values become an error.
2281     ///
2282     /// ```rust
2283     /// # use clap::{App, Arg, ErrorKind};
2284     /// let res = App::new("prog")
2285     ///     .arg(Arg::with_name("cfg")
2286     ///         .long("config")
2287     ///         .short("v")
2288     ///         .empty_values(false))
2289     ///     .get_matches_from_safe(vec![
2290     ///         "prog", "--config="
2291     ///     ]);
2292     ///
2293     /// assert!(res.is_err());
2294     /// assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue);
2295     /// ```
2296     /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
empty_values(mut self, ev: bool) -> Self2297     pub fn empty_values(mut self, ev: bool) -> Self {
2298         if ev {
2299             self.set(ArgSettings::EmptyValues)
2300         } else {
2301             self = self.set(ArgSettings::TakesValue);
2302             self.unset(ArgSettings::EmptyValues)
2303         }
2304     }
2305 
2306     /// Hides an argument from help message output.
2307     ///
2308     /// **NOTE:** Implicitly sets [`Arg::hidden_short_help(true)`] and [`Arg::hidden_long_help(true)`]
2309     /// when set to true
2310     ///
2311     /// **NOTE:** This does **not** hide the argument from usage strings on error
2312     ///
2313     /// # Examples
2314     ///
2315     /// ```rust
2316     /// # use clap::{App, Arg};
2317     /// Arg::with_name("debug")
2318     ///     .hidden(true)
2319     /// # ;
2320     /// ```
2321     /// Setting `hidden(true)` will hide the argument when displaying help text
2322     ///
2323     /// ```rust
2324     /// # use clap::{App, Arg};
2325     /// let m = App::new("prog")
2326     ///     .arg(Arg::with_name("cfg")
2327     ///         .long("config")
2328     ///         .hidden(true)
2329     ///         .help("Some help text describing the --config arg"))
2330     ///     .get_matches_from(vec![
2331     ///         "prog", "--help"
2332     ///     ]);
2333     /// ```
2334     ///
2335     /// The above example displays
2336     ///
2337     /// ```notrust
2338     /// helptest
2339     ///
2340     /// USAGE:
2341     ///    helptest [FLAGS]
2342     ///
2343     /// FLAGS:
2344     /// -h, --help       Prints help information
2345     /// -V, --version    Prints version information
2346     /// ```
2347     /// [`Arg::hidden_short_help(true)`]: ./struct.Arg.html#method.hidden_short_help
2348     /// [`Arg::hidden_long_help(true)`]: ./struct.Arg.html#method.hidden_long_help
hidden(self, h: bool) -> Self2349     pub fn hidden(self, h: bool) -> Self {
2350         if h {
2351             self.set(ArgSettings::Hidden)
2352         } else {
2353             self.unset(ArgSettings::Hidden)
2354         }
2355     }
2356 
2357     /// Specifies a list of possible values for this argument. At runtime, `clap` verifies that
2358     /// only one of the specified values was used, or fails with an error message.
2359     ///
2360     /// **NOTE:** This setting only applies to [options] and [positional arguments]
2361     ///
2362     /// # Examples
2363     ///
2364     /// ```rust
2365     /// # use clap::{App, Arg};
2366     /// Arg::with_name("mode")
2367     ///     .takes_value(true)
2368     ///     .possible_values(&["fast", "slow", "medium"])
2369     /// # ;
2370     /// ```
2371     ///
2372     /// ```rust
2373     /// # use clap::{App, Arg};
2374     /// let m = App::new("prog")
2375     ///     .arg(Arg::with_name("mode")
2376     ///         .long("mode")
2377     ///         .takes_value(true)
2378     ///         .possible_values(&["fast", "slow", "medium"]))
2379     ///     .get_matches_from(vec![
2380     ///         "prog", "--mode", "fast"
2381     ///     ]);
2382     /// assert!(m.is_present("mode"));
2383     /// assert_eq!(m.value_of("mode"), Some("fast"));
2384     /// ```
2385     ///
2386     /// The next example shows a failed parse from using a value which wasn't defined as one of the
2387     /// possible values.
2388     ///
2389     /// ```rust
2390     /// # use clap::{App, Arg, ErrorKind};
2391     /// let res = App::new("prog")
2392     ///     .arg(Arg::with_name("mode")
2393     ///         .long("mode")
2394     ///         .takes_value(true)
2395     ///         .possible_values(&["fast", "slow", "medium"]))
2396     ///     .get_matches_from_safe(vec![
2397     ///         "prog", "--mode", "wrong"
2398     ///     ]);
2399     /// assert!(res.is_err());
2400     /// assert_eq!(res.unwrap_err().kind, ErrorKind::InvalidValue);
2401     /// ```
2402     /// [options]: ./struct.Arg.html#method.takes_value
2403     /// [positional arguments]: ./struct.Arg.html#method.index
possible_values(mut self, names: &[&'b str]) -> Self2404     pub fn possible_values(mut self, names: &[&'b str]) -> Self {
2405         if let Some(ref mut vec) = self.v.possible_vals {
2406             for s in names {
2407                 vec.push(s);
2408             }
2409         } else {
2410             self.v.possible_vals = Some(names.iter().map(|s| *s).collect::<Vec<_>>());
2411         }
2412         self
2413     }
2414 
2415     /// Specifies a possible value for this argument, one at a time. At runtime, `clap` verifies
2416     /// that only one of the specified values was used, or fails with error message.
2417     ///
2418     /// **NOTE:** This setting only applies to [options] and [positional arguments]
2419     ///
2420     /// # Examples
2421     ///
2422     /// ```rust
2423     /// # use clap::{App, Arg};
2424     /// Arg::with_name("mode")
2425     ///     .takes_value(true)
2426     ///     .possible_value("fast")
2427     ///     .possible_value("slow")
2428     ///     .possible_value("medium")
2429     /// # ;
2430     /// ```
2431     ///
2432     /// ```rust
2433     /// # use clap::{App, Arg};
2434     /// let m = App::new("prog")
2435     ///     .arg(Arg::with_name("mode")
2436     ///         .long("mode")
2437     ///         .takes_value(true)
2438     ///         .possible_value("fast")
2439     ///         .possible_value("slow")
2440     ///         .possible_value("medium"))
2441     ///     .get_matches_from(vec![
2442     ///         "prog", "--mode", "fast"
2443     ///     ]);
2444     /// assert!(m.is_present("mode"));
2445     /// assert_eq!(m.value_of("mode"), Some("fast"));
2446     /// ```
2447     ///
2448     /// The next example shows a failed parse from using a value which wasn't defined as one of the
2449     /// possible values.
2450     ///
2451     /// ```rust
2452     /// # use clap::{App, Arg, ErrorKind};
2453     /// let res = App::new("prog")
2454     ///     .arg(Arg::with_name("mode")
2455     ///         .long("mode")
2456     ///         .takes_value(true)
2457     ///         .possible_value("fast")
2458     ///         .possible_value("slow")
2459     ///         .possible_value("medium"))
2460     ///     .get_matches_from_safe(vec![
2461     ///         "prog", "--mode", "wrong"
2462     ///     ]);
2463     /// assert!(res.is_err());
2464     /// assert_eq!(res.unwrap_err().kind, ErrorKind::InvalidValue);
2465     /// ```
2466     /// [options]: ./struct.Arg.html#method.takes_value
2467     /// [positional arguments]: ./struct.Arg.html#method.index
possible_value(mut self, name: &'b str) -> Self2468     pub fn possible_value(mut self, name: &'b str) -> Self {
2469         if let Some(ref mut vec) = self.v.possible_vals {
2470             vec.push(name);
2471         } else {
2472             self.v.possible_vals = Some(vec![name]);
2473         }
2474         self
2475     }
2476 
2477     /// When used with [`Arg::possible_values`] it allows the argument value to pass validation even if
2478     /// the case differs from that of the specified `possible_value`.
2479     ///
2480     /// **Pro Tip:** Use this setting with [`arg_enum!`]
2481     ///
2482     /// # Examples
2483     ///
2484     /// ```rust
2485     /// # use clap::{App, Arg};
2486     /// # use std::ascii::AsciiExt;
2487     /// let m = App::new("pv")
2488     ///     .arg(Arg::with_name("option")
2489     ///         .long("--option")
2490     ///         .takes_value(true)
2491     ///         .possible_value("test123")
2492     ///         .case_insensitive(true))
2493     ///     .get_matches_from(vec![
2494     ///         "pv", "--option", "TeSt123",
2495     ///     ]);
2496     ///
2497     /// assert!(m.value_of("option").unwrap().eq_ignore_ascii_case("test123"));
2498     /// ```
2499     ///
2500     /// This setting also works when multiple values can be defined:
2501     ///
2502     /// ```rust
2503     /// # use clap::{App, Arg};
2504     /// let m = App::new("pv")
2505     ///     .arg(Arg::with_name("option")
2506     ///         .short("-o")
2507     ///         .long("--option")
2508     ///         .takes_value(true)
2509     ///         .possible_value("test123")
2510     ///         .possible_value("test321")
2511     ///         .multiple(true)
2512     ///         .case_insensitive(true))
2513     ///     .get_matches_from(vec![
2514     ///         "pv", "--option", "TeSt123", "teST123", "tESt321"
2515     ///     ]);
2516     ///
2517     /// let matched_vals = m.values_of("option").unwrap().collect::<Vec<_>>();
2518     /// assert_eq!(&*matched_vals, &["TeSt123", "teST123", "tESt321"]);
2519     /// ```
2520     /// [`Arg::case_insensitive(true)`]: ./struct.Arg.html#method.possible_values
2521     /// [`arg_enum!`]: ./macro.arg_enum.html
case_insensitive(self, ci: bool) -> Self2522     pub fn case_insensitive(self, ci: bool) -> Self {
2523         if ci {
2524             self.set(ArgSettings::CaseInsensitive)
2525         } else {
2526             self.unset(ArgSettings::CaseInsensitive)
2527         }
2528     }
2529 
2530     /// Specifies the name of the [`ArgGroup`] the argument belongs to.
2531     ///
2532     /// # Examples
2533     ///
2534     /// ```rust
2535     /// # use clap::{App, Arg};
2536     /// Arg::with_name("debug")
2537     ///     .long("debug")
2538     ///     .group("mode")
2539     /// # ;
2540     /// ```
2541     ///
2542     /// Multiple arguments can be a member of a single group and then the group checked as if it
2543     /// was one of said arguments.
2544     ///
2545     /// ```rust
2546     /// # use clap::{App, Arg};
2547     /// let m = App::new("prog")
2548     ///     .arg(Arg::with_name("debug")
2549     ///         .long("debug")
2550     ///         .group("mode"))
2551     ///     .arg(Arg::with_name("verbose")
2552     ///         .long("verbose")
2553     ///         .group("mode"))
2554     ///     .get_matches_from(vec![
2555     ///         "prog", "--debug"
2556     ///     ]);
2557     /// assert!(m.is_present("mode"));
2558     /// ```
2559     /// [`ArgGroup`]: ./struct.ArgGroup.html
group(mut self, name: &'a str) -> Self2560     pub fn group(mut self, name: &'a str) -> Self {
2561         if let Some(ref mut vec) = self.b.groups {
2562             vec.push(name);
2563         } else {
2564             self.b.groups = Some(vec![name]);
2565         }
2566         self
2567     }
2568 
2569     /// Specifies the names of multiple [`ArgGroup`]'s the argument belongs to.
2570     ///
2571     /// # Examples
2572     ///
2573     /// ```rust
2574     /// # use clap::{App, Arg};
2575     /// Arg::with_name("debug")
2576     ///     .long("debug")
2577     ///     .groups(&["mode", "verbosity"])
2578     /// # ;
2579     /// ```
2580     ///
2581     /// Arguments can be members of multiple groups and then the group checked as if it
2582     /// was one of said arguments.
2583     ///
2584     /// ```rust
2585     /// # use clap::{App, Arg};
2586     /// let m = App::new("prog")
2587     ///     .arg(Arg::with_name("debug")
2588     ///         .long("debug")
2589     ///         .groups(&["mode", "verbosity"]))
2590     ///     .arg(Arg::with_name("verbose")
2591     ///         .long("verbose")
2592     ///         .groups(&["mode", "verbosity"]))
2593     ///     .get_matches_from(vec![
2594     ///         "prog", "--debug"
2595     ///     ]);
2596     /// assert!(m.is_present("mode"));
2597     /// assert!(m.is_present("verbosity"));
2598     /// ```
2599     /// [`ArgGroup`]: ./struct.ArgGroup.html
groups(mut self, names: &[&'a str]) -> Self2600     pub fn groups(mut self, names: &[&'a str]) -> Self {
2601         if let Some(ref mut vec) = self.b.groups {
2602             for s in names {
2603                 vec.push(s);
2604             }
2605         } else {
2606             self.b.groups = Some(names.into_iter().map(|s| *s).collect::<Vec<_>>());
2607         }
2608         self
2609     }
2610 
2611     /// Specifies how many values are required to satisfy this argument. For example, if you had a
2612     /// `-f <file>` argument where you wanted exactly 3 'files' you would set
2613     /// `.number_of_values(3)`, and this argument wouldn't be satisfied unless the user provided
2614     /// 3 and only 3 values.
2615     ///
2616     /// **NOTE:** Does *not* require [`Arg::multiple(true)`] to be set. Setting
2617     /// [`Arg::multiple(true)`] would allow `-f <file> <file> <file> -f <file> <file> <file>` where
2618     /// as *not* setting [`Arg::multiple(true)`] would only allow one occurrence of this argument.
2619     ///
2620     /// # Examples
2621     ///
2622     /// ```rust
2623     /// # use clap::{App, Arg};
2624     /// Arg::with_name("file")
2625     ///     .short("f")
2626     ///     .number_of_values(3)
2627     /// # ;
2628     /// ```
2629     ///
2630     /// Not supplying the correct number of values is an error
2631     ///
2632     /// ```rust
2633     /// # use clap::{App, Arg, ErrorKind};
2634     /// let res = App::new("prog")
2635     ///     .arg(Arg::with_name("file")
2636     ///         .takes_value(true)
2637     ///         .number_of_values(2)
2638     ///         .short("F"))
2639     ///     .get_matches_from_safe(vec![
2640     ///         "prog", "-F", "file1"
2641     ///     ]);
2642     ///
2643     /// assert!(res.is_err());
2644     /// assert_eq!(res.unwrap_err().kind, ErrorKind::WrongNumberOfValues);
2645     /// ```
2646     /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
number_of_values(mut self, qty: u64) -> Self2647     pub fn number_of_values(mut self, qty: u64) -> Self {
2648         self.setb(ArgSettings::TakesValue);
2649         self.v.num_vals = Some(qty);
2650         self
2651     }
2652 
2653     /// Allows one to perform a custom validation on the argument value. You provide a closure
2654     /// which accepts a [`String`] value, and return a [`Result`] where the [`Err(String)`] is a
2655     /// message displayed to the user.
2656     ///
2657     /// **NOTE:** The error message does *not* need to contain the `error:` portion, only the
2658     /// message as all errors will appear as
2659     /// `error: Invalid value for '<arg>': <YOUR MESSAGE>` where `<arg>` is replaced by the actual
2660     /// arg, and `<YOUR MESSAGE>` is the `String` you return as the error.
2661     ///
2662     /// **NOTE:** There is a small performance hit for using validators, as they are implemented
2663     /// with [`Rc`] pointers. And the value to be checked will be allocated an extra time in order
2664     /// to to be passed to the closure. This performance hit is extremely minimal in the grand
2665     /// scheme of things.
2666     ///
2667     /// # Examples
2668     ///
2669     /// ```rust
2670     /// # use clap::{App, Arg};
2671     /// fn has_at(v: String) -> Result<(), String> {
2672     ///     if v.contains("@") { return Ok(()); }
2673     ///     Err(String::from("The value did not contain the required @ sigil"))
2674     /// }
2675     /// let res = App::new("prog")
2676     ///     .arg(Arg::with_name("file")
2677     ///         .index(1)
2678     ///         .validator(has_at))
2679     ///     .get_matches_from_safe(vec![
2680     ///         "prog", "some@file"
2681     ///     ]);
2682     /// assert!(res.is_ok());
2683     /// assert_eq!(res.unwrap().value_of("file"), Some("some@file"));
2684     /// ```
2685     /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
2686     /// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
2687     /// [`Err(String)`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err
2688     /// [`Rc`]: https://doc.rust-lang.org/std/rc/struct.Rc.html
validator<F>(mut self, f: F) -> Self where F: Fn(String) -> Result<(), String> + 'static,2689     pub fn validator<F>(mut self, f: F) -> Self
2690     where
2691         F: Fn(String) -> Result<(), String> + 'static,
2692     {
2693         self.v.validator = Some(Rc::new(f));
2694         self
2695     }
2696 
2697     /// Works identically to Validator but is intended to be used with values that could
2698     /// contain non UTF-8 formatted strings.
2699     ///
2700     /// # Examples
2701     ///
2702     #[cfg_attr(not(unix), doc = " ```ignore")]
2703     #[cfg_attr(unix, doc = " ```rust")]
2704     /// # use clap::{App, Arg};
2705     /// # use std::ffi::{OsStr, OsString};
2706     /// # use std::os::unix::ffi::OsStrExt;
2707     /// fn has_ampersand(v: &OsStr) -> Result<(), OsString> {
2708     ///     if v.as_bytes().iter().any(|b| *b == b'&') { return Ok(()); }
2709     ///     Err(OsString::from("The value did not contain the required & sigil"))
2710     /// }
2711     /// let res = App::new("prog")
2712     ///     .arg(Arg::with_name("file")
2713     ///         .index(1)
2714     ///         .validator_os(has_ampersand))
2715     ///     .get_matches_from_safe(vec![
2716     ///         "prog", "Fish & chips"
2717     ///     ]);
2718     /// assert!(res.is_ok());
2719     /// assert_eq!(res.unwrap().value_of("file"), Some("Fish & chips"));
2720     /// ```
2721     /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
2722     /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html
2723     /// [`OsString`]: https://doc.rust-lang.org/std/ffi/struct.OsString.html
2724     /// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
2725     /// [`Err(String)`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err
2726     /// [`Rc`]: https://doc.rust-lang.org/std/rc/struct.Rc.html
validator_os<F>(mut self, f: F) -> Self where F: Fn(&OsStr) -> Result<(), OsString> + 'static,2727     pub fn validator_os<F>(mut self, f: F) -> Self
2728     where
2729         F: Fn(&OsStr) -> Result<(), OsString> + 'static,
2730     {
2731         self.v.validator_os = Some(Rc::new(f));
2732         self
2733     }
2734 
2735     /// Specifies the *maximum* number of values are for this argument. For example, if you had a
2736     /// `-f <file>` argument where you wanted up to 3 'files' you would set `.max_values(3)`, and
2737     /// this argument would be satisfied if the user provided, 1, 2, or 3 values.
2738     ///
2739     /// **NOTE:** This does *not* implicitly set [`Arg::multiple(true)`]. This is because
2740     /// `-o val -o val` is multiple occurrences but a single value and `-o val1 val2` is a single
2741     /// occurrence with multiple values. For positional arguments this **does** set
2742     /// [`Arg::multiple(true)`] because there is no way to determine the difference between multiple
2743     /// occurrences and multiple values.
2744     ///
2745     /// # Examples
2746     ///
2747     /// ```rust
2748     /// # use clap::{App, Arg};
2749     /// Arg::with_name("file")
2750     ///     .short("f")
2751     ///     .max_values(3)
2752     /// # ;
2753     /// ```
2754     ///
2755     /// Supplying less than the maximum number of values is allowed
2756     ///
2757     /// ```rust
2758     /// # use clap::{App, Arg};
2759     /// let res = App::new("prog")
2760     ///     .arg(Arg::with_name("file")
2761     ///         .takes_value(true)
2762     ///         .max_values(3)
2763     ///         .short("F"))
2764     ///     .get_matches_from_safe(vec![
2765     ///         "prog", "-F", "file1", "file2"
2766     ///     ]);
2767     ///
2768     /// assert!(res.is_ok());
2769     /// let m = res.unwrap();
2770     /// let files: Vec<_> = m.values_of("file").unwrap().collect();
2771     /// assert_eq!(files, ["file1", "file2"]);
2772     /// ```
2773     ///
2774     /// Supplying more than the maximum number of values is an error
2775     ///
2776     /// ```rust
2777     /// # use clap::{App, Arg, ErrorKind};
2778     /// let res = App::new("prog")
2779     ///     .arg(Arg::with_name("file")
2780     ///         .takes_value(true)
2781     ///         .max_values(2)
2782     ///         .short("F"))
2783     ///     .get_matches_from_safe(vec![
2784     ///         "prog", "-F", "file1", "file2", "file3"
2785     ///     ]);
2786     ///
2787     /// assert!(res.is_err());
2788     /// assert_eq!(res.unwrap_err().kind, ErrorKind::TooManyValues);
2789     /// ```
2790     /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
max_values(mut self, qty: u64) -> Self2791     pub fn max_values(mut self, qty: u64) -> Self {
2792         self.setb(ArgSettings::TakesValue);
2793         self.v.max_vals = Some(qty);
2794         self
2795     }
2796 
2797     /// Specifies the *minimum* number of values for this argument. For example, if you had a
2798     /// `-f <file>` argument where you wanted at least 2 'files' you would set
2799     /// `.min_values(2)`, and this argument would be satisfied if the user provided, 2 or more
2800     /// values.
2801     ///
2802     /// **NOTE:** This does not implicitly set [`Arg::multiple(true)`]. This is because
2803     /// `-o val -o val` is multiple occurrences but a single value and `-o val1 val2` is a single
2804     /// occurrence with multiple values. For positional arguments this **does** set
2805     /// [`Arg::multiple(true)`] because there is no way to determine the difference between multiple
2806     /// occurrences and multiple values.
2807     ///
2808     /// # Examples
2809     ///
2810     /// ```rust
2811     /// # use clap::{App, Arg};
2812     /// Arg::with_name("file")
2813     ///     .short("f")
2814     ///     .min_values(3)
2815     /// # ;
2816     /// ```
2817     ///
2818     /// Supplying more than the minimum number of values is allowed
2819     ///
2820     /// ```rust
2821     /// # use clap::{App, Arg};
2822     /// let res = App::new("prog")
2823     ///     .arg(Arg::with_name("file")
2824     ///         .takes_value(true)
2825     ///         .min_values(2)
2826     ///         .short("F"))
2827     ///     .get_matches_from_safe(vec![
2828     ///         "prog", "-F", "file1", "file2", "file3"
2829     ///     ]);
2830     ///
2831     /// assert!(res.is_ok());
2832     /// let m = res.unwrap();
2833     /// let files: Vec<_> = m.values_of("file").unwrap().collect();
2834     /// assert_eq!(files, ["file1", "file2", "file3"]);
2835     /// ```
2836     ///
2837     /// Supplying less than the minimum number of values is an error
2838     ///
2839     /// ```rust
2840     /// # use clap::{App, Arg, ErrorKind};
2841     /// let res = App::new("prog")
2842     ///     .arg(Arg::with_name("file")
2843     ///         .takes_value(true)
2844     ///         .min_values(2)
2845     ///         .short("F"))
2846     ///     .get_matches_from_safe(vec![
2847     ///         "prog", "-F", "file1"
2848     ///     ]);
2849     ///
2850     /// assert!(res.is_err());
2851     /// assert_eq!(res.unwrap_err().kind, ErrorKind::TooFewValues);
2852     /// ```
2853     /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
min_values(mut self, qty: u64) -> Self2854     pub fn min_values(mut self, qty: u64) -> Self {
2855         self.v.min_vals = Some(qty);
2856         self.set(ArgSettings::TakesValue)
2857     }
2858 
2859     /// Specifies whether or not an argument should allow grouping of multiple values via a
2860     /// delimiter. I.e. should `--option=val1,val2,val3` be parsed as three values (`val1`, `val2`,
2861     /// and `val3`) or as a single value (`val1,val2,val3`). Defaults to using `,` (comma) as the
2862     /// value delimiter for all arguments that accept values (options and positional arguments)
2863     ///
2864     /// **NOTE:** The default is `false`. When set to `true` the default [`Arg::value_delimiter`]
2865     /// is the comma `,`.
2866     ///
2867     /// # Examples
2868     ///
2869     /// The following example shows the default behavior.
2870     ///
2871     /// ```rust
2872     /// # use clap::{App, Arg};
2873     /// let delims = App::new("prog")
2874     ///     .arg(Arg::with_name("option")
2875     ///         .long("option")
2876     ///         .use_delimiter(true)
2877     ///         .takes_value(true))
2878     ///     .get_matches_from(vec![
2879     ///         "prog", "--option=val1,val2,val3",
2880     ///     ]);
2881     ///
2882     /// assert!(delims.is_present("option"));
2883     /// assert_eq!(delims.occurrences_of("option"), 1);
2884     /// assert_eq!(delims.values_of("option").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);
2885     /// ```
2886     /// The next example shows the difference when turning delimiters off. This is the default
2887     /// behavior
2888     ///
2889     /// ```rust
2890     /// # use clap::{App, Arg};
2891     /// let nodelims = App::new("prog")
2892     ///     .arg(Arg::with_name("option")
2893     ///         .long("option")
2894     ///         .use_delimiter(false)
2895     ///         .takes_value(true))
2896     ///     .get_matches_from(vec![
2897     ///         "prog", "--option=val1,val2,val3",
2898     ///     ]);
2899     ///
2900     /// assert!(nodelims.is_present("option"));
2901     /// assert_eq!(nodelims.occurrences_of("option"), 1);
2902     /// assert_eq!(nodelims.value_of("option").unwrap(), "val1,val2,val3");
2903     /// ```
2904     /// [`Arg::value_delimiter`]: ./struct.Arg.html#method.value_delimiter
use_delimiter(mut self, d: bool) -> Self2905     pub fn use_delimiter(mut self, d: bool) -> Self {
2906         if d {
2907             if self.v.val_delim.is_none() {
2908                 self.v.val_delim = Some(',');
2909             }
2910             self.setb(ArgSettings::TakesValue);
2911             self.setb(ArgSettings::UseValueDelimiter);
2912             self.unset(ArgSettings::ValueDelimiterNotSet)
2913         } else {
2914             self.v.val_delim = None;
2915             self.unsetb(ArgSettings::UseValueDelimiter);
2916             self.unset(ArgSettings::ValueDelimiterNotSet)
2917         }
2918     }
2919 
2920     /// Specifies that *multiple values* may only be set using the delimiter. This means if an
2921     /// if an option is encountered, and no delimiter is found, it automatically assumed that no
2922     /// additional values for that option follow. This is unlike the default, where it is generally
2923     /// assumed that more values will follow regardless of whether or not a delimiter is used.
2924     ///
2925     /// **NOTE:** The default is `false`.
2926     ///
2927     /// **NOTE:** Setting this to true implies [`Arg::use_delimiter(true)`]
2928     ///
2929     /// **NOTE:** It's a good idea to inform the user that use of a delimiter is required, either
2930     /// through help text or other means.
2931     ///
2932     /// # Examples
2933     ///
2934     /// These examples demonstrate what happens when `require_delimiter(true)` is used. Notice
2935     /// everything works in this first example, as we use a delimiter, as expected.
2936     ///
2937     /// ```rust
2938     /// # use clap::{App, Arg};
2939     /// let delims = App::new("prog")
2940     ///     .arg(Arg::with_name("opt")
2941     ///         .short("o")
2942     ///         .takes_value(true)
2943     ///         .multiple(true)
2944     ///         .require_delimiter(true))
2945     ///     .get_matches_from(vec![
2946     ///         "prog", "-o", "val1,val2,val3",
2947     ///     ]);
2948     ///
2949     /// assert!(delims.is_present("opt"));
2950     /// assert_eq!(delims.values_of("opt").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);
2951     /// ```
2952     /// In this next example, we will *not* use a delimiter. Notice it's now an error.
2953     ///
2954     /// ```rust
2955     /// # use clap::{App, Arg, ErrorKind};
2956     /// let res = App::new("prog")
2957     ///     .arg(Arg::with_name("opt")
2958     ///         .short("o")
2959     ///         .takes_value(true)
2960     ///         .multiple(true)
2961     ///         .require_delimiter(true))
2962     ///     .get_matches_from_safe(vec![
2963     ///         "prog", "-o", "val1", "val2", "val3",
2964     ///     ]);
2965     ///
2966     /// assert!(res.is_err());
2967     /// let err = res.unwrap_err();
2968     /// assert_eq!(err.kind, ErrorKind::UnknownArgument);
2969     /// ```
2970     /// What's happening is `-o` is getting `val1`, and because delimiters are required yet none
2971     /// were present, it stops parsing `-o`. At this point it reaches `val2` and because no
2972     /// positional arguments have been defined, it's an error of an unexpected argument.
2973     ///
2974     /// In this final example, we contrast the above with `clap`'s default behavior where the above
2975     /// is *not* an error.
2976     ///
2977     /// ```rust
2978     /// # use clap::{App, Arg};
2979     /// let delims = App::new("prog")
2980     ///     .arg(Arg::with_name("opt")
2981     ///         .short("o")
2982     ///         .takes_value(true)
2983     ///         .multiple(true))
2984     ///     .get_matches_from(vec![
2985     ///         "prog", "-o", "val1", "val2", "val3",
2986     ///     ]);
2987     ///
2988     /// assert!(delims.is_present("opt"));
2989     /// assert_eq!(delims.values_of("opt").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);
2990     /// ```
2991     /// [`Arg::use_delimiter(true)`]: ./struct.Arg.html#method.use_delimiter
require_delimiter(mut self, d: bool) -> Self2992     pub fn require_delimiter(mut self, d: bool) -> Self {
2993         if d {
2994             self = self.use_delimiter(true);
2995             self.unsetb(ArgSettings::ValueDelimiterNotSet);
2996             self.setb(ArgSettings::UseValueDelimiter);
2997             self.set(ArgSettings::RequireDelimiter)
2998         } else {
2999             self = self.use_delimiter(false);
3000             self.unsetb(ArgSettings::UseValueDelimiter);
3001             self.unset(ArgSettings::RequireDelimiter)
3002         }
3003     }
3004 
3005     /// Specifies the separator to use when values are clumped together, defaults to `,` (comma).
3006     ///
3007     /// **NOTE:** implicitly sets [`Arg::use_delimiter(true)`]
3008     ///
3009     /// **NOTE:** implicitly sets [`Arg::takes_value(true)`]
3010     ///
3011     /// # Examples
3012     ///
3013     /// ```rust
3014     /// # use clap::{App, Arg};
3015     /// let m = App::new("prog")
3016     ///     .arg(Arg::with_name("config")
3017     ///         .short("c")
3018     ///         .long("config")
3019     ///         .value_delimiter(";"))
3020     ///     .get_matches_from(vec![
3021     ///         "prog", "--config=val1;val2;val3"
3022     ///     ]);
3023     ///
3024     /// assert_eq!(m.values_of("config").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"])
3025     /// ```
3026     /// [`Arg::use_delimiter(true)`]: ./struct.Arg.html#method.use_delimiter
3027     /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
value_delimiter(mut self, d: &str) -> Self3028     pub fn value_delimiter(mut self, d: &str) -> Self {
3029         self.unsetb(ArgSettings::ValueDelimiterNotSet);
3030         self.setb(ArgSettings::TakesValue);
3031         self.setb(ArgSettings::UseValueDelimiter);
3032         self.v.val_delim = Some(
3033             d.chars()
3034                 .nth(0)
3035                 .expect("Failed to get value_delimiter from arg"),
3036         );
3037         self
3038     }
3039 
3040     /// Specify multiple names for values of option arguments. These names are cosmetic only, used
3041     /// for help and usage strings only. The names are **not** used to access arguments. The values
3042     /// of the arguments are accessed in numeric order (i.e. if you specify two names `one` and
3043     /// `two` `one` will be the first matched value, `two` will be the second).
3044     ///
3045     /// This setting can be very helpful when describing the type of input the user should be
3046     /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to
3047     /// use all capital letters for the value name.
3048     ///
3049     /// **Pro Tip:** It may help to use [`Arg::next_line_help(true)`] if there are long, or
3050     /// multiple value names in order to not throw off the help text alignment of all options.
3051     ///
3052     /// **NOTE:** This implicitly sets [`Arg::number_of_values`] if the number of value names is
3053     /// greater than one. I.e. be aware that the number of "names" you set for the values, will be
3054     /// the *exact* number of values required to satisfy this argument
3055     ///
3056     /// **NOTE:** implicitly sets [`Arg::takes_value(true)`]
3057     ///
3058     /// **NOTE:** Does *not* require or imply [`Arg::multiple(true)`].
3059     ///
3060     /// # Examples
3061     ///
3062     /// ```rust
3063     /// # use clap::{App, Arg};
3064     /// Arg::with_name("speed")
3065     ///     .short("s")
3066     ///     .value_names(&["fast", "slow"])
3067     /// # ;
3068     /// ```
3069     ///
3070     /// ```rust
3071     /// # use clap::{App, Arg};
3072     /// let m = App::new("prog")
3073     ///     .arg(Arg::with_name("io")
3074     ///         .long("io-files")
3075     ///         .value_names(&["INFILE", "OUTFILE"]))
3076     ///     .get_matches_from(vec![
3077     ///         "prog", "--help"
3078     ///     ]);
3079     /// ```
3080     /// Running the above program produces the following output
3081     ///
3082     /// ```notrust
3083     /// valnames
3084     ///
3085     /// USAGE:
3086     ///    valnames [FLAGS] [OPTIONS]
3087     ///
3088     /// FLAGS:
3089     ///     -h, --help       Prints help information
3090     ///     -V, --version    Prints version information
3091     ///
3092     /// OPTIONS:
3093     ///     --io-files <INFILE> <OUTFILE>    Some help text
3094     /// ```
3095     /// [`Arg::next_line_help(true)`]: ./struct.Arg.html#method.next_line_help
3096     /// [`Arg::number_of_values`]: ./struct.Arg.html#method.number_of_values
3097     /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
3098     /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
value_names(mut self, names: &[&'b str]) -> Self3099     pub fn value_names(mut self, names: &[&'b str]) -> Self {
3100         self.setb(ArgSettings::TakesValue);
3101         if self.is_set(ArgSettings::ValueDelimiterNotSet) {
3102             self.unsetb(ArgSettings::ValueDelimiterNotSet);
3103             self.setb(ArgSettings::UseValueDelimiter);
3104         }
3105         if let Some(ref mut vals) = self.v.val_names {
3106             let mut l = vals.len();
3107             for s in names {
3108                 vals.insert(l, s);
3109                 l += 1;
3110             }
3111         } else {
3112             let mut vm = VecMap::new();
3113             for (i, n) in names.iter().enumerate() {
3114                 vm.insert(i, *n);
3115             }
3116             self.v.val_names = Some(vm);
3117         }
3118         self
3119     }
3120 
3121     /// Specifies the name for value of [option] or [positional] arguments inside of help
3122     /// documentation. This name is cosmetic only, the name is **not** used to access arguments.
3123     /// This setting can be very helpful when describing the type of input the user should be
3124     /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to
3125     /// use all capital letters for the value name.
3126     ///
3127     /// **NOTE:** implicitly sets [`Arg::takes_value(true)`]
3128     ///
3129     /// # Examples
3130     ///
3131     /// ```rust
3132     /// # use clap::{App, Arg};
3133     /// Arg::with_name("cfg")
3134     ///     .long("config")
3135     ///     .value_name("FILE")
3136     /// # ;
3137     /// ```
3138     ///
3139     /// ```rust
3140     /// # use clap::{App, Arg};
3141     /// let m = App::new("prog")
3142     ///     .arg(Arg::with_name("config")
3143     ///         .long("config")
3144     ///         .value_name("FILE"))
3145     ///     .get_matches_from(vec![
3146     ///         "prog", "--help"
3147     ///     ]);
3148     /// ```
3149     /// Running the above program produces the following output
3150     ///
3151     /// ```notrust
3152     /// valnames
3153     ///
3154     /// USAGE:
3155     ///    valnames [FLAGS] [OPTIONS]
3156     ///
3157     /// FLAGS:
3158     ///     -h, --help       Prints help information
3159     ///     -V, --version    Prints version information
3160     ///
3161     /// OPTIONS:
3162     ///     --config <FILE>     Some help text
3163     /// ```
3164     /// [option]: ./struct.Arg.html#method.takes_value
3165     /// [positional]: ./struct.Arg.html#method.index
3166     /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
value_name(mut self, name: &'b str) -> Self3167     pub fn value_name(mut self, name: &'b str) -> Self {
3168         self.setb(ArgSettings::TakesValue);
3169         if let Some(ref mut vals) = self.v.val_names {
3170             let l = vals.len();
3171             vals.insert(l, name);
3172         } else {
3173             let mut vm = VecMap::new();
3174             vm.insert(0, name);
3175             self.v.val_names = Some(vm);
3176         }
3177         self
3178     }
3179 
3180     /// Specifies the value of the argument when *not* specified at runtime.
3181     ///
3182     /// **NOTE:** If the user *does not* use this argument at runtime, [`ArgMatches::occurrences_of`]
3183     /// will return `0` even though the [`ArgMatches::value_of`] will return the default specified.
3184     ///
3185     /// **NOTE:** If the user *does not* use this argument at runtime [`ArgMatches::is_present`] will
3186     /// still return `true`. If you wish to determine whether the argument was used at runtime or
3187     /// not, consider [`ArgMatches::occurrences_of`] which will return `0` if the argument was *not*
3188     /// used at runtime.
3189     ///
3190     /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value_if`] but slightly
3191     /// different. `Arg::default_value` *only* takes affect when the user has not provided this arg
3192     /// at runtime. `Arg::default_value_if` however only takes affect when the user has not provided
3193     /// a value at runtime **and** these other conditions are met as well. If you have set
3194     /// `Arg::default_value` and `Arg::default_value_if`, and the user **did not** provide a this
3195     /// arg at runtime, nor did were the conditions met for `Arg::default_value_if`, the
3196     /// `Arg::default_value` will be applied.
3197     ///
3198     /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`].
3199     ///
3200     /// **NOTE:** This setting effectively disables `AppSettings::ArgRequiredElseHelp` if used in
3201     /// conjunction as it ensures that some argument will always be present.
3202     ///
3203     /// # Examples
3204     ///
3205     /// First we use the default value without providing any value at runtime.
3206     ///
3207     /// ```rust
3208     /// # use clap::{App, Arg};
3209     /// let m = App::new("prog")
3210     ///     .arg(Arg::with_name("opt")
3211     ///         .long("myopt")
3212     ///         .default_value("myval"))
3213     ///     .get_matches_from(vec![
3214     ///         "prog"
3215     ///     ]);
3216     ///
3217     /// assert_eq!(m.value_of("opt"), Some("myval"));
3218     /// assert!(m.is_present("opt"));
3219     /// assert_eq!(m.occurrences_of("opt"), 0);
3220     /// ```
3221     ///
3222     /// Next we provide a value at runtime to override the default.
3223     ///
3224     /// ```rust
3225     /// # use clap::{App, Arg};
3226     /// let m = App::new("prog")
3227     ///     .arg(Arg::with_name("opt")
3228     ///         .long("myopt")
3229     ///         .default_value("myval"))
3230     ///     .get_matches_from(vec![
3231     ///         "prog", "--myopt=non_default"
3232     ///     ]);
3233     ///
3234     /// assert_eq!(m.value_of("opt"), Some("non_default"));
3235     /// assert!(m.is_present("opt"));
3236     /// assert_eq!(m.occurrences_of("opt"), 1);
3237     /// ```
3238     /// [`ArgMatches::occurrences_of`]: ./struct.ArgMatches.html#method.occurrences_of
3239     /// [`ArgMatches::value_of`]: ./struct.ArgMatches.html#method.value_of
3240     /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
3241     /// [`ArgMatches::is_present`]: ./struct.ArgMatches.html#method.is_present
3242     /// [`Arg::default_value_if`]: ./struct.Arg.html#method.default_value_if
default_value(self, val: &'a str) -> Self3243     pub fn default_value(self, val: &'a str) -> Self {
3244         self.default_value_os(OsStr::from_bytes(val.as_bytes()))
3245     }
3246 
3247     /// Provides a default value in the exact same manner as [`Arg::default_value`]
3248     /// only using [`OsStr`]s instead.
3249     /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value
3250     /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html
default_value_os(mut self, val: &'a OsStr) -> Self3251     pub fn default_value_os(mut self, val: &'a OsStr) -> Self {
3252         self.setb(ArgSettings::TakesValue);
3253         self.v.default_val = Some(val);
3254         self
3255     }
3256 
3257     /// Specifies the value of the argument if `arg` has been used at runtime. If `val` is set to
3258     /// `None`, `arg` only needs to be present. If `val` is set to `"some-val"` then `arg` must be
3259     /// present at runtime **and** have the value `val`.
3260     ///
3261     /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value`] but slightly
3262     /// different. `Arg::default_value` *only* takes affect when the user has not provided this arg
3263     /// at runtime. This setting however only takes affect when the user has not provided a value at
3264     /// runtime **and** these other conditions are met as well. If you have set `Arg::default_value`
3265     /// and `Arg::default_value_if`, and the user **did not** provide a this arg at runtime, nor did
3266     /// were the conditions met for `Arg::default_value_if`, the `Arg::default_value` will be
3267     /// applied.
3268     ///
3269     /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`].
3270     ///
3271     /// **NOTE:** If using YAML the values should be laid out as follows (`None` can be represented
3272     /// as `null` in YAML)
3273     ///
3274     /// ```yaml
3275     /// default_value_if:
3276     ///     - [arg, val, default]
3277     /// ```
3278     ///
3279     /// # Examples
3280     ///
3281     /// First we use the default value only if another arg is present at runtime.
3282     ///
3283     /// ```rust
3284     /// # use clap::{App, Arg};
3285     /// let m = App::new("prog")
3286     ///     .arg(Arg::with_name("flag")
3287     ///         .long("flag"))
3288     ///     .arg(Arg::with_name("other")
3289     ///         .long("other")
3290     ///         .default_value_if("flag", None, "default"))
3291     ///     .get_matches_from(vec![
3292     ///         "prog", "--flag"
3293     ///     ]);
3294     ///
3295     /// assert_eq!(m.value_of("other"), Some("default"));
3296     /// ```
3297     ///
3298     /// Next we run the same test, but without providing `--flag`.
3299     ///
3300     /// ```rust
3301     /// # use clap::{App, Arg};
3302     /// let m = App::new("prog")
3303     ///     .arg(Arg::with_name("flag")
3304     ///         .long("flag"))
3305     ///     .arg(Arg::with_name("other")
3306     ///         .long("other")
3307     ///         .default_value_if("flag", None, "default"))
3308     ///     .get_matches_from(vec![
3309     ///         "prog"
3310     ///     ]);
3311     ///
3312     /// assert_eq!(m.value_of("other"), None);
3313     /// ```
3314     ///
3315     /// Now lets only use the default value if `--opt` contains the value `special`.
3316     ///
3317     /// ```rust
3318     /// # use clap::{App, Arg};
3319     /// let m = App::new("prog")
3320     ///     .arg(Arg::with_name("opt")
3321     ///         .takes_value(true)
3322     ///         .long("opt"))
3323     ///     .arg(Arg::with_name("other")
3324     ///         .long("other")
3325     ///         .default_value_if("opt", Some("special"), "default"))
3326     ///     .get_matches_from(vec![
3327     ///         "prog", "--opt", "special"
3328     ///     ]);
3329     ///
3330     /// assert_eq!(m.value_of("other"), Some("default"));
3331     /// ```
3332     ///
3333     /// We can run the same test and provide any value *other than* `special` and we won't get a
3334     /// default value.
3335     ///
3336     /// ```rust
3337     /// # use clap::{App, Arg};
3338     /// let m = App::new("prog")
3339     ///     .arg(Arg::with_name("opt")
3340     ///         .takes_value(true)
3341     ///         .long("opt"))
3342     ///     .arg(Arg::with_name("other")
3343     ///         .long("other")
3344     ///         .default_value_if("opt", Some("special"), "default"))
3345     ///     .get_matches_from(vec![
3346     ///         "prog", "--opt", "hahaha"
3347     ///     ]);
3348     ///
3349     /// assert_eq!(m.value_of("other"), None);
3350     /// ```
3351     /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
3352     /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value
default_value_if(self, arg: &'a str, val: Option<&'b str>, default: &'b str) -> Self3353     pub fn default_value_if(self, arg: &'a str, val: Option<&'b str>, default: &'b str) -> Self {
3354         self.default_value_if_os(
3355             arg,
3356             val.map(str::as_bytes).map(OsStr::from_bytes),
3357             OsStr::from_bytes(default.as_bytes()),
3358         )
3359     }
3360 
3361     /// Provides a conditional default value in the exact same manner as [`Arg::default_value_if`]
3362     /// only using [`OsStr`]s instead.
3363     /// [`Arg::default_value_if`]: ./struct.Arg.html#method.default_value_if
3364     /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html
default_value_if_os( mut self, arg: &'a str, val: Option<&'b OsStr>, default: &'b OsStr, ) -> Self3365     pub fn default_value_if_os(
3366         mut self,
3367         arg: &'a str,
3368         val: Option<&'b OsStr>,
3369         default: &'b OsStr,
3370     ) -> Self {
3371         self.setb(ArgSettings::TakesValue);
3372         if let Some(ref mut vm) = self.v.default_vals_ifs {
3373             let l = vm.len();
3374             vm.insert(l, (arg, val, default));
3375         } else {
3376             let mut vm = VecMap::new();
3377             vm.insert(0, (arg, val, default));
3378             self.v.default_vals_ifs = Some(vm);
3379         }
3380         self
3381     }
3382 
3383     /// Specifies multiple values and conditions in the same manner as [`Arg::default_value_if`].
3384     /// The method takes a slice of tuples in the `(arg, Option<val>, default)` format.
3385     ///
3386     /// **NOTE**: The conditions are stored in order and evaluated in the same order. I.e. the first
3387     /// if multiple conditions are true, the first one found will be applied and the ultimate value.
3388     ///
3389     /// **NOTE:** If using YAML the values should be laid out as follows
3390     ///
3391     /// ```yaml
3392     /// default_value_if:
3393     ///     - [arg, val, default]
3394     ///     - [arg2, null, default2]
3395     /// ```
3396     ///
3397     /// # Examples
3398     ///
3399     /// First we use the default value only if another arg is present at runtime.
3400     ///
3401     /// ```rust
3402     /// # use clap::{App, Arg};
3403     /// let m = App::new("prog")
3404     ///     .arg(Arg::with_name("flag")
3405     ///         .long("flag"))
3406     ///     .arg(Arg::with_name("opt")
3407     ///         .long("opt")
3408     ///         .takes_value(true))
3409     ///     .arg(Arg::with_name("other")
3410     ///         .long("other")
3411     ///         .default_value_ifs(&[
3412     ///             ("flag", None, "default"),
3413     ///             ("opt", Some("channal"), "chan"),
3414     ///         ]))
3415     ///     .get_matches_from(vec![
3416     ///         "prog", "--opt", "channal"
3417     ///     ]);
3418     ///
3419     /// assert_eq!(m.value_of("other"), Some("chan"));
3420     /// ```
3421     ///
3422     /// Next we run the same test, but without providing `--flag`.
3423     ///
3424     /// ```rust
3425     /// # use clap::{App, Arg};
3426     /// let m = App::new("prog")
3427     ///     .arg(Arg::with_name("flag")
3428     ///         .long("flag"))
3429     ///     .arg(Arg::with_name("other")
3430     ///         .long("other")
3431     ///         .default_value_ifs(&[
3432     ///             ("flag", None, "default"),
3433     ///             ("opt", Some("channal"), "chan"),
3434     ///         ]))
3435     ///     .get_matches_from(vec![
3436     ///         "prog"
3437     ///     ]);
3438     ///
3439     /// assert_eq!(m.value_of("other"), None);
3440     /// ```
3441     ///
3442     /// We can also see that these values are applied in order, and if more than one condition is
3443     /// true, only the first evaluated "wins"
3444     ///
3445     /// ```rust
3446     /// # use clap::{App, Arg};
3447     /// let m = App::new("prog")
3448     ///     .arg(Arg::with_name("flag")
3449     ///         .long("flag"))
3450     ///     .arg(Arg::with_name("opt")
3451     ///         .long("opt")
3452     ///         .takes_value(true))
3453     ///     .arg(Arg::with_name("other")
3454     ///         .long("other")
3455     ///         .default_value_ifs(&[
3456     ///             ("flag", None, "default"),
3457     ///             ("opt", Some("channal"), "chan"),
3458     ///         ]))
3459     ///     .get_matches_from(vec![
3460     ///         "prog", "--opt", "channal", "--flag"
3461     ///     ]);
3462     ///
3463     /// assert_eq!(m.value_of("other"), Some("default"));
3464     /// ```
3465     /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
3466     /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value
default_value_ifs(mut self, ifs: &[(&'a str, Option<&'b str>, &'b str)]) -> Self3467     pub fn default_value_ifs(mut self, ifs: &[(&'a str, Option<&'b str>, &'b str)]) -> Self {
3468         for &(arg, val, default) in ifs {
3469             self = self.default_value_if_os(
3470                 arg,
3471                 val.map(str::as_bytes).map(OsStr::from_bytes),
3472                 OsStr::from_bytes(default.as_bytes()),
3473             );
3474         }
3475         self
3476     }
3477 
3478     /// Provides multiple conditional default values in the exact same manner as
3479     /// [`Arg::default_value_ifs`] only using [`OsStr`]s instead.
3480     /// [`Arg::default_value_ifs`]: ./struct.Arg.html#method.default_value_ifs
3481     /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html
3482     #[cfg_attr(feature = "lints", allow(explicit_counter_loop))]
default_value_ifs_os(mut self, ifs: &[(&'a str, Option<&'b OsStr>, &'b OsStr)]) -> Self3483     pub fn default_value_ifs_os(mut self, ifs: &[(&'a str, Option<&'b OsStr>, &'b OsStr)]) -> Self {
3484         for &(arg, val, default) in ifs {
3485             self = self.default_value_if_os(arg, val, default);
3486         }
3487         self
3488     }
3489 
3490     /// Specifies that if the value is not passed in as an argument, that it should be retrieved
3491     /// from the environment, if available. If it is not present in the environment, then default
3492     /// rules will apply.
3493     ///
3494     /// **NOTE:** If the user *does not* use this argument at runtime, [`ArgMatches::occurrences_of`]
3495     /// will return `0` even though the [`ArgMatches::value_of`] will return the default specified.
3496     ///
3497     /// **NOTE:** If the user *does not* use this argument at runtime [`ArgMatches::is_present`] will
3498     /// return `true` if the variable is present in the environment . If you wish to determine whether
3499     /// the argument was used at runtime or not, consider [`ArgMatches::occurrences_of`] which will
3500     /// return `0` if the argument was *not* used at runtime.
3501     ///
3502     /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`].
3503     ///
3504     /// **NOTE:** If [`Arg::multiple(true)`] is set then [`Arg::use_delimiter(true)`] should also be
3505     /// set. Otherwise, only a single argument will be returned from the environment variable. The
3506     /// default delimiter is `,` and follows all the other delimiter rules.
3507     ///
3508     /// # Examples
3509     ///
3510     /// In this example, we show the variable coming from the environment:
3511     ///
3512     /// ```rust
3513     /// # use std::env;
3514     /// # use clap::{App, Arg};
3515     ///
3516     /// env::set_var("MY_FLAG", "env");
3517     ///
3518     /// let m = App::new("prog")
3519     ///     .arg(Arg::with_name("flag")
3520     ///         .long("flag")
3521     ///         .env("MY_FLAG"))
3522     ///     .get_matches_from(vec![
3523     ///         "prog"
3524     ///     ]);
3525     ///
3526     /// assert_eq!(m.value_of("flag"), Some("env"));
3527     /// ```
3528     ///
3529     /// In this example, we show the variable coming from an option on the CLI:
3530     ///
3531     /// ```rust
3532     /// # use std::env;
3533     /// # use clap::{App, Arg};
3534     ///
3535     /// env::set_var("MY_FLAG", "env");
3536     ///
3537     /// let m = App::new("prog")
3538     ///     .arg(Arg::with_name("flag")
3539     ///         .long("flag")
3540     ///         .env("MY_FLAG"))
3541     ///     .get_matches_from(vec![
3542     ///         "prog", "--flag", "opt"
3543     ///     ]);
3544     ///
3545     /// assert_eq!(m.value_of("flag"), Some("opt"));
3546     /// ```
3547     ///
3548     /// In this example, we show the variable coming from the environment even with the
3549     /// presence of a default:
3550     ///
3551     /// ```rust
3552     /// # use std::env;
3553     /// # use clap::{App, Arg};
3554     ///
3555     /// env::set_var("MY_FLAG", "env");
3556     ///
3557     /// let m = App::new("prog")
3558     ///     .arg(Arg::with_name("flag")
3559     ///         .long("flag")
3560     ///         .env("MY_FLAG")
3561     ///         .default_value("default"))
3562     ///     .get_matches_from(vec![
3563     ///         "prog"
3564     ///     ]);
3565     ///
3566     /// assert_eq!(m.value_of("flag"), Some("env"));
3567     /// ```
3568     ///
3569     /// In this example, we show the use of multiple values in a single environment variable:
3570     ///
3571     /// ```rust
3572     /// # use std::env;
3573     /// # use clap::{App, Arg};
3574     ///
3575     /// env::set_var("MY_FLAG_MULTI", "env1,env2");
3576     ///
3577     /// let m = App::new("prog")
3578     ///     .arg(Arg::with_name("flag")
3579     ///         .long("flag")
3580     ///         .env("MY_FLAG_MULTI")
3581     ///         .multiple(true)
3582     ///         .use_delimiter(true))
3583     ///     .get_matches_from(vec![
3584     ///         "prog"
3585     ///     ]);
3586     ///
3587     /// assert_eq!(m.values_of("flag").unwrap().collect::<Vec<_>>(), vec!["env1", "env2"]);
3588     /// ```
3589     /// [`ArgMatches::occurrences_of`]: ./struct.ArgMatches.html#method.occurrences_of
3590     /// [`ArgMatches::value_of`]: ./struct.ArgMatches.html#method.value_of
3591     /// [`ArgMatches::is_present`]: ./struct.ArgMatches.html#method.is_present
3592     /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value
3593     /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
3594     /// [`Arg::use_delimiter(true)`]: ./struct.Arg.html#method.use_delimiter
env(self, name: &'a str) -> Self3595     pub fn env(self, name: &'a str) -> Self {
3596         self.env_os(OsStr::new(name))
3597     }
3598 
3599     /// Specifies that if the value is not passed in as an argument, that it should be retrieved
3600     /// from the environment if available in the exact same manner as [`Arg::env`] only using
3601     /// [`OsStr`]s instead.
env_os(mut self, name: &'a OsStr) -> Self3602     pub fn env_os(mut self, name: &'a OsStr) -> Self {
3603         self.setb(ArgSettings::TakesValue);
3604 
3605         self.v.env = Some((name, env::var_os(name)));
3606         self
3607     }
3608 
3609     /// @TODO @p2 @docs @release: write docs
hide_env_values(self, hide: bool) -> Self3610     pub fn hide_env_values(self, hide: bool) -> Self {
3611         if hide {
3612             self.set(ArgSettings::HideEnvValues)
3613         } else {
3614             self.unset(ArgSettings::HideEnvValues)
3615         }
3616     }
3617 
3618     /// When set to `true` the help string will be displayed on the line after the argument and
3619     /// indented once. This can be helpful for arguments with very long or complex help messages.
3620     /// This can also be helpful for arguments with very long flag names, or many/long value names.
3621     ///
3622     /// **NOTE:** To apply this setting to all arguments consider using
3623     /// [`AppSettings::NextLineHelp`]
3624     ///
3625     /// # Examples
3626     ///
3627     /// ```rust
3628     /// # use clap::{App, Arg};
3629     /// let m = App::new("prog")
3630     ///     .arg(Arg::with_name("opt")
3631     ///         .long("long-option-flag")
3632     ///         .short("o")
3633     ///         .takes_value(true)
3634     ///         .value_names(&["value1", "value2"])
3635     ///         .help("Some really long help and complex\n\
3636     ///                help that makes more sense to be\n\
3637     ///                on a line after the option")
3638     ///         .next_line_help(true))
3639     ///     .get_matches_from(vec![
3640     ///         "prog", "--help"
3641     ///     ]);
3642     /// ```
3643     ///
3644     /// The above example displays the following help message
3645     ///
3646     /// ```notrust
3647     /// nlh
3648     ///
3649     /// USAGE:
3650     ///     nlh [FLAGS] [OPTIONS]
3651     ///
3652     /// FLAGS:
3653     ///     -h, --help       Prints help information
3654     ///     -V, --version    Prints version information
3655     ///
3656     /// OPTIONS:
3657     ///     -o, --long-option-flag <value1> <value2>
3658     ///         Some really long help and complex
3659     ///         help that makes more sense to be
3660     ///         on a line after the option
3661     /// ```
3662     /// [`AppSettings::NextLineHelp`]: ./enum.AppSettings.html#variant.NextLineHelp
next_line_help(mut self, nlh: bool) -> Self3663     pub fn next_line_help(mut self, nlh: bool) -> Self {
3664         if nlh {
3665             self.setb(ArgSettings::NextLineHelp);
3666         } else {
3667             self.unsetb(ArgSettings::NextLineHelp);
3668         }
3669         self
3670     }
3671 
3672     /// Allows custom ordering of args within the help message. Args with a lower value will be
3673     /// displayed first in the help message. This is helpful when one would like to emphasise
3674     /// frequently used args, or prioritize those towards the top of the list. Duplicate values
3675     /// **are** allowed. Args with duplicate display orders will be displayed in alphabetical
3676     /// order.
3677     ///
3678     /// **NOTE:** The default is 999 for all arguments.
3679     ///
3680     /// **NOTE:** This setting is ignored for [positional arguments] which are always displayed in
3681     /// [index] order.
3682     ///
3683     /// # Examples
3684     ///
3685     /// ```rust
3686     /// # use clap::{App, Arg};
3687     /// let m = App::new("prog")
3688     ///     .arg(Arg::with_name("a") // Typically args are grouped alphabetically by name.
3689     ///                              // Args without a display_order have a value of 999 and are
3690     ///                              // displayed alphabetically with all other 999 valued args.
3691     ///         .long("long-option")
3692     ///         .short("o")
3693     ///         .takes_value(true)
3694     ///         .help("Some help and text"))
3695     ///     .arg(Arg::with_name("b")
3696     ///         .long("other-option")
3697     ///         .short("O")
3698     ///         .takes_value(true)
3699     ///         .display_order(1)   // In order to force this arg to appear *first*
3700     ///                             // all we have to do is give it a value lower than 999.
3701     ///                             // Any other args with a value of 1 will be displayed
3702     ///                             // alphabetically with this one...then 2 values, then 3, etc.
3703     ///         .help("I should be first!"))
3704     ///     .get_matches_from(vec![
3705     ///         "prog", "--help"
3706     ///     ]);
3707     /// ```
3708     ///
3709     /// The above example displays the following help message
3710     ///
3711     /// ```notrust
3712     /// cust-ord
3713     ///
3714     /// USAGE:
3715     ///     cust-ord [FLAGS] [OPTIONS]
3716     ///
3717     /// FLAGS:
3718     ///     -h, --help       Prints help information
3719     ///     -V, --version    Prints version information
3720     ///
3721     /// OPTIONS:
3722     ///     -O, --other-option <b>    I should be first!
3723     ///     -o, --long-option <a>     Some help and text
3724     /// ```
3725     /// [positional arguments]: ./struct.Arg.html#method.index
3726     /// [index]: ./struct.Arg.html#method.index
display_order(mut self, ord: usize) -> Self3727     pub fn display_order(mut self, ord: usize) -> Self {
3728         self.s.disp_ord = ord;
3729         self
3730     }
3731 
3732     /// Indicates that all parameters passed after this should not be parsed
3733     /// individually, but rather passed in their entirety. It is worth noting
3734     /// that setting this requires all values to come after a `--` to indicate they
3735     /// should all be captured. For example:
3736     ///
3737     /// ```notrust
3738     /// --foo something -- -v -v -v -b -b -b --baz -q -u -x
3739     /// ```
3740     /// Will result in everything after `--` to be considered one raw argument. This behavior
3741     /// may not be exactly what you are expecting and using [`AppSettings::TrailingVarArg`]
3742     /// may be more appropriate.
3743     ///
3744     /// **NOTE:** Implicitly sets [`Arg::multiple(true)`], [`Arg::allow_hyphen_values(true)`], and
3745     /// [`Arg::last(true)`] when set to `true`
3746     ///
3747     /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
3748     /// [`Arg::allow_hyphen_values(true)`]: ./struct.Arg.html#method.allow_hyphen_values
3749     /// [`Arg::last(true)`]: ./struct.Arg.html#method.last
3750     /// [`AppSettings::TrailingVarArg`]: ./enum.AppSettings.html#variant.TrailingVarArg
raw(self, raw: bool) -> Self3751     pub fn raw(self, raw: bool) -> Self {
3752         self.multiple(raw).allow_hyphen_values(raw).last(raw)
3753     }
3754 
3755     /// Hides an argument from short help message output.
3756     ///
3757     /// **NOTE:** This does **not** hide the argument from usage strings on error
3758     ///
3759     /// **NOTE:** Setting this option will cause next-line-help output style to be used
3760     /// when long help (`--help`) is called.
3761     ///
3762     /// # Examples
3763     ///
3764     /// ```rust
3765     /// # use clap::{App, Arg};
3766     /// Arg::with_name("debug")
3767     ///     .hidden_short_help(true)
3768     /// # ;
3769     /// ```
3770     /// Setting `hidden_short_help(true)` will hide the argument when displaying short help text
3771     ///
3772     /// ```rust
3773     /// # use clap::{App, Arg};
3774     /// let m = App::new("prog")
3775     ///     .arg(Arg::with_name("cfg")
3776     ///         .long("config")
3777     ///         .hidden_short_help(true)
3778     ///         .help("Some help text describing the --config arg"))
3779     ///     .get_matches_from(vec![
3780     ///         "prog", "-h"
3781     ///     ]);
3782     /// ```
3783     ///
3784     /// The above example displays
3785     ///
3786     /// ```notrust
3787     /// helptest
3788     ///
3789     /// USAGE:
3790     ///    helptest [FLAGS]
3791     ///
3792     /// FLAGS:
3793     /// -h, --help       Prints help information
3794     /// -V, --version    Prints version information
3795     /// ```
3796     ///
3797     /// However, when --help is called
3798     ///
3799     /// ```rust
3800     /// # use clap::{App, Arg};
3801     /// let m = App::new("prog")
3802     ///     .arg(Arg::with_name("cfg")
3803     ///         .long("config")
3804     ///         .hidden_short_help(true)
3805     ///         .help("Some help text describing the --config arg"))
3806     ///     .get_matches_from(vec![
3807     ///         "prog", "--help"
3808     ///     ]);
3809     /// ```
3810     ///
3811     /// Then the following would be displayed
3812     ///
3813     /// ```notrust
3814     /// helptest
3815     ///
3816     /// USAGE:
3817     ///    helptest [FLAGS]
3818     ///
3819     /// FLAGS:
3820     ///     --config     Some help text describing the --config arg
3821     /// -h, --help       Prints help information
3822     /// -V, --version    Prints version information
3823     /// ```
hidden_short_help(self, hide: bool) -> Self3824     pub fn hidden_short_help(self, hide: bool) -> Self {
3825         if hide {
3826             self.set(ArgSettings::HiddenShortHelp)
3827         } else {
3828             self.unset(ArgSettings::HiddenShortHelp)
3829         }
3830     }
3831 
3832     /// Hides an argument from long help message output.
3833     ///
3834     /// **NOTE:** This does **not** hide the argument from usage strings on error
3835     ///
3836     /// **NOTE:** Setting this option will cause next-line-help output style to be used
3837     /// when long help (`--help`) is called.
3838     ///
3839     /// # Examples
3840     ///
3841     /// ```rust
3842     /// # use clap::{App, Arg};
3843     /// Arg::with_name("debug")
3844     ///     .hidden_long_help(true)
3845     /// # ;
3846     /// ```
3847     /// Setting `hidden_long_help(true)` will hide the argument when displaying long help text
3848     ///
3849     /// ```rust
3850     /// # use clap::{App, Arg};
3851     /// let m = App::new("prog")
3852     ///     .arg(Arg::with_name("cfg")
3853     ///         .long("config")
3854     ///         .hidden_long_help(true)
3855     ///         .help("Some help text describing the --config arg"))
3856     ///     .get_matches_from(vec![
3857     ///         "prog", "--help"
3858     ///     ]);
3859     /// ```
3860     ///
3861     /// The above example displays
3862     ///
3863     /// ```notrust
3864     /// helptest
3865     ///
3866     /// USAGE:
3867     ///    helptest [FLAGS]
3868     ///
3869     /// FLAGS:
3870     /// -h, --help       Prints help information
3871     /// -V, --version    Prints version information
3872     /// ```
3873     ///
3874     /// However, when -h is called
3875     ///
3876     /// ```rust
3877     /// # use clap::{App, Arg};
3878     /// let m = App::new("prog")
3879     ///     .arg(Arg::with_name("cfg")
3880     ///         .long("config")
3881     ///         .hidden_long_help(true)
3882     ///         .help("Some help text describing the --config arg"))
3883     ///     .get_matches_from(vec![
3884     ///         "prog", "-h"
3885     ///     ]);
3886     /// ```
3887     ///
3888     /// Then the following would be displayed
3889     ///
3890     /// ```notrust
3891     /// helptest
3892     ///
3893     /// USAGE:
3894     ///    helptest [FLAGS]
3895     ///
3896     /// FLAGS:
3897     ///     --config     Some help text describing the --config arg
3898     /// -h, --help       Prints help information
3899     /// -V, --version    Prints version information
3900     /// ```
hidden_long_help(self, hide: bool) -> Self3901     pub fn hidden_long_help(self, hide: bool) -> Self {
3902         if hide {
3903             self.set(ArgSettings::HiddenLongHelp)
3904         } else {
3905             self.unset(ArgSettings::HiddenLongHelp)
3906         }
3907     }
3908 
3909     /// Checks if one of the [`ArgSettings`] settings is set for the argument.
3910     ///
3911     /// [`ArgSettings`]: ./enum.ArgSettings.html
is_set(&self, s: ArgSettings) -> bool3912     pub fn is_set(&self, s: ArgSettings) -> bool {
3913         self.b.is_set(s)
3914     }
3915 
3916     /// Sets one of the [`ArgSettings`] settings for the argument.
3917     ///
3918     /// [`ArgSettings`]: ./enum.ArgSettings.html
set(mut self, s: ArgSettings) -> Self3919     pub fn set(mut self, s: ArgSettings) -> Self {
3920         self.setb(s);
3921         self
3922     }
3923 
3924     /// Unsets one of the [`ArgSettings`] settings for the argument.
3925     ///
3926     /// [`ArgSettings`]: ./enum.ArgSettings.html
unset(mut self, s: ArgSettings) -> Self3927     pub fn unset(mut self, s: ArgSettings) -> Self {
3928         self.unsetb(s);
3929         self
3930     }
3931 
3932     #[doc(hidden)]
setb(&mut self, s: ArgSettings)3933     pub fn setb(&mut self, s: ArgSettings) {
3934         self.b.set(s);
3935     }
3936 
3937     #[doc(hidden)]
unsetb(&mut self, s: ArgSettings)3938     pub fn unsetb(&mut self, s: ArgSettings) {
3939         self.b.unset(s);
3940     }
3941 }
3942 
3943 impl<'a, 'b, 'z> From<&'z Arg<'a, 'b>> for Arg<'a, 'b> {
from(a: &'z Arg<'a, 'b>) -> Self3944     fn from(a: &'z Arg<'a, 'b>) -> Self {
3945         Arg {
3946             b: a.b.clone(),
3947             v: a.v.clone(),
3948             s: a.s.clone(),
3949             index: a.index,
3950             r_ifs: a.r_ifs.clone(),
3951         }
3952     }
3953 }
3954 
3955 impl<'n, 'e> PartialEq for Arg<'n, 'e> {
eq(&self, other: &Arg<'n, 'e>) -> bool3956     fn eq(&self, other: &Arg<'n, 'e>) -> bool {
3957         self.b == other.b
3958     }
3959 }
3960