]> git.proxmox.com Git - rustc.git/blob - vendor/clap/src/builder/arg.rs
New upstream version 1.63.0+dfsg1
[rustc.git] / vendor / clap / src / builder / arg.rs
1 #![allow(deprecated)]
2
3 // Std
4 use std::{
5 borrow::Cow,
6 cmp::{Ord, Ordering},
7 error::Error,
8 ffi::OsStr,
9 fmt::{self, Display, Formatter},
10 str,
11 sync::{Arc, Mutex},
12 };
13 #[cfg(feature = "env")]
14 use std::{env, ffi::OsString};
15
16 #[cfg(feature = "yaml")]
17 use yaml_rust::Yaml;
18
19 // Internal
20 use crate::builder::usage_parser::UsageParser;
21 use crate::builder::ArgPredicate;
22 use crate::util::{Id, Key};
23 use crate::ArgAction;
24 use crate::PossibleValue;
25 use crate::ValueHint;
26 use crate::INTERNAL_ERROR_MSG;
27 use crate::{ArgFlags, ArgSettings};
28
29 #[cfg(feature = "regex")]
30 use crate::builder::RegexRef;
31
32 /// The abstract representation of a command line argument. Used to set all the options and
33 /// relationships that define a valid argument for the program.
34 ///
35 /// There are two methods for constructing [`Arg`]s, using the builder pattern and setting options
36 /// manually, or using a usage string which is far less verbose but has fewer options. You can also
37 /// use a combination of the two methods to achieve the best of both worlds.
38 ///
39 /// - [Basic API][crate::Arg#basic-api]
40 /// - [Value Handling][crate::Arg#value-handling]
41 /// - [Help][crate::Arg#help-1]
42 /// - [Advanced Argument Relations][crate::Arg#advanced-argument-relations]
43 /// - [Reflection][crate::Arg#reflection]
44 ///
45 /// # Examples
46 ///
47 /// ```rust
48 /// # use clap::{Arg, arg};
49 /// // Using the traditional builder pattern and setting each option manually
50 /// let cfg = Arg::new("config")
51 /// .short('c')
52 /// .long("config")
53 /// .takes_value(true)
54 /// .value_name("FILE")
55 /// .help("Provides a config file to myprog");
56 /// // Using a usage string (setting a similar argument to the one above)
57 /// let input = arg!(-i --input <FILE> "Provides an input file to the program");
58 /// ```
59 #[allow(missing_debug_implementations)]
60 #[derive(Default, Clone)]
61 pub struct Arg<'help> {
62 pub(crate) id: Id,
63 pub(crate) provider: ArgProvider,
64 pub(crate) name: &'help str,
65 pub(crate) help: Option<&'help str>,
66 pub(crate) long_help: Option<&'help str>,
67 pub(crate) action: Option<ArgAction>,
68 pub(crate) value_parser: Option<super::ValueParser>,
69 pub(crate) blacklist: Vec<Id>,
70 pub(crate) settings: ArgFlags,
71 pub(crate) overrides: Vec<Id>,
72 pub(crate) groups: Vec<Id>,
73 pub(crate) requires: Vec<(ArgPredicate<'help>, Id)>,
74 pub(crate) r_ifs: Vec<(Id, &'help str)>,
75 pub(crate) r_ifs_all: Vec<(Id, &'help str)>,
76 pub(crate) r_unless: Vec<Id>,
77 pub(crate) r_unless_all: Vec<Id>,
78 pub(crate) short: Option<char>,
79 pub(crate) long: Option<&'help str>,
80 pub(crate) aliases: Vec<(&'help str, bool)>, // (name, visible)
81 pub(crate) short_aliases: Vec<(char, bool)>, // (name, visible)
82 pub(crate) disp_ord: DisplayOrder,
83 pub(crate) possible_vals: Vec<PossibleValue<'help>>,
84 pub(crate) val_names: Vec<&'help str>,
85 pub(crate) num_vals: Option<usize>,
86 pub(crate) max_occurs: Option<usize>,
87 pub(crate) max_vals: Option<usize>,
88 pub(crate) min_vals: Option<usize>,
89 pub(crate) validator: Option<Arc<Mutex<Validator<'help>>>>,
90 pub(crate) validator_os: Option<Arc<Mutex<ValidatorOs<'help>>>>,
91 pub(crate) val_delim: Option<char>,
92 pub(crate) default_vals: Vec<&'help OsStr>,
93 pub(crate) default_vals_ifs: Vec<(Id, ArgPredicate<'help>, Option<&'help OsStr>)>,
94 pub(crate) default_missing_vals: Vec<&'help OsStr>,
95 #[cfg(feature = "env")]
96 pub(crate) env: Option<(&'help OsStr, Option<OsString>)>,
97 pub(crate) terminator: Option<&'help str>,
98 pub(crate) index: Option<usize>,
99 pub(crate) help_heading: Option<Option<&'help str>>,
100 pub(crate) value_hint: Option<ValueHint>,
101 }
102
103 /// # Basic API
104 impl<'help> Arg<'help> {
105 /// Create a new [`Arg`] with a unique name.
106 ///
107 /// The name is used to check whether or not the argument was used at
108 /// runtime, get values, set relationships with other args, etc..
109 ///
110 /// **NOTE:** In the case of arguments that take values (i.e. [`Arg::takes_value(true)`])
111 /// and positional arguments (i.e. those without a preceding `-` or `--`) the name will also
112 /// be displayed when the user prints the usage/help information of the program.
113 ///
114 /// # Examples
115 ///
116 /// ```rust
117 /// # use clap::{Command, Arg};
118 /// Arg::new("config")
119 /// # ;
120 /// ```
121 /// [`Arg::takes_value(true)`]: Arg::takes_value()
122 pub fn new<S: Into<&'help str>>(n: S) -> Self {
123 Arg::default().name(n)
124 }
125
126 /// Set the identifier used for referencing this argument in the clap API.
127 ///
128 /// See [`Arg::new`] for more details.
129 #[must_use]
130 pub fn id<S: Into<&'help str>>(mut self, n: S) -> Self {
131 let name = n.into();
132 self.id = Id::from(&*name);
133 self.name = name;
134 self
135 }
136
137 /// Deprecated, replaced with [`Arg::id`]
138 #[cfg_attr(
139 feature = "deprecated",
140 deprecated(since = "3.1.0", note = "Replaced with `Arg::id`")
141 )]
142 pub fn name<S: Into<&'help str>>(self, n: S) -> Self {
143 self.id(n)
144 }
145
146 /// Sets the short version of the argument without the preceding `-`.
147 ///
148 /// By default `V` and `h` are used by the auto-generated `version` and `help` arguments,
149 /// respectively. You may use the uppercase `V` or lowercase `h` for your own arguments, in
150 /// which case `clap` simply will not assign those to the auto-generated
151 /// `version` or `help` arguments.
152 ///
153 /// # Examples
154 ///
155 /// When calling `short`, use a single valid UTF-8 character which will allow using the
156 /// argument via a single hyphen (`-`) such as `-c`:
157 ///
158 /// ```rust
159 /// # use clap::{Command, Arg};
160 /// let m = Command::new("prog")
161 /// .arg(Arg::new("config")
162 /// .short('c')
163 /// .takes_value(true))
164 /// .get_matches_from(vec![
165 /// "prog", "-c", "file.toml"
166 /// ]);
167 ///
168 /// assert_eq!(m.get_one::<String>("config").map(String::as_str), Some("file.toml"));
169 /// ```
170 #[inline]
171 #[must_use]
172 pub fn short(mut self, s: char) -> Self {
173 assert!(s != '-', "short option name cannot be `-`");
174
175 self.short = Some(s);
176 self
177 }
178
179 /// Sets the long version of the argument without the preceding `--`.
180 ///
181 /// By default `version` and `help` are used by the auto-generated `version` and `help`
182 /// arguments, respectively. You may use the word `version` or `help` for the long form of your
183 /// own arguments, in which case `clap` simply will not assign those to the auto-generated
184 /// `version` or `help` arguments.
185 ///
186 /// **NOTE:** Any leading `-` characters will be stripped
187 ///
188 /// # Examples
189 ///
190 /// To set `long` use a word containing valid UTF-8. If you supply a double leading
191 /// `--` such as `--config` they will be stripped. Hyphens in the middle of the word, however,
192 /// will *not* be stripped (i.e. `config-file` is allowed).
193 ///
194 /// Setting `long` allows using the argument via a double hyphen (`--`) such as `--config`
195 ///
196 /// ```rust
197 /// # use clap::{Command, Arg};
198 /// let m = Command::new("prog")
199 /// .arg(Arg::new("cfg")
200 /// .long("config")
201 /// .takes_value(true))
202 /// .get_matches_from(vec![
203 /// "prog", "--config", "file.toml"
204 /// ]);
205 ///
206 /// assert_eq!(m.get_one::<String>("cfg").map(String::as_str), Some("file.toml"));
207 /// ```
208 #[inline]
209 #[must_use]
210 pub fn long(mut self, l: &'help str) -> Self {
211 #[cfg(feature = "unstable-v4")]
212 {
213 self.long = Some(l);
214 }
215 #[cfg(not(feature = "unstable-v4"))]
216 {
217 self.long = Some(l.trim_start_matches(|c| c == '-'));
218 }
219 self
220 }
221
222 /// Add an alias, which functions as a hidden long flag.
223 ///
224 /// This is more efficient, and easier than creating multiple hidden arguments as one only
225 /// needs to check for the existence of this command, and not all variants.
226 ///
227 /// # Examples
228 ///
229 /// ```rust
230 /// # use clap::{Command, Arg};
231 /// let m = Command::new("prog")
232 /// .arg(Arg::new("test")
233 /// .long("test")
234 /// .alias("alias")
235 /// .takes_value(true))
236 /// .get_matches_from(vec![
237 /// "prog", "--alias", "cool"
238 /// ]);
239 /// assert!(m.contains_id("test"));
240 /// assert_eq!(m.value_of("test"), Some("cool"));
241 /// ```
242 #[must_use]
243 pub fn alias<S: Into<&'help str>>(mut self, name: S) -> Self {
244 self.aliases.push((name.into(), false));
245 self
246 }
247
248 /// Add an alias, which functions as a hidden short flag.
249 ///
250 /// This is more efficient, and easier than creating multiple hidden arguments as one only
251 /// needs to check for the existence of this command, and not all variants.
252 ///
253 /// # Examples
254 ///
255 /// ```rust
256 /// # use clap::{Command, Arg};
257 /// let m = Command::new("prog")
258 /// .arg(Arg::new("test")
259 /// .short('t')
260 /// .short_alias('e')
261 /// .takes_value(true))
262 /// .get_matches_from(vec![
263 /// "prog", "-e", "cool"
264 /// ]);
265 /// assert!(m.contains_id("test"));
266 /// assert_eq!(m.value_of("test"), Some("cool"));
267 /// ```
268 #[must_use]
269 pub fn short_alias(mut self, name: char) -> Self {
270 assert!(name != '-', "short alias name cannot be `-`");
271
272 self.short_aliases.push((name, false));
273 self
274 }
275
276 /// Add aliases, which function as hidden long flags.
277 ///
278 /// This is more efficient, and easier than creating multiple hidden subcommands as one only
279 /// needs to check for the existence of this command, and not all variants.
280 ///
281 /// # Examples
282 ///
283 /// ```rust
284 /// # use clap::{Command, Arg, ArgAction};
285 /// let m = Command::new("prog")
286 /// .arg(Arg::new("test")
287 /// .long("test")
288 /// .aliases(&["do-stuff", "do-tests", "tests"])
289 /// .action(ArgAction::SetTrue)
290 /// .help("the file to add")
291 /// .required(false))
292 /// .get_matches_from(vec![
293 /// "prog", "--do-tests"
294 /// ]);
295 /// assert_eq!(*m.get_one::<bool>("test").expect("defaulted by clap"), true);
296 /// ```
297 #[must_use]
298 pub fn aliases(mut self, names: &[&'help str]) -> Self {
299 self.aliases.extend(names.iter().map(|&x| (x, false)));
300 self
301 }
302
303 /// Add aliases, which functions as a hidden short flag.
304 ///
305 /// This is more efficient, and easier than creating multiple hidden subcommands as one only
306 /// needs to check for the existence of this command, and not all variants.
307 ///
308 /// # Examples
309 ///
310 /// ```rust
311 /// # use clap::{Command, Arg, ArgAction};
312 /// let m = Command::new("prog")
313 /// .arg(Arg::new("test")
314 /// .short('t')
315 /// .short_aliases(&['e', 's'])
316 /// .action(ArgAction::SetTrue)
317 /// .help("the file to add")
318 /// .required(false))
319 /// .get_matches_from(vec![
320 /// "prog", "-s"
321 /// ]);
322 /// assert_eq!(*m.get_one::<bool>("test").expect("defaulted by clap"), true);
323 /// ```
324 #[must_use]
325 pub fn short_aliases(mut self, names: &[char]) -> Self {
326 for s in names {
327 assert!(s != &'-', "short alias name cannot be `-`");
328 self.short_aliases.push((*s, false));
329 }
330 self
331 }
332
333 /// Add an alias, which functions as a visible long flag.
334 ///
335 /// Like [`Arg::alias`], except that they are visible inside the help message.
336 ///
337 /// # Examples
338 ///
339 /// ```rust
340 /// # use clap::{Command, Arg};
341 /// let m = Command::new("prog")
342 /// .arg(Arg::new("test")
343 /// .visible_alias("something-awesome")
344 /// .long("test")
345 /// .takes_value(true))
346 /// .get_matches_from(vec![
347 /// "prog", "--something-awesome", "coffee"
348 /// ]);
349 /// assert!(m.contains_id("test"));
350 /// assert_eq!(m.value_of("test"), Some("coffee"));
351 /// ```
352 /// [`Command::alias`]: Arg::alias()
353 #[must_use]
354 pub fn visible_alias<S: Into<&'help str>>(mut self, name: S) -> Self {
355 self.aliases.push((name.into(), true));
356 self
357 }
358
359 /// Add an alias, which functions as a visible short flag.
360 ///
361 /// Like [`Arg::short_alias`], except that they are visible inside the help message.
362 ///
363 /// # Examples
364 ///
365 /// ```rust
366 /// # use clap::{Command, Arg};
367 /// let m = Command::new("prog")
368 /// .arg(Arg::new("test")
369 /// .long("test")
370 /// .visible_short_alias('t')
371 /// .takes_value(true))
372 /// .get_matches_from(vec![
373 /// "prog", "-t", "coffee"
374 /// ]);
375 /// assert!(m.contains_id("test"));
376 /// assert_eq!(m.value_of("test"), Some("coffee"));
377 /// ```
378 #[must_use]
379 pub fn visible_short_alias(mut self, name: char) -> Self {
380 assert!(name != '-', "short alias name cannot be `-`");
381
382 self.short_aliases.push((name, true));
383 self
384 }
385
386 /// Add aliases, which function as visible long flags.
387 ///
388 /// Like [`Arg::aliases`], except that they are visible inside the help message.
389 ///
390 /// # Examples
391 ///
392 /// ```rust
393 /// # use clap::{Command, Arg, ArgAction};
394 /// let m = Command::new("prog")
395 /// .arg(Arg::new("test")
396 /// .long("test")
397 /// .action(ArgAction::SetTrue)
398 /// .visible_aliases(&["something", "awesome", "cool"]))
399 /// .get_matches_from(vec![
400 /// "prog", "--awesome"
401 /// ]);
402 /// assert_eq!(*m.get_one::<bool>("test").expect("defaulted by clap"), true);
403 /// ```
404 /// [`Command::aliases`]: Arg::aliases()
405 #[must_use]
406 pub fn visible_aliases(mut self, names: &[&'help str]) -> Self {
407 self.aliases.extend(names.iter().map(|n| (*n, true)));
408 self
409 }
410
411 /// Add aliases, which function as visible short flags.
412 ///
413 /// Like [`Arg::short_aliases`], except that they are visible inside the help message.
414 ///
415 /// # Examples
416 ///
417 /// ```rust
418 /// # use clap::{Command, Arg, ArgAction};
419 /// let m = Command::new("prog")
420 /// .arg(Arg::new("test")
421 /// .long("test")
422 /// .action(ArgAction::SetTrue)
423 /// .visible_short_aliases(&['t', 'e']))
424 /// .get_matches_from(vec![
425 /// "prog", "-t"
426 /// ]);
427 /// assert_eq!(*m.get_one::<bool>("test").expect("defaulted by clap"), true);
428 /// ```
429 #[must_use]
430 pub fn visible_short_aliases(mut self, names: &[char]) -> Self {
431 for n in names {
432 assert!(n != &'-', "short alias name cannot be `-`");
433 self.short_aliases.push((*n, true));
434 }
435 self
436 }
437
438 /// Specifies the index of a positional argument **starting at** 1.
439 ///
440 /// **NOTE:** The index refers to position according to **other positional argument**. It does
441 /// not define position in the argument list as a whole.
442 ///
443 /// **NOTE:** You can optionally leave off the `index` method, and the index will be
444 /// assigned in order of evaluation. Utilizing the `index` method allows for setting
445 /// indexes out of order
446 ///
447 /// **NOTE:** This is only meant to be used for positional arguments and shouldn't to be used
448 /// with [`Arg::short`] or [`Arg::long`].
449 ///
450 /// **NOTE:** When utilized with [`Arg::multiple_values(true)`], only the **last** positional argument
451 /// may be defined as multiple (i.e. with the highest index)
452 ///
453 /// # Panics
454 ///
455 /// [`Command`] will [`panic!`] if indexes are skipped (such as defining `index(1)` and `index(3)`
456 /// but not `index(2)`, or a positional argument is defined as multiple and is not the highest
457 /// index
458 ///
459 /// # Examples
460 ///
461 /// ```rust
462 /// # use clap::{Command, Arg};
463 /// Arg::new("config")
464 /// .index(1)
465 /// # ;
466 /// ```
467 ///
468 /// ```rust
469 /// # use clap::{Command, Arg};
470 /// let m = Command::new("prog")
471 /// .arg(Arg::new("mode")
472 /// .index(1))
473 /// .arg(Arg::new("debug")
474 /// .long("debug"))
475 /// .get_matches_from(vec![
476 /// "prog", "--debug", "fast"
477 /// ]);
478 ///
479 /// assert!(m.contains_id("mode"));
480 /// assert_eq!(m.value_of("mode"), Some("fast")); // notice index(1) means "first positional"
481 /// // *not* first argument
482 /// ```
483 /// [`Arg::short`]: Arg::short()
484 /// [`Arg::long`]: Arg::long()
485 /// [`Arg::multiple_values(true)`]: Arg::multiple_values()
486 /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html
487 /// [`Command`]: crate::Command
488 #[inline]
489 #[must_use]
490 pub fn index(mut self, idx: usize) -> Self {
491 self.index = Some(idx);
492 self
493 }
494
495 /// This arg is the last, or final, positional argument (i.e. has the highest
496 /// index) and is *only* able to be accessed via the `--` syntax (i.e. `$ prog args --
497 /// last_arg`).
498 ///
499 /// Even, if no other arguments are left to parse, if the user omits the `--` syntax
500 /// they will receive an [`UnknownArgument`] error. Setting an argument to `.last(true)` also
501 /// allows one to access this arg early using the `--` syntax. Accessing an arg early, even with
502 /// the `--` syntax is otherwise not possible.
503 ///
504 /// **NOTE:** This will change the usage string to look like `$ prog [OPTIONS] [-- <ARG>]` if
505 /// `ARG` is marked as `.last(true)`.
506 ///
507 /// **NOTE:** This setting will imply [`crate::Command::dont_collapse_args_in_usage`] because failing
508 /// to set this can make the usage string very confusing.
509 ///
510 /// **NOTE**: This setting only applies to positional arguments, and has no effect on OPTIONS
511 ///
512 /// **NOTE:** Setting this requires [`Arg::takes_value`]
513 ///
514 /// **CAUTION:** Using this setting *and* having child subcommands is not
515 /// recommended with the exception of *also* using
516 /// [`crate::Command::args_conflicts_with_subcommands`]
517 /// (or [`crate::Command::subcommand_negates_reqs`] if the argument marked `Last` is also
518 /// marked [`Arg::required`])
519 ///
520 /// # Examples
521 ///
522 /// ```rust
523 /// # use clap::Arg;
524 /// Arg::new("args")
525 /// .takes_value(true)
526 /// .last(true)
527 /// # ;
528 /// ```
529 ///
530 /// Setting `last` ensures the arg has the highest [index] of all positional args
531 /// and requires that the `--` syntax be used to access it early.
532 ///
533 /// ```rust
534 /// # use clap::{Command, Arg};
535 /// let res = Command::new("prog")
536 /// .arg(Arg::new("first"))
537 /// .arg(Arg::new("second"))
538 /// .arg(Arg::new("third")
539 /// .takes_value(true)
540 /// .last(true))
541 /// .try_get_matches_from(vec![
542 /// "prog", "one", "--", "three"
543 /// ]);
544 ///
545 /// assert!(res.is_ok());
546 /// let m = res.unwrap();
547 /// assert_eq!(m.value_of("third"), Some("three"));
548 /// assert!(m.value_of("second").is_none());
549 /// ```
550 ///
551 /// Even if the positional argument marked `Last` is the only argument left to parse,
552 /// failing to use the `--` syntax results in an error.
553 ///
554 /// ```rust
555 /// # use clap::{Command, Arg, ErrorKind};
556 /// let res = Command::new("prog")
557 /// .arg(Arg::new("first"))
558 /// .arg(Arg::new("second"))
559 /// .arg(Arg::new("third")
560 /// .takes_value(true)
561 /// .last(true))
562 /// .try_get_matches_from(vec![
563 /// "prog", "one", "two", "three"
564 /// ]);
565 ///
566 /// assert!(res.is_err());
567 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
568 /// ```
569 /// [index]: Arg::index()
570 /// [`UnknownArgument`]: crate::ErrorKind::UnknownArgument
571 #[inline]
572 #[must_use]
573 pub fn last(self, yes: bool) -> Self {
574 if yes {
575 self.setting(ArgSettings::Last)
576 } else {
577 self.unset_setting(ArgSettings::Last)
578 }
579 }
580
581 /// Specifies that the argument must be present.
582 ///
583 /// Required by default means it is required, when no other conflicting rules or overrides have
584 /// been evaluated. Conflicting rules take precedence over being required.
585 ///
586 /// **Pro tip:** Flags (i.e. not positional, or arguments that take values) shouldn't be
587 /// required by default. This is because if a flag were to be required, it should simply be
588 /// implied. No additional information is required from user. Flags by their very nature are
589 /// simply boolean on/off switches. The only time a user *should* be required to use a flag
590 /// is if the operation is destructive in nature, and the user is essentially proving to you,
591 /// "Yes, I know what I'm doing."
592 ///
593 /// # Examples
594 ///
595 /// ```rust
596 /// # use clap::Arg;
597 /// Arg::new("config")
598 /// .required(true)
599 /// # ;
600 /// ```
601 ///
602 /// Setting required requires that the argument be used at runtime.
603 ///
604 /// ```rust
605 /// # use clap::{Command, Arg};
606 /// let res = Command::new("prog")
607 /// .arg(Arg::new("cfg")
608 /// .required(true)
609 /// .takes_value(true)
610 /// .long("config"))
611 /// .try_get_matches_from(vec![
612 /// "prog", "--config", "file.conf",
613 /// ]);
614 ///
615 /// assert!(res.is_ok());
616 /// ```
617 ///
618 /// Setting required and then *not* supplying that argument at runtime is an error.
619 ///
620 /// ```rust
621 /// # use clap::{Command, Arg, ErrorKind};
622 /// let res = Command::new("prog")
623 /// .arg(Arg::new("cfg")
624 /// .required(true)
625 /// .takes_value(true)
626 /// .long("config"))
627 /// .try_get_matches_from(vec![
628 /// "prog"
629 /// ]);
630 ///
631 /// assert!(res.is_err());
632 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
633 /// ```
634 #[inline]
635 #[must_use]
636 pub fn required(self, yes: bool) -> Self {
637 if yes {
638 self.setting(ArgSettings::Required)
639 } else {
640 self.unset_setting(ArgSettings::Required)
641 }
642 }
643
644 /// Sets an argument that is required when this one is present
645 ///
646 /// i.e. when using this argument, the following argument *must* be present.
647 ///
648 /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required
649 ///
650 /// # Examples
651 ///
652 /// ```rust
653 /// # use clap::Arg;
654 /// Arg::new("config")
655 /// .requires("input")
656 /// # ;
657 /// ```
658 ///
659 /// Setting [`Arg::requires(name)`] requires that the argument be used at runtime if the
660 /// defining argument is used. If the defining argument isn't used, the other argument isn't
661 /// required
662 ///
663 /// ```rust
664 /// # use clap::{Command, Arg};
665 /// let res = Command::new("prog")
666 /// .arg(Arg::new("cfg")
667 /// .takes_value(true)
668 /// .requires("input")
669 /// .long("config"))
670 /// .arg(Arg::new("input"))
671 /// .try_get_matches_from(vec![
672 /// "prog"
673 /// ]);
674 ///
675 /// assert!(res.is_ok()); // We didn't use cfg, so input wasn't required
676 /// ```
677 ///
678 /// Setting [`Arg::requires(name)`] and *not* supplying that argument is an error.
679 ///
680 /// ```rust
681 /// # use clap::{Command, Arg, ErrorKind};
682 /// let res = Command::new("prog")
683 /// .arg(Arg::new("cfg")
684 /// .takes_value(true)
685 /// .requires("input")
686 /// .long("config"))
687 /// .arg(Arg::new("input"))
688 /// .try_get_matches_from(vec![
689 /// "prog", "--config", "file.conf"
690 /// ]);
691 ///
692 /// assert!(res.is_err());
693 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
694 /// ```
695 /// [`Arg::requires(name)`]: Arg::requires()
696 /// [Conflicting]: Arg::conflicts_with()
697 /// [override]: Arg::overrides_with()
698 #[must_use]
699 pub fn requires<T: Key>(mut self, arg_id: T) -> Self {
700 self.requires.push((ArgPredicate::IsPresent, arg_id.into()));
701 self
702 }
703
704 /// This argument must be passed alone; it conflicts with all other arguments.
705 ///
706 /// # Examples
707 ///
708 /// ```rust
709 /// # use clap::Arg;
710 /// Arg::new("config")
711 /// .exclusive(true)
712 /// # ;
713 /// ```
714 ///
715 /// Setting an exclusive argument and having any other arguments present at runtime
716 /// is an error.
717 ///
718 /// ```rust
719 /// # use clap::{Command, Arg, ErrorKind};
720 /// let res = Command::new("prog")
721 /// .arg(Arg::new("exclusive")
722 /// .takes_value(true)
723 /// .exclusive(true)
724 /// .long("exclusive"))
725 /// .arg(Arg::new("debug")
726 /// .long("debug"))
727 /// .arg(Arg::new("input"))
728 /// .try_get_matches_from(vec![
729 /// "prog", "--exclusive", "file.conf", "file.txt"
730 /// ]);
731 ///
732 /// assert!(res.is_err());
733 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict);
734 /// ```
735 #[inline]
736 #[must_use]
737 pub fn exclusive(self, yes: bool) -> Self {
738 if yes {
739 self.setting(ArgSettings::Exclusive)
740 } else {
741 self.unset_setting(ArgSettings::Exclusive)
742 }
743 }
744
745 /// Specifies that an argument can be matched to all child [`Subcommand`]s.
746 ///
747 /// **NOTE:** Global arguments *only* propagate down, **not** up (to parent commands), however
748 /// their values once a user uses them will be propagated back up to parents. In effect, this
749 /// means one should *define* all global arguments at the top level, however it doesn't matter
750 /// where the user *uses* the global argument.
751 ///
752 /// # Examples
753 ///
754 /// Assume an application with two subcommands, and you'd like to define a
755 /// `--verbose` flag that can be called on any of the subcommands and parent, but you don't
756 /// want to clutter the source with three duplicate [`Arg`] definitions.
757 ///
758 /// ```rust
759 /// # use clap::{Command, Arg, ArgAction};
760 /// let m = Command::new("prog")
761 /// .arg(Arg::new("verb")
762 /// .long("verbose")
763 /// .short('v')
764 /// .action(ArgAction::SetTrue)
765 /// .global(true))
766 /// .subcommand(Command::new("test"))
767 /// .subcommand(Command::new("do-stuff"))
768 /// .get_matches_from(vec![
769 /// "prog", "do-stuff", "--verbose"
770 /// ]);
771 ///
772 /// assert_eq!(m.subcommand_name(), Some("do-stuff"));
773 /// let sub_m = m.subcommand_matches("do-stuff").unwrap();
774 /// assert_eq!(*sub_m.get_one::<bool>("verb").expect("defaulted by clap"), true);
775 /// ```
776 ///
777 /// [`Subcommand`]: crate::Subcommand
778 #[inline]
779 #[must_use]
780 pub fn global(self, yes: bool) -> Self {
781 if yes {
782 self.setting(ArgSettings::Global)
783 } else {
784 self.unset_setting(ArgSettings::Global)
785 }
786 }
787
788 /// Deprecated, replaced with [`Arg::action`] ([Issue #3772](https://github.com/clap-rs/clap/issues/3772))
789 #[inline]
790 #[must_use]
791 #[cfg_attr(
792 feature = "deprecated",
793 deprecated(since = "3.2.0", note = "Replaced with `Arg::action` (Issue #3772)")
794 )]
795 pub fn multiple_occurrences(self, yes: bool) -> Self {
796 if yes {
797 self.setting(ArgSettings::MultipleOccurrences)
798 } else {
799 self.unset_setting(ArgSettings::MultipleOccurrences)
800 }
801 }
802
803 /// Deprecated, for flags this is replaced with `action(ArgAction::Count).value_parser(value_parser!(u8).range(..max))`
804 #[inline]
805 #[must_use]
806 #[cfg_attr(
807 feature = "deprecated",
808 deprecated(
809 since = "3.2.0",
810 note = "For flags, replaced with `action(ArgAction::Count).value_parser(value_parser!(u8).range(..max))`"
811 )
812 )]
813 pub fn max_occurrences(mut self, qty: usize) -> Self {
814 self.max_occurs = Some(qty);
815 if qty > 1 {
816 self.multiple_occurrences(true)
817 } else {
818 self
819 }
820 }
821
822 /// Check if the [`ArgSettings`] variant is currently set on the argument.
823 ///
824 /// [`ArgSettings`]: crate::ArgSettings
825 #[inline]
826 pub fn is_set(&self, s: ArgSettings) -> bool {
827 self.settings.is_set(s)
828 }
829
830 /// Apply a setting to the argument.
831 ///
832 /// See [`ArgSettings`] for a full list of possibilities and examples.
833 ///
834 /// # Examples
835 ///
836 /// ```no_run
837 /// # use clap::{Arg, ArgSettings};
838 /// Arg::new("config")
839 /// .setting(ArgSettings::Required)
840 /// .setting(ArgSettings::TakesValue)
841 /// # ;
842 /// ```
843 ///
844 /// ```no_run
845 /// # use clap::{Arg, ArgSettings};
846 /// Arg::new("config")
847 /// .setting(ArgSettings::Required | ArgSettings::TakesValue)
848 /// # ;
849 /// ```
850 #[inline]
851 #[must_use]
852 pub fn setting<F>(mut self, setting: F) -> Self
853 where
854 F: Into<ArgFlags>,
855 {
856 self.settings.insert(setting.into());
857 self
858 }
859
860 /// Remove a setting from the argument.
861 ///
862 /// See [`ArgSettings`] for a full list of possibilities and examples.
863 ///
864 /// # Examples
865 ///
866 /// ```no_run
867 /// # use clap::{Arg, ArgSettings};
868 /// Arg::new("config")
869 /// .unset_setting(ArgSettings::Required)
870 /// .unset_setting(ArgSettings::TakesValue)
871 /// # ;
872 /// ```
873 ///
874 /// ```no_run
875 /// # use clap::{Arg, ArgSettings};
876 /// Arg::new("config")
877 /// .unset_setting(ArgSettings::Required | ArgSettings::TakesValue)
878 /// # ;
879 /// ```
880 #[inline]
881 #[must_use]
882 pub fn unset_setting<F>(mut self, setting: F) -> Self
883 where
884 F: Into<ArgFlags>,
885 {
886 self.settings.remove(setting.into());
887 self
888 }
889 }
890
891 /// # Value Handling
892 impl<'help> Arg<'help> {
893 /// Specifies that the argument takes a value at run time.
894 ///
895 /// **NOTE:** values for arguments may be specified in any of the following methods
896 ///
897 /// - Using a space such as `-o value` or `--option value`
898 /// - Using an equals and no space such as `-o=value` or `--option=value`
899 /// - Use a short and no space such as `-ovalue`
900 ///
901 /// **NOTE:** By default, args which allow [multiple values] are delimited by commas, meaning
902 /// `--option=val1,val2,val3` is three values for the `--option` argument. If you wish to
903 /// change the delimiter to another character you can use [`Arg::value_delimiter(char)`],
904 /// alternatively you can turn delimiting values **OFF** by using
905 /// [`Arg::use_value_delimiter(false)`][Arg::use_value_delimiter]
906 ///
907 /// # Examples
908 ///
909 /// ```rust
910 /// # use clap::{Command, Arg};
911 /// let m = Command::new("prog")
912 /// .arg(Arg::new("mode")
913 /// .long("mode")
914 /// .takes_value(true))
915 /// .get_matches_from(vec![
916 /// "prog", "--mode", "fast"
917 /// ]);
918 ///
919 /// assert!(m.contains_id("mode"));
920 /// assert_eq!(m.value_of("mode"), Some("fast"));
921 /// ```
922 /// [`Arg::value_delimiter(char)`]: Arg::value_delimiter()
923 /// [multiple values]: Arg::multiple_values
924 #[inline]
925 #[must_use]
926 pub fn takes_value(self, yes: bool) -> Self {
927 if yes {
928 self.setting(ArgSettings::TakesValue)
929 } else {
930 self.unset_setting(ArgSettings::TakesValue)
931 }
932 }
933
934 /// Specify the behavior when parsing an argument
935 ///
936 /// # Examples
937 ///
938 /// ```rust
939 /// # use clap::Command;
940 /// # use clap::Arg;
941 /// let cmd = Command::new("mycmd")
942 /// .arg(
943 /// Arg::new("flag")
944 /// .long("flag")
945 /// .action(clap::ArgAction::Set)
946 /// );
947 ///
948 /// let matches = cmd.try_get_matches_from(["mycmd", "--flag", "value"]).unwrap();
949 /// assert!(matches.contains_id("flag"));
950 /// assert_eq!(matches.occurrences_of("flag"), 0);
951 /// assert_eq!(
952 /// matches.get_many::<String>("flag").unwrap_or_default().map(|v| v.as_str()).collect::<Vec<_>>(),
953 /// vec!["value"]
954 /// );
955 /// ```
956 #[inline]
957 #[must_use]
958 pub fn action(mut self, action: ArgAction) -> Self {
959 self.action = Some(action);
960 self
961 }
962
963 /// Specify the type of the argument.
964 ///
965 /// This allows parsing and validating a value before storing it into
966 /// [`ArgMatches`][crate::ArgMatches].
967 ///
968 /// See also
969 /// - [`value_parser!`][crate::value_parser!] for auto-selecting a value parser for a given type
970 /// - [`BoolishValueParser`][crate::builder::BoolishValueParser], and [`FalseyValueParser`][crate::builder::FalseyValueParser] for alternative `bool` implementations
971 /// - [`NonEmptyStringValueParser`][crate::builder::NonEmptyStringValueParser] for basic validation for strings
972 /// - [`RangedI64ValueParser`][crate::builder::RangedI64ValueParser] and [`RangedU64ValueParser`][crate::builder::RangedU64ValueParser] for numeric ranges
973 /// - [`EnumValueParser`][crate::builder::EnumValueParser] and [`PossibleValuesParser`][crate::builder::PossibleValuesParser] for static enumerated values
974 /// - or any other [`TypedValueParser`][crate::builder::TypedValueParser] implementation
975 ///
976 /// ```rust
977 /// let mut cmd = clap::Command::new("raw")
978 /// .arg(
979 /// clap::Arg::new("color")
980 /// .long("color")
981 /// .value_parser(["always", "auto", "never"])
982 /// .default_value("auto")
983 /// )
984 /// .arg(
985 /// clap::Arg::new("hostname")
986 /// .long("hostname")
987 /// .value_parser(clap::builder::NonEmptyStringValueParser::new())
988 /// .takes_value(true)
989 /// .required(true)
990 /// )
991 /// .arg(
992 /// clap::Arg::new("port")
993 /// .long("port")
994 /// .value_parser(clap::value_parser!(u16).range(3000..))
995 /// .takes_value(true)
996 /// .required(true)
997 /// );
998 ///
999 /// let m = cmd.try_get_matches_from_mut(
1000 /// ["cmd", "--hostname", "rust-lang.org", "--port", "3001"]
1001 /// ).unwrap();
1002 ///
1003 /// let color: &String = m.get_one("color")
1004 /// .expect("default");
1005 /// assert_eq!(color, "auto");
1006 ///
1007 /// let hostname: &String = m.get_one("hostname")
1008 /// .expect("required");
1009 /// assert_eq!(hostname, "rust-lang.org");
1010 ///
1011 /// let port: u16 = *m.get_one("port")
1012 /// .expect("required");
1013 /// assert_eq!(port, 3001);
1014 /// ```
1015 pub fn value_parser(mut self, parser: impl Into<super::ValueParser>) -> Self {
1016 self.value_parser = Some(parser.into());
1017 self
1018 }
1019
1020 /// Specifies that the argument may have an unknown number of values
1021 ///
1022 /// Without any other settings, this argument may appear only *once*.
1023 ///
1024 /// For example, `--opt val1 val2` is allowed, but `--opt val1 val2 --opt val3` is not.
1025 ///
1026 /// **NOTE:** Setting this requires [`Arg::takes_value`].
1027 ///
1028 /// **WARNING:**
1029 ///
1030 /// Setting `multiple_values` for an argument that takes a value, but with no other details can
1031 /// be dangerous in some circumstances. Because multiple values are allowed,
1032 /// `--option val1 val2 val3` is perfectly valid. Be careful when designing a CLI where
1033 /// positional arguments are *also* expected as `clap` will continue parsing *values* until one
1034 /// of the following happens:
1035 ///
1036 /// - It reaches the [maximum number of values]
1037 /// - It reaches a [specific number of values]
1038 /// - It finds another flag or option (i.e. something that starts with a `-`)
1039 /// - It reaches a [value terminator][Arg::value_terminator] is reached
1040 ///
1041 /// Alternatively, [require a delimiter between values][Arg::require_delimiter].
1042 ///
1043 /// **WARNING:**
1044 ///
1045 /// When using args with `multiple_values` and [`subcommands`], one needs to consider the
1046 /// possibility of an argument value being the same as a valid subcommand. By default `clap` will
1047 /// parse the argument in question as a value *only if* a value is possible at that moment.
1048 /// Otherwise it will be parsed as a subcommand. In effect, this means using `multiple_values` with no
1049 /// additional parameters and a value that coincides with a subcommand name, the subcommand
1050 /// cannot be called unless another argument is passed between them.
1051 ///
1052 /// As an example, consider a CLI with an option `--ui-paths=<paths>...` and subcommand `signer`
1053 ///
1054 /// The following would be parsed as values to `--ui-paths`.
1055 ///
1056 /// ```text
1057 /// $ program --ui-paths path1 path2 signer
1058 /// ```
1059 ///
1060 /// This is because `--ui-paths` accepts multiple values. `clap` will continue parsing values
1061 /// until another argument is reached and it knows `--ui-paths` is done parsing.
1062 ///
1063 /// By adding additional parameters to `--ui-paths` we can solve this issue. Consider adding
1064 /// [`Arg::number_of_values(1)`] or using *only* [`ArgAction::Append`]. The following are all
1065 /// valid, and `signer` is parsed as a subcommand in the first case, but a value in the second
1066 /// case.
1067 ///
1068 /// ```text
1069 /// $ program --ui-paths path1 signer
1070 /// $ program --ui-paths path1 --ui-paths signer signer
1071 /// ```
1072 ///
1073 /// # Examples
1074 ///
1075 /// An example with options
1076 ///
1077 /// ```rust
1078 /// # use clap::{Command, Arg};
1079 /// let m = Command::new("prog")
1080 /// .arg(Arg::new("file")
1081 /// .takes_value(true)
1082 /// .multiple_values(true)
1083 /// .short('F'))
1084 /// .get_matches_from(vec![
1085 /// "prog", "-F", "file1", "file2", "file3"
1086 /// ]);
1087 ///
1088 /// assert!(m.contains_id("file"));
1089 /// let files: Vec<_> = m.values_of("file").unwrap().collect();
1090 /// assert_eq!(files, ["file1", "file2", "file3"]);
1091 /// ```
1092 ///
1093 /// Although `multiple_values` has been specified, we cannot use the argument more than once.
1094 ///
1095 /// ```rust
1096 /// # use clap::{Command, Arg, ErrorKind};
1097 /// let res = Command::new("prog")
1098 /// .arg(Arg::new("file")
1099 /// .takes_value(true)
1100 /// .multiple_values(true)
1101 /// .short('F'))
1102 /// .try_get_matches_from(vec![
1103 /// "prog", "-F", "file1", "-F", "file2", "-F", "file3"
1104 /// ]);
1105 ///
1106 /// assert!(res.is_err());
1107 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnexpectedMultipleUsage)
1108 /// ```
1109 ///
1110 /// A common mistake is to define an option which allows multiple values, and a positional
1111 /// argument.
1112 ///
1113 /// ```rust
1114 /// # use clap::{Command, Arg};
1115 /// let m = Command::new("prog")
1116 /// .arg(Arg::new("file")
1117 /// .takes_value(true)
1118 /// .multiple_values(true)
1119 /// .short('F'))
1120 /// .arg(Arg::new("word"))
1121 /// .get_matches_from(vec![
1122 /// "prog", "-F", "file1", "file2", "file3", "word"
1123 /// ]);
1124 ///
1125 /// assert!(m.contains_id("file"));
1126 /// let files: Vec<_> = m.values_of("file").unwrap().collect();
1127 /// assert_eq!(files, ["file1", "file2", "file3", "word"]); // wait...what?!
1128 /// assert!(!m.contains_id("word")); // but we clearly used word!
1129 /// ```
1130 ///
1131 /// The problem is `clap` doesn't know when to stop parsing values for "files". This is further
1132 /// compounded by if we'd said `word -F file1 file2` it would have worked fine, so it would
1133 /// appear to only fail sometimes...not good!
1134 ///
1135 /// A solution for the example above is to limit how many values with a [maximum], or [specific]
1136 /// number, or to say [`ArgAction::Append`] is ok, but multiple values is not.
1137 ///
1138 /// ```rust
1139 /// # use clap::{Command, Arg, ArgAction};
1140 /// let m = Command::new("prog")
1141 /// .arg(Arg::new("file")
1142 /// .takes_value(true)
1143 /// .action(ArgAction::Append)
1144 /// .short('F'))
1145 /// .arg(Arg::new("word"))
1146 /// .get_matches_from(vec![
1147 /// "prog", "-F", "file1", "-F", "file2", "-F", "file3", "word"
1148 /// ]);
1149 ///
1150 /// assert!(m.contains_id("file"));
1151 /// let files: Vec<_> = m.values_of("file").unwrap().collect();
1152 /// assert_eq!(files, ["file1", "file2", "file3"]);
1153 /// assert!(m.contains_id("word"));
1154 /// assert_eq!(m.value_of("word"), Some("word"));
1155 /// ```
1156 ///
1157 /// As a final example, let's fix the above error and get a pretty message to the user :)
1158 ///
1159 /// ```rust
1160 /// # use clap::{Command, Arg, ErrorKind, ArgAction};
1161 /// let res = Command::new("prog")
1162 /// .arg(Arg::new("file")
1163 /// .takes_value(true)
1164 /// .action(ArgAction::Append)
1165 /// .short('F'))
1166 /// .arg(Arg::new("word"))
1167 /// .try_get_matches_from(vec![
1168 /// "prog", "-F", "file1", "file2", "file3", "word"
1169 /// ]);
1170 ///
1171 /// assert!(res.is_err());
1172 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
1173 /// ```
1174 ///
1175 /// [`subcommands`]: crate::Command::subcommand()
1176 /// [`Arg::number_of_values(1)`]: Arg::number_of_values()
1177 /// [maximum number of values]: Arg::max_values()
1178 /// [specific number of values]: Arg::number_of_values()
1179 /// [maximum]: Arg::max_values()
1180 /// [specific]: Arg::number_of_values()
1181 #[inline]
1182 #[must_use]
1183 pub fn multiple_values(self, yes: bool) -> Self {
1184 if yes {
1185 self.setting(ArgSettings::MultipleValues)
1186 } else {
1187 self.unset_setting(ArgSettings::MultipleValues)
1188 }
1189 }
1190
1191 /// The number of values allowed for this argument.
1192 ///
1193 /// For example, if you had a
1194 /// `-f <file>` argument where you wanted exactly 3 'files' you would set
1195 /// `.number_of_values(3)`, and this argument wouldn't be satisfied unless the user provided
1196 /// 3 and only 3 values.
1197 ///
1198 /// **NOTE:** Does *not* require [`Arg::multiple_occurrences(true)`] to be set. Setting
1199 /// [`Arg::multiple_occurrences(true)`] would allow `-f <file> <file> <file> -f <file> <file> <file>` where
1200 /// as *not* setting it would only allow one occurrence of this argument.
1201 ///
1202 /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] and [`Arg::multiple_values(true)`].
1203 ///
1204 /// # Examples
1205 ///
1206 /// ```rust
1207 /// # use clap::{Command, Arg};
1208 /// Arg::new("file")
1209 /// .short('f')
1210 /// .number_of_values(3);
1211 /// ```
1212 ///
1213 /// Not supplying the correct number of values is an error
1214 ///
1215 /// ```rust
1216 /// # use clap::{Command, Arg, ErrorKind};
1217 /// let res = Command::new("prog")
1218 /// .arg(Arg::new("file")
1219 /// .takes_value(true)
1220 /// .number_of_values(2)
1221 /// .short('F'))
1222 /// .try_get_matches_from(vec![
1223 /// "prog", "-F", "file1"
1224 /// ]);
1225 ///
1226 /// assert!(res.is_err());
1227 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::WrongNumberOfValues);
1228 /// ```
1229 /// [`Arg::multiple_occurrences(true)`]: Arg::multiple_occurrences()
1230 #[inline]
1231 #[must_use]
1232 pub fn number_of_values(mut self, qty: usize) -> Self {
1233 self.num_vals = Some(qty);
1234 self.takes_value(true).multiple_values(true)
1235 }
1236
1237 /// The *maximum* number of values are for this argument.
1238 ///
1239 /// For example, if you had a
1240 /// `-f <file>` argument where you wanted up to 3 'files' you would set `.max_values(3)`, and
1241 /// this argument would be satisfied if the user provided, 1, 2, or 3 values.
1242 ///
1243 /// **NOTE:** This does *not* implicitly set [`Arg::multiple_occurrences(true)`]. This is because
1244 /// `-o val -o val` is multiple occurrences but a single value and `-o val1 val2` is a single
1245 /// occurrence with multiple values. For positional arguments this **does** set
1246 /// [`Arg::multiple_occurrences(true)`] because there is no way to determine the difference between multiple
1247 /// occurrences and multiple values.
1248 ///
1249 /// # Examples
1250 ///
1251 /// ```rust
1252 /// # use clap::{Command, Arg};
1253 /// Arg::new("file")
1254 /// .short('f')
1255 /// .max_values(3);
1256 /// ```
1257 ///
1258 /// Supplying less than the maximum number of values is allowed
1259 ///
1260 /// ```rust
1261 /// # use clap::{Command, Arg};
1262 /// let res = Command::new("prog")
1263 /// .arg(Arg::new("file")
1264 /// .takes_value(true)
1265 /// .max_values(3)
1266 /// .short('F'))
1267 /// .try_get_matches_from(vec![
1268 /// "prog", "-F", "file1", "file2"
1269 /// ]);
1270 ///
1271 /// assert!(res.is_ok());
1272 /// let m = res.unwrap();
1273 /// let files: Vec<_> = m.values_of("file").unwrap().collect();
1274 /// assert_eq!(files, ["file1", "file2"]);
1275 /// ```
1276 ///
1277 /// Supplying more than the maximum number of values is an error
1278 ///
1279 /// ```rust
1280 /// # use clap::{Command, Arg, ErrorKind};
1281 /// let res = Command::new("prog")
1282 /// .arg(Arg::new("file")
1283 /// .takes_value(true)
1284 /// .max_values(2)
1285 /// .short('F'))
1286 /// .try_get_matches_from(vec![
1287 /// "prog", "-F", "file1", "file2", "file3"
1288 /// ]);
1289 ///
1290 /// assert!(res.is_err());
1291 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
1292 /// ```
1293 /// [`Arg::multiple_occurrences(true)`]: Arg::multiple_occurrences()
1294 #[inline]
1295 #[must_use]
1296 pub fn max_values(mut self, qty: usize) -> Self {
1297 self.max_vals = Some(qty);
1298 self.takes_value(true).multiple_values(true)
1299 }
1300
1301 /// The *minimum* number of values for this argument.
1302 ///
1303 /// For example, if you had a
1304 /// `-f <file>` argument where you wanted at least 2 'files' you would set
1305 /// `.min_values(2)`, and this argument would be satisfied if the user provided, 2 or more
1306 /// values.
1307 ///
1308 /// **NOTE:** This does not implicitly set [`Arg::multiple_occurrences(true)`]. This is because
1309 /// `-o val -o val` is multiple occurrences but a single value and `-o val1 val2` is a single
1310 /// occurrence with multiple values. For positional arguments this **does** set
1311 /// [`Arg::multiple_occurrences(true)`] because there is no way to determine the difference between multiple
1312 /// occurrences and multiple values.
1313 ///
1314 /// **NOTE:** Passing a non-zero value is not the same as specifying [`Arg::required(true)`].
1315 /// This is due to min and max validation only being performed for present arguments,
1316 /// marking them as required will thus perform validation and a min value of 1
1317 /// is unnecessary, ignored if not required.
1318 ///
1319 /// # Examples
1320 ///
1321 /// ```rust
1322 /// # use clap::{Command, Arg};
1323 /// Arg::new("file")
1324 /// .short('f')
1325 /// .min_values(3);
1326 /// ```
1327 ///
1328 /// Supplying more than the minimum number of values is allowed
1329 ///
1330 /// ```rust
1331 /// # use clap::{Command, Arg};
1332 /// let res = Command::new("prog")
1333 /// .arg(Arg::new("file")
1334 /// .takes_value(true)
1335 /// .min_values(2)
1336 /// .short('F'))
1337 /// .try_get_matches_from(vec![
1338 /// "prog", "-F", "file1", "file2", "file3"
1339 /// ]);
1340 ///
1341 /// assert!(res.is_ok());
1342 /// let m = res.unwrap();
1343 /// let files: Vec<_> = m.values_of("file").unwrap().collect();
1344 /// assert_eq!(files, ["file1", "file2", "file3"]);
1345 /// ```
1346 ///
1347 /// Supplying less than the minimum number of values is an error
1348 ///
1349 /// ```rust
1350 /// # use clap::{Command, Arg, ErrorKind};
1351 /// let res = Command::new("prog")
1352 /// .arg(Arg::new("file")
1353 /// .takes_value(true)
1354 /// .min_values(2)
1355 /// .short('F'))
1356 /// .try_get_matches_from(vec![
1357 /// "prog", "-F", "file1"
1358 /// ]);
1359 ///
1360 /// assert!(res.is_err());
1361 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::TooFewValues);
1362 /// ```
1363 /// [`Arg::multiple_occurrences(true)`]: Arg::multiple_occurrences()
1364 /// [`Arg::required(true)`]: Arg::required()
1365 #[inline]
1366 #[must_use]
1367 pub fn min_values(mut self, qty: usize) -> Self {
1368 self.min_vals = Some(qty);
1369 self.takes_value(true).multiple_values(true)
1370 }
1371
1372 /// Placeholder for the argument's value in the help message / usage.
1373 ///
1374 /// This name is cosmetic only; the name is **not** used to access arguments.
1375 /// This setting can be very helpful when describing the type of input the user should be
1376 /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to
1377 /// use all capital letters for the value name.
1378 ///
1379 /// **NOTE:** implicitly sets [`Arg::takes_value(true)`]
1380 ///
1381 /// # Examples
1382 ///
1383 /// ```rust
1384 /// # use clap::{Command, Arg};
1385 /// Arg::new("cfg")
1386 /// .long("config")
1387 /// .value_name("FILE")
1388 /// # ;
1389 /// ```
1390 ///
1391 /// ```rust
1392 /// # use clap::{Command, Arg};
1393 /// let m = Command::new("prog")
1394 /// .arg(Arg::new("config")
1395 /// .long("config")
1396 /// .value_name("FILE")
1397 /// .help("Some help text"))
1398 /// .get_matches_from(vec![
1399 /// "prog", "--help"
1400 /// ]);
1401 /// ```
1402 /// Running the above program produces the following output
1403 ///
1404 /// ```text
1405 /// valnames
1406 ///
1407 /// USAGE:
1408 /// valnames [OPTIONS]
1409 ///
1410 /// OPTIONS:
1411 /// --config <FILE> Some help text
1412 /// -h, --help Print help information
1413 /// -V, --version Print version information
1414 /// ```
1415 /// [option]: Arg::takes_value()
1416 /// [positional]: Arg::index()
1417 /// [`Arg::takes_value(true)`]: Arg::takes_value()
1418 #[inline]
1419 #[must_use]
1420 pub fn value_name(self, name: &'help str) -> Self {
1421 self.value_names(&[name])
1422 }
1423
1424 /// Placeholders for the argument's values in the help message / usage.
1425 ///
1426 /// These names are cosmetic only, used for help and usage strings only. The names are **not**
1427 /// used to access arguments. The values of the arguments are accessed in numeric order (i.e.
1428 /// if you specify two names `one` and `two` `one` will be the first matched value, `two` will
1429 /// be the second).
1430 ///
1431 /// This setting can be very helpful when describing the type of input the user should be
1432 /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to
1433 /// use all capital letters for the value name.
1434 ///
1435 /// **Pro Tip:** It may help to use [`Arg::next_line_help(true)`] if there are long, or
1436 /// multiple value names in order to not throw off the help text alignment of all options.
1437 ///
1438 /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] and [`Arg::multiple_values(true)`].
1439 ///
1440 /// # Examples
1441 ///
1442 /// ```rust
1443 /// # use clap::{Command, Arg};
1444 /// Arg::new("speed")
1445 /// .short('s')
1446 /// .value_names(&["fast", "slow"]);
1447 /// ```
1448 ///
1449 /// ```rust
1450 /// # use clap::{Command, Arg};
1451 /// let m = Command::new("prog")
1452 /// .arg(Arg::new("io")
1453 /// .long("io-files")
1454 /// .value_names(&["INFILE", "OUTFILE"]))
1455 /// .get_matches_from(vec![
1456 /// "prog", "--help"
1457 /// ]);
1458 /// ```
1459 ///
1460 /// Running the above program produces the following output
1461 ///
1462 /// ```text
1463 /// valnames
1464 ///
1465 /// USAGE:
1466 /// valnames [OPTIONS]
1467 ///
1468 /// OPTIONS:
1469 /// -h, --help Print help information
1470 /// --io-files <INFILE> <OUTFILE> Some help text
1471 /// -V, --version Print version information
1472 /// ```
1473 /// [`Arg::next_line_help(true)`]: Arg::next_line_help()
1474 /// [`Arg::number_of_values`]: Arg::number_of_values()
1475 /// [`Arg::takes_value(true)`]: Arg::takes_value()
1476 /// [`Arg::multiple_values(true)`]: Arg::multiple_values()
1477 #[must_use]
1478 pub fn value_names(mut self, names: &[&'help str]) -> Self {
1479 self.val_names = names.to_vec();
1480 self.takes_value(true)
1481 }
1482
1483 /// Provide the shell a hint about how to complete this argument.
1484 ///
1485 /// See [`ValueHint`][crate::ValueHint] for more information.
1486 ///
1487 /// **NOTE:** implicitly sets [`Arg::takes_value(true)`].
1488 ///
1489 /// For example, to take a username as argument:
1490 ///
1491 /// ```
1492 /// # use clap::{Arg, ValueHint};
1493 /// Arg::new("user")
1494 /// .short('u')
1495 /// .long("user")
1496 /// .value_hint(ValueHint::Username);
1497 /// ```
1498 ///
1499 /// To take a full command line and its arguments (for example, when writing a command wrapper):
1500 ///
1501 /// ```
1502 /// # use clap::{Command, Arg, ValueHint};
1503 /// Command::new("prog")
1504 /// .trailing_var_arg(true)
1505 /// .arg(
1506 /// Arg::new("command")
1507 /// .takes_value(true)
1508 /// .multiple_values(true)
1509 /// .value_hint(ValueHint::CommandWithArguments)
1510 /// );
1511 /// ```
1512 #[must_use]
1513 pub fn value_hint(mut self, value_hint: ValueHint) -> Self {
1514 self.value_hint = Some(value_hint);
1515 self.takes_value(true)
1516 }
1517
1518 /// Deprecated, replaced with [`Arg::value_parser(...)`]
1519 #[inline]
1520 #[must_use]
1521 #[cfg_attr(
1522 feature = "deprecated",
1523 deprecated(since = "3.2.0", note = "Replaced with `Arg::value_parser(...)`")
1524 )]
1525 pub fn validator<F, O, E>(mut self, mut f: F) -> Self
1526 where
1527 F: FnMut(&str) -> Result<O, E> + Send + 'help,
1528 E: Into<Box<dyn Error + Send + Sync + 'static>>,
1529 {
1530 self.validator = Some(Arc::new(Mutex::new(move |s: &str| {
1531 f(s).map(|_| ()).map_err(|e| e.into())
1532 })));
1533 self
1534 }
1535
1536 /// Deprecated, replaced with [`Arg::value_parser(...)`]
1537 #[must_use]
1538 #[cfg_attr(
1539 feature = "deprecated",
1540 deprecated(since = "3.2.0", note = "Replaced with `Arg::value_parser(...)`")
1541 )]
1542 pub fn validator_os<F, O, E>(mut self, mut f: F) -> Self
1543 where
1544 F: FnMut(&OsStr) -> Result<O, E> + Send + 'help,
1545 E: Into<Box<dyn Error + Send + Sync + 'static>>,
1546 {
1547 self.validator_os = Some(Arc::new(Mutex::new(move |s: &OsStr| {
1548 f(s).map(|_| ()).map_err(|e| e.into())
1549 })));
1550 self
1551 }
1552
1553 /// Deprecated in [Issue #3743](https://github.com/clap-rs/clap/issues/3743), replaced with [`Arg::value_parser(...)`]
1554 #[cfg_attr(
1555 feature = "deprecated",
1556 deprecated(
1557 since = "3.2.0",
1558 note = "Deprecated in Issue #3743; eplaced with `Arg::value_parser(...)`"
1559 )
1560 )]
1561 #[cfg(feature = "regex")]
1562 #[must_use]
1563 pub fn validator_regex(
1564 self,
1565 regex: impl Into<RegexRef<'help>>,
1566 err_message: &'help str,
1567 ) -> Self {
1568 let regex = regex.into();
1569 self.validator(move |s: &str| {
1570 if regex.is_match(s) {
1571 Ok(())
1572 } else {
1573 Err(err_message)
1574 }
1575 })
1576 }
1577
1578 /// Deprecated, replaced with [`Arg::value_parser(PossibleValuesParser::new(...))`]
1579 #[cfg_attr(
1580 feature = "deprecated",
1581 deprecated(
1582 since = "3.2.0",
1583 note = "Replaced with `Arg::value_parser(PossibleValuesParser::new(...)).takes_value(true)`"
1584 )
1585 )]
1586 #[must_use]
1587 pub fn possible_value<T>(mut self, value: T) -> Self
1588 where
1589 T: Into<PossibleValue<'help>>,
1590 {
1591 self.possible_vals.push(value.into());
1592 self.takes_value(true)
1593 }
1594
1595 /// Deprecated, replaced with [`Arg::value_parser(PossibleValuesParser::new(...))`]
1596 #[cfg_attr(
1597 feature = "deprecated",
1598 deprecated(
1599 since = "3.2.0",
1600 note = "Replaced with `Arg::value_parser(PossibleValuesParser::new(...)).takes_value(true)`"
1601 )
1602 )]
1603 #[must_use]
1604 pub fn possible_values<I, T>(mut self, values: I) -> Self
1605 where
1606 I: IntoIterator<Item = T>,
1607 T: Into<PossibleValue<'help>>,
1608 {
1609 self.possible_vals
1610 .extend(values.into_iter().map(|value| value.into()));
1611 self.takes_value(true)
1612 }
1613
1614 /// Match values against [`Arg::possible_values`] without matching case.
1615 ///
1616 /// When other arguments are conditionally required based on the
1617 /// value of a case-insensitive argument, the equality check done
1618 /// by [`Arg::required_if_eq`], [`Arg::required_if_eq_any`], or
1619 /// [`Arg::required_if_eq_all`] is case-insensitive.
1620 ///
1621 ///
1622 /// **NOTE:** Setting this requires [`Arg::takes_value`]
1623 ///
1624 /// **NOTE:** To do unicode case folding, enable the `unicode` feature flag.
1625 ///
1626 /// # Examples
1627 ///
1628 /// ```rust
1629 /// # use clap::{Command, Arg};
1630 /// let m = Command::new("pv")
1631 /// .arg(Arg::new("option")
1632 /// .long("option")
1633 /// .takes_value(true)
1634 /// .ignore_case(true)
1635 /// .value_parser(["test123"]))
1636 /// .get_matches_from(vec![
1637 /// "pv", "--option", "TeSt123",
1638 /// ]);
1639 ///
1640 /// assert!(m.value_of("option").unwrap().eq_ignore_ascii_case("test123"));
1641 /// ```
1642 ///
1643 /// This setting also works when multiple values can be defined:
1644 ///
1645 /// ```rust
1646 /// # use clap::{Command, Arg};
1647 /// let m = Command::new("pv")
1648 /// .arg(Arg::new("option")
1649 /// .short('o')
1650 /// .long("option")
1651 /// .takes_value(true)
1652 /// .ignore_case(true)
1653 /// .multiple_values(true)
1654 /// .value_parser(["test123", "test321"]))
1655 /// .get_matches_from(vec![
1656 /// "pv", "--option", "TeSt123", "teST123", "tESt321"
1657 /// ]);
1658 ///
1659 /// let matched_vals = m.values_of("option").unwrap().collect::<Vec<_>>();
1660 /// assert_eq!(&*matched_vals, &["TeSt123", "teST123", "tESt321"]);
1661 /// ```
1662 #[inline]
1663 #[must_use]
1664 pub fn ignore_case(self, yes: bool) -> Self {
1665 if yes {
1666 self.setting(ArgSettings::IgnoreCase)
1667 } else {
1668 self.unset_setting(ArgSettings::IgnoreCase)
1669 }
1670 }
1671
1672 /// Allows values which start with a leading hyphen (`-`)
1673 ///
1674 /// **NOTE:** Setting this requires [`Arg::takes_value`]
1675 ///
1676 /// **WARNING**: Take caution when using this setting combined with
1677 /// [`Arg::multiple_values`], as this becomes ambiguous `$ prog --arg -- -- val`. All
1678 /// three `--, --, val` will be values when the user may have thought the second `--` would
1679 /// constitute the normal, "Only positional args follow" idiom. To fix this, consider using
1680 /// [`Arg::multiple_occurrences`] which only allows a single value at a time.
1681 ///
1682 /// **WARNING**: When building your CLIs, consider the effects of allowing leading hyphens and
1683 /// the user passing in a value that matches a valid short. For example, `prog -opt -F` where
1684 /// `-F` is supposed to be a value, yet `-F` is *also* a valid short for another arg.
1685 /// Care should be taken when designing these args. This is compounded by the ability to "stack"
1686 /// short args. I.e. if `-val` is supposed to be a value, but `-v`, `-a`, and `-l` are all valid
1687 /// shorts.
1688 ///
1689 /// # Examples
1690 ///
1691 /// ```rust
1692 /// # use clap::{Command, Arg};
1693 /// let m = Command::new("prog")
1694 /// .arg(Arg::new("pat")
1695 /// .takes_value(true)
1696 /// .allow_hyphen_values(true)
1697 /// .long("pattern"))
1698 /// .get_matches_from(vec![
1699 /// "prog", "--pattern", "-file"
1700 /// ]);
1701 ///
1702 /// assert_eq!(m.value_of("pat"), Some("-file"));
1703 /// ```
1704 ///
1705 /// Not setting `Arg::allow_hyphen_values(true)` and supplying a value which starts with a
1706 /// hyphen is an error.
1707 ///
1708 /// ```rust
1709 /// # use clap::{Command, Arg, ErrorKind};
1710 /// let res = Command::new("prog")
1711 /// .arg(Arg::new("pat")
1712 /// .takes_value(true)
1713 /// .long("pattern"))
1714 /// .try_get_matches_from(vec![
1715 /// "prog", "--pattern", "-file"
1716 /// ]);
1717 ///
1718 /// assert!(res.is_err());
1719 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
1720 /// ```
1721 /// [`Arg::number_of_values(1)`]: Arg::number_of_values()
1722 #[inline]
1723 #[must_use]
1724 pub fn allow_hyphen_values(self, yes: bool) -> Self {
1725 if yes {
1726 self.setting(ArgSettings::AllowHyphenValues)
1727 } else {
1728 self.unset_setting(ArgSettings::AllowHyphenValues)
1729 }
1730 }
1731
1732 /// Deprecated, replaced with [`Arg::value_parser(...)`] with either [`ValueParser::os_string()`][crate::builder::ValueParser::os_string]
1733 /// or [`ValueParser::path_buf()`][crate::builder::ValueParser::path_buf]
1734 #[inline]
1735 #[must_use]
1736 #[cfg_attr(
1737 feature = "deprecated",
1738 deprecated(
1739 since = "3.2.0",
1740 note = "Replaced with `Arg::value_parser(...)` with either `ValueParser::os_string()` or `ValueParser::path_buf()`"
1741 )
1742 )]
1743 pub fn allow_invalid_utf8(self, yes: bool) -> Self {
1744 if yes {
1745 self.setting(ArgSettings::AllowInvalidUtf8)
1746 } else {
1747 self.unset_setting(ArgSettings::AllowInvalidUtf8)
1748 }
1749 }
1750
1751 /// Deprecated, replaced with [`Arg::value_parser(NonEmptyStringValueParser::new())`]
1752 #[inline]
1753 #[must_use]
1754 #[cfg_attr(
1755 feature = "deprecated",
1756 deprecated(
1757 since = "3.2.0",
1758 note = "Replaced with `Arg::value_parser(NonEmptyStringValueParser::new())`"
1759 )
1760 )]
1761 pub fn forbid_empty_values(self, yes: bool) -> Self {
1762 if yes {
1763 self.setting(ArgSettings::ForbidEmptyValues)
1764 } else {
1765 self.unset_setting(ArgSettings::ForbidEmptyValues)
1766 }
1767 }
1768
1769 /// Requires that options use the `--option=val` syntax
1770 ///
1771 /// i.e. an equals between the option and associated value.
1772 ///
1773 /// **NOTE:** Setting this requires [`Arg::takes_value`]
1774 ///
1775 /// # Examples
1776 ///
1777 /// Setting `require_equals` requires that the option have an equals sign between
1778 /// it and the associated value.
1779 ///
1780 /// ```rust
1781 /// # use clap::{Command, Arg};
1782 /// let res = Command::new("prog")
1783 /// .arg(Arg::new("cfg")
1784 /// .takes_value(true)
1785 /// .require_equals(true)
1786 /// .long("config"))
1787 /// .try_get_matches_from(vec![
1788 /// "prog", "--config=file.conf"
1789 /// ]);
1790 ///
1791 /// assert!(res.is_ok());
1792 /// ```
1793 ///
1794 /// Setting `require_equals` and *not* supplying the equals will cause an
1795 /// error.
1796 ///
1797 /// ```rust
1798 /// # use clap::{Command, Arg, ErrorKind};
1799 /// let res = Command::new("prog")
1800 /// .arg(Arg::new("cfg")
1801 /// .takes_value(true)
1802 /// .require_equals(true)
1803 /// .long("config"))
1804 /// .try_get_matches_from(vec![
1805 /// "prog", "--config", "file.conf"
1806 /// ]);
1807 ///
1808 /// assert!(res.is_err());
1809 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::NoEquals);
1810 /// ```
1811 #[inline]
1812 #[must_use]
1813 pub fn require_equals(self, yes: bool) -> Self {
1814 if yes {
1815 self.setting(ArgSettings::RequireEquals)
1816 } else {
1817 self.unset_setting(ArgSettings::RequireEquals)
1818 }
1819 }
1820
1821 /// Specifies that an argument should allow grouping of multiple values via a
1822 /// delimiter.
1823 ///
1824 /// i.e. should `--option=val1,val2,val3` be parsed as three values (`val1`, `val2`,
1825 /// and `val3`) or as a single value (`val1,val2,val3`). Defaults to using `,` (comma) as the
1826 /// value delimiter for all arguments that accept values (options and positional arguments)
1827 ///
1828 /// **NOTE:** When this setting is used, it will default [`Arg::value_delimiter`]
1829 /// to the comma `,`.
1830 ///
1831 /// **NOTE:** Implicitly sets [`Arg::takes_value`]
1832 ///
1833 /// # Examples
1834 ///
1835 /// The following example shows the default behavior.
1836 ///
1837 /// ```rust
1838 /// # use clap::{Command, Arg};
1839 /// let delims = Command::new("prog")
1840 /// .arg(Arg::new("option")
1841 /// .long("option")
1842 /// .use_value_delimiter(true)
1843 /// .takes_value(true))
1844 /// .get_matches_from(vec![
1845 /// "prog", "--option=val1,val2,val3",
1846 /// ]);
1847 ///
1848 /// assert!(delims.contains_id("option"));
1849 /// assert_eq!(delims.values_of("option").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);
1850 /// ```
1851 /// The next example shows the difference when turning delimiters off. This is the default
1852 /// behavior
1853 ///
1854 /// ```rust
1855 /// # use clap::{Command, Arg};
1856 /// let nodelims = Command::new("prog")
1857 /// .arg(Arg::new("option")
1858 /// .long("option")
1859 /// .takes_value(true))
1860 /// .get_matches_from(vec![
1861 /// "prog", "--option=val1,val2,val3",
1862 /// ]);
1863 ///
1864 /// assert!(nodelims.contains_id("option"));
1865 /// assert_eq!(nodelims.value_of("option").unwrap(), "val1,val2,val3");
1866 /// ```
1867 /// [`Arg::value_delimiter`]: Arg::value_delimiter()
1868 #[inline]
1869 #[must_use]
1870 pub fn use_value_delimiter(mut self, yes: bool) -> Self {
1871 if yes {
1872 if self.val_delim.is_none() {
1873 self.val_delim = Some(',');
1874 }
1875 self.takes_value(true)
1876 .setting(ArgSettings::UseValueDelimiter)
1877 } else {
1878 self.val_delim = None;
1879 self.unset_setting(ArgSettings::UseValueDelimiter)
1880 }
1881 }
1882
1883 /// Deprecated, replaced with [`Arg::use_value_delimiter`]
1884 #[inline]
1885 #[must_use]
1886 #[cfg_attr(
1887 feature = "deprecated",
1888 deprecated(since = "3.1.0", note = "Replaced with `Arg::use_value_delimiter`")
1889 )]
1890 pub fn use_delimiter(self, yes: bool) -> Self {
1891 self.use_value_delimiter(yes)
1892 }
1893
1894 /// Separator between the arguments values, defaults to `,` (comma).
1895 ///
1896 /// **NOTE:** implicitly sets [`Arg::use_value_delimiter(true)`]
1897 ///
1898 /// **NOTE:** implicitly sets [`Arg::takes_value(true)`]
1899 ///
1900 /// # Examples
1901 ///
1902 /// ```rust
1903 /// # use clap::{Command, Arg};
1904 /// let m = Command::new("prog")
1905 /// .arg(Arg::new("config")
1906 /// .short('c')
1907 /// .long("config")
1908 /// .value_delimiter(';'))
1909 /// .get_matches_from(vec![
1910 /// "prog", "--config=val1;val2;val3"
1911 /// ]);
1912 ///
1913 /// assert_eq!(m.values_of("config").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"])
1914 /// ```
1915 /// [`Arg::use_value_delimiter(true)`]: Arg::use_value_delimiter()
1916 /// [`Arg::takes_value(true)`]: Arg::takes_value()
1917 #[inline]
1918 #[must_use]
1919 pub fn value_delimiter(mut self, d: char) -> Self {
1920 self.val_delim = Some(d);
1921 self.takes_value(true).use_value_delimiter(true)
1922 }
1923
1924 /// Specifies that *multiple values* may only be set using the delimiter.
1925 ///
1926 /// This means if an option is encountered, and no delimiter is found, it is assumed that no
1927 /// additional values for that option follow. This is unlike the default, where it is generally
1928 /// assumed that more values will follow regardless of whether or not a delimiter is used.
1929 ///
1930 /// **NOTE:** The default is `false`.
1931 ///
1932 /// **NOTE:** Setting this requires [`Arg::use_value_delimiter`] and
1933 /// [`Arg::takes_value`]
1934 ///
1935 /// **NOTE:** It's a good idea to inform the user that use of a delimiter is required, either
1936 /// through help text or other means.
1937 ///
1938 /// # Examples
1939 ///
1940 /// These examples demonstrate what happens when `require_delimiter(true)` is used. Notice
1941 /// everything works in this first example, as we use a delimiter, as expected.
1942 ///
1943 /// ```rust
1944 /// # use clap::{Command, Arg};
1945 /// let delims = Command::new("prog")
1946 /// .arg(Arg::new("opt")
1947 /// .short('o')
1948 /// .takes_value(true)
1949 /// .use_value_delimiter(true)
1950 /// .require_delimiter(true)
1951 /// .multiple_values(true))
1952 /// .get_matches_from(vec![
1953 /// "prog", "-o", "val1,val2,val3",
1954 /// ]);
1955 ///
1956 /// assert!(delims.contains_id("opt"));
1957 /// assert_eq!(delims.values_of("opt").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);
1958 /// ```
1959 ///
1960 /// In this next example, we will *not* use a delimiter. Notice it's now an error.
1961 ///
1962 /// ```rust
1963 /// # use clap::{Command, Arg, ErrorKind};
1964 /// let res = Command::new("prog")
1965 /// .arg(Arg::new("opt")
1966 /// .short('o')
1967 /// .takes_value(true)
1968 /// .use_value_delimiter(true)
1969 /// .require_delimiter(true))
1970 /// .try_get_matches_from(vec![
1971 /// "prog", "-o", "val1", "val2", "val3",
1972 /// ]);
1973 ///
1974 /// assert!(res.is_err());
1975 /// let err = res.unwrap_err();
1976 /// assert_eq!(err.kind(), ErrorKind::UnknownArgument);
1977 /// ```
1978 ///
1979 /// What's happening is `-o` is getting `val1`, and because delimiters are required yet none
1980 /// were present, it stops parsing `-o`. At this point it reaches `val2` and because no
1981 /// positional arguments have been defined, it's an error of an unexpected argument.
1982 ///
1983 /// In this final example, we contrast the above with `clap`'s default behavior where the above
1984 /// is *not* an error.
1985 ///
1986 /// ```rust
1987 /// # use clap::{Command, Arg};
1988 /// let delims = Command::new("prog")
1989 /// .arg(Arg::new("opt")
1990 /// .short('o')
1991 /// .takes_value(true)
1992 /// .multiple_values(true))
1993 /// .get_matches_from(vec![
1994 /// "prog", "-o", "val1", "val2", "val3",
1995 /// ]);
1996 ///
1997 /// assert!(delims.contains_id("opt"));
1998 /// assert_eq!(delims.values_of("opt").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);
1999 /// ```
2000 #[inline]
2001 #[must_use]
2002 pub fn require_value_delimiter(self, yes: bool) -> Self {
2003 if yes {
2004 self.setting(ArgSettings::RequireDelimiter)
2005 } else {
2006 self.unset_setting(ArgSettings::RequireDelimiter)
2007 }
2008 }
2009
2010 /// Deprecated, replaced with [`Arg::require_value_delimiter`]
2011 #[inline]
2012 #[must_use]
2013 #[cfg_attr(
2014 feature = "deprecated",
2015 deprecated(since = "3.1.0", note = "Replaced with `Arg::require_value_delimiter`")
2016 )]
2017 pub fn require_delimiter(self, yes: bool) -> Self {
2018 self.require_value_delimiter(yes)
2019 }
2020
2021 /// Sentinel to **stop** parsing multiple values of a give argument.
2022 ///
2023 /// By default when
2024 /// one sets [`multiple_values(true)`] on an argument, clap will continue parsing values for that
2025 /// argument until it reaches another valid argument, or one of the other more specific settings
2026 /// for multiple values is used (such as [`min_values`], [`max_values`] or
2027 /// [`number_of_values`]).
2028 ///
2029 /// **NOTE:** This setting only applies to [options] and [positional arguments]
2030 ///
2031 /// **NOTE:** When the terminator is passed in on the command line, it is **not** stored as one
2032 /// of the values
2033 ///
2034 /// # Examples
2035 ///
2036 /// ```rust
2037 /// # use clap::{Command, Arg};
2038 /// Arg::new("vals")
2039 /// .takes_value(true)
2040 /// .multiple_values(true)
2041 /// .value_terminator(";")
2042 /// # ;
2043 /// ```
2044 ///
2045 /// The following example uses two arguments, a sequence of commands, and the location in which
2046 /// to perform them
2047 ///
2048 /// ```rust
2049 /// # use clap::{Command, Arg};
2050 /// let m = Command::new("prog")
2051 /// .arg(Arg::new("cmds")
2052 /// .takes_value(true)
2053 /// .multiple_values(true)
2054 /// .allow_hyphen_values(true)
2055 /// .value_terminator(";"))
2056 /// .arg(Arg::new("location"))
2057 /// .get_matches_from(vec![
2058 /// "prog", "find", "-type", "f", "-name", "special", ";", "/home/clap"
2059 /// ]);
2060 /// let cmds: Vec<_> = m.values_of("cmds").unwrap().collect();
2061 /// assert_eq!(&cmds, &["find", "-type", "f", "-name", "special"]);
2062 /// assert_eq!(m.value_of("location"), Some("/home/clap"));
2063 /// ```
2064 /// [options]: Arg::takes_value()
2065 /// [positional arguments]: Arg::index()
2066 /// [`multiple_values(true)`]: Arg::multiple_values()
2067 /// [`min_values`]: Arg::min_values()
2068 /// [`number_of_values`]: Arg::number_of_values()
2069 /// [`max_values`]: Arg::max_values()
2070 #[inline]
2071 #[must_use]
2072 pub fn value_terminator(mut self, term: &'help str) -> Self {
2073 self.terminator = Some(term);
2074 self.takes_value(true)
2075 }
2076
2077 /// Consume all following arguments.
2078 ///
2079 /// Do not be parse them individually, but rather pass them in entirety.
2080 ///
2081 /// It is worth noting that setting this requires all values to come after a `--` to indicate
2082 /// they should all be captured. For example:
2083 ///
2084 /// ```text
2085 /// --foo something -- -v -v -v -b -b -b --baz -q -u -x
2086 /// ```
2087 ///
2088 /// Will result in everything after `--` to be considered one raw argument. This behavior
2089 /// may not be exactly what you are expecting and using [`crate::Command::trailing_var_arg`]
2090 /// may be more appropriate.
2091 ///
2092 /// **NOTE:** Implicitly sets [`Arg::takes_value(true)`] [`Arg::multiple_values(true)`],
2093 /// [`Arg::allow_hyphen_values(true)`], and [`Arg::last(true)`] when set to `true`.
2094 ///
2095 /// [`Arg::takes_value(true)`]: Arg::takes_value()
2096 /// [`Arg::multiple_values(true)`]: Arg::multiple_values()
2097 /// [`Arg::allow_hyphen_values(true)`]: Arg::allow_hyphen_values()
2098 /// [`Arg::last(true)`]: Arg::last()
2099 #[inline]
2100 #[must_use]
2101 pub fn raw(self, yes: bool) -> Self {
2102 self.takes_value(yes)
2103 .multiple_values(yes)
2104 .allow_hyphen_values(yes)
2105 .last(yes)
2106 }
2107
2108 /// Value for the argument when not present.
2109 ///
2110 /// **NOTE:** If the user *does not* use this argument at runtime, [`ArgMatches::occurrences_of`]
2111 /// will return `0` even though the [`ArgMatches::value_of`] will return the default specified.
2112 ///
2113 /// **NOTE:** If the user *does not* use this argument at runtime [`ArgMatches::contains_id`] will
2114 /// still return `true`. If you wish to determine whether the argument was used at runtime or
2115 /// not, consider [`ArgMatches::value_source`][crate::ArgMatches::value_source].
2116 ///
2117 /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value_if`] but slightly
2118 /// different. `Arg::default_value` *only* takes effect when the user has not provided this arg
2119 /// at runtime. `Arg::default_value_if` however only takes effect when the user has not provided
2120 /// a value at runtime **and** these other conditions are met as well. If you have set
2121 /// `Arg::default_value` and `Arg::default_value_if`, and the user **did not** provide this arg
2122 /// at runtime, nor were the conditions met for `Arg::default_value_if`, the `Arg::default_value`
2123 /// will be applied.
2124 ///
2125 /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`].
2126 ///
2127 /// # Examples
2128 ///
2129 /// First we use the default value without providing any value at runtime.
2130 ///
2131 /// ```rust
2132 /// # use clap::{Command, Arg, ValueSource};
2133 /// let m = Command::new("prog")
2134 /// .arg(Arg::new("opt")
2135 /// .long("myopt")
2136 /// .default_value("myval"))
2137 /// .get_matches_from(vec![
2138 /// "prog"
2139 /// ]);
2140 ///
2141 /// assert_eq!(m.value_of("opt"), Some("myval"));
2142 /// assert!(m.contains_id("opt"));
2143 /// assert_eq!(m.value_source("opt"), Some(ValueSource::DefaultValue));
2144 /// ```
2145 ///
2146 /// Next we provide a value at runtime to override the default.
2147 ///
2148 /// ```rust
2149 /// # use clap::{Command, Arg, ValueSource};
2150 /// let m = Command::new("prog")
2151 /// .arg(Arg::new("opt")
2152 /// .long("myopt")
2153 /// .default_value("myval"))
2154 /// .get_matches_from(vec![
2155 /// "prog", "--myopt=non_default"
2156 /// ]);
2157 ///
2158 /// assert_eq!(m.value_of("opt"), Some("non_default"));
2159 /// assert!(m.contains_id("opt"));
2160 /// assert_eq!(m.value_source("opt"), Some(ValueSource::CommandLine));
2161 /// ```
2162 /// [`ArgMatches::occurrences_of`]: crate::ArgMatches::occurrences_of()
2163 /// [`ArgMatches::value_of`]: crate::ArgMatches::value_of()
2164 /// [`Arg::takes_value(true)`]: Arg::takes_value()
2165 /// [`ArgMatches::contains_id`]: crate::ArgMatches::contains_id()
2166 /// [`Arg::default_value_if`]: Arg::default_value_if()
2167 #[inline]
2168 #[must_use]
2169 pub fn default_value(self, val: &'help str) -> Self {
2170 self.default_values_os(&[OsStr::new(val)])
2171 }
2172
2173 /// Value for the argument when not present.
2174 ///
2175 /// See [`Arg::default_value`].
2176 ///
2177 /// [`Arg::default_value`]: Arg::default_value()
2178 /// [`OsStr`]: std::ffi::OsStr
2179 #[inline]
2180 #[must_use]
2181 pub fn default_value_os(self, val: &'help OsStr) -> Self {
2182 self.default_values_os(&[val])
2183 }
2184
2185 /// Value for the argument when not present.
2186 ///
2187 /// See [`Arg::default_value`].
2188 ///
2189 /// [`Arg::default_value`]: Arg::default_value()
2190 #[inline]
2191 #[must_use]
2192 pub fn default_values(self, vals: &[&'help str]) -> Self {
2193 let vals_vec: Vec<_> = vals.iter().map(|val| OsStr::new(*val)).collect();
2194 self.default_values_os(&vals_vec[..])
2195 }
2196
2197 /// Value for the argument when not present.
2198 ///
2199 /// See [`Arg::default_values`].
2200 ///
2201 /// [`Arg::default_values`]: Arg::default_values()
2202 /// [`OsStr`]: std::ffi::OsStr
2203 #[inline]
2204 #[must_use]
2205 pub fn default_values_os(mut self, vals: &[&'help OsStr]) -> Self {
2206 self.default_vals = vals.to_vec();
2207 self.takes_value(true)
2208 }
2209
2210 /// Value for the argument when the flag is present but no value is specified.
2211 ///
2212 /// This configuration option is often used to give the user a shortcut and allow them to
2213 /// efficiently specify an option argument without requiring an explicitly value. The `--color`
2214 /// argument is a common example. By, supplying an default, such as `default_missing_value("always")`,
2215 /// the user can quickly just add `--color` to the command line to produce the desired color output.
2216 ///
2217 /// **NOTE:** using this configuration option requires the use of the `.min_values(0)` and the
2218 /// `.require_equals(true)` configuration option. These are required in order to unambiguously
2219 /// determine what, if any, value was supplied for the argument.
2220 ///
2221 /// # Examples
2222 ///
2223 /// For POSIX style `--color`:
2224 /// ```rust
2225 /// # use clap::{Command, Arg, ValueSource};
2226 /// fn cli() -> Command<'static> {
2227 /// Command::new("prog")
2228 /// .arg(Arg::new("color").long("color")
2229 /// .value_name("WHEN")
2230 /// .value_parser(["always", "auto", "never"])
2231 /// .default_value("auto")
2232 /// .min_values(0)
2233 /// .require_equals(true)
2234 /// .default_missing_value("always")
2235 /// .help("Specify WHEN to colorize output.")
2236 /// )
2237 /// }
2238 ///
2239 /// // first, we'll provide no arguments
2240 /// let m = cli().get_matches_from(vec![
2241 /// "prog"
2242 /// ]);
2243 /// assert_eq!(m.value_of("color"), Some("auto"));
2244 /// assert_eq!(m.value_source("color"), Some(ValueSource::DefaultValue));
2245 ///
2246 /// // next, we'll provide a runtime value to override the default (as usually done).
2247 /// let m = cli().get_matches_from(vec![
2248 /// "prog", "--color=never"
2249 /// ]);
2250 /// assert_eq!(m.value_of("color"), Some("never"));
2251 /// assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine));
2252 ///
2253 /// // finally, we will use the shortcut and only provide the argument without a value.
2254 /// let m = cli().get_matches_from(vec![
2255 /// "prog", "--color"
2256 /// ]);
2257 /// assert_eq!(m.value_of("color"), Some("always"));
2258 /// assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine));
2259 /// ```
2260 ///
2261 /// For bool literals:
2262 /// ```rust
2263 /// # use clap::{Command, Arg, ValueSource, value_parser};
2264 /// fn cli() -> Command<'static> {
2265 /// Command::new("prog")
2266 /// .arg(Arg::new("create").long("create")
2267 /// .value_name("BOOL")
2268 /// .value_parser(value_parser!(bool))
2269 /// .min_values(0)
2270 /// .require_equals(true)
2271 /// .default_missing_value("true")
2272 /// )
2273 /// }
2274 ///
2275 /// // first, we'll provide no arguments
2276 /// let m = cli().get_matches_from(vec![
2277 /// "prog"
2278 /// ]);
2279 /// assert_eq!(m.get_one::<bool>("create").copied(), None);
2280 ///
2281 /// // next, we'll provide a runtime value to override the default (as usually done).
2282 /// let m = cli().get_matches_from(vec![
2283 /// "prog", "--create=false"
2284 /// ]);
2285 /// assert_eq!(m.get_one::<bool>("create").copied(), Some(false));
2286 /// assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine));
2287 ///
2288 /// // finally, we will use the shortcut and only provide the argument without a value.
2289 /// let m = cli().get_matches_from(vec![
2290 /// "prog", "--create"
2291 /// ]);
2292 /// assert_eq!(m.get_one::<bool>("create").copied(), Some(true));
2293 /// assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine));
2294 /// ```
2295 ///
2296 /// [`ArgMatches::value_of`]: ArgMatches::value_of()
2297 /// [`Arg::takes_value(true)`]: Arg::takes_value()
2298 /// [`Arg::default_value`]: Arg::default_value()
2299 #[inline]
2300 #[must_use]
2301 pub fn default_missing_value(self, val: &'help str) -> Self {
2302 self.default_missing_values_os(&[OsStr::new(val)])
2303 }
2304
2305 /// Value for the argument when the flag is present but no value is specified.
2306 ///
2307 /// See [`Arg::default_missing_value`].
2308 ///
2309 /// [`Arg::default_missing_value`]: Arg::default_missing_value()
2310 /// [`OsStr`]: std::ffi::OsStr
2311 #[inline]
2312 #[must_use]
2313 pub fn default_missing_value_os(self, val: &'help OsStr) -> Self {
2314 self.default_missing_values_os(&[val])
2315 }
2316
2317 /// Value for the argument when the flag is present but no value is specified.
2318 ///
2319 /// See [`Arg::default_missing_value`].
2320 ///
2321 /// [`Arg::default_missing_value`]: Arg::default_missing_value()
2322 #[inline]
2323 #[must_use]
2324 pub fn default_missing_values(self, vals: &[&'help str]) -> Self {
2325 let vals_vec: Vec<_> = vals.iter().map(|val| OsStr::new(*val)).collect();
2326 self.default_missing_values_os(&vals_vec[..])
2327 }
2328
2329 /// Value for the argument when the flag is present but no value is specified.
2330 ///
2331 /// See [`Arg::default_missing_values`].
2332 ///
2333 /// [`Arg::default_missing_values`]: Arg::default_missing_values()
2334 /// [`OsStr`]: std::ffi::OsStr
2335 #[inline]
2336 #[must_use]
2337 pub fn default_missing_values_os(mut self, vals: &[&'help OsStr]) -> Self {
2338 self.default_missing_vals = vals.to_vec();
2339 self.takes_value(true)
2340 }
2341
2342 /// Read from `name` environment variable when argument is not present.
2343 ///
2344 /// If it is not present in the environment, then default
2345 /// rules will apply.
2346 ///
2347 /// If user sets the argument in the environment:
2348 /// - When [`Arg::takes_value(true)`] is not set, the flag is considered raised.
2349 /// - When [`Arg::takes_value(true)`] is set, [`ArgMatches::value_of`] will
2350 /// return value of the environment variable.
2351 ///
2352 /// If user doesn't set the argument in the environment:
2353 /// - When [`Arg::takes_value(true)`] is not set, the flag is considered off.
2354 /// - When [`Arg::takes_value(true)`] is set, [`ArgMatches::value_of`] will
2355 /// return the default specified.
2356 ///
2357 /// # Examples
2358 ///
2359 /// In this example, we show the variable coming from the environment:
2360 ///
2361 /// ```rust
2362 /// # use std::env;
2363 /// # use clap::{Command, Arg};
2364 ///
2365 /// env::set_var("MY_FLAG", "env");
2366 ///
2367 /// let m = Command::new("prog")
2368 /// .arg(Arg::new("flag")
2369 /// .long("flag")
2370 /// .env("MY_FLAG")
2371 /// .takes_value(true))
2372 /// .get_matches_from(vec![
2373 /// "prog"
2374 /// ]);
2375 ///
2376 /// assert_eq!(m.value_of("flag"), Some("env"));
2377 /// ```
2378 ///
2379 /// In this example, because [`Arg::takes_value(false)`] (by default),
2380 /// `prog` is a flag that accepts an optional, case-insensitive boolean literal.
2381 /// A `false` literal is `n`, `no`, `f`, `false`, `off` or `0`.
2382 /// An absent environment variable will also be considered as `false`.
2383 /// Anything else will considered as `true`.
2384 ///
2385 /// ```rust
2386 /// # use std::env;
2387 /// # use clap::{Command, Arg};
2388 ///
2389 /// env::set_var("TRUE_FLAG", "true");
2390 /// env::set_var("FALSE_FLAG", "0");
2391 ///
2392 /// let m = Command::new("prog")
2393 /// .arg(Arg::new("true_flag")
2394 /// .long("true_flag")
2395 /// .env("TRUE_FLAG"))
2396 /// .arg(Arg::new("false_flag")
2397 /// .long("false_flag")
2398 /// .env("FALSE_FLAG"))
2399 /// .arg(Arg::new("absent_flag")
2400 /// .long("absent_flag")
2401 /// .env("ABSENT_FLAG"))
2402 /// .get_matches_from(vec![
2403 /// "prog"
2404 /// ]);
2405 ///
2406 /// assert!(m.is_present("true_flag"));
2407 /// assert_eq!(m.value_of("true_flag"), None);
2408 /// assert!(!m.is_present("false_flag"));
2409 /// assert!(!m.is_present("absent_flag"));
2410 /// ```
2411 ///
2412 /// In this example, we show the variable coming from an option on the CLI:
2413 ///
2414 /// ```rust
2415 /// # use std::env;
2416 /// # use clap::{Command, Arg};
2417 ///
2418 /// env::set_var("MY_FLAG", "env");
2419 ///
2420 /// let m = Command::new("prog")
2421 /// .arg(Arg::new("flag")
2422 /// .long("flag")
2423 /// .env("MY_FLAG")
2424 /// .takes_value(true))
2425 /// .get_matches_from(vec![
2426 /// "prog", "--flag", "opt"
2427 /// ]);
2428 ///
2429 /// assert_eq!(m.value_of("flag"), Some("opt"));
2430 /// ```
2431 ///
2432 /// In this example, we show the variable coming from the environment even with the
2433 /// presence of a default:
2434 ///
2435 /// ```rust
2436 /// # use std::env;
2437 /// # use clap::{Command, Arg};
2438 ///
2439 /// env::set_var("MY_FLAG", "env");
2440 ///
2441 /// let m = Command::new("prog")
2442 /// .arg(Arg::new("flag")
2443 /// .long("flag")
2444 /// .env("MY_FLAG")
2445 /// .takes_value(true)
2446 /// .default_value("default"))
2447 /// .get_matches_from(vec![
2448 /// "prog"
2449 /// ]);
2450 ///
2451 /// assert_eq!(m.value_of("flag"), Some("env"));
2452 /// ```
2453 ///
2454 /// In this example, we show the use of multiple values in a single environment variable:
2455 ///
2456 /// ```rust
2457 /// # use std::env;
2458 /// # use clap::{Command, Arg};
2459 ///
2460 /// env::set_var("MY_FLAG_MULTI", "env1,env2");
2461 ///
2462 /// let m = Command::new("prog")
2463 /// .arg(Arg::new("flag")
2464 /// .long("flag")
2465 /// .env("MY_FLAG_MULTI")
2466 /// .takes_value(true)
2467 /// .multiple_values(true)
2468 /// .use_value_delimiter(true))
2469 /// .get_matches_from(vec![
2470 /// "prog"
2471 /// ]);
2472 ///
2473 /// assert_eq!(m.values_of("flag").unwrap().collect::<Vec<_>>(), vec!["env1", "env2"]);
2474 /// ```
2475 /// [`ArgMatches::value_of`]: crate::ArgMatches::value_of()
2476 /// [`Arg::takes_value(true)`]: Arg::takes_value()
2477 /// [`Arg::use_value_delimiter(true)`]: Arg::use_value_delimiter()
2478 #[cfg(feature = "env")]
2479 #[inline]
2480 #[must_use]
2481 pub fn env(self, name: &'help str) -> Self {
2482 self.env_os(OsStr::new(name))
2483 }
2484
2485 /// Read from `name` environment variable when argument is not present.
2486 ///
2487 /// See [`Arg::env`].
2488 #[cfg(feature = "env")]
2489 #[inline]
2490 #[must_use]
2491 pub fn env_os(mut self, name: &'help OsStr) -> Self {
2492 self.env = Some((name, env::var_os(name)));
2493 self
2494 }
2495 }
2496
2497 /// # Help
2498 impl<'help> Arg<'help> {
2499 /// Sets the description of the argument for short help (`-h`).
2500 ///
2501 /// Typically, this is a short (one line) description of the arg.
2502 ///
2503 /// If [`Arg::long_help`] is not specified, this message will be displayed for `--help`.
2504 ///
2505 /// **NOTE:** Only `Arg::help` is used in completion script generation in order to be concise
2506 ///
2507 /// # Examples
2508 ///
2509 /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to
2510 /// include a newline in the help text and have the following text be properly aligned with all
2511 /// the other help text.
2512 ///
2513 /// Setting `help` displays a short message to the side of the argument when the user passes
2514 /// `-h` or `--help` (by default).
2515 ///
2516 /// ```rust
2517 /// # use clap::{Command, Arg};
2518 /// let m = Command::new("prog")
2519 /// .arg(Arg::new("cfg")
2520 /// .long("config")
2521 /// .help("Some help text describing the --config arg"))
2522 /// .get_matches_from(vec![
2523 /// "prog", "--help"
2524 /// ]);
2525 /// ```
2526 ///
2527 /// The above example displays
2528 ///
2529 /// ```notrust
2530 /// helptest
2531 ///
2532 /// USAGE:
2533 /// helptest [OPTIONS]
2534 ///
2535 /// OPTIONS:
2536 /// --config Some help text describing the --config arg
2537 /// -h, --help Print help information
2538 /// -V, --version Print version information
2539 /// ```
2540 /// [`Arg::long_help`]: Arg::long_help()
2541 #[inline]
2542 #[must_use]
2543 pub fn help(mut self, h: impl Into<Option<&'help str>>) -> Self {
2544 self.help = h.into();
2545 self
2546 }
2547
2548 /// Sets the description of the argument for long help (`--help`).
2549 ///
2550 /// Typically this a more detailed (multi-line) message
2551 /// that describes the arg.
2552 ///
2553 /// If [`Arg::help`] is not specified, this message will be displayed for `-h`.
2554 ///
2555 /// **NOTE:** Only [`Arg::help`] is used in completion script generation in order to be concise
2556 ///
2557 /// # Examples
2558 ///
2559 /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to
2560 /// include a newline in the help text and have the following text be properly aligned with all
2561 /// the other help text.
2562 ///
2563 /// Setting `help` displays a short message to the side of the argument when the user passes
2564 /// `-h` or `--help` (by default).
2565 ///
2566 /// ```rust
2567 /// # use clap::{Command, Arg};
2568 /// let m = Command::new("prog")
2569 /// .arg(Arg::new("cfg")
2570 /// .long("config")
2571 /// .long_help(
2572 /// "The config file used by the myprog must be in JSON format
2573 /// with only valid keys and may not contain other nonsense
2574 /// that cannot be read by this program. Obviously I'm going on
2575 /// and on, so I'll stop now."))
2576 /// .get_matches_from(vec![
2577 /// "prog", "--help"
2578 /// ]);
2579 /// ```
2580 ///
2581 /// The above example displays
2582 ///
2583 /// ```text
2584 /// prog
2585 ///
2586 /// USAGE:
2587 /// prog [OPTIONS]
2588 ///
2589 /// OPTIONS:
2590 /// --config
2591 /// The config file used by the myprog must be in JSON format
2592 /// with only valid keys and may not contain other nonsense
2593 /// that cannot be read by this program. Obviously I'm going on
2594 /// and on, so I'll stop now.
2595 ///
2596 /// -h, --help
2597 /// Print help information
2598 ///
2599 /// -V, --version
2600 /// Print version information
2601 /// ```
2602 /// [`Arg::help`]: Arg::help()
2603 #[inline]
2604 #[must_use]
2605 pub fn long_help(mut self, h: impl Into<Option<&'help str>>) -> Self {
2606 self.long_help = h.into();
2607 self
2608 }
2609
2610 /// Allows custom ordering of args within the help message.
2611 ///
2612 /// Args with a lower value will be displayed first in the help message. This is helpful when
2613 /// one would like to emphasise frequently used args, or prioritize those towards the top of
2614 /// the list. Args with duplicate display orders will be displayed in alphabetical order.
2615 ///
2616 /// **NOTE:** The default is 999 for all arguments.
2617 ///
2618 /// **NOTE:** This setting is ignored for [positional arguments] which are always displayed in
2619 /// [index] order.
2620 ///
2621 /// # Examples
2622 ///
2623 /// ```rust
2624 /// # use clap::{Command, Arg};
2625 /// let m = Command::new("prog")
2626 /// .arg(Arg::new("a") // Typically args are grouped alphabetically by name.
2627 /// // Args without a display_order have a value of 999 and are
2628 /// // displayed alphabetically with all other 999 valued args.
2629 /// .long("long-option")
2630 /// .short('o')
2631 /// .takes_value(true)
2632 /// .help("Some help and text"))
2633 /// .arg(Arg::new("b")
2634 /// .long("other-option")
2635 /// .short('O')
2636 /// .takes_value(true)
2637 /// .display_order(1) // In order to force this arg to appear *first*
2638 /// // all we have to do is give it a value lower than 999.
2639 /// // Any other args with a value of 1 will be displayed
2640 /// // alphabetically with this one...then 2 values, then 3, etc.
2641 /// .help("I should be first!"))
2642 /// .get_matches_from(vec![
2643 /// "prog", "--help"
2644 /// ]);
2645 /// ```
2646 ///
2647 /// The above example displays the following help message
2648 ///
2649 /// ```text
2650 /// cust-ord
2651 ///
2652 /// USAGE:
2653 /// cust-ord [OPTIONS]
2654 ///
2655 /// OPTIONS:
2656 /// -h, --help Print help information
2657 /// -V, --version Print version information
2658 /// -O, --other-option <b> I should be first!
2659 /// -o, --long-option <a> Some help and text
2660 /// ```
2661 /// [positional arguments]: Arg::index()
2662 /// [index]: Arg::index()
2663 #[inline]
2664 #[must_use]
2665 pub fn display_order(mut self, ord: usize) -> Self {
2666 self.disp_ord.set_explicit(ord);
2667 self
2668 }
2669
2670 /// Override the [current] help section.
2671 ///
2672 /// [current]: crate::Command::help_heading
2673 #[inline]
2674 #[must_use]
2675 pub fn help_heading<O>(mut self, heading: O) -> Self
2676 where
2677 O: Into<Option<&'help str>>,
2678 {
2679 self.help_heading = Some(heading.into());
2680 self
2681 }
2682
2683 /// Render the [help][Arg::help] on the line after the argument.
2684 ///
2685 /// This can be helpful for arguments with very long or complex help messages.
2686 /// This can also be helpful for arguments with very long flag names, or many/long value names.
2687 ///
2688 /// **NOTE:** To apply this setting to all arguments and subcommands, consider using
2689 /// [`crate::Command::next_line_help`]
2690 ///
2691 /// # Examples
2692 ///
2693 /// ```rust
2694 /// # use clap::{Command, Arg};
2695 /// let m = Command::new("prog")
2696 /// .arg(Arg::new("opt")
2697 /// .long("long-option-flag")
2698 /// .short('o')
2699 /// .takes_value(true)
2700 /// .next_line_help(true)
2701 /// .value_names(&["value1", "value2"])
2702 /// .help("Some really long help and complex\n\
2703 /// help that makes more sense to be\n\
2704 /// on a line after the option"))
2705 /// .get_matches_from(vec![
2706 /// "prog", "--help"
2707 /// ]);
2708 /// ```
2709 ///
2710 /// The above example displays the following help message
2711 ///
2712 /// ```text
2713 /// nlh
2714 ///
2715 /// USAGE:
2716 /// nlh [OPTIONS]
2717 ///
2718 /// OPTIONS:
2719 /// -h, --help Print help information
2720 /// -V, --version Print version information
2721 /// -o, --long-option-flag <value1> <value2>
2722 /// Some really long help and complex
2723 /// help that makes more sense to be
2724 /// on a line after the option
2725 /// ```
2726 #[inline]
2727 #[must_use]
2728 pub fn next_line_help(self, yes: bool) -> Self {
2729 if yes {
2730 self.setting(ArgSettings::NextLineHelp)
2731 } else {
2732 self.unset_setting(ArgSettings::NextLineHelp)
2733 }
2734 }
2735
2736 /// Do not display the argument in help message.
2737 ///
2738 /// **NOTE:** This does **not** hide the argument from usage strings on error
2739 ///
2740 /// # Examples
2741 ///
2742 /// Setting `Hidden` will hide the argument when displaying help text
2743 ///
2744 /// ```rust
2745 /// # use clap::{Command, Arg};
2746 /// let m = Command::new("prog")
2747 /// .arg(Arg::new("cfg")
2748 /// .long("config")
2749 /// .hide(true)
2750 /// .help("Some help text describing the --config arg"))
2751 /// .get_matches_from(vec![
2752 /// "prog", "--help"
2753 /// ]);
2754 /// ```
2755 ///
2756 /// The above example displays
2757 ///
2758 /// ```text
2759 /// helptest
2760 ///
2761 /// USAGE:
2762 /// helptest [OPTIONS]
2763 ///
2764 /// OPTIONS:
2765 /// -h, --help Print help information
2766 /// -V, --version Print version information
2767 /// ```
2768 #[inline]
2769 #[must_use]
2770 pub fn hide(self, yes: bool) -> Self {
2771 if yes {
2772 self.setting(ArgSettings::Hidden)
2773 } else {
2774 self.unset_setting(ArgSettings::Hidden)
2775 }
2776 }
2777
2778 /// Do not display the [possible values][crate::builder::ValueParser::possible_values] in the help message.
2779 ///
2780 /// This is useful for args with many values, or ones which are explained elsewhere in the
2781 /// help text.
2782 ///
2783 /// **NOTE:** Setting this requires [`Arg::takes_value`]
2784 ///
2785 /// To set this for all arguments, see
2786 /// [`Command::hide_possible_values`][crate::Command::hide_possible_values].
2787 ///
2788 /// # Examples
2789 ///
2790 /// ```rust
2791 /// # use clap::{Command, Arg};
2792 /// let m = Command::new("prog")
2793 /// .arg(Arg::new("mode")
2794 /// .long("mode")
2795 /// .value_parser(["fast", "slow"])
2796 /// .takes_value(true)
2797 /// .hide_possible_values(true));
2798 /// ```
2799 /// If we were to run the above program with `--help` the `[values: fast, slow]` portion of
2800 /// the help text would be omitted.
2801 #[inline]
2802 #[must_use]
2803 pub fn hide_possible_values(self, yes: bool) -> Self {
2804 if yes {
2805 self.setting(ArgSettings::HidePossibleValues)
2806 } else {
2807 self.unset_setting(ArgSettings::HidePossibleValues)
2808 }
2809 }
2810
2811 /// Do not display the default value of the argument in the help message.
2812 ///
2813 /// This is useful when default behavior of an arg is explained elsewhere in the help text.
2814 ///
2815 /// **NOTE:** Setting this requires [`Arg::takes_value`]
2816 ///
2817 /// # Examples
2818 ///
2819 /// ```rust
2820 /// # use clap::{Command, Arg};
2821 /// let m = Command::new("connect")
2822 /// .arg(Arg::new("host")
2823 /// .long("host")
2824 /// .default_value("localhost")
2825 /// .takes_value(true)
2826 /// .hide_default_value(true));
2827 ///
2828 /// ```
2829 ///
2830 /// If we were to run the above program with `--help` the `[default: localhost]` portion of
2831 /// the help text would be omitted.
2832 #[inline]
2833 #[must_use]
2834 pub fn hide_default_value(self, yes: bool) -> Self {
2835 if yes {
2836 self.setting(ArgSettings::HideDefaultValue)
2837 } else {
2838 self.unset_setting(ArgSettings::HideDefaultValue)
2839 }
2840 }
2841
2842 /// Do not display in help the environment variable name.
2843 ///
2844 /// This is useful when the variable option is explained elsewhere in the help text.
2845 ///
2846 /// # Examples
2847 ///
2848 /// ```rust
2849 /// # use clap::{Command, Arg};
2850 /// let m = Command::new("prog")
2851 /// .arg(Arg::new("mode")
2852 /// .long("mode")
2853 /// .env("MODE")
2854 /// .takes_value(true)
2855 /// .hide_env(true));
2856 /// ```
2857 ///
2858 /// If we were to run the above program with `--help` the `[env: MODE]` portion of the help
2859 /// text would be omitted.
2860 #[cfg(feature = "env")]
2861 #[inline]
2862 #[must_use]
2863 pub fn hide_env(self, yes: bool) -> Self {
2864 if yes {
2865 self.setting(ArgSettings::HideEnv)
2866 } else {
2867 self.unset_setting(ArgSettings::HideEnv)
2868 }
2869 }
2870
2871 /// Do not display in help any values inside the associated ENV variables for the argument.
2872 ///
2873 /// This is useful when ENV vars contain sensitive values.
2874 ///
2875 /// # Examples
2876 ///
2877 /// ```rust
2878 /// # use clap::{Command, Arg};
2879 /// let m = Command::new("connect")
2880 /// .arg(Arg::new("host")
2881 /// .long("host")
2882 /// .env("CONNECT")
2883 /// .takes_value(true)
2884 /// .hide_env_values(true));
2885 ///
2886 /// ```
2887 ///
2888 /// If we were to run the above program with `$ CONNECT=super_secret connect --help` the
2889 /// `[default: CONNECT=super_secret]` portion of the help text would be omitted.
2890 #[cfg(feature = "env")]
2891 #[inline]
2892 #[must_use]
2893 pub fn hide_env_values(self, yes: bool) -> Self {
2894 if yes {
2895 self.setting(ArgSettings::HideEnvValues)
2896 } else {
2897 self.unset_setting(ArgSettings::HideEnvValues)
2898 }
2899 }
2900
2901 /// Hides an argument from short help (`-h`).
2902 ///
2903 /// **NOTE:** This does **not** hide the argument from usage strings on error
2904 ///
2905 /// **NOTE:** Setting this option will cause next-line-help output style to be used
2906 /// when long help (`--help`) is called.
2907 ///
2908 /// # Examples
2909 ///
2910 /// ```rust
2911 /// # use clap::{Command, Arg};
2912 /// Arg::new("debug")
2913 /// .hide_short_help(true);
2914 /// ```
2915 ///
2916 /// Setting `hide_short_help(true)` will hide the argument when displaying short help text
2917 ///
2918 /// ```rust
2919 /// # use clap::{Command, Arg};
2920 /// let m = Command::new("prog")
2921 /// .arg(Arg::new("cfg")
2922 /// .long("config")
2923 /// .hide_short_help(true)
2924 /// .help("Some help text describing the --config arg"))
2925 /// .get_matches_from(vec![
2926 /// "prog", "-h"
2927 /// ]);
2928 /// ```
2929 ///
2930 /// The above example displays
2931 ///
2932 /// ```text
2933 /// helptest
2934 ///
2935 /// USAGE:
2936 /// helptest [OPTIONS]
2937 ///
2938 /// OPTIONS:
2939 /// -h, --help Print help information
2940 /// -V, --version Print version information
2941 /// ```
2942 ///
2943 /// However, when --help is called
2944 ///
2945 /// ```rust
2946 /// # use clap::{Command, Arg};
2947 /// let m = Command::new("prog")
2948 /// .arg(Arg::new("cfg")
2949 /// .long("config")
2950 /// .hide_short_help(true)
2951 /// .help("Some help text describing the --config arg"))
2952 /// .get_matches_from(vec![
2953 /// "prog", "--help"
2954 /// ]);
2955 /// ```
2956 ///
2957 /// Then the following would be displayed
2958 ///
2959 /// ```text
2960 /// helptest
2961 ///
2962 /// USAGE:
2963 /// helptest [OPTIONS]
2964 ///
2965 /// OPTIONS:
2966 /// --config Some help text describing the --config arg
2967 /// -h, --help Print help information
2968 /// -V, --version Print version information
2969 /// ```
2970 #[inline]
2971 #[must_use]
2972 pub fn hide_short_help(self, yes: bool) -> Self {
2973 if yes {
2974 self.setting(ArgSettings::HiddenShortHelp)
2975 } else {
2976 self.unset_setting(ArgSettings::HiddenShortHelp)
2977 }
2978 }
2979
2980 /// Hides an argument from long help (`--help`).
2981 ///
2982 /// **NOTE:** This does **not** hide the argument from usage strings on error
2983 ///
2984 /// **NOTE:** Setting this option will cause next-line-help output style to be used
2985 /// when long help (`--help`) is called.
2986 ///
2987 /// # Examples
2988 ///
2989 /// Setting `hide_long_help(true)` will hide the argument when displaying long help text
2990 ///
2991 /// ```rust
2992 /// # use clap::{Command, Arg};
2993 /// let m = Command::new("prog")
2994 /// .arg(Arg::new("cfg")
2995 /// .long("config")
2996 /// .hide_long_help(true)
2997 /// .help("Some help text describing the --config arg"))
2998 /// .get_matches_from(vec![
2999 /// "prog", "--help"
3000 /// ]);
3001 /// ```
3002 ///
3003 /// The above example displays
3004 ///
3005 /// ```text
3006 /// helptest
3007 ///
3008 /// USAGE:
3009 /// helptest [OPTIONS]
3010 ///
3011 /// OPTIONS:
3012 /// -h, --help Print help information
3013 /// -V, --version Print version information
3014 /// ```
3015 ///
3016 /// However, when -h is called
3017 ///
3018 /// ```rust
3019 /// # use clap::{Command, Arg};
3020 /// let m = Command::new("prog")
3021 /// .arg(Arg::new("cfg")
3022 /// .long("config")
3023 /// .hide_long_help(true)
3024 /// .help("Some help text describing the --config arg"))
3025 /// .get_matches_from(vec![
3026 /// "prog", "-h"
3027 /// ]);
3028 /// ```
3029 ///
3030 /// Then the following would be displayed
3031 ///
3032 /// ```text
3033 /// helptest
3034 ///
3035 /// USAGE:
3036 /// helptest [OPTIONS]
3037 ///
3038 /// OPTIONS:
3039 /// --config Some help text describing the --config arg
3040 /// -h, --help Print help information
3041 /// -V, --version Print version information
3042 /// ```
3043 #[inline]
3044 #[must_use]
3045 pub fn hide_long_help(self, yes: bool) -> Self {
3046 if yes {
3047 self.setting(ArgSettings::HiddenLongHelp)
3048 } else {
3049 self.unset_setting(ArgSettings::HiddenLongHelp)
3050 }
3051 }
3052 }
3053
3054 /// # Advanced Argument Relations
3055 impl<'help> Arg<'help> {
3056 /// The name of the [`ArgGroup`] the argument belongs to.
3057 ///
3058 /// # Examples
3059 ///
3060 /// ```rust
3061 /// # use clap::{Command, Arg};
3062 /// Arg::new("debug")
3063 /// .long("debug")
3064 /// .group("mode")
3065 /// # ;
3066 /// ```
3067 ///
3068 /// Multiple arguments can be a member of a single group and then the group checked as if it
3069 /// was one of said arguments.
3070 ///
3071 /// ```rust
3072 /// # use clap::{Command, Arg};
3073 /// let m = Command::new("prog")
3074 /// .arg(Arg::new("debug")
3075 /// .long("debug")
3076 /// .group("mode"))
3077 /// .arg(Arg::new("verbose")
3078 /// .long("verbose")
3079 /// .group("mode"))
3080 /// .get_matches_from(vec![
3081 /// "prog", "--debug"
3082 /// ]);
3083 /// assert!(m.contains_id("mode"));
3084 /// ```
3085 ///
3086 /// [`ArgGroup`]: crate::ArgGroup
3087 #[must_use]
3088 pub fn group<T: Key>(mut self, group_id: T) -> Self {
3089 self.groups.push(group_id.into());
3090 self
3091 }
3092
3093 /// The names of [`ArgGroup`]'s the argument belongs to.
3094 ///
3095 /// # Examples
3096 ///
3097 /// ```rust
3098 /// # use clap::{Command, Arg};
3099 /// Arg::new("debug")
3100 /// .long("debug")
3101 /// .groups(&["mode", "verbosity"])
3102 /// # ;
3103 /// ```
3104 ///
3105 /// Arguments can be members of multiple groups and then the group checked as if it
3106 /// was one of said arguments.
3107 ///
3108 /// ```rust
3109 /// # use clap::{Command, Arg};
3110 /// let m = Command::new("prog")
3111 /// .arg(Arg::new("debug")
3112 /// .long("debug")
3113 /// .groups(&["mode", "verbosity"]))
3114 /// .arg(Arg::new("verbose")
3115 /// .long("verbose")
3116 /// .groups(&["mode", "verbosity"]))
3117 /// .get_matches_from(vec![
3118 /// "prog", "--debug"
3119 /// ]);
3120 /// assert!(m.contains_id("mode"));
3121 /// assert!(m.contains_id("verbosity"));
3122 /// ```
3123 ///
3124 /// [`ArgGroup`]: crate::ArgGroup
3125 #[must_use]
3126 pub fn groups<T: Key>(mut self, group_ids: &[T]) -> Self {
3127 self.groups.extend(group_ids.iter().map(Id::from));
3128 self
3129 }
3130
3131 /// Specifies the value of the argument if `arg` has been used at runtime.
3132 ///
3133 /// If `val` is set to `None`, `arg` only needs to be present. If `val` is set to `"some-val"`
3134 /// then `arg` must be present at runtime **and** have the value `val`.
3135 ///
3136 /// If `default` is set to `None`, `default_value` will be removed.
3137 ///
3138 /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value`] but slightly
3139 /// different. `Arg::default_value` *only* takes effect when the user has not provided this arg
3140 /// at runtime. This setting however only takes effect when the user has not provided a value at
3141 /// runtime **and** these other conditions are met as well. If you have set `Arg::default_value`
3142 /// and `Arg::default_value_if`, and the user **did not** provide this arg at runtime, nor were
3143 /// the conditions met for `Arg::default_value_if`, the `Arg::default_value` will be applied.
3144 ///
3145 /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`].
3146 ///
3147 /// # Examples
3148 ///
3149 /// First we use the default value only if another arg is present at runtime.
3150 ///
3151 /// ```rust
3152 /// # use clap::{Command, Arg};
3153 /// let m = Command::new("prog")
3154 /// .arg(Arg::new("flag")
3155 /// .long("flag"))
3156 /// .arg(Arg::new("other")
3157 /// .long("other")
3158 /// .default_value_if("flag", None, Some("default")))
3159 /// .get_matches_from(vec![
3160 /// "prog", "--flag"
3161 /// ]);
3162 ///
3163 /// assert_eq!(m.value_of("other"), Some("default"));
3164 /// ```
3165 ///
3166 /// Next we run the same test, but without providing `--flag`.
3167 ///
3168 /// ```rust
3169 /// # use clap::{Command, Arg};
3170 /// let m = Command::new("prog")
3171 /// .arg(Arg::new("flag")
3172 /// .long("flag"))
3173 /// .arg(Arg::new("other")
3174 /// .long("other")
3175 /// .default_value_if("flag", None, Some("default")))
3176 /// .get_matches_from(vec![
3177 /// "prog"
3178 /// ]);
3179 ///
3180 /// assert_eq!(m.value_of("other"), None);
3181 /// ```
3182 ///
3183 /// Now lets only use the default value if `--opt` contains the value `special`.
3184 ///
3185 /// ```rust
3186 /// # use clap::{Command, Arg};
3187 /// let m = Command::new("prog")
3188 /// .arg(Arg::new("opt")
3189 /// .takes_value(true)
3190 /// .long("opt"))
3191 /// .arg(Arg::new("other")
3192 /// .long("other")
3193 /// .default_value_if("opt", Some("special"), Some("default")))
3194 /// .get_matches_from(vec![
3195 /// "prog", "--opt", "special"
3196 /// ]);
3197 ///
3198 /// assert_eq!(m.value_of("other"), Some("default"));
3199 /// ```
3200 ///
3201 /// We can run the same test and provide any value *other than* `special` and we won't get a
3202 /// default value.
3203 ///
3204 /// ```rust
3205 /// # use clap::{Command, Arg};
3206 /// let m = Command::new("prog")
3207 /// .arg(Arg::new("opt")
3208 /// .takes_value(true)
3209 /// .long("opt"))
3210 /// .arg(Arg::new("other")
3211 /// .long("other")
3212 /// .default_value_if("opt", Some("special"), Some("default")))
3213 /// .get_matches_from(vec![
3214 /// "prog", "--opt", "hahaha"
3215 /// ]);
3216 ///
3217 /// assert_eq!(m.value_of("other"), None);
3218 /// ```
3219 ///
3220 /// If we want to unset the default value for an Arg based on the presence or
3221 /// value of some other Arg.
3222 ///
3223 /// ```rust
3224 /// # use clap::{Command, Arg};
3225 /// let m = Command::new("prog")
3226 /// .arg(Arg::new("flag")
3227 /// .long("flag"))
3228 /// .arg(Arg::new("other")
3229 /// .long("other")
3230 /// .default_value("default")
3231 /// .default_value_if("flag", None, None))
3232 /// .get_matches_from(vec![
3233 /// "prog", "--flag"
3234 /// ]);
3235 ///
3236 /// assert_eq!(m.value_of("other"), None);
3237 /// ```
3238 /// [`Arg::takes_value(true)`]: Arg::takes_value()
3239 /// [`Arg::default_value`]: Arg::default_value()
3240 #[must_use]
3241 pub fn default_value_if<T: Key>(
3242 self,
3243 arg_id: T,
3244 val: Option<&'help str>,
3245 default: Option<&'help str>,
3246 ) -> Self {
3247 self.default_value_if_os(arg_id, val.map(OsStr::new), default.map(OsStr::new))
3248 }
3249
3250 /// Provides a conditional default value in the exact same manner as [`Arg::default_value_if`]
3251 /// only using [`OsStr`]s instead.
3252 ///
3253 /// [`Arg::default_value_if`]: Arg::default_value_if()
3254 /// [`OsStr`]: std::ffi::OsStr
3255 #[must_use]
3256 pub fn default_value_if_os<T: Key>(
3257 mut self,
3258 arg_id: T,
3259 val: Option<&'help OsStr>,
3260 default: Option<&'help OsStr>,
3261 ) -> Self {
3262 self.default_vals_ifs
3263 .push((arg_id.into(), val.into(), default));
3264 self.takes_value(true)
3265 }
3266
3267 /// Specifies multiple values and conditions in the same manner as [`Arg::default_value_if`].
3268 ///
3269 /// The method takes a slice of tuples in the `(arg, Option<val>, default)` format.
3270 ///
3271 /// **NOTE**: The conditions are stored in order and evaluated in the same order. I.e. the first
3272 /// if multiple conditions are true, the first one found will be applied and the ultimate value.
3273 ///
3274 /// # Examples
3275 ///
3276 /// First we use the default value only if another arg is present at runtime.
3277 ///
3278 /// ```rust
3279 /// # use clap::{Command, Arg};
3280 /// let m = Command::new("prog")
3281 /// .arg(Arg::new("flag")
3282 /// .long("flag"))
3283 /// .arg(Arg::new("opt")
3284 /// .long("opt")
3285 /// .takes_value(true))
3286 /// .arg(Arg::new("other")
3287 /// .long("other")
3288 /// .default_value_ifs(&[
3289 /// ("flag", None, Some("default")),
3290 /// ("opt", Some("channal"), Some("chan")),
3291 /// ]))
3292 /// .get_matches_from(vec![
3293 /// "prog", "--opt", "channal"
3294 /// ]);
3295 ///
3296 /// assert_eq!(m.value_of("other"), Some("chan"));
3297 /// ```
3298 ///
3299 /// Next we run the same test, but without providing `--flag`.
3300 ///
3301 /// ```rust
3302 /// # use clap::{Command, Arg};
3303 /// let m = Command::new("prog")
3304 /// .arg(Arg::new("flag")
3305 /// .long("flag"))
3306 /// .arg(Arg::new("other")
3307 /// .long("other")
3308 /// .default_value_ifs(&[
3309 /// ("flag", None, Some("default")),
3310 /// ("opt", Some("channal"), Some("chan")),
3311 /// ]))
3312 /// .get_matches_from(vec![
3313 /// "prog"
3314 /// ]);
3315 ///
3316 /// assert_eq!(m.value_of("other"), None);
3317 /// ```
3318 ///
3319 /// We can also see that these values are applied in order, and if more than one condition is
3320 /// true, only the first evaluated "wins"
3321 ///
3322 /// ```rust
3323 /// # use clap::{Command, Arg};
3324 /// let m = Command::new("prog")
3325 /// .arg(Arg::new("flag")
3326 /// .long("flag"))
3327 /// .arg(Arg::new("opt")
3328 /// .long("opt")
3329 /// .takes_value(true))
3330 /// .arg(Arg::new("other")
3331 /// .long("other")
3332 /// .default_value_ifs(&[
3333 /// ("flag", None, Some("default")),
3334 /// ("opt", Some("channal"), Some("chan")),
3335 /// ]))
3336 /// .get_matches_from(vec![
3337 /// "prog", "--opt", "channal", "--flag"
3338 /// ]);
3339 ///
3340 /// assert_eq!(m.value_of("other"), Some("default"));
3341 /// ```
3342 /// [`Arg::takes_value(true)`]: Arg::takes_value()
3343 /// [`Arg::default_value_if`]: Arg::default_value_if()
3344 #[must_use]
3345 pub fn default_value_ifs<T: Key>(
3346 mut self,
3347 ifs: &[(T, Option<&'help str>, Option<&'help str>)],
3348 ) -> Self {
3349 for (arg, val, default) in ifs {
3350 self = self.default_value_if_os(arg, val.map(OsStr::new), default.map(OsStr::new));
3351 }
3352 self
3353 }
3354
3355 /// Provides multiple conditional default values in the exact same manner as
3356 /// [`Arg::default_value_ifs`] only using [`OsStr`]s instead.
3357 ///
3358 /// [`Arg::default_value_ifs`]: Arg::default_value_ifs()
3359 /// [`OsStr`]: std::ffi::OsStr
3360 #[must_use]
3361 pub fn default_value_ifs_os<T: Key>(
3362 mut self,
3363 ifs: &[(T, Option<&'help OsStr>, Option<&'help OsStr>)],
3364 ) -> Self {
3365 for (arg, val, default) in ifs {
3366 self = self.default_value_if_os(arg, *val, *default);
3367 }
3368 self
3369 }
3370
3371 /// Set this arg as [required] as long as the specified argument is not present at runtime.
3372 ///
3373 /// **Pro Tip:** Using `Arg::required_unless_present` implies [`Arg::required`] and is therefore not
3374 /// mandatory to also set.
3375 ///
3376 /// # Examples
3377 ///
3378 /// ```rust
3379 /// # use clap::Arg;
3380 /// Arg::new("config")
3381 /// .required_unless_present("debug")
3382 /// # ;
3383 /// ```
3384 ///
3385 /// In the following example, the required argument is *not* provided,
3386 /// but it's not an error because the `unless` arg has been supplied.
3387 ///
3388 /// ```rust
3389 /// # use clap::{Command, Arg};
3390 /// let res = Command::new("prog")
3391 /// .arg(Arg::new("cfg")
3392 /// .required_unless_present("dbg")
3393 /// .takes_value(true)
3394 /// .long("config"))
3395 /// .arg(Arg::new("dbg")
3396 /// .long("debug"))
3397 /// .try_get_matches_from(vec![
3398 /// "prog", "--debug"
3399 /// ]);
3400 ///
3401 /// assert!(res.is_ok());
3402 /// ```
3403 ///
3404 /// Setting `Arg::required_unless_present(name)` and *not* supplying `name` or this arg is an error.
3405 ///
3406 /// ```rust
3407 /// # use clap::{Command, Arg, ErrorKind};
3408 /// let res = Command::new("prog")
3409 /// .arg(Arg::new("cfg")
3410 /// .required_unless_present("dbg")
3411 /// .takes_value(true)
3412 /// .long("config"))
3413 /// .arg(Arg::new("dbg")
3414 /// .long("debug"))
3415 /// .try_get_matches_from(vec![
3416 /// "prog"
3417 /// ]);
3418 ///
3419 /// assert!(res.is_err());
3420 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3421 /// ```
3422 /// [required]: Arg::required()
3423 #[must_use]
3424 pub fn required_unless_present<T: Key>(mut self, arg_id: T) -> Self {
3425 self.r_unless.push(arg_id.into());
3426 self
3427 }
3428
3429 /// Sets this arg as [required] unless *all* of the specified arguments are present at runtime.
3430 ///
3431 /// In other words, parsing will succeed only if user either
3432 /// * supplies the `self` arg.
3433 /// * supplies *all* of the `names` arguments.
3434 ///
3435 /// **NOTE:** If you wish for this argument to only be required unless *any of* these args are
3436 /// present see [`Arg::required_unless_present_any`]
3437 ///
3438 /// # Examples
3439 ///
3440 /// ```rust
3441 /// # use clap::Arg;
3442 /// Arg::new("config")
3443 /// .required_unless_present_all(&["cfg", "dbg"])
3444 /// # ;
3445 /// ```
3446 ///
3447 /// In the following example, the required argument is *not* provided, but it's not an error
3448 /// because *all* of the `names` args have been supplied.
3449 ///
3450 /// ```rust
3451 /// # use clap::{Command, Arg};
3452 /// let res = Command::new("prog")
3453 /// .arg(Arg::new("cfg")
3454 /// .required_unless_present_all(&["dbg", "infile"])
3455 /// .takes_value(true)
3456 /// .long("config"))
3457 /// .arg(Arg::new("dbg")
3458 /// .long("debug"))
3459 /// .arg(Arg::new("infile")
3460 /// .short('i')
3461 /// .takes_value(true))
3462 /// .try_get_matches_from(vec![
3463 /// "prog", "--debug", "-i", "file"
3464 /// ]);
3465 ///
3466 /// assert!(res.is_ok());
3467 /// ```
3468 ///
3469 /// Setting [`Arg::required_unless_present_all(names)`] and *not* supplying
3470 /// either *all* of `unless` args or the `self` arg is an error.
3471 ///
3472 /// ```rust
3473 /// # use clap::{Command, Arg, ErrorKind};
3474 /// let res = Command::new("prog")
3475 /// .arg(Arg::new("cfg")
3476 /// .required_unless_present_all(&["dbg", "infile"])
3477 /// .takes_value(true)
3478 /// .long("config"))
3479 /// .arg(Arg::new("dbg")
3480 /// .long("debug"))
3481 /// .arg(Arg::new("infile")
3482 /// .short('i')
3483 /// .takes_value(true))
3484 /// .try_get_matches_from(vec![
3485 /// "prog"
3486 /// ]);
3487 ///
3488 /// assert!(res.is_err());
3489 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3490 /// ```
3491 /// [required]: Arg::required()
3492 /// [`Arg::required_unless_present_any`]: Arg::required_unless_present_any()
3493 /// [`Arg::required_unless_present_all(names)`]: Arg::required_unless_present_all()
3494 #[must_use]
3495 pub fn required_unless_present_all<T, I>(mut self, names: I) -> Self
3496 where
3497 I: IntoIterator<Item = T>,
3498 T: Key,
3499 {
3500 self.r_unless_all.extend(names.into_iter().map(Id::from));
3501 self
3502 }
3503
3504 /// Sets this arg as [required] unless *any* of the specified arguments are present at runtime.
3505 ///
3506 /// In other words, parsing will succeed only if user either
3507 /// * supplies the `self` arg.
3508 /// * supplies *one or more* of the `unless` arguments.
3509 ///
3510 /// **NOTE:** If you wish for this argument to be required unless *all of* these args are
3511 /// present see [`Arg::required_unless_present_all`]
3512 ///
3513 /// # Examples
3514 ///
3515 /// ```rust
3516 /// # use clap::Arg;
3517 /// Arg::new("config")
3518 /// .required_unless_present_any(&["cfg", "dbg"])
3519 /// # ;
3520 /// ```
3521 ///
3522 /// Setting [`Arg::required_unless_present_any(names)`] requires that the argument be used at runtime
3523 /// *unless* *at least one of* the args in `names` are present. In the following example, the
3524 /// required argument is *not* provided, but it's not an error because one the `unless` args
3525 /// have been supplied.
3526 ///
3527 /// ```rust
3528 /// # use clap::{Command, Arg};
3529 /// let res = Command::new("prog")
3530 /// .arg(Arg::new("cfg")
3531 /// .required_unless_present_any(&["dbg", "infile"])
3532 /// .takes_value(true)
3533 /// .long("config"))
3534 /// .arg(Arg::new("dbg")
3535 /// .long("debug"))
3536 /// .arg(Arg::new("infile")
3537 /// .short('i')
3538 /// .takes_value(true))
3539 /// .try_get_matches_from(vec![
3540 /// "prog", "--debug"
3541 /// ]);
3542 ///
3543 /// assert!(res.is_ok());
3544 /// ```
3545 ///
3546 /// Setting [`Arg::required_unless_present_any(names)`] and *not* supplying *at least one of* `names`
3547 /// or this arg is an error.
3548 ///
3549 /// ```rust
3550 /// # use clap::{Command, Arg, ErrorKind};
3551 /// let res = Command::new("prog")
3552 /// .arg(Arg::new("cfg")
3553 /// .required_unless_present_any(&["dbg", "infile"])
3554 /// .takes_value(true)
3555 /// .long("config"))
3556 /// .arg(Arg::new("dbg")
3557 /// .long("debug"))
3558 /// .arg(Arg::new("infile")
3559 /// .short('i')
3560 /// .takes_value(true))
3561 /// .try_get_matches_from(vec![
3562 /// "prog"
3563 /// ]);
3564 ///
3565 /// assert!(res.is_err());
3566 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3567 /// ```
3568 /// [required]: Arg::required()
3569 /// [`Arg::required_unless_present_any(names)`]: Arg::required_unless_present_any()
3570 /// [`Arg::required_unless_present_all`]: Arg::required_unless_present_all()
3571 #[must_use]
3572 pub fn required_unless_present_any<T, I>(mut self, names: I) -> Self
3573 where
3574 I: IntoIterator<Item = T>,
3575 T: Key,
3576 {
3577 self.r_unless.extend(names.into_iter().map(Id::from));
3578 self
3579 }
3580
3581 /// This argument is [required] only if the specified `arg` is present at runtime and its value
3582 /// equals `val`.
3583 ///
3584 /// # Examples
3585 ///
3586 /// ```rust
3587 /// # use clap::Arg;
3588 /// Arg::new("config")
3589 /// .required_if_eq("other_arg", "value")
3590 /// # ;
3591 /// ```
3592 ///
3593 /// ```rust
3594 /// # use clap::{Command, Arg, ErrorKind};
3595 /// let res = Command::new("prog")
3596 /// .arg(Arg::new("cfg")
3597 /// .takes_value(true)
3598 /// .required_if_eq("other", "special")
3599 /// .long("config"))
3600 /// .arg(Arg::new("other")
3601 /// .long("other")
3602 /// .takes_value(true))
3603 /// .try_get_matches_from(vec![
3604 /// "prog", "--other", "not-special"
3605 /// ]);
3606 ///
3607 /// assert!(res.is_ok()); // We didn't use --other=special, so "cfg" wasn't required
3608 ///
3609 /// let res = Command::new("prog")
3610 /// .arg(Arg::new("cfg")
3611 /// .takes_value(true)
3612 /// .required_if_eq("other", "special")
3613 /// .long("config"))
3614 /// .arg(Arg::new("other")
3615 /// .long("other")
3616 /// .takes_value(true))
3617 /// .try_get_matches_from(vec![
3618 /// "prog", "--other", "special"
3619 /// ]);
3620 ///
3621 /// // We did use --other=special so "cfg" had become required but was missing.
3622 /// assert!(res.is_err());
3623 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3624 ///
3625 /// let res = Command::new("prog")
3626 /// .arg(Arg::new("cfg")
3627 /// .takes_value(true)
3628 /// .required_if_eq("other", "special")
3629 /// .long("config"))
3630 /// .arg(Arg::new("other")
3631 /// .long("other")
3632 /// .takes_value(true))
3633 /// .try_get_matches_from(vec![
3634 /// "prog", "--other", "SPECIAL"
3635 /// ]);
3636 ///
3637 /// // By default, the comparison is case-sensitive, so "cfg" wasn't required
3638 /// assert!(res.is_ok());
3639 ///
3640 /// let res = Command::new("prog")
3641 /// .arg(Arg::new("cfg")
3642 /// .takes_value(true)
3643 /// .required_if_eq("other", "special")
3644 /// .long("config"))
3645 /// .arg(Arg::new("other")
3646 /// .long("other")
3647 /// .ignore_case(true)
3648 /// .takes_value(true))
3649 /// .try_get_matches_from(vec![
3650 /// "prog", "--other", "SPECIAL"
3651 /// ]);
3652 ///
3653 /// // However, case-insensitive comparisons can be enabled. This typically occurs when using Arg::possible_values().
3654 /// assert!(res.is_err());
3655 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3656 /// ```
3657 /// [`Arg::requires(name)`]: Arg::requires()
3658 /// [Conflicting]: Arg::conflicts_with()
3659 /// [required]: Arg::required()
3660 #[must_use]
3661 pub fn required_if_eq<T: Key>(mut self, arg_id: T, val: &'help str) -> Self {
3662 self.r_ifs.push((arg_id.into(), val));
3663 self
3664 }
3665
3666 /// Specify this argument is [required] based on multiple conditions.
3667 ///
3668 /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become
3669 /// valid if one of the specified `arg`'s value equals its corresponding `val`.
3670 ///
3671 /// # Examples
3672 ///
3673 /// ```rust
3674 /// # use clap::Arg;
3675 /// Arg::new("config")
3676 /// .required_if_eq_any(&[
3677 /// ("extra", "val"),
3678 /// ("option", "spec")
3679 /// ])
3680 /// # ;
3681 /// ```
3682 ///
3683 /// Setting `Arg::required_if_eq_any(&[(arg, val)])` makes this arg required if any of the `arg`s
3684 /// are used at runtime and it's corresponding value is equal to `val`. If the `arg`'s value is
3685 /// anything other than `val`, this argument isn't required.
3686 ///
3687 /// ```rust
3688 /// # use clap::{Command, Arg};
3689 /// let res = Command::new("prog")
3690 /// .arg(Arg::new("cfg")
3691 /// .required_if_eq_any(&[
3692 /// ("extra", "val"),
3693 /// ("option", "spec")
3694 /// ])
3695 /// .takes_value(true)
3696 /// .long("config"))
3697 /// .arg(Arg::new("extra")
3698 /// .takes_value(true)
3699 /// .long("extra"))
3700 /// .arg(Arg::new("option")
3701 /// .takes_value(true)
3702 /// .long("option"))
3703 /// .try_get_matches_from(vec![
3704 /// "prog", "--option", "other"
3705 /// ]);
3706 ///
3707 /// assert!(res.is_ok()); // We didn't use --option=spec, or --extra=val so "cfg" isn't required
3708 /// ```
3709 ///
3710 /// Setting `Arg::required_if_eq_any(&[(arg, val)])` and having any of the `arg`s used with its
3711 /// value of `val` but *not* using this arg is an error.
3712 ///
3713 /// ```rust
3714 /// # use clap::{Command, Arg, ErrorKind};
3715 /// let res = Command::new("prog")
3716 /// .arg(Arg::new("cfg")
3717 /// .required_if_eq_any(&[
3718 /// ("extra", "val"),
3719 /// ("option", "spec")
3720 /// ])
3721 /// .takes_value(true)
3722 /// .long("config"))
3723 /// .arg(Arg::new("extra")
3724 /// .takes_value(true)
3725 /// .long("extra"))
3726 /// .arg(Arg::new("option")
3727 /// .takes_value(true)
3728 /// .long("option"))
3729 /// .try_get_matches_from(vec![
3730 /// "prog", "--option", "spec"
3731 /// ]);
3732 ///
3733 /// assert!(res.is_err());
3734 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3735 /// ```
3736 /// [`Arg::requires(name)`]: Arg::requires()
3737 /// [Conflicting]: Arg::conflicts_with()
3738 /// [required]: Arg::required()
3739 #[must_use]
3740 pub fn required_if_eq_any<T: Key>(mut self, ifs: &[(T, &'help str)]) -> Self {
3741 self.r_ifs
3742 .extend(ifs.iter().map(|(id, val)| (Id::from_ref(id), *val)));
3743 self
3744 }
3745
3746 /// Specify this argument is [required] based on multiple conditions.
3747 ///
3748 /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become
3749 /// valid if every one of the specified `arg`'s value equals its corresponding `val`.
3750 ///
3751 /// # Examples
3752 ///
3753 /// ```rust
3754 /// # use clap::Arg;
3755 /// Arg::new("config")
3756 /// .required_if_eq_all(&[
3757 /// ("extra", "val"),
3758 /// ("option", "spec")
3759 /// ])
3760 /// # ;
3761 /// ```
3762 ///
3763 /// Setting `Arg::required_if_eq_all(&[(arg, val)])` makes this arg required if all of the `arg`s
3764 /// are used at runtime and every value is equal to its corresponding `val`. If the `arg`'s value is
3765 /// anything other than `val`, this argument isn't required.
3766 ///
3767 /// ```rust
3768 /// # use clap::{Command, Arg};
3769 /// let res = Command::new("prog")
3770 /// .arg(Arg::new("cfg")
3771 /// .required_if_eq_all(&[
3772 /// ("extra", "val"),
3773 /// ("option", "spec")
3774 /// ])
3775 /// .takes_value(true)
3776 /// .long("config"))
3777 /// .arg(Arg::new("extra")
3778 /// .takes_value(true)
3779 /// .long("extra"))
3780 /// .arg(Arg::new("option")
3781 /// .takes_value(true)
3782 /// .long("option"))
3783 /// .try_get_matches_from(vec![
3784 /// "prog", "--option", "spec"
3785 /// ]);
3786 ///
3787 /// assert!(res.is_ok()); // We didn't use --option=spec --extra=val so "cfg" isn't required
3788 /// ```
3789 ///
3790 /// Setting `Arg::required_if_eq_all(&[(arg, val)])` and having all of the `arg`s used with its
3791 /// value of `val` but *not* using this arg is an error.
3792 ///
3793 /// ```rust
3794 /// # use clap::{Command, Arg, ErrorKind};
3795 /// let res = Command::new("prog")
3796 /// .arg(Arg::new("cfg")
3797 /// .required_if_eq_all(&[
3798 /// ("extra", "val"),
3799 /// ("option", "spec")
3800 /// ])
3801 /// .takes_value(true)
3802 /// .long("config"))
3803 /// .arg(Arg::new("extra")
3804 /// .takes_value(true)
3805 /// .long("extra"))
3806 /// .arg(Arg::new("option")
3807 /// .takes_value(true)
3808 /// .long("option"))
3809 /// .try_get_matches_from(vec![
3810 /// "prog", "--extra", "val", "--option", "spec"
3811 /// ]);
3812 ///
3813 /// assert!(res.is_err());
3814 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3815 /// ```
3816 /// [required]: Arg::required()
3817 #[must_use]
3818 pub fn required_if_eq_all<T: Key>(mut self, ifs: &[(T, &'help str)]) -> Self {
3819 self.r_ifs_all
3820 .extend(ifs.iter().map(|(id, val)| (Id::from_ref(id), *val)));
3821 self
3822 }
3823
3824 /// Require another argument if this arg was present at runtime and its value equals to `val`.
3825 ///
3826 /// This method takes `value, another_arg` pair. At runtime, clap will check
3827 /// if this arg (`self`) is present and its value equals to `val`.
3828 /// If it does, `another_arg` will be marked as required.
3829 ///
3830 /// # Examples
3831 ///
3832 /// ```rust
3833 /// # use clap::Arg;
3834 /// Arg::new("config")
3835 /// .requires_if("val", "arg")
3836 /// # ;
3837 /// ```
3838 ///
3839 /// Setting `Arg::requires_if(val, arg)` requires that the `arg` be used at runtime if the
3840 /// defining argument's value is equal to `val`. If the defining argument is anything other than
3841 /// `val`, the other argument isn't required.
3842 ///
3843 /// ```rust
3844 /// # use clap::{Command, Arg};
3845 /// let res = Command::new("prog")
3846 /// .arg(Arg::new("cfg")
3847 /// .takes_value(true)
3848 /// .requires_if("my.cfg", "other")
3849 /// .long("config"))
3850 /// .arg(Arg::new("other"))
3851 /// .try_get_matches_from(vec![
3852 /// "prog", "--config", "some.cfg"
3853 /// ]);
3854 ///
3855 /// assert!(res.is_ok()); // We didn't use --config=my.cfg, so other wasn't required
3856 /// ```
3857 ///
3858 /// Setting `Arg::requires_if(val, arg)` and setting the value to `val` but *not* supplying
3859 /// `arg` is an error.
3860 ///
3861 /// ```rust
3862 /// # use clap::{Command, Arg, ErrorKind};
3863 /// let res = Command::new("prog")
3864 /// .arg(Arg::new("cfg")
3865 /// .takes_value(true)
3866 /// .requires_if("my.cfg", "input")
3867 /// .long("config"))
3868 /// .arg(Arg::new("input"))
3869 /// .try_get_matches_from(vec![
3870 /// "prog", "--config", "my.cfg"
3871 /// ]);
3872 ///
3873 /// assert!(res.is_err());
3874 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3875 /// ```
3876 /// [`Arg::requires(name)`]: Arg::requires()
3877 /// [Conflicting]: Arg::conflicts_with()
3878 /// [override]: Arg::overrides_with()
3879 #[must_use]
3880 pub fn requires_if<T: Key>(mut self, val: &'help str, arg_id: T) -> Self {
3881 self.requires
3882 .push((ArgPredicate::Equals(OsStr::new(val)), arg_id.into()));
3883 self
3884 }
3885
3886 /// Allows multiple conditional requirements.
3887 ///
3888 /// The requirement will only become valid if this arg's value equals `val`.
3889 ///
3890 /// # Examples
3891 ///
3892 /// ```rust
3893 /// # use clap::Arg;
3894 /// Arg::new("config")
3895 /// .requires_ifs(&[
3896 /// ("val", "arg"),
3897 /// ("other_val", "arg2"),
3898 /// ])
3899 /// # ;
3900 /// ```
3901 ///
3902 /// Setting `Arg::requires_ifs(&["val", "arg"])` requires that the `arg` be used at runtime if the
3903 /// defining argument's value is equal to `val`. If the defining argument's value is anything other
3904 /// than `val`, `arg` isn't required.
3905 ///
3906 /// ```rust
3907 /// # use clap::{Command, Arg, ErrorKind};
3908 /// let res = Command::new("prog")
3909 /// .arg(Arg::new("cfg")
3910 /// .takes_value(true)
3911 /// .requires_ifs(&[
3912 /// ("special.conf", "opt"),
3913 /// ("other.conf", "other"),
3914 /// ])
3915 /// .long("config"))
3916 /// .arg(Arg::new("opt")
3917 /// .long("option")
3918 /// .takes_value(true))
3919 /// .arg(Arg::new("other"))
3920 /// .try_get_matches_from(vec![
3921 /// "prog", "--config", "special.conf"
3922 /// ]);
3923 ///
3924 /// assert!(res.is_err()); // We used --config=special.conf so --option <val> is required
3925 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3926 /// ```
3927 /// [`Arg::requires(name)`]: Arg::requires()
3928 /// [Conflicting]: Arg::conflicts_with()
3929 /// [override]: Arg::overrides_with()
3930 #[must_use]
3931 pub fn requires_ifs<T: Key>(mut self, ifs: &[(&'help str, T)]) -> Self {
3932 self.requires.extend(
3933 ifs.iter()
3934 .map(|(val, arg)| (ArgPredicate::Equals(OsStr::new(*val)), Id::from(arg))),
3935 );
3936 self
3937 }
3938
3939 /// Require these arguments names when this one is presen
3940 ///
3941 /// i.e. when using this argument, the following arguments *must* be present.
3942 ///
3943 /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required
3944 /// by default.
3945 ///
3946 /// # Examples
3947 ///
3948 /// ```rust
3949 /// # use clap::Arg;
3950 /// Arg::new("config")
3951 /// .requires_all(&["input", "output"])
3952 /// # ;
3953 /// ```
3954 ///
3955 /// Setting `Arg::requires_all(&[arg, arg2])` requires that all the arguments be used at
3956 /// runtime if the defining argument is used. If the defining argument isn't used, the other
3957 /// argument isn't required
3958 ///
3959 /// ```rust
3960 /// # use clap::{Command, Arg};
3961 /// let res = Command::new("prog")
3962 /// .arg(Arg::new("cfg")
3963 /// .takes_value(true)
3964 /// .requires("input")
3965 /// .long("config"))
3966 /// .arg(Arg::new("input"))
3967 /// .arg(Arg::new("output"))
3968 /// .try_get_matches_from(vec![
3969 /// "prog"
3970 /// ]);
3971 ///
3972 /// assert!(res.is_ok()); // We didn't use cfg, so input and output weren't required
3973 /// ```
3974 ///
3975 /// Setting `Arg::requires_all(&[arg, arg2])` and *not* supplying all the arguments is an
3976 /// error.
3977 ///
3978 /// ```rust
3979 /// # use clap::{Command, Arg, ErrorKind};
3980 /// let res = Command::new("prog")
3981 /// .arg(Arg::new("cfg")
3982 /// .takes_value(true)
3983 /// .requires_all(&["input", "output"])
3984 /// .long("config"))
3985 /// .arg(Arg::new("input"))
3986 /// .arg(Arg::new("output"))
3987 /// .try_get_matches_from(vec![
3988 /// "prog", "--config", "file.conf", "in.txt"
3989 /// ]);
3990 ///
3991 /// assert!(res.is_err());
3992 /// // We didn't use output
3993 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3994 /// ```
3995 /// [Conflicting]: Arg::conflicts_with()
3996 /// [override]: Arg::overrides_with()
3997 #[must_use]
3998 pub fn requires_all<T: Key>(mut self, names: &[T]) -> Self {
3999 self.requires
4000 .extend(names.iter().map(|s| (ArgPredicate::IsPresent, s.into())));
4001 self
4002 }
4003
4004 /// This argument is mutually exclusive with the specified argument.
4005 ///
4006 /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules
4007 /// only need to be set for one of the two arguments, they do not need to be set for each.
4008 ///
4009 /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments
4010 /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not
4011 /// need to also do B.conflicts_with(A))
4012 ///
4013 /// **NOTE:** [`Arg::conflicts_with_all(names)`] allows specifying an argument which conflicts with more than one argument.
4014 ///
4015 /// **NOTE** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument.
4016 ///
4017 /// # Examples
4018 ///
4019 /// ```rust
4020 /// # use clap::Arg;
4021 /// Arg::new("config")
4022 /// .conflicts_with("debug")
4023 /// # ;
4024 /// ```
4025 ///
4026 /// Setting conflicting argument, and having both arguments present at runtime is an error.
4027 ///
4028 /// ```rust
4029 /// # use clap::{Command, Arg, ErrorKind};
4030 /// let res = Command::new("prog")
4031 /// .arg(Arg::new("cfg")
4032 /// .takes_value(true)
4033 /// .conflicts_with("debug")
4034 /// .long("config"))
4035 /// .arg(Arg::new("debug")
4036 /// .long("debug"))
4037 /// .try_get_matches_from(vec![
4038 /// "prog", "--debug", "--config", "file.conf"
4039 /// ]);
4040 ///
4041 /// assert!(res.is_err());
4042 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict);
4043 /// ```
4044 ///
4045 /// [`Arg::conflicts_with_all(names)`]: Arg::conflicts_with_all()
4046 /// [`Arg::exclusive(true)`]: Arg::exclusive()
4047 #[must_use]
4048 pub fn conflicts_with<T: Key>(mut self, arg_id: T) -> Self {
4049 self.blacklist.push(arg_id.into());
4050 self
4051 }
4052
4053 /// This argument is mutually exclusive with the specified arguments.
4054 ///
4055 /// See [`Arg::conflicts_with`].
4056 ///
4057 /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules
4058 /// only need to be set for one of the two arguments, they do not need to be set for each.
4059 ///
4060 /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments
4061 /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need
4062 /// need to also do B.conflicts_with(A))
4063 ///
4064 /// **NOTE:** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument.
4065 ///
4066 /// # Examples
4067 ///
4068 /// ```rust
4069 /// # use clap::Arg;
4070 /// Arg::new("config")
4071 /// .conflicts_with_all(&["debug", "input"])
4072 /// # ;
4073 /// ```
4074 ///
4075 /// Setting conflicting argument, and having any of the arguments present at runtime with a
4076 /// conflicting argument is an error.
4077 ///
4078 /// ```rust
4079 /// # use clap::{Command, Arg, ErrorKind};
4080 /// let res = Command::new("prog")
4081 /// .arg(Arg::new("cfg")
4082 /// .takes_value(true)
4083 /// .conflicts_with_all(&["debug", "input"])
4084 /// .long("config"))
4085 /// .arg(Arg::new("debug")
4086 /// .long("debug"))
4087 /// .arg(Arg::new("input"))
4088 /// .try_get_matches_from(vec![
4089 /// "prog", "--config", "file.conf", "file.txt"
4090 /// ]);
4091 ///
4092 /// assert!(res.is_err());
4093 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict);
4094 /// ```
4095 /// [`Arg::conflicts_with`]: Arg::conflicts_with()
4096 /// [`Arg::exclusive(true)`]: Arg::exclusive()
4097 #[must_use]
4098 pub fn conflicts_with_all(mut self, names: &[&str]) -> Self {
4099 self.blacklist.extend(names.iter().copied().map(Id::from));
4100 self
4101 }
4102
4103 /// Sets an overridable argument.
4104 ///
4105 /// i.e. this argument and the following argument
4106 /// will override each other in POSIX style (whichever argument was specified at runtime
4107 /// **last** "wins")
4108 ///
4109 /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any
4110 /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed
4111 ///
4112 /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with`].
4113 ///
4114 /// **WARNING:** Positional arguments and options which accept
4115 /// [`Arg::multiple_occurrences`] cannot override themselves (or we
4116 /// would never be able to advance to the next positional). If a positional
4117 /// argument or option with one of the [`Arg::multiple_occurrences`]
4118 /// settings lists itself as an override, it is simply ignored.
4119 ///
4120 /// # Examples
4121 ///
4122 /// ```rust
4123 /// # use clap::{Command, arg};
4124 /// let m = Command::new("prog")
4125 /// .arg(arg!(-f --flag "some flag")
4126 /// .conflicts_with("debug"))
4127 /// .arg(arg!(-d --debug "other flag"))
4128 /// .arg(arg!(-c --color "third flag")
4129 /// .overrides_with("flag"))
4130 /// .get_matches_from(vec![
4131 /// "prog", "-f", "-d", "-c"]);
4132 /// // ^~~~~~~~~~~~^~~~~ flag is overridden by color
4133 ///
4134 /// assert!(m.is_present("color"));
4135 /// assert!(m.is_present("debug")); // even though flag conflicts with debug, it's as if flag
4136 /// // was never used because it was overridden with color
4137 /// assert!(!m.is_present("flag"));
4138 /// ```
4139 /// Care must be taken when using this setting, and having an arg override with itself. This
4140 /// is common practice when supporting things like shell aliases, config files, etc.
4141 /// However, when combined with multiple values, it can get dicy.
4142 /// Here is how clap handles such situations:
4143 ///
4144 /// When a flag overrides itself, it's as if the flag was only ever used once (essentially
4145 /// preventing a "Unexpected multiple usage" error):
4146 ///
4147 /// ```rust
4148 /// # use clap::{Command, arg};
4149 /// let m = Command::new("posix")
4150 /// .arg(arg!(--flag "some flag").overrides_with("flag"))
4151 /// .get_matches_from(vec!["posix", "--flag", "--flag"]);
4152 /// assert!(m.is_present("flag"));
4153 /// ```
4154 ///
4155 /// Making an arg [`Arg::multiple_occurrences`] and override itself
4156 /// is essentially meaningless. Therefore clap ignores an override of self
4157 /// if it's a flag and it already accepts multiple occurrences.
4158 ///
4159 /// ```
4160 /// # use clap::{Command, arg};
4161 /// let m = Command::new("posix")
4162 /// .arg(arg!(--flag ... "some flag").overrides_with("flag"))
4163 /// .get_matches_from(vec!["", "--flag", "--flag", "--flag", "--flag"]);
4164 /// assert!(m.is_present("flag"));
4165 /// ```
4166 ///
4167 /// Now notice with options (which *do not* set
4168 /// [`Arg::multiple_occurrences`]), it's as if only the last
4169 /// occurrence happened.
4170 ///
4171 /// ```
4172 /// # use clap::{Command, arg};
4173 /// let m = Command::new("posix")
4174 /// .arg(arg!(--opt <val> "some option").overrides_with("opt"))
4175 /// .get_matches_from(vec!["", "--opt=some", "--opt=other"]);
4176 /// assert!(m.is_present("opt"));
4177 /// assert_eq!(m.value_of("opt"), Some("other"));
4178 /// ```
4179 ///
4180 /// This will also work when [`Arg::multiple_values`] is enabled:
4181 ///
4182 /// ```
4183 /// # use clap::{Command, Arg};
4184 /// let m = Command::new("posix")
4185 /// .arg(
4186 /// Arg::new("opt")
4187 /// .long("opt")
4188 /// .takes_value(true)
4189 /// .multiple_values(true)
4190 /// .overrides_with("opt")
4191 /// )
4192 /// .get_matches_from(vec!["", "--opt", "1", "2", "--opt", "3", "4", "5"]);
4193 /// assert!(m.is_present("opt"));
4194 /// assert_eq!(m.values_of("opt").unwrap().collect::<Vec<_>>(), &["3", "4", "5"]);
4195 /// ```
4196 ///
4197 /// Just like flags, options with [`Arg::multiple_occurrences`] set
4198 /// will ignore the "override self" setting.
4199 ///
4200 /// ```
4201 /// # use clap::{Command, arg};
4202 /// let m = Command::new("posix")
4203 /// .arg(arg!(--opt <val> ... "some option")
4204 /// .multiple_values(true)
4205 /// .overrides_with("opt"))
4206 /// .get_matches_from(vec!["", "--opt", "first", "over", "--opt", "other", "val"]);
4207 /// assert!(m.is_present("opt"));
4208 /// assert_eq!(m.values_of("opt").unwrap().collect::<Vec<_>>(), &["first", "over", "other", "val"]);
4209 /// ```
4210 #[must_use]
4211 pub fn overrides_with<T: Key>(mut self, arg_id: T) -> Self {
4212 self.overrides.push(arg_id.into());
4213 self
4214 }
4215
4216 /// Sets multiple mutually overridable arguments by name.
4217 ///
4218 /// i.e. this argument and the following argument will override each other in POSIX style
4219 /// (whichever argument was specified at runtime **last** "wins")
4220 ///
4221 /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any
4222 /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed
4223 ///
4224 /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with_all`].
4225 ///
4226 /// # Examples
4227 ///
4228 /// ```rust
4229 /// # use clap::{Command, arg};
4230 /// let m = Command::new("prog")
4231 /// .arg(arg!(-f --flag "some flag")
4232 /// .conflicts_with("color"))
4233 /// .arg(arg!(-d --debug "other flag"))
4234 /// .arg(arg!(-c --color "third flag")
4235 /// .overrides_with_all(&["flag", "debug"]))
4236 /// .get_matches_from(vec![
4237 /// "prog", "-f", "-d", "-c"]);
4238 /// // ^~~~~~^~~~~~~~~ flag and debug are overridden by color
4239 ///
4240 /// assert!(m.is_present("color")); // even though flag conflicts with color, it's as if flag
4241 /// // and debug were never used because they were overridden
4242 /// // with color
4243 /// assert!(!m.is_present("debug"));
4244 /// assert!(!m.is_present("flag"));
4245 /// ```
4246 #[must_use]
4247 pub fn overrides_with_all<T: Key>(mut self, names: &[T]) -> Self {
4248 self.overrides.extend(names.iter().map(Id::from));
4249 self
4250 }
4251 }
4252
4253 /// # Reflection
4254 impl<'help> Arg<'help> {
4255 /// Get the name of the argument
4256 #[inline]
4257 pub fn get_id(&self) -> &'help str {
4258 self.name
4259 }
4260
4261 /// Deprecated, replaced with [`Arg::get_id`]
4262 #[cfg_attr(
4263 feature = "deprecated",
4264 deprecated(since = "3.1.0", note = "Replaced with `Arg::get_id`")
4265 )]
4266 pub fn get_name(&self) -> &'help str {
4267 self.get_id()
4268 }
4269
4270 /// Get the help specified for this argument, if any
4271 #[inline]
4272 pub fn get_help(&self) -> Option<&'help str> {
4273 self.help
4274 }
4275
4276 /// Get the long help specified for this argument, if any
4277 ///
4278 /// # Examples
4279 ///
4280 /// ```rust
4281 /// # use clap::Arg;
4282 /// let arg = Arg::new("foo").long_help("long help");
4283 /// assert_eq!(Some("long help"), arg.get_long_help());
4284 /// ```
4285 ///
4286 #[inline]
4287 pub fn get_long_help(&self) -> Option<&'help str> {
4288 self.long_help
4289 }
4290
4291 /// Get the help heading specified for this argument, if any
4292 #[inline]
4293 pub fn get_help_heading(&self) -> Option<&'help str> {
4294 self.help_heading.unwrap_or_default()
4295 }
4296
4297 /// Get the short option name for this argument, if any
4298 #[inline]
4299 pub fn get_short(&self) -> Option<char> {
4300 self.short
4301 }
4302
4303 /// Get visible short aliases for this argument, if any
4304 #[inline]
4305 pub fn get_visible_short_aliases(&self) -> Option<Vec<char>> {
4306 if self.short_aliases.is_empty() {
4307 None
4308 } else {
4309 Some(
4310 self.short_aliases
4311 .iter()
4312 .filter_map(|(c, v)| if *v { Some(c) } else { None })
4313 .copied()
4314 .collect(),
4315 )
4316 }
4317 }
4318
4319 /// Get the short option name and its visible aliases, if any
4320 #[inline]
4321 pub fn get_short_and_visible_aliases(&self) -> Option<Vec<char>> {
4322 let mut shorts = match self.short {
4323 Some(short) => vec![short],
4324 None => return None,
4325 };
4326 if let Some(aliases) = self.get_visible_short_aliases() {
4327 shorts.extend(aliases);
4328 }
4329 Some(shorts)
4330 }
4331
4332 /// Get the long option name for this argument, if any
4333 #[inline]
4334 pub fn get_long(&self) -> Option<&'help str> {
4335 self.long
4336 }
4337
4338 /// Get visible aliases for this argument, if any
4339 #[inline]
4340 pub fn get_visible_aliases(&self) -> Option<Vec<&'help str>> {
4341 if self.aliases.is_empty() {
4342 None
4343 } else {
4344 Some(
4345 self.aliases
4346 .iter()
4347 .filter_map(|(s, v)| if *v { Some(s) } else { None })
4348 .copied()
4349 .collect(),
4350 )
4351 }
4352 }
4353
4354 /// Get the long option name and its visible aliases, if any
4355 #[inline]
4356 pub fn get_long_and_visible_aliases(&self) -> Option<Vec<&'help str>> {
4357 let mut longs = match self.long {
4358 Some(long) => vec![long],
4359 None => return None,
4360 };
4361 if let Some(aliases) = self.get_visible_aliases() {
4362 longs.extend(aliases);
4363 }
4364 Some(longs)
4365 }
4366
4367 /// Deprecated, replaced with [`Arg::get_value_parser().possible_values()`]
4368 #[cfg_attr(
4369 feature = "deprecated",
4370 deprecated(
4371 since = "3.2.0",
4372 note = "Replaced with `Arg::get_value_parser().possible_values()`"
4373 )
4374 )]
4375 pub fn get_possible_values(&self) -> Option<&[PossibleValue<'help>]> {
4376 if self.possible_vals.is_empty() {
4377 None
4378 } else {
4379 Some(&self.possible_vals)
4380 }
4381 }
4382
4383 pub(crate) fn get_possible_values2(&self) -> Vec<PossibleValue<'help>> {
4384 #![allow(deprecated)]
4385 if !self.is_takes_value_set() {
4386 vec![]
4387 } else if let Some(pvs) = self.get_possible_values() {
4388 // Check old first in case the user explicitly set possible values and the derive inferred
4389 // a `ValueParser` with some.
4390 pvs.to_vec()
4391 } else {
4392 self.get_value_parser()
4393 .possible_values()
4394 .map(|pvs| pvs.collect())
4395 .unwrap_or_default()
4396 }
4397 }
4398
4399 /// Get the names of values for this argument.
4400 #[inline]
4401 pub fn get_value_names(&self) -> Option<&[&'help str]> {
4402 if self.val_names.is_empty() {
4403 None
4404 } else {
4405 Some(&self.val_names)
4406 }
4407 }
4408
4409 /// Get the number of values for this argument.
4410 #[inline]
4411 pub fn get_num_vals(&self) -> Option<usize> {
4412 self.num_vals
4413 }
4414
4415 /// Get the delimiter between multiple values
4416 #[inline]
4417 pub fn get_value_delimiter(&self) -> Option<char> {
4418 self.val_delim
4419 }
4420
4421 /// Get the index of this argument, if any
4422 #[inline]
4423 pub fn get_index(&self) -> Option<usize> {
4424 self.index
4425 }
4426
4427 /// Get the value hint of this argument
4428 pub fn get_value_hint(&self) -> ValueHint {
4429 self.value_hint.unwrap_or_else(|| {
4430 if self.is_takes_value_set() {
4431 let type_id = self.get_value_parser().type_id();
4432 if type_id == crate::parser::AnyValueId::of::<std::path::PathBuf>() {
4433 ValueHint::AnyPath
4434 } else {
4435 ValueHint::default()
4436 }
4437 } else {
4438 ValueHint::default()
4439 }
4440 })
4441 }
4442
4443 /// Deprecated, replaced with [`Arg::is_global_set`]
4444 #[cfg_attr(
4445 feature = "deprecated",
4446 deprecated(since = "3.1.0", note = "Replaced with `Arg::is_global_set`")
4447 )]
4448 pub fn get_global(&self) -> bool {
4449 self.is_global_set()
4450 }
4451
4452 /// Get the environment variable name specified for this argument, if any
4453 ///
4454 /// # Examples
4455 ///
4456 /// ```rust
4457 /// # use std::ffi::OsStr;
4458 /// # use clap::Arg;
4459 /// let arg = Arg::new("foo").env("ENVIRONMENT");
4460 /// assert_eq!(Some(OsStr::new("ENVIRONMENT")), arg.get_env());
4461 /// ```
4462 #[cfg(feature = "env")]
4463 pub fn get_env(&self) -> Option<&OsStr> {
4464 self.env.as_ref().map(|x| x.0)
4465 }
4466
4467 /// Get the default values specified for this argument, if any
4468 ///
4469 /// # Examples
4470 ///
4471 /// ```rust
4472 /// # use clap::Arg;
4473 /// let arg = Arg::new("foo").default_value("default value");
4474 /// assert_eq!(&["default value"], arg.get_default_values());
4475 /// ```
4476 pub fn get_default_values(&self) -> &[&OsStr] {
4477 &self.default_vals
4478 }
4479
4480 /// Checks whether this argument is a positional or not.
4481 ///
4482 /// # Examples
4483 ///
4484 /// ```
4485 /// # use clap::Arg;
4486 /// let arg = Arg::new("foo");
4487 /// assert_eq!(true, arg.is_positional());
4488 ///
4489 /// let arg = Arg::new("foo").long("foo");
4490 /// assert_eq!(false, arg.is_positional());
4491 /// ```
4492 pub fn is_positional(&self) -> bool {
4493 self.long.is_none() && self.short.is_none()
4494 }
4495
4496 /// Reports whether [`Arg::required`] is set
4497 pub fn is_required_set(&self) -> bool {
4498 self.is_set(ArgSettings::Required)
4499 }
4500
4501 /// Report whether [`Arg::multiple_values`] is set
4502 pub fn is_multiple_values_set(&self) -> bool {
4503 self.is_set(ArgSettings::MultipleValues)
4504 }
4505
4506 /// [`Arg::multiple_occurrences`] is going away ([Issue #3772](https://github.com/clap-rs/clap/issues/3772))
4507 #[cfg_attr(
4508 feature = "deprecated",
4509 deprecated(since = "3.2.0", note = "`multiple_occurrences` away (Issue #3772)")
4510 )]
4511 pub fn is_multiple_occurrences_set(&self) -> bool {
4512 self.is_set(ArgSettings::MultipleOccurrences)
4513 }
4514
4515 /// Report whether [`Arg::is_takes_value_set`] is set
4516 pub fn is_takes_value_set(&self) -> bool {
4517 self.is_set(ArgSettings::TakesValue)
4518 }
4519
4520 /// Report whether [`Arg::allow_hyphen_values`] is set
4521 pub fn is_allow_hyphen_values_set(&self) -> bool {
4522 self.is_set(ArgSettings::AllowHyphenValues)
4523 }
4524
4525 /// Deprecated, replaced with [`Arg::get_value_parser()`]
4526 #[cfg_attr(
4527 feature = "deprecated",
4528 deprecated(since = "3.2.0", note = "Replaced with `Arg::get_value_parser()`")
4529 )]
4530 pub fn is_forbid_empty_values_set(&self) -> bool {
4531 self.is_set(ArgSettings::ForbidEmptyValues)
4532 }
4533
4534 /// Deprecated, replaced with [`Arg::get_value_parser()`
4535 #[cfg_attr(
4536 feature = "deprecated",
4537 deprecated(since = "3.2.0", note = "Replaced with `Arg::get_value_parser()`")
4538 )]
4539 pub fn is_allow_invalid_utf8_set(&self) -> bool {
4540 self.is_set(ArgSettings::AllowInvalidUtf8)
4541 }
4542
4543 /// Behavior when parsing the argument
4544 pub fn get_action(&self) -> &super::ArgAction {
4545 const DEFAULT: super::ArgAction = super::ArgAction::StoreValue;
4546 self.action.as_ref().unwrap_or(&DEFAULT)
4547 }
4548
4549 /// Configured parser for argument values
4550 ///
4551 /// # Example
4552 ///
4553 /// ```rust
4554 /// let cmd = clap::Command::new("raw")
4555 /// .arg(
4556 /// clap::Arg::new("port")
4557 /// .value_parser(clap::value_parser!(usize))
4558 /// );
4559 /// let value_parser = cmd.get_arguments()
4560 /// .find(|a| a.get_id() == "port").unwrap()
4561 /// .get_value_parser();
4562 /// println!("{:?}", value_parser);
4563 /// ```
4564 pub fn get_value_parser(&self) -> &super::ValueParser {
4565 if let Some(value_parser) = self.value_parser.as_ref() {
4566 value_parser
4567 } else if self.is_allow_invalid_utf8_set() {
4568 static DEFAULT: super::ValueParser = super::ValueParser::os_string();
4569 &DEFAULT
4570 } else {
4571 static DEFAULT: super::ValueParser = super::ValueParser::string();
4572 &DEFAULT
4573 }
4574 }
4575
4576 /// Report whether [`Arg::global`] is set
4577 pub fn is_global_set(&self) -> bool {
4578 self.is_set(ArgSettings::Global)
4579 }
4580
4581 /// Report whether [`Arg::next_line_help`] is set
4582 pub fn is_next_line_help_set(&self) -> bool {
4583 self.is_set(ArgSettings::NextLineHelp)
4584 }
4585
4586 /// Report whether [`Arg::hide`] is set
4587 pub fn is_hide_set(&self) -> bool {
4588 self.is_set(ArgSettings::Hidden)
4589 }
4590
4591 /// Report whether [`Arg::hide_default_value`] is set
4592 pub fn is_hide_default_value_set(&self) -> bool {
4593 self.is_set(ArgSettings::HideDefaultValue)
4594 }
4595
4596 /// Report whether [`Arg::hide_possible_values`] is set
4597 pub fn is_hide_possible_values_set(&self) -> bool {
4598 self.is_set(ArgSettings::HidePossibleValues)
4599 }
4600
4601 /// Report whether [`Arg::hide_env`] is set
4602 #[cfg(feature = "env")]
4603 pub fn is_hide_env_set(&self) -> bool {
4604 self.is_set(ArgSettings::HideEnv)
4605 }
4606
4607 /// Report whether [`Arg::hide_env_values`] is set
4608 #[cfg(feature = "env")]
4609 pub fn is_hide_env_values_set(&self) -> bool {
4610 self.is_set(ArgSettings::HideEnvValues)
4611 }
4612
4613 /// Report whether [`Arg::hide_short_help`] is set
4614 pub fn is_hide_short_help_set(&self) -> bool {
4615 self.is_set(ArgSettings::HiddenShortHelp)
4616 }
4617
4618 /// Report whether [`Arg::hide_long_help`] is set
4619 pub fn is_hide_long_help_set(&self) -> bool {
4620 self.is_set(ArgSettings::HiddenLongHelp)
4621 }
4622
4623 /// Report whether [`Arg::use_value_delimiter`] is set
4624 pub fn is_use_value_delimiter_set(&self) -> bool {
4625 self.is_set(ArgSettings::UseValueDelimiter)
4626 }
4627
4628 /// Report whether [`Arg::require_value_delimiter`] is set
4629 pub fn is_require_value_delimiter_set(&self) -> bool {
4630 self.is_set(ArgSettings::RequireDelimiter)
4631 }
4632
4633 /// Report whether [`Arg::require_equals`] is set
4634 pub fn is_require_equals_set(&self) -> bool {
4635 self.is_set(ArgSettings::RequireEquals)
4636 }
4637
4638 /// Reports whether [`Arg::exclusive`] is set
4639 pub fn is_exclusive_set(&self) -> bool {
4640 self.is_set(ArgSettings::Exclusive)
4641 }
4642
4643 /// Reports whether [`Arg::last`] is set
4644 pub fn is_last_set(&self) -> bool {
4645 self.is_set(ArgSettings::Last)
4646 }
4647
4648 /// Reports whether [`Arg::ignore_case`] is set
4649 pub fn is_ignore_case_set(&self) -> bool {
4650 self.is_set(ArgSettings::IgnoreCase)
4651 }
4652 }
4653
4654 /// # Deprecated
4655 impl<'help> Arg<'help> {
4656 /// Deprecated, replaced with [`Arg::new`]
4657 #[cfg_attr(
4658 feature = "deprecated",
4659 deprecated(since = "3.0.0", note = "Replaced with `Arg::new`")
4660 )]
4661 #[doc(hidden)]
4662 pub fn with_name<S: Into<&'help str>>(n: S) -> Self {
4663 Self::new(n)
4664 }
4665
4666 /// Deprecated in [Issue #3087](https://github.com/clap-rs/clap/issues/3087), maybe [`clap::Parser`][crate::Parser] would fit your use case?
4667 #[cfg(feature = "yaml")]
4668 #[cfg_attr(
4669 feature = "deprecated",
4670 deprecated(
4671 since = "3.0.0",
4672 note = "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?"
4673 )
4674 )]
4675 #[doc(hidden)]
4676 pub fn from_yaml(y: &'help Yaml) -> Self {
4677 #![allow(deprecated)]
4678 let yaml_file_hash = y.as_hash().expect("YAML file must be a hash");
4679 // We WANT this to panic on error...so expect() is good.
4680 let (name_yaml, yaml) = yaml_file_hash
4681 .iter()
4682 .next()
4683 .expect("There must be one arg in the YAML file");
4684 let name_str = name_yaml.as_str().expect("Arg name must be a string");
4685 let mut a = Arg::new(name_str);
4686
4687 for (k, v) in yaml.as_hash().expect("Arg must be a hash") {
4688 a = match k.as_str().expect("Arg fields must be strings") {
4689 "short" => yaml_to_char!(a, v, short),
4690 "long" => yaml_to_str!(a, v, long),
4691 "aliases" => yaml_vec_or_str!(a, v, alias),
4692 "help" => yaml_to_str!(a, v, help),
4693 "long_help" => yaml_to_str!(a, v, long_help),
4694 "required" => yaml_to_bool!(a, v, required),
4695 "required_if" => yaml_tuple2!(a, v, required_if_eq),
4696 "required_ifs" => yaml_tuple2!(a, v, required_if_eq),
4697 "takes_value" => yaml_to_bool!(a, v, takes_value),
4698 "index" => yaml_to_usize!(a, v, index),
4699 "global" => yaml_to_bool!(a, v, global),
4700 "multiple" => yaml_to_bool!(a, v, multiple),
4701 "hidden" => yaml_to_bool!(a, v, hide),
4702 "next_line_help" => yaml_to_bool!(a, v, next_line_help),
4703 "group" => yaml_to_str!(a, v, group),
4704 "number_of_values" => yaml_to_usize!(a, v, number_of_values),
4705 "max_values" => yaml_to_usize!(a, v, max_values),
4706 "min_values" => yaml_to_usize!(a, v, min_values),
4707 "value_name" => yaml_to_str!(a, v, value_name),
4708 "use_delimiter" => yaml_to_bool!(a, v, use_delimiter),
4709 "allow_hyphen_values" => yaml_to_bool!(a, v, allow_hyphen_values),
4710 "last" => yaml_to_bool!(a, v, last),
4711 "require_delimiter" => yaml_to_bool!(a, v, require_delimiter),
4712 "value_delimiter" => yaml_to_char!(a, v, value_delimiter),
4713 "required_unless" => yaml_to_str!(a, v, required_unless_present),
4714 "display_order" => yaml_to_usize!(a, v, display_order),
4715 "default_value" => yaml_to_str!(a, v, default_value),
4716 "default_value_if" => yaml_tuple3!(a, v, default_value_if),
4717 "default_value_ifs" => yaml_tuple3!(a, v, default_value_if),
4718 #[cfg(feature = "env")]
4719 "env" => yaml_to_str!(a, v, env),
4720 "value_names" => yaml_vec_or_str!(a, v, value_name),
4721 "groups" => yaml_vec_or_str!(a, v, group),
4722 "requires" => yaml_vec_or_str!(a, v, requires),
4723 "requires_if" => yaml_tuple2!(a, v, requires_if),
4724 "requires_ifs" => yaml_tuple2!(a, v, requires_if),
4725 "conflicts_with" => yaml_vec_or_str!(a, v, conflicts_with),
4726 "overrides_with" => yaml_to_str!(a, v, overrides_with),
4727 "possible_values" => yaml_vec_or_str!(a, v, possible_value),
4728 "case_insensitive" => yaml_to_bool!(a, v, ignore_case),
4729 "required_unless_one" => yaml_vec!(a, v, required_unless_present_any),
4730 "required_unless_all" => yaml_vec!(a, v, required_unless_present_all),
4731 s => {
4732 panic!(
4733 "Unknown setting '{}' in YAML file for arg '{}'",
4734 s, name_str
4735 )
4736 }
4737 }
4738 }
4739
4740 a
4741 }
4742
4743 /// Deprecated in [Issue #3086](https://github.com/clap-rs/clap/issues/3086), see [`arg!`][crate::arg!].
4744 #[cfg_attr(
4745 feature = "deprecated",
4746 deprecated(since = "3.0.0", note = "Deprecated in Issue #3086, see `clap::arg!")
4747 )]
4748 #[doc(hidden)]
4749 pub fn from_usage(u: &'help str) -> Self {
4750 UsageParser::from_usage(u).parse()
4751 }
4752
4753 /// Deprecated, replaced with [`Arg::required_unless_present`]
4754 #[cfg_attr(
4755 feature = "deprecated",
4756 deprecated(since = "3.0.0", note = "Replaced with `Arg::required_unless_present`")
4757 )]
4758 #[doc(hidden)]
4759 #[must_use]
4760 pub fn required_unless<T: Key>(self, arg_id: T) -> Self {
4761 self.required_unless_present(arg_id)
4762 }
4763
4764 /// Deprecated, replaced with [`Arg::required_unless_present_all`]
4765 #[cfg_attr(
4766 feature = "deprecated",
4767 deprecated(
4768 since = "3.0.0",
4769 note = "Replaced with `Arg::required_unless_present_all`"
4770 )
4771 )]
4772 #[doc(hidden)]
4773 #[must_use]
4774 pub fn required_unless_all<T, I>(self, names: I) -> Self
4775 where
4776 I: IntoIterator<Item = T>,
4777 T: Key,
4778 {
4779 self.required_unless_present_all(names)
4780 }
4781
4782 /// Deprecated, replaced with [`Arg::required_unless_present_any`]
4783 #[cfg_attr(
4784 feature = "deprecated",
4785 deprecated(
4786 since = "3.0.0",
4787 note = "Replaced with `Arg::required_unless_present_any`"
4788 )
4789 )]
4790 #[doc(hidden)]
4791 #[must_use]
4792 pub fn required_unless_one<T, I>(self, names: I) -> Self
4793 where
4794 I: IntoIterator<Item = T>,
4795 T: Key,
4796 {
4797 self.required_unless_present_any(names)
4798 }
4799
4800 /// Deprecated, replaced with [`Arg::required_if_eq`]
4801 #[cfg_attr(
4802 feature = "deprecated",
4803 deprecated(since = "3.0.0", note = "Replaced with `Arg::required_if_eq`")
4804 )]
4805 #[doc(hidden)]
4806 #[must_use]
4807 pub fn required_if<T: Key>(self, arg_id: T, val: &'help str) -> Self {
4808 self.required_if_eq(arg_id, val)
4809 }
4810
4811 /// Deprecated, replaced with [`Arg::required_if_eq_any`]
4812 #[cfg_attr(
4813 feature = "deprecated",
4814 deprecated(since = "3.0.0", note = "Replaced with `Arg::required_if_eq_any`")
4815 )]
4816 #[doc(hidden)]
4817 #[must_use]
4818 pub fn required_ifs<T: Key>(self, ifs: &[(T, &'help str)]) -> Self {
4819 self.required_if_eq_any(ifs)
4820 }
4821
4822 /// Deprecated, replaced with [`Arg::hide`]
4823 #[cfg_attr(
4824 feature = "deprecated",
4825 deprecated(since = "3.0.0", note = "Replaced with `Arg::hide`")
4826 )]
4827 #[doc(hidden)]
4828 #[inline]
4829 #[must_use]
4830 pub fn hidden(self, yes: bool) -> Self {
4831 self.hide(yes)
4832 }
4833
4834 /// Deprecated, replaced with [`Arg::ignore_case`]
4835 #[cfg_attr(
4836 feature = "deprecated",
4837 deprecated(since = "3.0.0", note = "Replaced with `Arg::ignore_case`")
4838 )]
4839 #[doc(hidden)]
4840 #[inline]
4841 #[must_use]
4842 pub fn case_insensitive(self, yes: bool) -> Self {
4843 self.ignore_case(yes)
4844 }
4845
4846 /// Deprecated, replaced with [`Arg::forbid_empty_values`]
4847 #[cfg_attr(
4848 feature = "deprecated",
4849 deprecated(since = "3.0.0", note = "Replaced with `Arg::forbid_empty_values`")
4850 )]
4851 #[doc(hidden)]
4852 #[must_use]
4853 pub fn empty_values(self, yes: bool) -> Self {
4854 self.forbid_empty_values(!yes)
4855 }
4856
4857 /// Deprecated, replaced with [`Arg::multiple_occurrences`] (most likely what you want) and
4858 /// [`Arg::multiple_values`]
4859 #[cfg_attr(
4860 feature = "deprecated",
4861 deprecated(
4862 since = "3.0.0",
4863 note = "Split into `Arg::multiple_occurrences` (most likely what you want) and `Arg::multiple_values`"
4864 )
4865 )]
4866 #[doc(hidden)]
4867 #[must_use]
4868 pub fn multiple(self, yes: bool) -> Self {
4869 self.multiple_occurrences(yes).multiple_values(yes)
4870 }
4871
4872 /// Deprecated, replaced with [`Arg::hide_short_help`]
4873 #[cfg_attr(
4874 feature = "deprecated",
4875 deprecated(since = "3.0.0", note = "Replaced with `Arg::hide_short_help`")
4876 )]
4877 #[doc(hidden)]
4878 #[inline]
4879 #[must_use]
4880 pub fn hidden_short_help(self, yes: bool) -> Self {
4881 self.hide_short_help(yes)
4882 }
4883
4884 /// Deprecated, replaced with [`Arg::hide_long_help`]
4885 #[cfg_attr(
4886 feature = "deprecated",
4887 deprecated(since = "3.0.0", note = "Replaced with `Arg::hide_long_help`")
4888 )]
4889 #[doc(hidden)]
4890 #[inline]
4891 #[must_use]
4892 pub fn hidden_long_help(self, yes: bool) -> Self {
4893 self.hide_long_help(yes)
4894 }
4895
4896 /// Deprecated, replaced with [`Arg::setting`]
4897 #[cfg_attr(
4898 feature = "deprecated",
4899 deprecated(since = "3.0.0", note = "Replaced with `Arg::setting`")
4900 )]
4901 #[doc(hidden)]
4902 #[must_use]
4903 pub fn set(self, s: ArgSettings) -> Self {
4904 self.setting(s)
4905 }
4906
4907 /// Deprecated, replaced with [`Arg::unset_setting`]
4908 #[cfg_attr(
4909 feature = "deprecated",
4910 deprecated(since = "3.0.0", note = "Replaced with `Arg::unset_setting`")
4911 )]
4912 #[doc(hidden)]
4913 #[must_use]
4914 pub fn unset(self, s: ArgSettings) -> Self {
4915 self.unset_setting(s)
4916 }
4917 }
4918
4919 /// # Internally used only
4920 impl<'help> Arg<'help> {
4921 pub(crate) fn _build(&mut self) {
4922 if self.is_positional() {
4923 self.settings.set(ArgSettings::TakesValue);
4924 }
4925 if let Some(action) = self.action.as_ref() {
4926 if let Some(default_value) = action.default_value() {
4927 if self.default_vals.is_empty() {
4928 self.default_vals = vec![default_value];
4929 }
4930 }
4931 if action.takes_values() {
4932 self.settings.set(ArgSettings::TakesValue);
4933 } else {
4934 self.settings.unset(ArgSettings::TakesValue);
4935 }
4936 match action {
4937 ArgAction::StoreValue
4938 | ArgAction::IncOccurrence
4939 | ArgAction::Help
4940 | ArgAction::Version => {}
4941 ArgAction::Set
4942 | ArgAction::Append
4943 | ArgAction::SetTrue
4944 | ArgAction::SetFalse
4945 | ArgAction::Count => {
4946 if !self.is_positional() {
4947 self.settings.set(ArgSettings::MultipleOccurrences);
4948 }
4949 }
4950 }
4951 }
4952
4953 if self.value_parser.is_none() {
4954 if let Some(default) = self.action.as_ref().and_then(|a| a.default_value_parser()) {
4955 self.value_parser = Some(default);
4956 } else if self.is_allow_invalid_utf8_set() {
4957 self.value_parser = Some(super::ValueParser::os_string());
4958 } else {
4959 self.value_parser = Some(super::ValueParser::string());
4960 }
4961 }
4962
4963 if (self.is_use_value_delimiter_set() || self.is_require_value_delimiter_set())
4964 && self.val_delim.is_none()
4965 {
4966 self.val_delim = Some(',');
4967 }
4968
4969 let val_names_len = self.val_names.len();
4970
4971 if val_names_len > 1 {
4972 self.settings.set(ArgSettings::MultipleValues);
4973
4974 if self.num_vals.is_none() {
4975 self.num_vals = Some(val_names_len);
4976 }
4977 }
4978
4979 let self_id = self.id.clone();
4980 if self.is_positional() || self.is_multiple_occurrences_set() {
4981 // Remove self-overrides where they don't make sense.
4982 //
4983 // We can evaluate switching this to a debug assert at a later time (though it will
4984 // require changing propagation of `AllArgsOverrideSelf`). Being conservative for now
4985 // due to where we are at in the release.
4986 self.overrides.retain(|e| *e != self_id);
4987 }
4988 }
4989
4990 pub(crate) fn generated(mut self) -> Self {
4991 self.provider = ArgProvider::Generated;
4992 self
4993 }
4994
4995 pub(crate) fn longest_filter(&self) -> bool {
4996 self.is_takes_value_set() || self.long.is_some() || self.short.is_none()
4997 }
4998
4999 // Used for positionals when printing
5000 pub(crate) fn multiple_str(&self) -> &str {
5001 let mult_vals = self.val_names.len() > 1;
5002 if (self.is_multiple_values_set() || self.is_multiple_occurrences_set()) && !mult_vals {
5003 "..."
5004 } else {
5005 ""
5006 }
5007 }
5008
5009 // Used for positionals when printing
5010 pub(crate) fn name_no_brackets(&self) -> Cow<str> {
5011 debug!("Arg::name_no_brackets:{}", self.name);
5012 let delim = if self.is_require_value_delimiter_set() {
5013 self.val_delim.expect(INTERNAL_ERROR_MSG)
5014 } else {
5015 ' '
5016 }
5017 .to_string();
5018 if !self.val_names.is_empty() {
5019 debug!("Arg::name_no_brackets: val_names={:#?}", self.val_names);
5020
5021 if self.val_names.len() > 1 {
5022 Cow::Owned(
5023 self.val_names
5024 .iter()
5025 .map(|n| format!("<{}>", n))
5026 .collect::<Vec<_>>()
5027 .join(&*delim),
5028 )
5029 } else {
5030 Cow::Borrowed(self.val_names.get(0).expect(INTERNAL_ERROR_MSG))
5031 }
5032 } else {
5033 debug!("Arg::name_no_brackets: just name");
5034 Cow::Borrowed(self.name)
5035 }
5036 }
5037
5038 /// Either multiple values or occurrences
5039 pub(crate) fn is_multiple(&self) -> bool {
5040 self.is_multiple_values_set() | self.is_multiple_occurrences_set()
5041 }
5042
5043 pub(crate) fn get_display_order(&self) -> usize {
5044 self.disp_ord.get_explicit()
5045 }
5046 }
5047
5048 impl<'help> From<&'_ Arg<'help>> for Arg<'help> {
5049 fn from(a: &Arg<'help>) -> Self {
5050 a.clone()
5051 }
5052 }
5053
5054 impl<'help> PartialEq for Arg<'help> {
5055 fn eq(&self, other: &Arg<'help>) -> bool {
5056 self.name == other.name
5057 }
5058 }
5059
5060 impl<'help> PartialOrd for Arg<'help> {
5061 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
5062 Some(self.cmp(other))
5063 }
5064 }
5065
5066 impl<'help> Ord for Arg<'help> {
5067 fn cmp(&self, other: &Arg) -> Ordering {
5068 self.name.cmp(other.name)
5069 }
5070 }
5071
5072 impl<'help> Eq for Arg<'help> {}
5073
5074 impl<'help> Display for Arg<'help> {
5075 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
5076 // Write the name such --long or -l
5077 if let Some(l) = self.long {
5078 write!(f, "--{}", l)?;
5079 } else if let Some(s) = self.short {
5080 write!(f, "-{}", s)?;
5081 }
5082 let mut need_closing_bracket = false;
5083 if !self.is_positional() && self.is_takes_value_set() {
5084 let is_optional_val = self.min_vals == Some(0);
5085 let sep = if self.is_require_equals_set() {
5086 if is_optional_val {
5087 need_closing_bracket = true;
5088 "[="
5089 } else {
5090 "="
5091 }
5092 } else if is_optional_val {
5093 need_closing_bracket = true;
5094 " ["
5095 } else {
5096 " "
5097 };
5098 f.write_str(sep)?;
5099 }
5100 if self.is_takes_value_set() || self.is_positional() {
5101 display_arg_val(self, |s, _| f.write_str(s))?;
5102 }
5103 if need_closing_bracket {
5104 f.write_str("]")?;
5105 }
5106
5107 Ok(())
5108 }
5109 }
5110
5111 impl<'help> fmt::Debug for Arg<'help> {
5112 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
5113 let mut ds = f.debug_struct("Arg");
5114
5115 #[allow(unused_mut)]
5116 let mut ds = ds
5117 .field("id", &self.id)
5118 .field("provider", &self.provider)
5119 .field("name", &self.name)
5120 .field("help", &self.help)
5121 .field("long_help", &self.long_help)
5122 .field("action", &self.action)
5123 .field("value_parser", &self.value_parser)
5124 .field("blacklist", &self.blacklist)
5125 .field("settings", &self.settings)
5126 .field("overrides", &self.overrides)
5127 .field("groups", &self.groups)
5128 .field("requires", &self.requires)
5129 .field("r_ifs", &self.r_ifs)
5130 .field("r_unless", &self.r_unless)
5131 .field("short", &self.short)
5132 .field("long", &self.long)
5133 .field("aliases", &self.aliases)
5134 .field("short_aliases", &self.short_aliases)
5135 .field("disp_ord", &self.disp_ord)
5136 .field("possible_vals", &self.possible_vals)
5137 .field("val_names", &self.val_names)
5138 .field("num_vals", &self.num_vals)
5139 .field("max_vals", &self.max_vals)
5140 .field("min_vals", &self.min_vals)
5141 .field(
5142 "validator",
5143 &self.validator.as_ref().map_or("None", |_| "Some(FnMut)"),
5144 )
5145 .field(
5146 "validator_os",
5147 &self.validator_os.as_ref().map_or("None", |_| "Some(FnMut)"),
5148 )
5149 .field("val_delim", &self.val_delim)
5150 .field("default_vals", &self.default_vals)
5151 .field("default_vals_ifs", &self.default_vals_ifs)
5152 .field("terminator", &self.terminator)
5153 .field("index", &self.index)
5154 .field("help_heading", &self.help_heading)
5155 .field("value_hint", &self.value_hint)
5156 .field("default_missing_vals", &self.default_missing_vals);
5157
5158 #[cfg(feature = "env")]
5159 {
5160 ds = ds.field("env", &self.env);
5161 }
5162
5163 ds.finish()
5164 }
5165 }
5166
5167 type Validator<'a> = dyn FnMut(&str) -> Result<(), Box<dyn Error + Send + Sync>> + Send + 'a;
5168 type ValidatorOs<'a> = dyn FnMut(&OsStr) -> Result<(), Box<dyn Error + Send + Sync>> + Send + 'a;
5169
5170 #[derive(Debug, Clone, Eq, PartialEq)]
5171 pub(crate) enum ArgProvider {
5172 Generated,
5173 GeneratedMutated,
5174 User,
5175 }
5176
5177 impl Default for ArgProvider {
5178 fn default() -> Self {
5179 ArgProvider::User
5180 }
5181 }
5182
5183 /// Write the values such as <name1> <name2>
5184 pub(crate) fn display_arg_val<F, T, E>(arg: &Arg, mut write: F) -> Result<(), E>
5185 where
5186 F: FnMut(&str, bool) -> Result<T, E>,
5187 {
5188 let mult_val = arg.is_multiple_values_set();
5189 let mult_occ = arg.is_multiple_occurrences_set();
5190 let delim = if arg.is_require_value_delimiter_set() {
5191 arg.val_delim.expect(INTERNAL_ERROR_MSG)
5192 } else {
5193 ' '
5194 }
5195 .to_string();
5196 if !arg.val_names.is_empty() {
5197 // If have val_name.
5198 match (arg.val_names.len(), arg.num_vals) {
5199 (1, Some(num_vals)) => {
5200 // If single value name with multiple num_of_vals, display all
5201 // the values with the single value name.
5202 let arg_name = format!("<{}>", arg.val_names.get(0).unwrap());
5203 for n in 1..=num_vals {
5204 write(&arg_name, true)?;
5205 if n != num_vals {
5206 write(&delim, false)?;
5207 }
5208 }
5209 }
5210 (num_val_names, _) => {
5211 // If multiple value names, display them sequentially(ignore num of vals).
5212 let mut it = arg.val_names.iter().peekable();
5213 while let Some(val) = it.next() {
5214 write(&format!("<{}>", val), true)?;
5215 if it.peek().is_some() {
5216 write(&delim, false)?;
5217 }
5218 }
5219 if (num_val_names == 1 && mult_val)
5220 || (arg.is_positional() && mult_occ)
5221 || num_val_names < arg.num_vals.unwrap_or(0)
5222 {
5223 write("...", true)?;
5224 }
5225 }
5226 }
5227 } else if let Some(num_vals) = arg.num_vals {
5228 // If number_of_values is specified, display the value multiple times.
5229 let arg_name = format!("<{}>", arg.name);
5230 for n in 1..=num_vals {
5231 write(&arg_name, true)?;
5232 if n != num_vals {
5233 write(&delim, false)?;
5234 }
5235 }
5236 } else if arg.is_positional() {
5237 // Value of positional argument with no num_vals and val_names.
5238 write(&format!("<{}>", arg.name), true)?;
5239
5240 if mult_val || mult_occ {
5241 write("...", true)?;
5242 }
5243 } else {
5244 // value of flag argument with no num_vals and val_names.
5245 write(&format!("<{}>", arg.name), true)?;
5246 if mult_val {
5247 write("...", true)?;
5248 }
5249 }
5250 Ok(())
5251 }
5252
5253 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
5254 pub(crate) enum DisplayOrder {
5255 None,
5256 Implicit(usize),
5257 Explicit(usize),
5258 }
5259
5260 impl DisplayOrder {
5261 pub(crate) fn set_explicit(&mut self, explicit: usize) {
5262 *self = Self::Explicit(explicit)
5263 }
5264
5265 pub(crate) fn set_implicit(&mut self, implicit: usize) {
5266 *self = (*self).max(Self::Implicit(implicit))
5267 }
5268
5269 pub(crate) fn make_explicit(&mut self) {
5270 match *self {
5271 Self::None | Self::Explicit(_) => {}
5272 Self::Implicit(disp) => self.set_explicit(disp),
5273 }
5274 }
5275
5276 pub(crate) fn get_explicit(self) -> usize {
5277 match self {
5278 Self::None | Self::Implicit(_) => 999,
5279 Self::Explicit(disp) => disp,
5280 }
5281 }
5282 }
5283
5284 impl Default for DisplayOrder {
5285 fn default() -> Self {
5286 Self::None
5287 }
5288 }
5289
5290 // Flags
5291 #[cfg(test)]
5292 mod test {
5293 use super::Arg;
5294
5295 #[test]
5296 fn flag_display() {
5297 let mut f = Arg::new("flg").multiple_occurrences(true);
5298 f.long = Some("flag");
5299
5300 assert_eq!(f.to_string(), "--flag");
5301
5302 let mut f2 = Arg::new("flg");
5303 f2.short = Some('f');
5304
5305 assert_eq!(f2.to_string(), "-f");
5306 }
5307
5308 #[test]
5309 fn flag_display_single_alias() {
5310 let mut f = Arg::new("flg");
5311 f.long = Some("flag");
5312 f.aliases = vec![("als", true)];
5313
5314 assert_eq!(f.to_string(), "--flag")
5315 }
5316
5317 #[test]
5318 fn flag_display_multiple_aliases() {
5319 let mut f = Arg::new("flg");
5320 f.short = Some('f');
5321 f.aliases = vec![
5322 ("alias_not_visible", false),
5323 ("f2", true),
5324 ("f3", true),
5325 ("f4", true),
5326 ];
5327 assert_eq!(f.to_string(), "-f");
5328 }
5329
5330 #[test]
5331 fn flag_display_single_short_alias() {
5332 let mut f = Arg::new("flg");
5333 f.short = Some('a');
5334 f.short_aliases = vec![('b', true)];
5335
5336 assert_eq!(f.to_string(), "-a")
5337 }
5338
5339 #[test]
5340 fn flag_display_multiple_short_aliases() {
5341 let mut f = Arg::new("flg");
5342 f.short = Some('a');
5343 f.short_aliases = vec![('b', false), ('c', true), ('d', true), ('e', true)];
5344 assert_eq!(f.to_string(), "-a");
5345 }
5346
5347 // Options
5348
5349 #[test]
5350 fn option_display_multiple_occurrences() {
5351 let o = Arg::new("opt")
5352 .long("option")
5353 .takes_value(true)
5354 .multiple_occurrences(true);
5355
5356 assert_eq!(o.to_string(), "--option <opt>");
5357 }
5358
5359 #[test]
5360 fn option_display_multiple_values() {
5361 let o = Arg::new("opt")
5362 .long("option")
5363 .takes_value(true)
5364 .multiple_values(true);
5365
5366 assert_eq!(o.to_string(), "--option <opt>...");
5367 }
5368
5369 #[test]
5370 fn option_display2() {
5371 let o2 = Arg::new("opt").short('o').value_names(&["file", "name"]);
5372
5373 assert_eq!(o2.to_string(), "-o <file> <name>");
5374 }
5375
5376 #[test]
5377 fn option_display3() {
5378 let o2 = Arg::new("opt")
5379 .short('o')
5380 .takes_value(true)
5381 .multiple_values(true)
5382 .value_names(&["file", "name"]);
5383
5384 assert_eq!(o2.to_string(), "-o <file> <name>");
5385 }
5386
5387 #[test]
5388 fn option_display_single_alias() {
5389 let o = Arg::new("opt")
5390 .takes_value(true)
5391 .long("option")
5392 .visible_alias("als");
5393
5394 assert_eq!(o.to_string(), "--option <opt>");
5395 }
5396
5397 #[test]
5398 fn option_display_multiple_aliases() {
5399 let o = Arg::new("opt")
5400 .long("option")
5401 .takes_value(true)
5402 .visible_aliases(&["als2", "als3", "als4"])
5403 .alias("als_not_visible");
5404
5405 assert_eq!(o.to_string(), "--option <opt>");
5406 }
5407
5408 #[test]
5409 fn option_display_single_short_alias() {
5410 let o = Arg::new("opt")
5411 .takes_value(true)
5412 .short('a')
5413 .visible_short_alias('b');
5414
5415 assert_eq!(o.to_string(), "-a <opt>");
5416 }
5417
5418 #[test]
5419 fn option_display_multiple_short_aliases() {
5420 let o = Arg::new("opt")
5421 .short('a')
5422 .takes_value(true)
5423 .visible_short_aliases(&['b', 'c', 'd'])
5424 .short_alias('e');
5425
5426 assert_eq!(o.to_string(), "-a <opt>");
5427 }
5428
5429 // Positionals
5430
5431 #[test]
5432 fn positional_display_multiple_values() {
5433 let p = Arg::new("pos")
5434 .index(1)
5435 .takes_value(true)
5436 .multiple_values(true);
5437
5438 assert_eq!(p.to_string(), "<pos>...");
5439 }
5440
5441 #[test]
5442 fn positional_display_multiple_occurrences() {
5443 let p = Arg::new("pos")
5444 .index(1)
5445 .takes_value(true)
5446 .multiple_occurrences(true);
5447
5448 assert_eq!(p.to_string(), "<pos>...");
5449 }
5450
5451 #[test]
5452 fn positional_display_required() {
5453 let p2 = Arg::new("pos").index(1).required(true);
5454
5455 assert_eq!(p2.to_string(), "<pos>");
5456 }
5457
5458 #[test]
5459 fn positional_display_val_names() {
5460 let p2 = Arg::new("pos").index(1).value_names(&["file1", "file2"]);
5461
5462 assert_eq!(p2.to_string(), "<file1> <file2>");
5463 }
5464
5465 #[test]
5466 fn positional_display_val_names_req() {
5467 let p2 = Arg::new("pos")
5468 .index(1)
5469 .required(true)
5470 .value_names(&["file1", "file2"]);
5471
5472 assert_eq!(p2.to_string(), "<file1> <file2>");
5473 }
5474 }