clap_builder/builder/
arg.rs

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