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