9 fmt
::{self, Display, Formatter}
,
13 #[cfg(feature = "env")]
14 use std
::{env, ffi::OsString}
;
16 #[cfg(feature = "yaml")]
20 use crate::builder
::usage_parser
::UsageParser
;
21 use crate::builder
::ArgPredicate
;
22 use crate::util
::{Id, Key}
;
24 use crate::PossibleValue
;
26 use crate::INTERNAL_ERROR_MSG
;
27 use crate::{ArgFlags, ArgSettings}
;
29 #[cfg(feature = "regex")]
30 use crate::builder
::RegexRef
;
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.
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.
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]
48 /// # use clap::{Arg, arg};
49 /// // Using the traditional builder pattern and setting each option manually
50 /// let cfg = Arg::new("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");
59 #[allow(missing_debug_implementations)]
60 #[derive(Default, Clone)]
61 pub struct Arg
<'help
> {
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
>,
104 impl<'help
> Arg
<'help
> {
105 /// Create a new [`Arg`] with a unique name.
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..
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.
117 /// # use clap::{Command, Arg};
118 /// Arg::new("config")
121 /// [`Arg::takes_value(true)`]: Arg::takes_value()
122 pub fn new
<S
: Into
<&'help
str>>(n
: S
) -> Self {
123 Arg
::default().name(n
)
126 /// Set the identifier used for referencing this argument in the clap API.
128 /// See [`Arg::new`] for more details.
130 pub fn id
<S
: Into
<&'help
str>>(mut self, n
: S
) -> Self {
132 self.id
= Id
::from(&*name
);
137 /// Deprecated, replaced with [`Arg::id`]
139 feature
= "deprecated",
140 deprecated(since
= "3.1.0", note
= "Replaced with `Arg::id`")
142 pub fn name
<S
: Into
<&'help
str>>(self, n
: S
) -> Self {
146 /// Sets the short version of the argument without the preceding `-`.
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.
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`:
159 /// # use clap::{Command, Arg};
160 /// let m = Command::new("prog")
161 /// .arg(Arg::new("config")
163 /// .takes_value(true))
164 /// .get_matches_from(vec![
165 /// "prog", "-c", "file.toml"
168 /// assert_eq!(m.get_one::<String>("config").map(String::as_str), Some("file.toml"));
172 pub fn short(mut self, s
: char) -> Self {
173 assert
!(s
!= '
-'
, "short option name cannot be `-`");
175 self.short
= Some(s
);
179 /// Sets the long version of the argument without the preceding `--`.
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.
186 /// **NOTE:** Any leading `-` characters will be stripped
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).
194 /// Setting `long` allows using the argument via a double hyphen (`--`) such as `--config`
197 /// # use clap::{Command, Arg};
198 /// let m = Command::new("prog")
199 /// .arg(Arg::new("cfg")
201 /// .takes_value(true))
202 /// .get_matches_from(vec![
203 /// "prog", "--config", "file.toml"
206 /// assert_eq!(m.get_one::<String>("cfg").map(String::as_str), Some("file.toml"));
210 pub fn long(mut self, l
: &'help
str) -> Self {
211 #[cfg(feature = "unstable-v4")]
215 #[cfg(not(feature = "unstable-v4"))]
217 self.long
= Some(l
.trim_start_matches(|c
| c
== '
-'
));
222 /// Add an alias, which functions as a hidden long flag.
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.
230 /// # use clap::{Command, Arg};
231 /// let m = Command::new("prog")
232 /// .arg(Arg::new("test")
235 /// .takes_value(true))
236 /// .get_matches_from(vec![
237 /// "prog", "--alias", "cool"
239 /// assert!(m.contains_id("test"));
240 /// assert_eq!(m.value_of("test"), Some("cool"));
243 pub fn alias
<S
: Into
<&'help
str>>(mut self, name
: S
) -> Self {
244 self.aliases
.push((name
.into(), false));
248 /// Add an alias, which functions as a hidden short flag.
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.
256 /// # use clap::{Command, Arg};
257 /// let m = Command::new("prog")
258 /// .arg(Arg::new("test")
260 /// .short_alias('e')
261 /// .takes_value(true))
262 /// .get_matches_from(vec![
263 /// "prog", "-e", "cool"
265 /// assert!(m.contains_id("test"));
266 /// assert_eq!(m.value_of("test"), Some("cool"));
269 pub fn short_alias(mut self, name
: char) -> Self {
270 assert
!(name
!= '
-'
, "short alias name cannot be `-`");
272 self.short_aliases
.push((name
, false));
276 /// Add aliases, which function as hidden long flags.
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.
284 /// # use clap::{Command, Arg, ArgAction};
285 /// let m = Command::new("prog")
286 /// .arg(Arg::new("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"
295 /// assert_eq!(*m.get_one::<bool>("test").expect("defaulted by clap"), true);
298 pub fn aliases(mut self, names
: &[&'help
str]) -> Self {
299 self.aliases
.extend(names
.iter().map(|&x
| (x
, false)));
303 /// Add aliases, which functions as a hidden short flag.
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.
311 /// # use clap::{Command, Arg, ArgAction};
312 /// let m = Command::new("prog")
313 /// .arg(Arg::new("test")
315 /// .short_aliases(&['e', 's'])
316 /// .action(ArgAction::SetTrue)
317 /// .help("the file to add")
318 /// .required(false))
319 /// .get_matches_from(vec![
322 /// assert_eq!(*m.get_one::<bool>("test").expect("defaulted by clap"), true);
325 pub fn short_aliases(mut self, names
: &[char]) -> Self {
327 assert
!(s
!= &'
-'
, "short alias name cannot be `-`");
328 self.short_aliases
.push((*s
, false));
333 /// Add an alias, which functions as a visible long flag.
335 /// Like [`Arg::alias`], except that they are visible inside the help message.
340 /// # use clap::{Command, Arg};
341 /// let m = Command::new("prog")
342 /// .arg(Arg::new("test")
343 /// .visible_alias("something-awesome")
345 /// .takes_value(true))
346 /// .get_matches_from(vec![
347 /// "prog", "--something-awesome", "coffee"
349 /// assert!(m.contains_id("test"));
350 /// assert_eq!(m.value_of("test"), Some("coffee"));
352 /// [`Command::alias`]: Arg::alias()
354 pub fn visible_alias
<S
: Into
<&'help
str>>(mut self, name
: S
) -> Self {
355 self.aliases
.push((name
.into(), true));
359 /// Add an alias, which functions as a visible short flag.
361 /// Like [`Arg::short_alias`], except that they are visible inside the help message.
366 /// # use clap::{Command, Arg};
367 /// let m = Command::new("prog")
368 /// .arg(Arg::new("test")
370 /// .visible_short_alias('t')
371 /// .takes_value(true))
372 /// .get_matches_from(vec![
373 /// "prog", "-t", "coffee"
375 /// assert!(m.contains_id("test"));
376 /// assert_eq!(m.value_of("test"), Some("coffee"));
379 pub fn visible_short_alias(mut self, name
: char) -> Self {
380 assert
!(name
!= '
-'
, "short alias name cannot be `-`");
382 self.short_aliases
.push((name
, true));
386 /// Add aliases, which function as visible long flags.
388 /// Like [`Arg::aliases`], except that they are visible inside the help message.
393 /// # use clap::{Command, Arg, ArgAction};
394 /// let m = Command::new("prog")
395 /// .arg(Arg::new("test")
397 /// .action(ArgAction::SetTrue)
398 /// .visible_aliases(&["something", "awesome", "cool"]))
399 /// .get_matches_from(vec![
400 /// "prog", "--awesome"
402 /// assert_eq!(*m.get_one::<bool>("test").expect("defaulted by clap"), true);
404 /// [`Command::aliases`]: Arg::aliases()
406 pub fn visible_aliases(mut self, names
: &[&'help
str]) -> Self {
407 self.aliases
.extend(names
.iter().map(|n
| (*n
, true)));
411 /// Add aliases, which function as visible short flags.
413 /// Like [`Arg::short_aliases`], except that they are visible inside the help message.
418 /// # use clap::{Command, Arg, ArgAction};
419 /// let m = Command::new("prog")
420 /// .arg(Arg::new("test")
422 /// .action(ArgAction::SetTrue)
423 /// .visible_short_aliases(&['t', 'e']))
424 /// .get_matches_from(vec![
427 /// assert_eq!(*m.get_one::<bool>("test").expect("defaulted by clap"), true);
430 pub fn visible_short_aliases(mut self, names
: &[char]) -> Self {
432 assert
!(n
!= &'
-'
, "short alias name cannot be `-`");
433 self.short_aliases
.push((*n
, true));
438 /// Specifies the index of a positional argument **starting at** 1.
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.
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
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`].
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)
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
462 /// # use clap::{Command, Arg};
463 /// Arg::new("config")
469 /// # use clap::{Command, Arg};
470 /// let m = Command::new("prog")
471 /// .arg(Arg::new("mode")
473 /// .arg(Arg::new("debug")
475 /// .get_matches_from(vec![
476 /// "prog", "--debug", "fast"
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
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
490 pub fn index(mut self, idx
: usize) -> Self {
491 self.index
= Some(idx
);
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 --
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.
504 /// **NOTE:** This will change the usage string to look like `$ prog [OPTIONS] [-- <ARG>]` if
505 /// `ARG` is marked as `.last(true)`.
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.
510 /// **NOTE**: This setting only applies to positional arguments, and has no effect on OPTIONS
512 /// **NOTE:** Setting this requires [`Arg::takes_value`]
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`])
525 /// .takes_value(true)
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.
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)
541 /// .try_get_matches_from(vec![
542 /// "prog", "one", "--", "three"
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());
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.
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)
562 /// .try_get_matches_from(vec![
563 /// "prog", "one", "two", "three"
566 /// assert!(res.is_err());
567 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
569 /// [index]: Arg::index()
570 /// [`UnknownArgument`]: crate::ErrorKind::UnknownArgument
573 pub fn last(self, yes
: bool
) -> Self {
575 self.setting(ArgSettings
::Last
)
577 self.unset_setting(ArgSettings
::Last
)
581 /// Specifies that the argument must be present.
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.
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."
597 /// Arg::new("config")
602 /// Setting required requires that the argument be used at runtime.
605 /// # use clap::{Command, Arg};
606 /// let res = Command::new("prog")
607 /// .arg(Arg::new("cfg")
609 /// .takes_value(true)
611 /// .try_get_matches_from(vec![
612 /// "prog", "--config", "file.conf",
615 /// assert!(res.is_ok());
618 /// Setting required and then *not* supplying that argument at runtime is an error.
621 /// # use clap::{Command, Arg, ErrorKind};
622 /// let res = Command::new("prog")
623 /// .arg(Arg::new("cfg")
625 /// .takes_value(true)
627 /// .try_get_matches_from(vec![
631 /// assert!(res.is_err());
632 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
636 pub fn required(self, yes
: bool
) -> Self {
638 self.setting(ArgSettings
::Required
)
640 self.unset_setting(ArgSettings
::Required
)
644 /// Sets an argument that is required when this one is present
646 /// i.e. when using this argument, the following argument *must* be present.
648 /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required
654 /// Arg::new("config")
655 /// .requires("input")
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
664 /// # use clap::{Command, Arg};
665 /// let res = Command::new("prog")
666 /// .arg(Arg::new("cfg")
667 /// .takes_value(true)
668 /// .requires("input")
670 /// .arg(Arg::new("input"))
671 /// .try_get_matches_from(vec![
675 /// assert!(res.is_ok()); // We didn't use cfg, so input wasn't required
678 /// Setting [`Arg::requires(name)`] and *not* supplying that argument is an error.
681 /// # use clap::{Command, Arg, ErrorKind};
682 /// let res = Command::new("prog")
683 /// .arg(Arg::new("cfg")
684 /// .takes_value(true)
685 /// .requires("input")
687 /// .arg(Arg::new("input"))
688 /// .try_get_matches_from(vec![
689 /// "prog", "--config", "file.conf"
692 /// assert!(res.is_err());
693 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
695 /// [`Arg::requires(name)`]: Arg::requires()
696 /// [Conflicting]: Arg::conflicts_with()
697 /// [override]: Arg::overrides_with()
699 pub fn requires
<T
: Key
>(mut self, arg_id
: T
) -> Self {
700 self.requires
.push((ArgPredicate
::IsPresent
, arg_id
.into()));
704 /// This argument must be passed alone; it conflicts with all other arguments.
710 /// Arg::new("config")
715 /// Setting an exclusive argument and having any other arguments present at runtime
719 /// # use clap::{Command, Arg, ErrorKind};
720 /// let res = Command::new("prog")
721 /// .arg(Arg::new("exclusive")
722 /// .takes_value(true)
724 /// .long("exclusive"))
725 /// .arg(Arg::new("debug")
727 /// .arg(Arg::new("input"))
728 /// .try_get_matches_from(vec![
729 /// "prog", "--exclusive", "file.conf", "file.txt"
732 /// assert!(res.is_err());
733 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict);
737 pub fn exclusive(self, yes
: bool
) -> Self {
739 self.setting(ArgSettings
::Exclusive
)
741 self.unset_setting(ArgSettings
::Exclusive
)
745 /// Specifies that an argument can be matched to all child [`Subcommand`]s.
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.
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.
759 /// # use clap::{Command, Arg, ArgAction};
760 /// let m = Command::new("prog")
761 /// .arg(Arg::new("verb")
764 /// .action(ArgAction::SetTrue)
766 /// .subcommand(Command::new("test"))
767 /// .subcommand(Command::new("do-stuff"))
768 /// .get_matches_from(vec![
769 /// "prog", "do-stuff", "--verbose"
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);
777 /// [`Subcommand`]: crate::Subcommand
780 pub fn global(self, yes
: bool
) -> Self {
782 self.setting(ArgSettings
::Global
)
784 self.unset_setting(ArgSettings
::Global
)
788 /// Deprecated, replaced with [`Arg::action`] ([Issue #3772](https://github.com/clap-rs/clap/issues/3772))
792 feature
= "deprecated",
793 deprecated(since
= "3.2.0", note
= "Replaced with `Arg::action` (Issue #3772)")
795 pub fn multiple_occurrences(self, yes
: bool
) -> Self {
797 self.setting(ArgSettings
::MultipleOccurrences
)
799 self.unset_setting(ArgSettings
::MultipleOccurrences
)
803 /// Deprecated, for flags this is replaced with `action(ArgAction::Count).value_parser(value_parser!(u8).range(..max))`
807 feature
= "deprecated",
810 note
= "For flags, replaced with `action(ArgAction::Count).value_parser(value_parser!(u8).range(..max))`"
813 pub fn max_occurrences(mut self, qty
: usize) -> Self {
814 self.max_occurs
= Some(qty
);
816 self.multiple_occurrences(true)
822 /// Check if the [`ArgSettings`] variant is currently set on the argument.
824 /// [`ArgSettings`]: crate::ArgSettings
826 pub fn is_set(&self, s
: ArgSettings
) -> bool
{
827 self.settings
.is_set(s
)
830 /// Apply a setting to the argument.
832 /// See [`ArgSettings`] for a full list of possibilities and examples.
837 /// # use clap::{Arg, ArgSettings};
838 /// Arg::new("config")
839 /// .setting(ArgSettings::Required)
840 /// .setting(ArgSettings::TakesValue)
845 /// # use clap::{Arg, ArgSettings};
846 /// Arg::new("config")
847 /// .setting(ArgSettings::Required | ArgSettings::TakesValue)
852 pub fn setting
<F
>(mut self, setting
: F
) -> Self
856 self.settings
.insert(setting
.into());
860 /// Remove a setting from the argument.
862 /// See [`ArgSettings`] for a full list of possibilities and examples.
867 /// # use clap::{Arg, ArgSettings};
868 /// Arg::new("config")
869 /// .unset_setting(ArgSettings::Required)
870 /// .unset_setting(ArgSettings::TakesValue)
875 /// # use clap::{Arg, ArgSettings};
876 /// Arg::new("config")
877 /// .unset_setting(ArgSettings::Required | ArgSettings::TakesValue)
882 pub fn unset_setting
<F
>(mut self, setting
: F
) -> Self
886 self.settings
.remove(setting
.into());
892 impl<'help
> Arg
<'help
> {
893 /// Specifies that the argument takes a value at run time.
895 /// **NOTE:** values for arguments may be specified in any of the following methods
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`
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]
910 /// # use clap::{Command, Arg};
911 /// let m = Command::new("prog")
912 /// .arg(Arg::new("mode")
914 /// .takes_value(true))
915 /// .get_matches_from(vec![
916 /// "prog", "--mode", "fast"
919 /// assert!(m.contains_id("mode"));
920 /// assert_eq!(m.value_of("mode"), Some("fast"));
922 /// [`Arg::value_delimiter(char)`]: Arg::value_delimiter()
923 /// [multiple values]: Arg::multiple_values
926 pub fn takes_value(self, yes
: bool
) -> Self {
928 self.setting(ArgSettings
::TakesValue
)
930 self.unset_setting(ArgSettings
::TakesValue
)
934 /// Specify the behavior when parsing an argument
939 /// # use clap::Command;
941 /// let cmd = Command::new("mycmd")
945 /// .action(clap::ArgAction::Set)
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);
952 /// matches.get_many::<String>("flag").unwrap_or_default().map(|v| v.as_str()).collect::<Vec<_>>(),
958 pub fn action(mut self, action
: ArgAction
) -> Self {
959 self.action
= Some(action
);
963 /// Specify the type of the argument.
965 /// This allows parsing and validating a value before storing it into
966 /// [`ArgMatches`][crate::ArgMatches].
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
977 /// let mut cmd = clap::Command::new("raw")
979 /// clap::Arg::new("color")
981 /// .value_parser(["always", "auto", "never"])
982 /// .default_value("auto")
985 /// clap::Arg::new("hostname")
986 /// .long("hostname")
987 /// .value_parser(clap::builder::NonEmptyStringValueParser::new())
988 /// .takes_value(true)
992 /// clap::Arg::new("port")
994 /// .value_parser(clap::value_parser!(u16).range(3000..))
995 /// .takes_value(true)
999 /// let m = cmd.try_get_matches_from_mut(
1000 /// ["cmd", "--hostname", "rust-lang.org", "--port", "3001"]
1003 /// let color: &String = m.get_one("color")
1004 /// .expect("default");
1005 /// assert_eq!(color, "auto");
1007 /// let hostname: &String = m.get_one("hostname")
1008 /// .expect("required");
1009 /// assert_eq!(hostname, "rust-lang.org");
1011 /// let port: u16 = *m.get_one("port")
1012 /// .expect("required");
1013 /// assert_eq!(port, 3001);
1015 pub fn value_parser(mut self, parser
: impl Into
<super::ValueParser
>) -> Self {
1016 self.value_parser
= Some(parser
.into());
1020 /// Specifies that the argument may have an unknown number of values
1022 /// Without any other settings, this argument may appear only *once*.
1024 /// For example, `--opt val1 val2` is allowed, but `--opt val1 val2 --opt val3` is not.
1026 /// **NOTE:** Setting this requires [`Arg::takes_value`].
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:
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
1041 /// Alternatively, [require a delimiter between values][Arg::require_delimiter].
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.
1052 /// As an example, consider a CLI with an option `--ui-paths=<paths>...` and subcommand `signer`
1054 /// The following would be parsed as values to `--ui-paths`.
1057 /// $ program --ui-paths path1 path2 signer
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.
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
1069 /// $ program --ui-paths path1 signer
1070 /// $ program --ui-paths path1 --ui-paths signer signer
1075 /// An example with options
1078 /// # use clap::{Command, Arg};
1079 /// let m = Command::new("prog")
1080 /// .arg(Arg::new("file")
1081 /// .takes_value(true)
1082 /// .multiple_values(true)
1084 /// .get_matches_from(vec![
1085 /// "prog", "-F", "file1", "file2", "file3"
1088 /// assert!(m.contains_id("file"));
1089 /// let files: Vec<_> = m.values_of("file").unwrap().collect();
1090 /// assert_eq!(files, ["file1", "file2", "file3"]);
1093 /// Although `multiple_values` has been specified, we cannot use the argument more than once.
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)
1102 /// .try_get_matches_from(vec![
1103 /// "prog", "-F", "file1", "-F", "file2", "-F", "file3"
1106 /// assert!(res.is_err());
1107 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnexpectedMultipleUsage)
1110 /// A common mistake is to define an option which allows multiple values, and a positional
1114 /// # use clap::{Command, Arg};
1115 /// let m = Command::new("prog")
1116 /// .arg(Arg::new("file")
1117 /// .takes_value(true)
1118 /// .multiple_values(true)
1120 /// .arg(Arg::new("word"))
1121 /// .get_matches_from(vec![
1122 /// "prog", "-F", "file1", "file2", "file3", "word"
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!
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!
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.
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)
1145 /// .arg(Arg::new("word"))
1146 /// .get_matches_from(vec![
1147 /// "prog", "-F", "file1", "-F", "file2", "-F", "file3", "word"
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"));
1157 /// As a final example, let's fix the above error and get a pretty message to the user :)
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)
1166 /// .arg(Arg::new("word"))
1167 /// .try_get_matches_from(vec![
1168 /// "prog", "-F", "file1", "file2", "file3", "word"
1171 /// assert!(res.is_err());
1172 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
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()
1183 pub fn multiple_values(self, yes
: bool
) -> Self {
1185 self.setting(ArgSettings
::MultipleValues
)
1187 self.unset_setting(ArgSettings
::MultipleValues
)
1191 /// The number of values allowed for this argument.
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.
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.
1202 /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] and [`Arg::multiple_values(true)`].
1207 /// # use clap::{Command, Arg};
1208 /// Arg::new("file")
1210 /// .number_of_values(3);
1213 /// Not supplying the correct number of values is an error
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)
1222 /// .try_get_matches_from(vec![
1223 /// "prog", "-F", "file1"
1226 /// assert!(res.is_err());
1227 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::WrongNumberOfValues);
1229 /// [`Arg::multiple_occurrences(true)`]: Arg::multiple_occurrences()
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)
1237 /// The *maximum* number of values are for this argument.
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.
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.
1252 /// # use clap::{Command, Arg};
1253 /// Arg::new("file")
1258 /// Supplying less than the maximum number of values is allowed
1261 /// # use clap::{Command, Arg};
1262 /// let res = Command::new("prog")
1263 /// .arg(Arg::new("file")
1264 /// .takes_value(true)
1267 /// .try_get_matches_from(vec![
1268 /// "prog", "-F", "file1", "file2"
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"]);
1277 /// Supplying more than the maximum number of values is an error
1280 /// # use clap::{Command, Arg, ErrorKind};
1281 /// let res = Command::new("prog")
1282 /// .arg(Arg::new("file")
1283 /// .takes_value(true)
1286 /// .try_get_matches_from(vec![
1287 /// "prog", "-F", "file1", "file2", "file3"
1290 /// assert!(res.is_err());
1291 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
1293 /// [`Arg::multiple_occurrences(true)`]: Arg::multiple_occurrences()
1296 pub fn max_values(mut self, qty
: usize) -> Self {
1297 self.max_vals
= Some(qty
);
1298 self.takes_value(true).multiple_values(true)
1301 /// The *minimum* number of values for this argument.
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
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.
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.
1322 /// # use clap::{Command, Arg};
1323 /// Arg::new("file")
1328 /// Supplying more than the minimum number of values is allowed
1331 /// # use clap::{Command, Arg};
1332 /// let res = Command::new("prog")
1333 /// .arg(Arg::new("file")
1334 /// .takes_value(true)
1337 /// .try_get_matches_from(vec![
1338 /// "prog", "-F", "file1", "file2", "file3"
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"]);
1347 /// Supplying less than the minimum number of values is an error
1350 /// # use clap::{Command, Arg, ErrorKind};
1351 /// let res = Command::new("prog")
1352 /// .arg(Arg::new("file")
1353 /// .takes_value(true)
1356 /// .try_get_matches_from(vec![
1357 /// "prog", "-F", "file1"
1360 /// assert!(res.is_err());
1361 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::TooFewValues);
1363 /// [`Arg::multiple_occurrences(true)`]: Arg::multiple_occurrences()
1364 /// [`Arg::required(true)`]: Arg::required()
1367 pub fn min_values(mut self, qty
: usize) -> Self {
1368 self.min_vals
= Some(qty
);
1369 self.takes_value(true).multiple_values(true)
1372 /// Placeholder for the argument's value in the help message / usage.
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.
1379 /// **NOTE:** implicitly sets [`Arg::takes_value(true)`]
1384 /// # use clap::{Command, Arg};
1387 /// .value_name("FILE")
1392 /// # use clap::{Command, Arg};
1393 /// let m = Command::new("prog")
1394 /// .arg(Arg::new("config")
1396 /// .value_name("FILE")
1397 /// .help("Some help text"))
1398 /// .get_matches_from(vec![
1399 /// "prog", "--help"
1402 /// Running the above program produces the following output
1408 /// valnames [OPTIONS]
1411 /// --config <FILE> Some help text
1412 /// -h, --help Print help information
1413 /// -V, --version Print version information
1415 /// [option]: Arg::takes_value()
1416 /// [positional]: Arg::index()
1417 /// [`Arg::takes_value(true)`]: Arg::takes_value()
1420 pub fn value_name(self, name
: &'help
str) -> Self {
1421 self.value_names(&[name
])
1424 /// Placeholders for the argument's values in the help message / usage.
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
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.
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.
1438 /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] and [`Arg::multiple_values(true)`].
1443 /// # use clap::{Command, Arg};
1444 /// Arg::new("speed")
1446 /// .value_names(&["fast", "slow"]);
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"
1460 /// Running the above program produces the following output
1466 /// valnames [OPTIONS]
1469 /// -h, --help Print help information
1470 /// --io-files <INFILE> <OUTFILE> Some help text
1471 /// -V, --version Print version information
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()
1478 pub fn value_names(mut self, names
: &[&'help
str]) -> Self {
1479 self.val_names
= names
.to_vec();
1480 self.takes_value(true)
1483 /// Provide the shell a hint about how to complete this argument.
1485 /// See [`ValueHint`][crate::ValueHint] for more information.
1487 /// **NOTE:** implicitly sets [`Arg::takes_value(true)`].
1489 /// For example, to take a username as argument:
1492 /// # use clap::{Arg, ValueHint};
1493 /// Arg::new("user")
1496 /// .value_hint(ValueHint::Username);
1499 /// To take a full command line and its arguments (for example, when writing a command wrapper):
1502 /// # use clap::{Command, Arg, ValueHint};
1503 /// Command::new("prog")
1504 /// .trailing_var_arg(true)
1506 /// Arg::new("command")
1507 /// .takes_value(true)
1508 /// .multiple_values(true)
1509 /// .value_hint(ValueHint::CommandWithArguments)
1513 pub fn value_hint(mut self, value_hint
: ValueHint
) -> Self {
1514 self.value_hint
= Some(value_hint
);
1515 self.takes_value(true)
1518 /// Deprecated, replaced with [`Arg::value_parser(...)`]
1522 feature
= "deprecated",
1523 deprecated(since
= "3.2.0", note
= "Replaced with `Arg::value_parser(...)`")
1525 pub fn validator
<F
, O
, E
>(mut self, mut f
: F
) -> Self
1527 F
: FnMut(&str) -> Result
<O
, E
> + Send
+ 'help
,
1528 E
: Into
<Box
<dyn Error
+ Send
+ Sync
+ '
static>>,
1530 self.validator
= Some(Arc
::new(Mutex
::new(move |s
: &str| {
1531 f(s
).map(|_
| ()).map_err(|e
| e
.into())
1536 /// Deprecated, replaced with [`Arg::value_parser(...)`]
1539 feature
= "deprecated",
1540 deprecated(since
= "3.2.0", note
= "Replaced with `Arg::value_parser(...)`")
1542 pub fn validator_os
<F
, O
, E
>(mut self, mut f
: F
) -> Self
1544 F
: FnMut(&OsStr
) -> Result
<O
, E
> + Send
+ 'help
,
1545 E
: Into
<Box
<dyn Error
+ Send
+ Sync
+ '
static>>,
1547 self.validator_os
= Some(Arc
::new(Mutex
::new(move |s
: &OsStr
| {
1548 f(s
).map(|_
| ()).map_err(|e
| e
.into())
1553 /// Deprecated in [Issue #3743](https://github.com/clap-rs/clap/issues/3743), replaced with [`Arg::value_parser(...)`]
1555 feature
= "deprecated",
1558 note
= "Deprecated in Issue #3743; eplaced with `Arg::value_parser(...)`"
1561 #[cfg(feature = "regex")]
1563 pub fn validator_regex(
1565 regex
: impl Into
<RegexRef
<'help
>>,
1566 err_message
: &'help
str,
1568 let regex
= regex
.into();
1569 self.validator(move |s
: &str| {
1570 if regex
.is_match(s
) {
1578 /// Deprecated, replaced with [`Arg::value_parser(PossibleValuesParser::new(...))`]
1580 feature
= "deprecated",
1583 note
= "Replaced with `Arg::value_parser(PossibleValuesParser::new(...)).takes_value(true)`"
1587 pub fn possible_value
<T
>(mut self, value
: T
) -> Self
1589 T
: Into
<PossibleValue
<'help
>>,
1591 self.possible_vals
.push(value
.into());
1592 self.takes_value(true)
1595 /// Deprecated, replaced with [`Arg::value_parser(PossibleValuesParser::new(...))`]
1597 feature
= "deprecated",
1600 note
= "Replaced with `Arg::value_parser(PossibleValuesParser::new(...)).takes_value(true)`"
1604 pub fn possible_values
<I
, T
>(mut self, values
: I
) -> Self
1606 I
: IntoIterator
<Item
= T
>,
1607 T
: Into
<PossibleValue
<'help
>>,
1610 .extend(values
.into_iter().map(|value
| value
.into()));
1611 self.takes_value(true)
1614 /// Match values against [`Arg::possible_values`] without matching case.
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.
1622 /// **NOTE:** Setting this requires [`Arg::takes_value`]
1624 /// **NOTE:** To do unicode case folding, enable the `unicode` feature flag.
1629 /// # use clap::{Command, Arg};
1630 /// let m = Command::new("pv")
1631 /// .arg(Arg::new("option")
1633 /// .takes_value(true)
1634 /// .ignore_case(true)
1635 /// .value_parser(["test123"]))
1636 /// .get_matches_from(vec![
1637 /// "pv", "--option", "TeSt123",
1640 /// assert!(m.value_of("option").unwrap().eq_ignore_ascii_case("test123"));
1643 /// This setting also works when multiple values can be defined:
1646 /// # use clap::{Command, Arg};
1647 /// let m = Command::new("pv")
1648 /// .arg(Arg::new("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"
1659 /// let matched_vals = m.values_of("option").unwrap().collect::<Vec<_>>();
1660 /// assert_eq!(&*matched_vals, &["TeSt123", "teST123", "tESt321"]);
1664 pub fn ignore_case(self, yes
: bool
) -> Self {
1666 self.setting(ArgSettings
::IgnoreCase
)
1668 self.unset_setting(ArgSettings
::IgnoreCase
)
1672 /// Allows values which start with a leading hyphen (`-`)
1674 /// **NOTE:** Setting this requires [`Arg::takes_value`]
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.
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
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"
1702 /// assert_eq!(m.value_of("pat"), Some("-file"));
1705 /// Not setting `Arg::allow_hyphen_values(true)` and supplying a value which starts with a
1706 /// hyphen is an error.
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"
1718 /// assert!(res.is_err());
1719 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
1721 /// [`Arg::number_of_values(1)`]: Arg::number_of_values()
1724 pub fn allow_hyphen_values(self, yes
: bool
) -> Self {
1726 self.setting(ArgSettings
::AllowHyphenValues
)
1728 self.unset_setting(ArgSettings
::AllowHyphenValues
)
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]
1737 feature
= "deprecated",
1740 note
= "Replaced with `Arg::value_parser(...)` with either `ValueParser::os_string()` or `ValueParser::path_buf()`"
1743 pub fn allow_invalid_utf8(self, yes
: bool
) -> Self {
1745 self.setting(ArgSettings
::AllowInvalidUtf8
)
1747 self.unset_setting(ArgSettings
::AllowInvalidUtf8
)
1751 /// Deprecated, replaced with [`Arg::value_parser(NonEmptyStringValueParser::new())`]
1755 feature
= "deprecated",
1758 note
= "Replaced with `Arg::value_parser(NonEmptyStringValueParser::new())`"
1761 pub fn forbid_empty_values(self, yes
: bool
) -> Self {
1763 self.setting(ArgSettings
::ForbidEmptyValues
)
1765 self.unset_setting(ArgSettings
::ForbidEmptyValues
)
1769 /// Requires that options use the `--option=val` syntax
1771 /// i.e. an equals between the option and associated value.
1773 /// **NOTE:** Setting this requires [`Arg::takes_value`]
1777 /// Setting `require_equals` requires that the option have an equals sign between
1778 /// it and the associated value.
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"
1791 /// assert!(res.is_ok());
1794 /// Setting `require_equals` and *not* supplying the equals will cause an
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"
1808 /// assert!(res.is_err());
1809 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::NoEquals);
1813 pub fn require_equals(self, yes
: bool
) -> Self {
1815 self.setting(ArgSettings
::RequireEquals
)
1817 self.unset_setting(ArgSettings
::RequireEquals
)
1821 /// Specifies that an argument should allow grouping of multiple values via a
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)
1828 /// **NOTE:** When this setting is used, it will default [`Arg::value_delimiter`]
1829 /// to the comma `,`.
1831 /// **NOTE:** Implicitly sets [`Arg::takes_value`]
1835 /// The following example shows the default behavior.
1838 /// # use clap::{Command, Arg};
1839 /// let delims = Command::new("prog")
1840 /// .arg(Arg::new("option")
1842 /// .use_value_delimiter(true)
1843 /// .takes_value(true))
1844 /// .get_matches_from(vec![
1845 /// "prog", "--option=val1,val2,val3",
1848 /// assert!(delims.contains_id("option"));
1849 /// assert_eq!(delims.values_of("option").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);
1851 /// The next example shows the difference when turning delimiters off. This is the default
1855 /// # use clap::{Command, Arg};
1856 /// let nodelims = Command::new("prog")
1857 /// .arg(Arg::new("option")
1859 /// .takes_value(true))
1860 /// .get_matches_from(vec![
1861 /// "prog", "--option=val1,val2,val3",
1864 /// assert!(nodelims.contains_id("option"));
1865 /// assert_eq!(nodelims.value_of("option").unwrap(), "val1,val2,val3");
1867 /// [`Arg::value_delimiter`]: Arg::value_delimiter()
1870 pub fn use_value_delimiter(mut self, yes
: bool
) -> Self {
1872 if self.val_delim
.is_none() {
1873 self.val_delim
= Some('
,'
);
1875 self.takes_value(true)
1876 .setting(ArgSettings
::UseValueDelimiter
)
1878 self.val_delim
= None
;
1879 self.unset_setting(ArgSettings
::UseValueDelimiter
)
1883 /// Deprecated, replaced with [`Arg::use_value_delimiter`]
1887 feature
= "deprecated",
1888 deprecated(since
= "3.1.0", note
= "Replaced with `Arg::use_value_delimiter`")
1890 pub fn use_delimiter(self, yes
: bool
) -> Self {
1891 self.use_value_delimiter(yes
)
1894 /// Separator between the arguments values, defaults to `,` (comma).
1896 /// **NOTE:** implicitly sets [`Arg::use_value_delimiter(true)`]
1898 /// **NOTE:** implicitly sets [`Arg::takes_value(true)`]
1903 /// # use clap::{Command, Arg};
1904 /// let m = Command::new("prog")
1905 /// .arg(Arg::new("config")
1908 /// .value_delimiter(';'))
1909 /// .get_matches_from(vec![
1910 /// "prog", "--config=val1;val2;val3"
1913 /// assert_eq!(m.values_of("config").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"])
1915 /// [`Arg::use_value_delimiter(true)`]: Arg::use_value_delimiter()
1916 /// [`Arg::takes_value(true)`]: Arg::takes_value()
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)
1924 /// Specifies that *multiple values* may only be set using the delimiter.
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.
1930 /// **NOTE:** The default is `false`.
1932 /// **NOTE:** Setting this requires [`Arg::use_value_delimiter`] and
1933 /// [`Arg::takes_value`]
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.
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.
1944 /// # use clap::{Command, Arg};
1945 /// let delims = Command::new("prog")
1946 /// .arg(Arg::new("opt")
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",
1956 /// assert!(delims.contains_id("opt"));
1957 /// assert_eq!(delims.values_of("opt").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);
1960 /// In this next example, we will *not* use a delimiter. Notice it's now an error.
1963 /// # use clap::{Command, Arg, ErrorKind};
1964 /// let res = Command::new("prog")
1965 /// .arg(Arg::new("opt")
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",
1974 /// assert!(res.is_err());
1975 /// let err = res.unwrap_err();
1976 /// assert_eq!(err.kind(), ErrorKind::UnknownArgument);
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.
1983 /// In this final example, we contrast the above with `clap`'s default behavior where the above
1984 /// is *not* an error.
1987 /// # use clap::{Command, Arg};
1988 /// let delims = Command::new("prog")
1989 /// .arg(Arg::new("opt")
1991 /// .takes_value(true)
1992 /// .multiple_values(true))
1993 /// .get_matches_from(vec![
1994 /// "prog", "-o", "val1", "val2", "val3",
1997 /// assert!(delims.contains_id("opt"));
1998 /// assert_eq!(delims.values_of("opt").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]);
2002 pub fn require_value_delimiter(self, yes
: bool
) -> Self {
2004 self.setting(ArgSettings
::RequireDelimiter
)
2006 self.unset_setting(ArgSettings
::RequireDelimiter
)
2010 /// Deprecated, replaced with [`Arg::require_value_delimiter`]
2014 feature
= "deprecated",
2015 deprecated(since
= "3.1.0", note
= "Replaced with `Arg::require_value_delimiter`")
2017 pub fn require_delimiter(self, yes
: bool
) -> Self {
2018 self.require_value_delimiter(yes
)
2021 /// Sentinel to **stop** parsing multiple values of a give argument.
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`]).
2029 /// **NOTE:** This setting only applies to [options] and [positional arguments]
2031 /// **NOTE:** When the terminator is passed in on the command line, it is **not** stored as one
2037 /// # use clap::{Command, Arg};
2038 /// Arg::new("vals")
2039 /// .takes_value(true)
2040 /// .multiple_values(true)
2041 /// .value_terminator(";")
2045 /// The following example uses two arguments, a sequence of commands, and the location in which
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"
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"));
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()
2072 pub fn value_terminator(mut self, term
: &'help
str) -> Self {
2073 self.terminator
= Some(term
);
2074 self.takes_value(true)
2077 /// Consume all following arguments.
2079 /// Do not be parse them individually, but rather pass them in entirety.
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:
2085 /// --foo something -- -v -v -v -b -b -b --baz -q -u -x
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.
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`.
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()
2101 pub fn raw(self, yes
: bool
) -> Self {
2102 self.takes_value(yes
)
2103 .multiple_values(yes
)
2104 .allow_hyphen_values(yes
)
2108 /// Value for the argument when not present.
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.
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].
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.
2125 /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`].
2129 /// First we use the default value without providing any value at runtime.
2132 /// # use clap::{Command, Arg, ValueSource};
2133 /// let m = Command::new("prog")
2134 /// .arg(Arg::new("opt")
2136 /// .default_value("myval"))
2137 /// .get_matches_from(vec![
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));
2146 /// Next we provide a value at runtime to override the default.
2149 /// # use clap::{Command, Arg, ValueSource};
2150 /// let m = Command::new("prog")
2151 /// .arg(Arg::new("opt")
2153 /// .default_value("myval"))
2154 /// .get_matches_from(vec![
2155 /// "prog", "--myopt=non_default"
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));
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()
2169 pub fn default_value(self, val
: &'help
str) -> Self {
2170 self.default_values_os(&[OsStr
::new(val
)])
2173 /// Value for the argument when not present.
2175 /// See [`Arg::default_value`].
2177 /// [`Arg::default_value`]: Arg::default_value()
2178 /// [`OsStr`]: std::ffi::OsStr
2181 pub fn default_value_os(self, val
: &'help OsStr
) -> Self {
2182 self.default_values_os(&[val
])
2185 /// Value for the argument when not present.
2187 /// See [`Arg::default_value`].
2189 /// [`Arg::default_value`]: Arg::default_value()
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
[..])
2197 /// Value for the argument when not present.
2199 /// See [`Arg::default_values`].
2201 /// [`Arg::default_values`]: Arg::default_values()
2202 /// [`OsStr`]: std::ffi::OsStr
2205 pub fn default_values_os(mut self, vals
: &[&'help OsStr
]) -> Self {
2206 self.default_vals
= vals
.to_vec();
2207 self.takes_value(true)
2210 /// Value for the argument when the flag is present but no value is specified.
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.
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.
2223 /// For POSIX style `--color`:
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")
2233 /// .require_equals(true)
2234 /// .default_missing_value("always")
2235 /// .help("Specify WHEN to colorize output.")
2239 /// // first, we'll provide no arguments
2240 /// let m = cli().get_matches_from(vec![
2243 /// assert_eq!(m.value_of("color"), Some("auto"));
2244 /// assert_eq!(m.value_source("color"), Some(ValueSource::DefaultValue));
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"
2250 /// assert_eq!(m.value_of("color"), Some("never"));
2251 /// assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine));
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"
2257 /// assert_eq!(m.value_of("color"), Some("always"));
2258 /// assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine));
2261 /// For bool literals:
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))
2270 /// .require_equals(true)
2271 /// .default_missing_value("true")
2275 /// // first, we'll provide no arguments
2276 /// let m = cli().get_matches_from(vec![
2279 /// assert_eq!(m.get_one::<bool>("create").copied(), None);
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"
2285 /// assert_eq!(m.get_one::<bool>("create").copied(), Some(false));
2286 /// assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine));
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"
2292 /// assert_eq!(m.get_one::<bool>("create").copied(), Some(true));
2293 /// assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine));
2296 /// [`ArgMatches::value_of`]: ArgMatches::value_of()
2297 /// [`Arg::takes_value(true)`]: Arg::takes_value()
2298 /// [`Arg::default_value`]: Arg::default_value()
2301 pub fn default_missing_value(self, val
: &'help
str) -> Self {
2302 self.default_missing_values_os(&[OsStr
::new(val
)])
2305 /// Value for the argument when the flag is present but no value is specified.
2307 /// See [`Arg::default_missing_value`].
2309 /// [`Arg::default_missing_value`]: Arg::default_missing_value()
2310 /// [`OsStr`]: std::ffi::OsStr
2313 pub fn default_missing_value_os(self, val
: &'help OsStr
) -> Self {
2314 self.default_missing_values_os(&[val
])
2317 /// Value for the argument when the flag is present but no value is specified.
2319 /// See [`Arg::default_missing_value`].
2321 /// [`Arg::default_missing_value`]: Arg::default_missing_value()
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
[..])
2329 /// Value for the argument when the flag is present but no value is specified.
2331 /// See [`Arg::default_missing_values`].
2333 /// [`Arg::default_missing_values`]: Arg::default_missing_values()
2334 /// [`OsStr`]: std::ffi::OsStr
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)
2342 /// Read from `name` environment variable when argument is not present.
2344 /// If it is not present in the environment, then default
2345 /// rules will apply.
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.
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.
2359 /// In this example, we show the variable coming from the environment:
2363 /// # use clap::{Command, Arg};
2365 /// env::set_var("MY_FLAG", "env");
2367 /// let m = Command::new("prog")
2368 /// .arg(Arg::new("flag")
2371 /// .takes_value(true))
2372 /// .get_matches_from(vec![
2376 /// assert_eq!(m.value_of("flag"), Some("env"));
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`.
2387 /// # use clap::{Command, Arg};
2389 /// env::set_var("TRUE_FLAG", "true");
2390 /// env::set_var("FALSE_FLAG", "0");
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![
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"));
2412 /// In this example, we show the variable coming from an option on the CLI:
2416 /// # use clap::{Command, Arg};
2418 /// env::set_var("MY_FLAG", "env");
2420 /// let m = Command::new("prog")
2421 /// .arg(Arg::new("flag")
2424 /// .takes_value(true))
2425 /// .get_matches_from(vec![
2426 /// "prog", "--flag", "opt"
2429 /// assert_eq!(m.value_of("flag"), Some("opt"));
2432 /// In this example, we show the variable coming from the environment even with the
2433 /// presence of a default:
2437 /// # use clap::{Command, Arg};
2439 /// env::set_var("MY_FLAG", "env");
2441 /// let m = Command::new("prog")
2442 /// .arg(Arg::new("flag")
2445 /// .takes_value(true)
2446 /// .default_value("default"))
2447 /// .get_matches_from(vec![
2451 /// assert_eq!(m.value_of("flag"), Some("env"));
2454 /// In this example, we show the use of multiple values in a single environment variable:
2458 /// # use clap::{Command, Arg};
2460 /// env::set_var("MY_FLAG_MULTI", "env1,env2");
2462 /// let m = Command::new("prog")
2463 /// .arg(Arg::new("flag")
2465 /// .env("MY_FLAG_MULTI")
2466 /// .takes_value(true)
2467 /// .multiple_values(true)
2468 /// .use_value_delimiter(true))
2469 /// .get_matches_from(vec![
2473 /// assert_eq!(m.values_of("flag").unwrap().collect::<Vec<_>>(), vec!["env1", "env2"]);
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")]
2481 pub fn env(self, name
: &'help
str) -> Self {
2482 self.env_os(OsStr
::new(name
))
2485 /// Read from `name` environment variable when argument is not present.
2487 /// See [`Arg::env`].
2488 #[cfg(feature = "env")]
2491 pub fn env_os(mut self, name
: &'help OsStr
) -> Self {
2492 self.env
= Some((name
, env
::var_os(name
)));
2498 impl<'help
> Arg
<'help
> {
2499 /// Sets the description of the argument for short help (`-h`).
2501 /// Typically, this is a short (one line) description of the arg.
2503 /// If [`Arg::long_help`] is not specified, this message will be displayed for `--help`.
2505 /// **NOTE:** Only `Arg::help` is used in completion script generation in order to be concise
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.
2513 /// Setting `help` displays a short message to the side of the argument when the user passes
2514 /// `-h` or `--help` (by default).
2517 /// # use clap::{Command, Arg};
2518 /// let m = Command::new("prog")
2519 /// .arg(Arg::new("cfg")
2521 /// .help("Some help text describing the --config arg"))
2522 /// .get_matches_from(vec![
2523 /// "prog", "--help"
2527 /// The above example displays
2533 /// helptest [OPTIONS]
2536 /// --config Some help text describing the --config arg
2537 /// -h, --help Print help information
2538 /// -V, --version Print version information
2540 /// [`Arg::long_help`]: Arg::long_help()
2543 pub fn help(mut self, h
: impl Into
<Option
<&'help
str>>) -> Self {
2544 self.help
= h
.into();
2548 /// Sets the description of the argument for long help (`--help`).
2550 /// Typically this a more detailed (multi-line) message
2551 /// that describes the arg.
2553 /// If [`Arg::help`] is not specified, this message will be displayed for `-h`.
2555 /// **NOTE:** Only [`Arg::help`] is used in completion script generation in order to be concise
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.
2563 /// Setting `help` displays a short message to the side of the argument when the user passes
2564 /// `-h` or `--help` (by default).
2567 /// # use clap::{Command, Arg};
2568 /// let m = Command::new("prog")
2569 /// .arg(Arg::new("cfg")
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"
2581 /// The above example displays
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.
2597 /// Print help information
2600 /// Print version information
2602 /// [`Arg::help`]: Arg::help()
2605 pub fn long_help(mut self, h
: impl Into
<Option
<&'help
str>>) -> Self {
2606 self.long_help
= h
.into();
2610 /// Allows custom ordering of args within the help message.
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.
2616 /// **NOTE:** The default is 999 for all arguments.
2618 /// **NOTE:** This setting is ignored for [positional arguments] which are always displayed in
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")
2631 /// .takes_value(true)
2632 /// .help("Some help and text"))
2633 /// .arg(Arg::new("b")
2634 /// .long("other-option")
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"
2647 /// The above example displays the following help message
2653 /// cust-ord [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
2661 /// [positional arguments]: Arg::index()
2662 /// [index]: Arg::index()
2665 pub fn display_order(mut self, ord
: usize) -> Self {
2666 self.disp_ord
.set_explicit(ord
);
2670 /// Override the [current] help section.
2672 /// [current]: crate::Command::help_heading
2675 pub fn help_heading
<O
>(mut self, heading
: O
) -> Self
2677 O
: Into
<Option
<&'help
str>>,
2679 self.help_heading
= Some(heading
.into());
2683 /// Render the [help][Arg::help] on the line after the argument.
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.
2688 /// **NOTE:** To apply this setting to all arguments and subcommands, consider using
2689 /// [`crate::Command::next_line_help`]
2694 /// # use clap::{Command, Arg};
2695 /// let m = Command::new("prog")
2696 /// .arg(Arg::new("opt")
2697 /// .long("long-option-flag")
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"
2710 /// The above example displays the following help message
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
2728 pub fn next_line_help(self, yes
: bool
) -> Self {
2730 self.setting(ArgSettings
::NextLineHelp
)
2732 self.unset_setting(ArgSettings
::NextLineHelp
)
2736 /// Do not display the argument in help message.
2738 /// **NOTE:** This does **not** hide the argument from usage strings on error
2742 /// Setting `Hidden` will hide the argument when displaying help text
2745 /// # use clap::{Command, Arg};
2746 /// let m = Command::new("prog")
2747 /// .arg(Arg::new("cfg")
2750 /// .help("Some help text describing the --config arg"))
2751 /// .get_matches_from(vec![
2752 /// "prog", "--help"
2756 /// The above example displays
2762 /// helptest [OPTIONS]
2765 /// -h, --help Print help information
2766 /// -V, --version Print version information
2770 pub fn hide(self, yes
: bool
) -> Self {
2772 self.setting(ArgSettings
::Hidden
)
2774 self.unset_setting(ArgSettings
::Hidden
)
2778 /// Do not display the [possible values][crate::builder::ValueParser::possible_values] in the help message.
2780 /// This is useful for args with many values, or ones which are explained elsewhere in the
2783 /// **NOTE:** Setting this requires [`Arg::takes_value`]
2785 /// To set this for all arguments, see
2786 /// [`Command::hide_possible_values`][crate::Command::hide_possible_values].
2791 /// # use clap::{Command, Arg};
2792 /// let m = Command::new("prog")
2793 /// .arg(Arg::new("mode")
2795 /// .value_parser(["fast", "slow"])
2796 /// .takes_value(true)
2797 /// .hide_possible_values(true));
2799 /// If we were to run the above program with `--help` the `[values: fast, slow]` portion of
2800 /// the help text would be omitted.
2803 pub fn hide_possible_values(self, yes
: bool
) -> Self {
2805 self.setting(ArgSettings
::HidePossibleValues
)
2807 self.unset_setting(ArgSettings
::HidePossibleValues
)
2811 /// Do not display the default value of the argument in the help message.
2813 /// This is useful when default behavior of an arg is explained elsewhere in the help text.
2815 /// **NOTE:** Setting this requires [`Arg::takes_value`]
2820 /// # use clap::{Command, Arg};
2821 /// let m = Command::new("connect")
2822 /// .arg(Arg::new("host")
2824 /// .default_value("localhost")
2825 /// .takes_value(true)
2826 /// .hide_default_value(true));
2830 /// If we were to run the above program with `--help` the `[default: localhost]` portion of
2831 /// the help text would be omitted.
2834 pub fn hide_default_value(self, yes
: bool
) -> Self {
2836 self.setting(ArgSettings
::HideDefaultValue
)
2838 self.unset_setting(ArgSettings
::HideDefaultValue
)
2842 /// Do not display in help the environment variable name.
2844 /// This is useful when the variable option is explained elsewhere in the help text.
2849 /// # use clap::{Command, Arg};
2850 /// let m = Command::new("prog")
2851 /// .arg(Arg::new("mode")
2854 /// .takes_value(true)
2855 /// .hide_env(true));
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")]
2863 pub fn hide_env(self, yes
: bool
) -> Self {
2865 self.setting(ArgSettings
::HideEnv
)
2867 self.unset_setting(ArgSettings
::HideEnv
)
2871 /// Do not display in help any values inside the associated ENV variables for the argument.
2873 /// This is useful when ENV vars contain sensitive values.
2878 /// # use clap::{Command, Arg};
2879 /// let m = Command::new("connect")
2880 /// .arg(Arg::new("host")
2883 /// .takes_value(true)
2884 /// .hide_env_values(true));
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")]
2893 pub fn hide_env_values(self, yes
: bool
) -> Self {
2895 self.setting(ArgSettings
::HideEnvValues
)
2897 self.unset_setting(ArgSettings
::HideEnvValues
)
2901 /// Hides an argument from short help (`-h`).
2903 /// **NOTE:** This does **not** hide the argument from usage strings on error
2905 /// **NOTE:** Setting this option will cause next-line-help output style to be used
2906 /// when long help (`--help`) is called.
2911 /// # use clap::{Command, Arg};
2912 /// Arg::new("debug")
2913 /// .hide_short_help(true);
2916 /// Setting `hide_short_help(true)` will hide the argument when displaying short help text
2919 /// # use clap::{Command, Arg};
2920 /// let m = Command::new("prog")
2921 /// .arg(Arg::new("cfg")
2923 /// .hide_short_help(true)
2924 /// .help("Some help text describing the --config arg"))
2925 /// .get_matches_from(vec![
2930 /// The above example displays
2936 /// helptest [OPTIONS]
2939 /// -h, --help Print help information
2940 /// -V, --version Print version information
2943 /// However, when --help is called
2946 /// # use clap::{Command, Arg};
2947 /// let m = Command::new("prog")
2948 /// .arg(Arg::new("cfg")
2950 /// .hide_short_help(true)
2951 /// .help("Some help text describing the --config arg"))
2952 /// .get_matches_from(vec![
2953 /// "prog", "--help"
2957 /// Then the following would be displayed
2963 /// helptest [OPTIONS]
2966 /// --config Some help text describing the --config arg
2967 /// -h, --help Print help information
2968 /// -V, --version Print version information
2972 pub fn hide_short_help(self, yes
: bool
) -> Self {
2974 self.setting(ArgSettings
::HiddenShortHelp
)
2976 self.unset_setting(ArgSettings
::HiddenShortHelp
)
2980 /// Hides an argument from long help (`--help`).
2982 /// **NOTE:** This does **not** hide the argument from usage strings on error
2984 /// **NOTE:** Setting this option will cause next-line-help output style to be used
2985 /// when long help (`--help`) is called.
2989 /// Setting `hide_long_help(true)` will hide the argument when displaying long help text
2992 /// # use clap::{Command, Arg};
2993 /// let m = Command::new("prog")
2994 /// .arg(Arg::new("cfg")
2996 /// .hide_long_help(true)
2997 /// .help("Some help text describing the --config arg"))
2998 /// .get_matches_from(vec![
2999 /// "prog", "--help"
3003 /// The above example displays
3009 /// helptest [OPTIONS]
3012 /// -h, --help Print help information
3013 /// -V, --version Print version information
3016 /// However, when -h is called
3019 /// # use clap::{Command, Arg};
3020 /// let m = Command::new("prog")
3021 /// .arg(Arg::new("cfg")
3023 /// .hide_long_help(true)
3024 /// .help("Some help text describing the --config arg"))
3025 /// .get_matches_from(vec![
3030 /// Then the following would be displayed
3036 /// helptest [OPTIONS]
3039 /// --config Some help text describing the --config arg
3040 /// -h, --help Print help information
3041 /// -V, --version Print version information
3045 pub fn hide_long_help(self, yes
: bool
) -> Self {
3047 self.setting(ArgSettings
::HiddenLongHelp
)
3049 self.unset_setting(ArgSettings
::HiddenLongHelp
)
3054 /// # Advanced Argument Relations
3055 impl<'help
> Arg
<'help
> {
3056 /// The name of the [`ArgGroup`] the argument belongs to.
3061 /// # use clap::{Command, Arg};
3062 /// Arg::new("debug")
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.
3072 /// # use clap::{Command, Arg};
3073 /// let m = Command::new("prog")
3074 /// .arg(Arg::new("debug")
3077 /// .arg(Arg::new("verbose")
3078 /// .long("verbose")
3080 /// .get_matches_from(vec![
3081 /// "prog", "--debug"
3083 /// assert!(m.contains_id("mode"));
3086 /// [`ArgGroup`]: crate::ArgGroup
3088 pub fn group
<T
: Key
>(mut self, group_id
: T
) -> Self {
3089 self.groups
.push(group_id
.into());
3093 /// The names of [`ArgGroup`]'s the argument belongs to.
3098 /// # use clap::{Command, Arg};
3099 /// Arg::new("debug")
3101 /// .groups(&["mode", "verbosity"])
3105 /// Arguments can be members of multiple groups and then the group checked as if it
3106 /// was one of said arguments.
3109 /// # use clap::{Command, Arg};
3110 /// let m = Command::new("prog")
3111 /// .arg(Arg::new("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"
3120 /// assert!(m.contains_id("mode"));
3121 /// assert!(m.contains_id("verbosity"));
3124 /// [`ArgGroup`]: crate::ArgGroup
3126 pub fn groups
<T
: Key
>(mut self, group_ids
: &[T
]) -> Self {
3127 self.groups
.extend(group_ids
.iter().map(Id
::from
));
3131 /// Specifies the value of the argument if `arg` has been used at runtime.
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`.
3136 /// If `default` is set to `None`, `default_value` will be removed.
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.
3145 /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`].
3149 /// First we use the default value only if another arg is present at runtime.
3152 /// # use clap::{Command, Arg};
3153 /// let m = Command::new("prog")
3154 /// .arg(Arg::new("flag")
3156 /// .arg(Arg::new("other")
3158 /// .default_value_if("flag", None, Some("default")))
3159 /// .get_matches_from(vec![
3160 /// "prog", "--flag"
3163 /// assert_eq!(m.value_of("other"), Some("default"));
3166 /// Next we run the same test, but without providing `--flag`.
3169 /// # use clap::{Command, Arg};
3170 /// let m = Command::new("prog")
3171 /// .arg(Arg::new("flag")
3173 /// .arg(Arg::new("other")
3175 /// .default_value_if("flag", None, Some("default")))
3176 /// .get_matches_from(vec![
3180 /// assert_eq!(m.value_of("other"), None);
3183 /// Now lets only use the default value if `--opt` contains the value `special`.
3186 /// # use clap::{Command, Arg};
3187 /// let m = Command::new("prog")
3188 /// .arg(Arg::new("opt")
3189 /// .takes_value(true)
3191 /// .arg(Arg::new("other")
3193 /// .default_value_if("opt", Some("special"), Some("default")))
3194 /// .get_matches_from(vec![
3195 /// "prog", "--opt", "special"
3198 /// assert_eq!(m.value_of("other"), Some("default"));
3201 /// We can run the same test and provide any value *other than* `special` and we won't get a
3205 /// # use clap::{Command, Arg};
3206 /// let m = Command::new("prog")
3207 /// .arg(Arg::new("opt")
3208 /// .takes_value(true)
3210 /// .arg(Arg::new("other")
3212 /// .default_value_if("opt", Some("special"), Some("default")))
3213 /// .get_matches_from(vec![
3214 /// "prog", "--opt", "hahaha"
3217 /// assert_eq!(m.value_of("other"), None);
3220 /// If we want to unset the default value for an Arg based on the presence or
3221 /// value of some other Arg.
3224 /// # use clap::{Command, Arg};
3225 /// let m = Command::new("prog")
3226 /// .arg(Arg::new("flag")
3228 /// .arg(Arg::new("other")
3230 /// .default_value("default")
3231 /// .default_value_if("flag", None, None))
3232 /// .get_matches_from(vec![
3233 /// "prog", "--flag"
3236 /// assert_eq!(m.value_of("other"), None);
3238 /// [`Arg::takes_value(true)`]: Arg::takes_value()
3239 /// [`Arg::default_value`]: Arg::default_value()
3241 pub fn default_value_if
<T
: Key
>(
3244 val
: Option
<&'help
str>,
3245 default: Option
<&'help
str>,
3247 self.default_value_if_os(arg_id
, val
.map(OsStr
::new
), default.map(OsStr
::new
))
3250 /// Provides a conditional default value in the exact same manner as [`Arg::default_value_if`]
3251 /// only using [`OsStr`]s instead.
3253 /// [`Arg::default_value_if`]: Arg::default_value_if()
3254 /// [`OsStr`]: std::ffi::OsStr
3256 pub fn default_value_if_os
<T
: Key
>(
3259 val
: Option
<&'help OsStr
>,
3260 default: Option
<&'help OsStr
>,
3262 self.default_vals_ifs
3263 .push((arg_id
.into(), val
.into(), default));
3264 self.takes_value(true)
3267 /// Specifies multiple values and conditions in the same manner as [`Arg::default_value_if`].
3269 /// The method takes a slice of tuples in the `(arg, Option<val>, default)` format.
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.
3276 /// First we use the default value only if another arg is present at runtime.
3279 /// # use clap::{Command, Arg};
3280 /// let m = Command::new("prog")
3281 /// .arg(Arg::new("flag")
3283 /// .arg(Arg::new("opt")
3285 /// .takes_value(true))
3286 /// .arg(Arg::new("other")
3288 /// .default_value_ifs(&[
3289 /// ("flag", None, Some("default")),
3290 /// ("opt", Some("channal"), Some("chan")),
3292 /// .get_matches_from(vec![
3293 /// "prog", "--opt", "channal"
3296 /// assert_eq!(m.value_of("other"), Some("chan"));
3299 /// Next we run the same test, but without providing `--flag`.
3302 /// # use clap::{Command, Arg};
3303 /// let m = Command::new("prog")
3304 /// .arg(Arg::new("flag")
3306 /// .arg(Arg::new("other")
3308 /// .default_value_ifs(&[
3309 /// ("flag", None, Some("default")),
3310 /// ("opt", Some("channal"), Some("chan")),
3312 /// .get_matches_from(vec![
3316 /// assert_eq!(m.value_of("other"), None);
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"
3323 /// # use clap::{Command, Arg};
3324 /// let m = Command::new("prog")
3325 /// .arg(Arg::new("flag")
3327 /// .arg(Arg::new("opt")
3329 /// .takes_value(true))
3330 /// .arg(Arg::new("other")
3332 /// .default_value_ifs(&[
3333 /// ("flag", None, Some("default")),
3334 /// ("opt", Some("channal"), Some("chan")),
3336 /// .get_matches_from(vec![
3337 /// "prog", "--opt", "channal", "--flag"
3340 /// assert_eq!(m.value_of("other"), Some("default"));
3342 /// [`Arg::takes_value(true)`]: Arg::takes_value()
3343 /// [`Arg::default_value_if`]: Arg::default_value_if()
3345 pub fn default_value_ifs
<T
: Key
>(
3347 ifs
: &[(T
, Option
<&'help
str>, Option
<&'help
str>)],
3349 for (arg
, val
, default) in ifs
{
3350 self = self.default_value_if_os(arg
, val
.map(OsStr
::new
), default.map(OsStr
::new
));
3355 /// Provides multiple conditional default values in the exact same manner as
3356 /// [`Arg::default_value_ifs`] only using [`OsStr`]s instead.
3358 /// [`Arg::default_value_ifs`]: Arg::default_value_ifs()
3359 /// [`OsStr`]: std::ffi::OsStr
3361 pub fn default_value_ifs_os
<T
: Key
>(
3363 ifs
: &[(T
, Option
<&'help OsStr
>, Option
<&'help OsStr
>)],
3365 for (arg
, val
, default) in ifs
{
3366 self = self.default_value_if_os(arg
, *val
, *default);
3371 /// Set this arg as [required] as long as the specified argument is not present at runtime.
3373 /// **Pro Tip:** Using `Arg::required_unless_present` implies [`Arg::required`] and is therefore not
3374 /// mandatory to also set.
3379 /// # use clap::Arg;
3380 /// Arg::new("config")
3381 /// .required_unless_present("debug")
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.
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")
3397 /// .try_get_matches_from(vec![
3398 /// "prog", "--debug"
3401 /// assert!(res.is_ok());
3404 /// Setting `Arg::required_unless_present(name)` and *not* supplying `name` or this arg is an error.
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")
3415 /// .try_get_matches_from(vec![
3419 /// assert!(res.is_err());
3420 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3422 /// [required]: Arg::required()
3424 pub fn required_unless_present
<T
: Key
>(mut self, arg_id
: T
) -> Self {
3425 self.r_unless
.push(arg_id
.into());
3429 /// Sets this arg as [required] unless *all* of the specified arguments are present at runtime.
3431 /// In other words, parsing will succeed only if user either
3432 /// * supplies the `self` arg.
3433 /// * supplies *all* of the `names` arguments.
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`]
3441 /// # use clap::Arg;
3442 /// Arg::new("config")
3443 /// .required_unless_present_all(&["cfg", "dbg"])
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.
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")
3459 /// .arg(Arg::new("infile")
3461 /// .takes_value(true))
3462 /// .try_get_matches_from(vec![
3463 /// "prog", "--debug", "-i", "file"
3466 /// assert!(res.is_ok());
3469 /// Setting [`Arg::required_unless_present_all(names)`] and *not* supplying
3470 /// either *all* of `unless` args or the `self` arg is an error.
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")
3481 /// .arg(Arg::new("infile")
3483 /// .takes_value(true))
3484 /// .try_get_matches_from(vec![
3488 /// assert!(res.is_err());
3489 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
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()
3495 pub fn required_unless_present_all
<T
, I
>(mut self, names
: I
) -> Self
3497 I
: IntoIterator
<Item
= T
>,
3500 self.r_unless_all
.extend(names
.into_iter().map(Id
::from
));
3504 /// Sets this arg as [required] unless *any* of the specified arguments are present at runtime.
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.
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`]
3516 /// # use clap::Arg;
3517 /// Arg::new("config")
3518 /// .required_unless_present_any(&["cfg", "dbg"])
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.
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")
3536 /// .arg(Arg::new("infile")
3538 /// .takes_value(true))
3539 /// .try_get_matches_from(vec![
3540 /// "prog", "--debug"
3543 /// assert!(res.is_ok());
3546 /// Setting [`Arg::required_unless_present_any(names)`] and *not* supplying *at least one of* `names`
3547 /// or this arg is an error.
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")
3558 /// .arg(Arg::new("infile")
3560 /// .takes_value(true))
3561 /// .try_get_matches_from(vec![
3565 /// assert!(res.is_err());
3566 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
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()
3572 pub fn required_unless_present_any
<T
, I
>(mut self, names
: I
) -> Self
3574 I
: IntoIterator
<Item
= T
>,
3577 self.r_unless
.extend(names
.into_iter().map(Id
::from
));
3581 /// This argument is [required] only if the specified `arg` is present at runtime and its value
3587 /// # use clap::Arg;
3588 /// Arg::new("config")
3589 /// .required_if_eq("other_arg", "value")
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")
3602 /// .takes_value(true))
3603 /// .try_get_matches_from(vec![
3604 /// "prog", "--other", "not-special"
3607 /// assert!(res.is_ok()); // We didn't use --other=special, so "cfg" wasn't required
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")
3616 /// .takes_value(true))
3617 /// .try_get_matches_from(vec![
3618 /// "prog", "--other", "special"
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);
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")
3632 /// .takes_value(true))
3633 /// .try_get_matches_from(vec![
3634 /// "prog", "--other", "SPECIAL"
3637 /// // By default, the comparison is case-sensitive, so "cfg" wasn't required
3638 /// assert!(res.is_ok());
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")
3647 /// .ignore_case(true)
3648 /// .takes_value(true))
3649 /// .try_get_matches_from(vec![
3650 /// "prog", "--other", "SPECIAL"
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);
3657 /// [`Arg::requires(name)`]: Arg::requires()
3658 /// [Conflicting]: Arg::conflicts_with()
3659 /// [required]: Arg::required()
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
));
3666 /// Specify this argument is [required] based on multiple conditions.
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`.
3674 /// # use clap::Arg;
3675 /// Arg::new("config")
3676 /// .required_if_eq_any(&[
3677 /// ("extra", "val"),
3678 /// ("option", "spec")
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.
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")
3695 /// .takes_value(true)
3696 /// .long("config"))
3697 /// .arg(Arg::new("extra")
3698 /// .takes_value(true)
3700 /// .arg(Arg::new("option")
3701 /// .takes_value(true)
3702 /// .long("option"))
3703 /// .try_get_matches_from(vec![
3704 /// "prog", "--option", "other"
3707 /// assert!(res.is_ok()); // We didn't use --option=spec, or --extra=val so "cfg" isn't required
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.
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")
3721 /// .takes_value(true)
3722 /// .long("config"))
3723 /// .arg(Arg::new("extra")
3724 /// .takes_value(true)
3726 /// .arg(Arg::new("option")
3727 /// .takes_value(true)
3728 /// .long("option"))
3729 /// .try_get_matches_from(vec![
3730 /// "prog", "--option", "spec"
3733 /// assert!(res.is_err());
3734 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3736 /// [`Arg::requires(name)`]: Arg::requires()
3737 /// [Conflicting]: Arg::conflicts_with()
3738 /// [required]: Arg::required()
3740 pub fn required_if_eq_any
<T
: Key
>(mut self, ifs
: &[(T
, &'help
str)]) -> Self {
3742 .extend(ifs
.iter().map(|(id
, val
)| (Id
::from_ref(id
), *val
)));
3746 /// Specify this argument is [required] based on multiple conditions.
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`.
3754 /// # use clap::Arg;
3755 /// Arg::new("config")
3756 /// .required_if_eq_all(&[
3757 /// ("extra", "val"),
3758 /// ("option", "spec")
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.
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")
3775 /// .takes_value(true)
3776 /// .long("config"))
3777 /// .arg(Arg::new("extra")
3778 /// .takes_value(true)
3780 /// .arg(Arg::new("option")
3781 /// .takes_value(true)
3782 /// .long("option"))
3783 /// .try_get_matches_from(vec![
3784 /// "prog", "--option", "spec"
3787 /// assert!(res.is_ok()); // We didn't use --option=spec --extra=val so "cfg" isn't required
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.
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")
3801 /// .takes_value(true)
3802 /// .long("config"))
3803 /// .arg(Arg::new("extra")
3804 /// .takes_value(true)
3806 /// .arg(Arg::new("option")
3807 /// .takes_value(true)
3808 /// .long("option"))
3809 /// .try_get_matches_from(vec![
3810 /// "prog", "--extra", "val", "--option", "spec"
3813 /// assert!(res.is_err());
3814 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3816 /// [required]: Arg::required()
3818 pub fn required_if_eq_all
<T
: Key
>(mut self, ifs
: &[(T
, &'help
str)]) -> Self {
3820 .extend(ifs
.iter().map(|(id
, val
)| (Id
::from_ref(id
), *val
)));
3824 /// Require another argument if this arg was present at runtime and its value equals to `val`.
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.
3833 /// # use clap::Arg;
3834 /// Arg::new("config")
3835 /// .requires_if("val", "arg")
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.
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"
3855 /// assert!(res.is_ok()); // We didn't use --config=my.cfg, so other wasn't required
3858 /// Setting `Arg::requires_if(val, arg)` and setting the value to `val` but *not* supplying
3859 /// `arg` is an error.
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"
3873 /// assert!(res.is_err());
3874 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3876 /// [`Arg::requires(name)`]: Arg::requires()
3877 /// [Conflicting]: Arg::conflicts_with()
3878 /// [override]: Arg::overrides_with()
3880 pub fn requires_if
<T
: Key
>(mut self, val
: &'help
str, arg_id
: T
) -> Self {
3882 .push((ArgPredicate
::Equals(OsStr
::new(val
)), arg_id
.into()));
3886 /// Allows multiple conditional requirements.
3888 /// The requirement will only become valid if this arg's value equals `val`.
3893 /// # use clap::Arg;
3894 /// Arg::new("config")
3895 /// .requires_ifs(&[
3897 /// ("other_val", "arg2"),
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.
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"),
3915 /// .long("config"))
3916 /// .arg(Arg::new("opt")
3918 /// .takes_value(true))
3919 /// .arg(Arg::new("other"))
3920 /// .try_get_matches_from(vec![
3921 /// "prog", "--config", "special.conf"
3924 /// assert!(res.is_err()); // We used --config=special.conf so --option <val> is required
3925 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3927 /// [`Arg::requires(name)`]: Arg::requires()
3928 /// [Conflicting]: Arg::conflicts_with()
3929 /// [override]: Arg::overrides_with()
3931 pub fn requires_ifs
<T
: Key
>(mut self, ifs
: &[(&'help
str, T
)]) -> Self {
3932 self.requires
.extend(
3934 .map(|(val
, arg
)| (ArgPredicate
::Equals(OsStr
::new(*val
)), Id
::from(arg
))),
3939 /// Require these arguments names when this one is presen
3941 /// i.e. when using this argument, the following arguments *must* be present.
3943 /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required
3949 /// # use clap::Arg;
3950 /// Arg::new("config")
3951 /// .requires_all(&["input", "output"])
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
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![
3972 /// assert!(res.is_ok()); // We didn't use cfg, so input and output weren't required
3975 /// Setting `Arg::requires_all(&[arg, arg2])` and *not* supplying all the arguments is an
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"
3991 /// assert!(res.is_err());
3992 /// // We didn't use output
3993 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3995 /// [Conflicting]: Arg::conflicts_with()
3996 /// [override]: Arg::overrides_with()
3998 pub fn requires_all
<T
: Key
>(mut self, names
: &[T
]) -> Self {
4000 .extend(names
.iter().map(|s
| (ArgPredicate
::IsPresent
, s
.into())));
4004 /// This argument is mutually exclusive with the specified argument.
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.
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))
4013 /// **NOTE:** [`Arg::conflicts_with_all(names)`] allows specifying an argument which conflicts with more than one argument.
4015 /// **NOTE** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument.
4020 /// # use clap::Arg;
4021 /// Arg::new("config")
4022 /// .conflicts_with("debug")
4026 /// Setting conflicting argument, and having both arguments present at runtime is an error.
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")
4037 /// .try_get_matches_from(vec![
4038 /// "prog", "--debug", "--config", "file.conf"
4041 /// assert!(res.is_err());
4042 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict);
4045 /// [`Arg::conflicts_with_all(names)`]: Arg::conflicts_with_all()
4046 /// [`Arg::exclusive(true)`]: Arg::exclusive()
4048 pub fn conflicts_with
<T
: Key
>(mut self, arg_id
: T
) -> Self {
4049 self.blacklist
.push(arg_id
.into());
4053 /// This argument is mutually exclusive with the specified arguments.
4055 /// See [`Arg::conflicts_with`].
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.
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))
4064 /// **NOTE:** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument.
4069 /// # use clap::Arg;
4070 /// Arg::new("config")
4071 /// .conflicts_with_all(&["debug", "input"])
4075 /// Setting conflicting argument, and having any of the arguments present at runtime with a
4076 /// conflicting argument is an error.
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")
4087 /// .arg(Arg::new("input"))
4088 /// .try_get_matches_from(vec![
4089 /// "prog", "--config", "file.conf", "file.txt"
4092 /// assert!(res.is_err());
4093 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict);
4095 /// [`Arg::conflicts_with`]: Arg::conflicts_with()
4096 /// [`Arg::exclusive(true)`]: Arg::exclusive()
4098 pub fn conflicts_with_all(mut self, names
: &[&str]) -> Self {
4099 self.blacklist
.extend(names
.iter().copied().map(Id
::from
));
4103 /// Sets an overridable argument.
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")
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
4112 /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with`].
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.
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
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"));
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:
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):
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"));
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.
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"));
4167 /// Now notice with options (which *do not* set
4168 /// [`Arg::multiple_occurrences`]), it's as if only the last
4169 /// occurrence happened.
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"));
4180 /// This will also work when [`Arg::multiple_values`] is enabled:
4183 /// # use clap::{Command, Arg};
4184 /// let m = Command::new("posix")
4188 /// .takes_value(true)
4189 /// .multiple_values(true)
4190 /// .overrides_with("opt")
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"]);
4197 /// Just like flags, options with [`Arg::multiple_occurrences`] set
4198 /// will ignore the "override self" setting.
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"]);
4211 pub fn overrides_with
<T
: Key
>(mut self, arg_id
: T
) -> Self {
4212 self.overrides
.push(arg_id
.into());
4216 /// Sets multiple mutually overridable arguments by name.
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")
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
4224 /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with_all`].
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
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
4243 /// assert!(!m.is_present("debug"));
4244 /// assert!(!m.is_present("flag"));
4247 pub fn overrides_with_all
<T
: Key
>(mut self, names
: &[T
]) -> Self {
4248 self.overrides
.extend(names
.iter().map(Id
::from
));
4254 impl<'help
> Arg
<'help
> {
4255 /// Get the name of the argument
4257 pub fn get_id(&self) -> &'help
str {
4261 /// Deprecated, replaced with [`Arg::get_id`]
4263 feature
= "deprecated",
4264 deprecated(since
= "3.1.0", note
= "Replaced with `Arg::get_id`")
4266 pub fn get_name(&self) -> &'help
str {
4270 /// Get the help specified for this argument, if any
4272 pub fn get_help(&self) -> Option
<&'help
str> {
4276 /// Get the long help specified for this argument, if any
4281 /// # use clap::Arg;
4282 /// let arg = Arg::new("foo").long_help("long help");
4283 /// assert_eq!(Some("long help"), arg.get_long_help());
4287 pub fn get_long_help(&self) -> Option
<&'help
str> {
4291 /// Get the help heading specified for this argument, if any
4293 pub fn get_help_heading(&self) -> Option
<&'help
str> {
4294 self.help_heading
.unwrap_or_default()
4297 /// Get the short option name for this argument, if any
4299 pub fn get_short(&self) -> Option
<char> {
4303 /// Get visible short aliases for this argument, if any
4305 pub fn get_visible_short_aliases(&self) -> Option
<Vec
<char>> {
4306 if self.short_aliases
.is_empty() {
4312 .filter_map(|(c
, v
)| if *v { Some(c) }
else { None }
)
4319 /// Get the short option name and its visible aliases, if any
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
,
4326 if let Some(aliases
) = self.get_visible_short_aliases() {
4327 shorts
.extend(aliases
);
4332 /// Get the long option name for this argument, if any
4334 pub fn get_long(&self) -> Option
<&'help
str> {
4338 /// Get visible aliases for this argument, if any
4340 pub fn get_visible_aliases(&self) -> Option
<Vec
<&'help
str>> {
4341 if self.aliases
.is_empty() {
4347 .filter_map(|(s
, v
)| if *v { Some(s) }
else { None }
)
4354 /// Get the long option name and its visible aliases, if any
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
,
4361 if let Some(aliases
) = self.get_visible_aliases() {
4362 longs
.extend(aliases
);
4367 /// Deprecated, replaced with [`Arg::get_value_parser().possible_values()`]
4369 feature
= "deprecated",
4372 note
= "Replaced with `Arg::get_value_parser().possible_values()`"
4375 pub fn get_possible_values(&self) -> Option
<&[PossibleValue
<'help
>]> {
4376 if self.possible_vals
.is_empty() {
4379 Some(&self.possible_vals
)
4383 pub(crate) fn get_possible_values2(&self) -> Vec
<PossibleValue
<'help
>> {
4384 #![allow(deprecated)]
4385 if !self.is_takes_value_set() {
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.
4392 self.get_value_parser()
4394 .map(|pvs
| pvs
.collect())
4395 .unwrap_or_default()
4399 /// Get the names of values for this argument.
4401 pub fn get_value_names(&self) -> Option
<&[&'help
str]> {
4402 if self.val_names
.is_empty() {
4405 Some(&self.val_names
)
4409 /// Get the number of values for this argument.
4411 pub fn get_num_vals(&self) -> Option
<usize> {
4415 /// Get the delimiter between multiple values
4417 pub fn get_value_delimiter(&self) -> Option
<char> {
4421 /// Get the index of this argument, if any
4423 pub fn get_index(&self) -> Option
<usize> {
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
>() {
4435 ValueHint
::default()
4438 ValueHint
::default()
4443 /// Deprecated, replaced with [`Arg::is_global_set`]
4445 feature
= "deprecated",
4446 deprecated(since
= "3.1.0", note
= "Replaced with `Arg::is_global_set`")
4448 pub fn get_global(&self) -> bool
{
4449 self.is_global_set()
4452 /// Get the environment variable name specified for this argument, if any
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());
4462 #[cfg(feature = "env")]
4463 pub fn get_env(&self) -> Option
<&OsStr
> {
4464 self.env
.as_ref().map(|x
| x
.0)
4467 /// Get the default values specified for this argument, if any
4472 /// # use clap::Arg;
4473 /// let arg = Arg::new("foo").default_value("default value");
4474 /// assert_eq!(&["default value"], arg.get_default_values());
4476 pub fn get_default_values(&self) -> &[&OsStr
] {
4480 /// Checks whether this argument is a positional or not.
4485 /// # use clap::Arg;
4486 /// let arg = Arg::new("foo");
4487 /// assert_eq!(true, arg.is_positional());
4489 /// let arg = Arg::new("foo").long("foo");
4490 /// assert_eq!(false, arg.is_positional());
4492 pub fn is_positional(&self) -> bool
{
4493 self.long
.is_none() && self.short
.is_none()
4496 /// Reports whether [`Arg::required`] is set
4497 pub fn is_required_set(&self) -> bool
{
4498 self.is_set(ArgSettings
::Required
)
4501 /// Report whether [`Arg::multiple_values`] is set
4502 pub fn is_multiple_values_set(&self) -> bool
{
4503 self.is_set(ArgSettings
::MultipleValues
)
4506 /// [`Arg::multiple_occurrences`] is going away ([Issue #3772](https://github.com/clap-rs/clap/issues/3772))
4508 feature
= "deprecated",
4509 deprecated(since
= "3.2.0", note
= "`multiple_occurrences` away (Issue #3772)")
4511 pub fn is_multiple_occurrences_set(&self) -> bool
{
4512 self.is_set(ArgSettings
::MultipleOccurrences
)
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
)
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
)
4525 /// Deprecated, replaced with [`Arg::get_value_parser()`]
4527 feature
= "deprecated",
4528 deprecated(since
= "3.2.0", note
= "Replaced with `Arg::get_value_parser()`")
4530 pub fn is_forbid_empty_values_set(&self) -> bool
{
4531 self.is_set(ArgSettings
::ForbidEmptyValues
)
4534 /// Deprecated, replaced with [`Arg::get_value_parser()`
4536 feature
= "deprecated",
4537 deprecated(since
= "3.2.0", note
= "Replaced with `Arg::get_value_parser()`")
4539 pub fn is_allow_invalid_utf8_set(&self) -> bool
{
4540 self.is_set(ArgSettings
::AllowInvalidUtf8
)
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
)
4549 /// Configured parser for argument values
4554 /// let cmd = clap::Command::new("raw")
4556 /// clap::Arg::new("port")
4557 /// .value_parser(clap::value_parser!(usize))
4559 /// let value_parser = cmd.get_arguments()
4560 /// .find(|a| a.get_id() == "port").unwrap()
4561 /// .get_value_parser();
4562 /// println!("{:?}", value_parser);
4564 pub fn get_value_parser(&self) -> &super::ValueParser
{
4565 if let Some(value_parser
) = self.value_parser
.as_ref() {
4567 } else if self.is_allow_invalid_utf8_set() {
4568 static DEFAULT
: super::ValueParser
= super::ValueParser
::os_string();
4571 static DEFAULT
: super::ValueParser
= super::ValueParser
::string();
4576 /// Report whether [`Arg::global`] is set
4577 pub fn is_global_set(&self) -> bool
{
4578 self.is_set(ArgSettings
::Global
)
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
)
4586 /// Report whether [`Arg::hide`] is set
4587 pub fn is_hide_set(&self) -> bool
{
4588 self.is_set(ArgSettings
::Hidden
)
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
)
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
)
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
)
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
)
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
)
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
)
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
)
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
)
4633 /// Report whether [`Arg::require_equals`] is set
4634 pub fn is_require_equals_set(&self) -> bool
{
4635 self.is_set(ArgSettings
::RequireEquals
)
4638 /// Reports whether [`Arg::exclusive`] is set
4639 pub fn is_exclusive_set(&self) -> bool
{
4640 self.is_set(ArgSettings
::Exclusive
)
4643 /// Reports whether [`Arg::last`] is set
4644 pub fn is_last_set(&self) -> bool
{
4645 self.is_set(ArgSettings
::Last
)
4648 /// Reports whether [`Arg::ignore_case`] is set
4649 pub fn is_ignore_case_set(&self) -> bool
{
4650 self.is_set(ArgSettings
::IgnoreCase
)
4655 impl<'help
> Arg
<'help
> {
4656 /// Deprecated, replaced with [`Arg::new`]
4658 feature
= "deprecated",
4659 deprecated(since
= "3.0.0", note
= "Replaced with `Arg::new`")
4662 pub fn with_name
<S
: Into
<&'help
str>>(n
: S
) -> Self {
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")]
4669 feature
= "deprecated",
4672 note
= "Deprecated in Issue #3087, maybe clap::Parser would fit your use case?"
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
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
);
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
),
4733 "Unknown setting '{}' in YAML file for arg '{}'",
4743 /// Deprecated in [Issue #3086](https://github.com/clap-rs/clap/issues/3086), see [`arg!`][crate::arg!].
4745 feature
= "deprecated",
4746 deprecated(since
= "3.0.0", note
= "Deprecated in Issue #3086, see `clap::arg!")
4749 pub fn from_usage(u
: &'help
str) -> Self {
4750 UsageParser
::from_usage(u
).parse()
4753 /// Deprecated, replaced with [`Arg::required_unless_present`]
4755 feature
= "deprecated",
4756 deprecated(since
= "3.0.0", note
= "Replaced with `Arg::required_unless_present`")
4760 pub fn required_unless
<T
: Key
>(self, arg_id
: T
) -> Self {
4761 self.required_unless_present(arg_id
)
4764 /// Deprecated, replaced with [`Arg::required_unless_present_all`]
4766 feature
= "deprecated",
4769 note
= "Replaced with `Arg::required_unless_present_all`"
4774 pub fn required_unless_all
<T
, I
>(self, names
: I
) -> Self
4776 I
: IntoIterator
<Item
= T
>,
4779 self.required_unless_present_all(names
)
4782 /// Deprecated, replaced with [`Arg::required_unless_present_any`]
4784 feature
= "deprecated",
4787 note
= "Replaced with `Arg::required_unless_present_any`"
4792 pub fn required_unless_one
<T
, I
>(self, names
: I
) -> Self
4794 I
: IntoIterator
<Item
= T
>,
4797 self.required_unless_present_any(names
)
4800 /// Deprecated, replaced with [`Arg::required_if_eq`]
4802 feature
= "deprecated",
4803 deprecated(since
= "3.0.0", note
= "Replaced with `Arg::required_if_eq`")
4807 pub fn required_if
<T
: Key
>(self, arg_id
: T
, val
: &'help
str) -> Self {
4808 self.required_if_eq(arg_id
, val
)
4811 /// Deprecated, replaced with [`Arg::required_if_eq_any`]
4813 feature
= "deprecated",
4814 deprecated(since
= "3.0.0", note
= "Replaced with `Arg::required_if_eq_any`")
4818 pub fn required_ifs
<T
: Key
>(self, ifs
: &[(T
, &'help
str)]) -> Self {
4819 self.required_if_eq_any(ifs
)
4822 /// Deprecated, replaced with [`Arg::hide`]
4824 feature
= "deprecated",
4825 deprecated(since
= "3.0.0", note
= "Replaced with `Arg::hide`")
4830 pub fn hidden(self, yes
: bool
) -> Self {
4834 /// Deprecated, replaced with [`Arg::ignore_case`]
4836 feature
= "deprecated",
4837 deprecated(since
= "3.0.0", note
= "Replaced with `Arg::ignore_case`")
4842 pub fn case_insensitive(self, yes
: bool
) -> Self {
4843 self.ignore_case(yes
)
4846 /// Deprecated, replaced with [`Arg::forbid_empty_values`]
4848 feature
= "deprecated",
4849 deprecated(since
= "3.0.0", note
= "Replaced with `Arg::forbid_empty_values`")
4853 pub fn empty_values(self, yes
: bool
) -> Self {
4854 self.forbid_empty_values(!yes
)
4857 /// Deprecated, replaced with [`Arg::multiple_occurrences`] (most likely what you want) and
4858 /// [`Arg::multiple_values`]
4860 feature
= "deprecated",
4863 note
= "Split into `Arg::multiple_occurrences` (most likely what you want) and `Arg::multiple_values`"
4868 pub fn multiple(self, yes
: bool
) -> Self {
4869 self.multiple_occurrences(yes
).multiple_values(yes
)
4872 /// Deprecated, replaced with [`Arg::hide_short_help`]
4874 feature
= "deprecated",
4875 deprecated(since
= "3.0.0", note
= "Replaced with `Arg::hide_short_help`")
4880 pub fn hidden_short_help(self, yes
: bool
) -> Self {
4881 self.hide_short_help(yes
)
4884 /// Deprecated, replaced with [`Arg::hide_long_help`]
4886 feature
= "deprecated",
4887 deprecated(since
= "3.0.0", note
= "Replaced with `Arg::hide_long_help`")
4892 pub fn hidden_long_help(self, yes
: bool
) -> Self {
4893 self.hide_long_help(yes
)
4896 /// Deprecated, replaced with [`Arg::setting`]
4898 feature
= "deprecated",
4899 deprecated(since
= "3.0.0", note
= "Replaced with `Arg::setting`")
4903 pub fn set(self, s
: ArgSettings
) -> Self {
4907 /// Deprecated, replaced with [`Arg::unset_setting`]
4909 feature
= "deprecated",
4910 deprecated(since
= "3.0.0", note
= "Replaced with `Arg::unset_setting`")
4914 pub fn unset(self, s
: ArgSettings
) -> Self {
4915 self.unset_setting(s
)
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
);
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
];
4931 if action
.takes_values() {
4932 self.settings
.set(ArgSettings
::TakesValue
);
4934 self.settings
.unset(ArgSettings
::TakesValue
);
4937 ArgAction
::StoreValue
4938 | ArgAction
::IncOccurrence
4940 | ArgAction
::Version
=> {}
4943 | ArgAction
::SetTrue
4944 | ArgAction
::SetFalse
4945 | ArgAction
::Count
=> {
4946 if !self.is_positional() {
4947 self.settings
.set(ArgSettings
::MultipleOccurrences
);
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());
4959 self.value_parser
= Some(super::ValueParser
::string());
4963 if (self.is_use_value_delimiter_set() || self.is_require_value_delimiter_set())
4964 && self.val_delim
.is_none()
4966 self.val_delim
= Some('
,'
);
4969 let val_names_len
= self.val_names
.len();
4971 if val_names_len
> 1 {
4972 self.settings
.set(ArgSettings
::MultipleValues
);
4974 if self.num_vals
.is_none() {
4975 self.num_vals
= Some(val_names_len
);
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.
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
);
4990 pub(crate) fn generated(mut self) -> Self {
4991 self.provider
= ArgProvider
::Generated
;
4995 pub(crate) fn longest_filter(&self) -> bool
{
4996 self.is_takes_value_set() || self.long
.is_some() || self.short
.is_none()
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
{
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
)
5018 if !self.val_names
.is_empty() {
5019 debug
!("Arg::name_no_brackets: val_names={:#?}", self.val_names
);
5021 if self.val_names
.len() > 1 {
5025 .map(|n
| format
!("<{}>", n
))
5026 .collect
::<Vec
<_
>>()
5030 Cow
::Borrowed(self.val_names
.get(0).expect(INTERNAL_ERROR_MSG
))
5033 debug
!("Arg::name_no_brackets: just name");
5034 Cow
::Borrowed(self.name
)
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()
5043 pub(crate) fn get_display_order(&self) -> usize {
5044 self.disp_ord
.get_explicit()
5048 impl<'help
> From
<&'_ Arg
<'help
>> for Arg
<'help
> {
5049 fn from(a
: &Arg
<'help
>) -> Self {
5054 impl<'help
> PartialEq
for Arg
<'help
> {
5055 fn eq(&self, other
: &Arg
<'help
>) -> bool
{
5056 self.name
== other
.name
5060 impl<'help
> PartialOrd
for Arg
<'help
> {
5061 fn partial_cmp(&self, other
: &Self) -> Option
<Ordering
> {
5062 Some(self.cmp(other
))
5066 impl<'help
> Ord
for Arg
<'help
> {
5067 fn cmp(&self, other
: &Arg
) -> Ordering
{
5068 self.name
.cmp(other
.name
)
5072 impl<'help
> Eq
for Arg
<'help
> {}
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
)?
;
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;
5092 } else if is_optional_val
{
5093 need_closing_bracket
= true;
5100 if self.is_takes_value_set() || self.is_positional() {
5101 display_arg_val(self, |s
, _
| f
.write_str(s
))?
;
5103 if need_closing_bracket
{
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");
5115 #[allow(unused_mut)]
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
)
5143 &self.validator
.as_ref().map_or("None", |_
| "Some(FnMut)"),
5147 &self.validator_os
.as_ref().map_or("None", |_
| "Some(FnMut)"),
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
);
5158 #[cfg(feature = "env")]
5160 ds
= ds
.field("env", &self.env
);
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
;
5170 #[derive(Debug, Clone, Eq, PartialEq)]
5171 pub(crate) enum ArgProvider
{
5177 impl Default
for ArgProvider
{
5178 fn default() -> Self {
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
>
5186 F
: FnMut(&str, bool
) -> Result
<T
, E
>,
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
)
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)?
;
5206 write(&delim
, false)?
;
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)?
;
5219 if (num_val_names
== 1 && mult_val
)
5220 || (arg
.is_positional() && mult_occ
)
5221 || num_val_names
< arg
.num_vals
.unwrap_or(0)
5223 write("...", true)?
;
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)?
;
5233 write(&delim
, false)?
;
5236 } else if arg
.is_positional() {
5237 // Value of positional argument with no num_vals and val_names.
5238 write(&format
!("<{}>", arg
.name
), true)?
;
5240 if mult_val
|| mult_occ
{
5241 write("...", true)?
;
5244 // value of flag argument with no num_vals and val_names.
5245 write(&format
!("<{}>", arg
.name
), true)?
;
5247 write("...", true)?
;
5253 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
5254 pub(crate) enum DisplayOrder
{
5261 pub(crate) fn set_explicit(&mut self, explicit
: usize) {
5262 *self = Self::Explicit(explicit
)
5265 pub(crate) fn set_implicit(&mut self, implicit
: usize) {
5266 *self = (*self).max(Self::Implicit(implicit
))
5269 pub(crate) fn make_explicit(&mut self) {
5271 Self::None
| Self::Explicit(_
) => {}
5272 Self::Implicit(disp
) => self.set_explicit(disp
),
5276 pub(crate) fn get_explicit(self) -> usize {
5278 Self::None
| Self::Implicit(_
) => 999,
5279 Self::Explicit(disp
) => disp
,
5284 impl Default
for DisplayOrder
{
5285 fn default() -> Self {
5297 let mut f
= Arg
::new("flg").multiple_occurrences(true);
5298 f
.long
= Some("flag");
5300 assert_eq
!(f
.to_string(), "--flag");
5302 let mut f2
= Arg
::new("flg");
5303 f2
.short
= Some('f'
);
5305 assert_eq
!(f2
.to_string(), "-f");
5309 fn flag_display_single_alias() {
5310 let mut f
= Arg
::new("flg");
5311 f
.long
= Some("flag");
5312 f
.aliases
= vec
![("als", true)];
5314 assert_eq
!(f
.to_string(), "--flag")
5318 fn flag_display_multiple_aliases() {
5319 let mut f
= Arg
::new("flg");
5320 f
.short
= Some('f'
);
5322 ("alias_not_visible", false),
5327 assert_eq
!(f
.to_string(), "-f");
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)];
5336 assert_eq
!(f
.to_string(), "-a")
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");
5350 fn option_display_multiple_occurrences() {
5351 let o
= Arg
::new("opt")
5354 .multiple_occurrences(true);
5356 assert_eq
!(o
.to_string(), "--option <opt>");
5360 fn option_display_multiple_values() {
5361 let o
= Arg
::new("opt")
5364 .multiple_values(true);
5366 assert_eq
!(o
.to_string(), "--option <opt>...");
5370 fn option_display2() {
5371 let o2
= Arg
::new("opt").short('o'
).value_names(&["file", "name"]);
5373 assert_eq
!(o2
.to_string(), "-o <file> <name>");
5377 fn option_display3() {
5378 let o2
= Arg
::new("opt")
5381 .multiple_values(true)
5382 .value_names(&["file", "name"]);
5384 assert_eq
!(o2
.to_string(), "-o <file> <name>");
5388 fn option_display_single_alias() {
5389 let o
= Arg
::new("opt")
5392 .visible_alias("als");
5394 assert_eq
!(o
.to_string(), "--option <opt>");
5398 fn option_display_multiple_aliases() {
5399 let o
= Arg
::new("opt")
5402 .visible_aliases(&["als2", "als3", "als4"])
5403 .alias("als_not_visible");
5405 assert_eq
!(o
.to_string(), "--option <opt>");
5409 fn option_display_single_short_alias() {
5410 let o
= Arg
::new("opt")
5413 .visible_short_alias('b'
);
5415 assert_eq
!(o
.to_string(), "-a <opt>");
5419 fn option_display_multiple_short_aliases() {
5420 let o
= Arg
::new("opt")
5423 .visible_short_aliases(&['b'
, 'c'
, 'd'
])
5426 assert_eq
!(o
.to_string(), "-a <opt>");
5432 fn positional_display_multiple_values() {
5433 let p
= Arg
::new("pos")
5436 .multiple_values(true);
5438 assert_eq
!(p
.to_string(), "<pos>...");
5442 fn positional_display_multiple_occurrences() {
5443 let p
= Arg
::new("pos")
5446 .multiple_occurrences(true);
5448 assert_eq
!(p
.to_string(), "<pos>...");
5452 fn positional_display_required() {
5453 let p2
= Arg
::new("pos").index(1).required(true);
5455 assert_eq
!(p2
.to_string(), "<pos>");
5459 fn positional_display_val_names() {
5460 let p2
= Arg
::new("pos").index(1).value_names(&["file1", "file2"]);
5462 assert_eq
!(p2
.to_string(), "<file1> <file2>");
5466 fn positional_display_val_names_req() {
5467 let p2
= Arg
::new("pos")
5470 .value_names(&["file1", "file2"]);
5472 assert_eq
!(p2
.to_string(), "<file1> <file2>");