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    /// # Examples
1661    ///
1662    /// ```rust
1663    /// # use clap_builder as clap;
1664    /// # use clap::{Command, Arg};
1665    /// let m = Command::new("prog")
1666    ///     .arg(Arg::new("config")
1667    ///         .short('c')
1668    ///         .long("config")
1669    ///         .value_delimiter(','))
1670    ///     .get_matches_from(vec![
1671    ///         "prog", "--config=val1,val2,val3"
1672    ///     ]);
1673    ///
1674    /// assert_eq!(m.get_many::<String>("config").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"])
1675    /// ```
1676    /// [`Arg::value_delimiter(',')`]: Arg::value_delimiter()
1677    /// [`Arg::action(ArgAction::Set)`]: Arg::action()
1678    #[inline]
1679    #[must_use]
1680    pub fn value_delimiter(mut self, d: impl IntoResettable<char>) -> Self {
1681        self.val_delim = d.into_resettable().into_option();
1682        self
1683    }
1684
1685    /// Sentinel to **stop** parsing multiple values of a given argument.
1686    ///
1687    /// By default when
1688    /// one sets [`num_args(1..)`] on an argument, clap will continue parsing values for that
1689    /// argument until it reaches another valid argument, or one of the other more specific settings
1690    /// for multiple values is used (such as [`num_args`]).
1691    ///
1692    /// <div class="warning">
1693    ///
1694    /// **NOTE:** This setting only applies to [options] and [positional arguments]
1695    ///
1696    /// </div>
1697    ///
1698    /// <div class="warning">
1699    ///
1700    /// **NOTE:** When the terminator is passed in on the command line, it is **not** stored as one
1701    /// of the values
1702    ///
1703    /// </div>
1704    ///
1705    /// # Examples
1706    ///
1707    /// ```rust
1708    /// # use clap_builder as clap;
1709    /// # use clap::{Command, Arg, ArgAction};
1710    /// Arg::new("vals")
1711    ///     .action(ArgAction::Set)
1712    ///     .num_args(1..)
1713    ///     .value_terminator(";")
1714    /// # ;
1715    /// ```
1716    ///
1717    /// The following example uses two arguments, a sequence of commands, and the location in which
1718    /// to perform them
1719    ///
1720    /// ```rust
1721    /// # use clap_builder as clap;
1722    /// # use clap::{Command, Arg, ArgAction};
1723    /// let m = Command::new("prog")
1724    ///     .arg(Arg::new("cmds")
1725    ///         .action(ArgAction::Set)
1726    ///         .num_args(1..)
1727    ///         .allow_hyphen_values(true)
1728    ///         .value_terminator(";"))
1729    ///     .arg(Arg::new("location"))
1730    ///     .get_matches_from(vec![
1731    ///         "prog", "find", "-type", "f", "-name", "special", ";", "/home/clap"
1732    ///     ]);
1733    /// let cmds: Vec<_> = m.get_many::<String>("cmds").unwrap().collect();
1734    /// assert_eq!(&cmds, &["find", "-type", "f", "-name", "special"]);
1735    /// assert_eq!(m.get_one::<String>("location").unwrap(), "/home/clap");
1736    /// ```
1737    /// [options]: Arg::action
1738    /// [positional arguments]: Arg::index()
1739    /// [`num_args(1..)`]: Arg::num_args()
1740    /// [`num_args`]: Arg::num_args()
1741    #[inline]
1742    #[must_use]
1743    pub fn value_terminator(mut self, term: impl IntoResettable<Str>) -> Self {
1744        self.terminator = term.into_resettable().into_option();
1745        self
1746    }
1747
1748    /// Consume all following arguments.
1749    ///
1750    /// Do not parse them individually, but rather pass them in entirety.
1751    ///
1752    /// It is worth noting that setting this requires all values to come after a `--` to indicate
1753    /// they should all be captured. For example:
1754    ///
1755    /// ```text
1756    /// --foo something -- -v -v -v -b -b -b --baz -q -u -x
1757    /// ```
1758    ///
1759    /// Will result in everything after `--` to be considered one raw argument. This behavior
1760    /// may not be exactly what you are expecting and using [`Arg::trailing_var_arg`]
1761    /// may be more appropriate.
1762    ///
1763    /// <div class="warning">
1764    ///
1765    /// **NOTE:** Implicitly sets [`Arg::action(ArgAction::Set)`] [`Arg::num_args(1..)`],
1766    ///
1767    /// </div>
1768    ///
1769    /// [`Arg::allow_hyphen_values(true)`], and [`Arg::last(true)`] when set to `true`.
1770    ///
1771    /// [`Arg::action(ArgAction::Set)`]: Arg::action()
1772    /// [`Arg::num_args(1..)`]: Arg::num_args()
1773    /// [`Arg::allow_hyphen_values(true)`]: Arg::allow_hyphen_values()
1774    /// [`Arg::last(true)`]: Arg::last()
1775    #[inline]
1776    #[must_use]
1777    pub fn raw(mut self, yes: bool) -> Self {
1778        if yes {
1779            self.num_vals.get_or_insert_with(|| (1..).into());
1780        }
1781        self.allow_hyphen_values(yes).last(yes)
1782    }
1783
1784    /// Value for the argument when not present.
1785    ///
1786    /// Like with command-line values, this will be split by [`Arg::value_delimiter`].
1787    ///
1788    /// <div class="warning">
1789    ///
1790    /// **NOTE:** If the user *does not* use this argument at runtime [`ArgMatches::contains_id`] will
1791    /// still return `true`. If you wish to determine whether the argument was used at runtime or
1792    /// not, consider [`ArgMatches::value_source`][crate::ArgMatches::value_source].
1793    ///
1794    /// </div>
1795    ///
1796    /// <div class="warning">
1797    ///
1798    /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value_if`] but slightly
1799    /// different. `Arg::default_value` *only* takes effect when the user has not provided this arg
1800    /// at runtime. `Arg::default_value_if` however only takes effect when the user has not provided
1801    /// a value at runtime **and** these other conditions are met as well. If you have set
1802    /// `Arg::default_value` and `Arg::default_value_if`, and the user **did not** provide this arg
1803    /// at runtime, nor were the conditions met for `Arg::default_value_if`, the `Arg::default_value`
1804    /// will be applied.
1805    ///
1806    /// </div>
1807    ///
1808    /// # Examples
1809    ///
1810    /// First we use the default value without providing any value at runtime.
1811    ///
1812    /// ```rust
1813    /// # use clap_builder as clap;
1814    /// # use clap::{Command, Arg, parser::ValueSource};
1815    /// let m = Command::new("prog")
1816    ///     .arg(Arg::new("opt")
1817    ///         .long("myopt")
1818    ///         .default_value("myval"))
1819    ///     .get_matches_from(vec![
1820    ///         "prog"
1821    ///     ]);
1822    ///
1823    /// assert_eq!(m.get_one::<String>("opt").unwrap(), "myval");
1824    /// assert!(m.contains_id("opt"));
1825    /// assert_eq!(m.value_source("opt"), Some(ValueSource::DefaultValue));
1826    /// ```
1827    ///
1828    /// Next we provide a value at runtime to override the default.
1829    ///
1830    /// ```rust
1831    /// # use clap_builder as clap;
1832    /// # use clap::{Command, Arg, parser::ValueSource};
1833    /// let m = Command::new("prog")
1834    ///     .arg(Arg::new("opt")
1835    ///         .long("myopt")
1836    ///         .default_value("myval"))
1837    ///     .get_matches_from(vec![
1838    ///         "prog", "--myopt=non_default"
1839    ///     ]);
1840    ///
1841    /// assert_eq!(m.get_one::<String>("opt").unwrap(), "non_default");
1842    /// assert!(m.contains_id("opt"));
1843    /// assert_eq!(m.value_source("opt"), Some(ValueSource::CommandLine));
1844    /// ```
1845    /// [`Arg::action(ArgAction::Set)`]: Arg::action()
1846    /// [`ArgMatches::contains_id`]: crate::ArgMatches::contains_id()
1847    /// [`Arg::default_value_if`]: Arg::default_value_if()
1848    #[inline]
1849    #[must_use]
1850    pub fn default_value(mut self, val: impl IntoResettable<OsStr>) -> Self {
1851        if let Some(val) = val.into_resettable().into_option() {
1852            self.default_values([val])
1853        } else {
1854            self.default_vals.clear();
1855            self
1856        }
1857    }
1858
1859    #[inline]
1860    #[must_use]
1861    #[doc(hidden)]
1862    #[cfg_attr(
1863        feature = "deprecated",
1864        deprecated(since = "4.0.0", note = "Replaced with `Arg::default_value`")
1865    )]
1866    pub fn default_value_os(self, val: impl Into<OsStr>) -> Self {
1867        self.default_values([val])
1868    }
1869
1870    /// Value for the argument when not present.
1871    ///
1872    /// See [`Arg::default_value`].
1873    ///
1874    /// [`Arg::default_value`]: Arg::default_value()
1875    #[inline]
1876    #[must_use]
1877    pub fn default_values(mut self, vals: impl IntoIterator<Item = impl Into<OsStr>>) -> Self {
1878        self.default_vals = vals.into_iter().map(|s| s.into()).collect();
1879        self
1880    }
1881
1882    #[inline]
1883    #[must_use]
1884    #[doc(hidden)]
1885    #[cfg_attr(
1886        feature = "deprecated",
1887        deprecated(since = "4.0.0", note = "Replaced with `Arg::default_values`")
1888    )]
1889    pub fn default_values_os(self, vals: impl IntoIterator<Item = impl Into<OsStr>>) -> Self {
1890        self.default_values(vals)
1891    }
1892
1893    /// Value for the argument when the flag is present but no value is specified.
1894    ///
1895    /// This configuration option is often used to give the user a shortcut and allow them to
1896    /// efficiently specify an option argument without requiring an explicitly value. The `--color`
1897    /// argument is a common example. By supplying a default, such as `default_missing_value("always")`,
1898    /// the user can quickly just add `--color` to the command line to produce the desired color output.
1899    ///
1900    /// Like with command-line values, this will be split by [`Arg::value_delimiter`].
1901    ///
1902    /// <div class="warning">
1903    ///
1904    /// **NOTE:** using this configuration option requires the use of the
1905    /// [`.num_args(0..N)`][Arg::num_args] and the
1906    /// [`.require_equals(true)`][Arg::require_equals] configuration option. These are required in
1907    /// order to unambiguously determine what, if any, value was supplied for the argument.
1908    ///
1909    /// </div>
1910    ///
1911    /// # Examples
1912    ///
1913    /// For POSIX style `--color`:
1914    /// ```rust
1915    /// # use clap_builder as clap;
1916    /// # use clap::{Command, Arg, parser::ValueSource};
1917    /// fn cli() -> Command {
1918    ///     Command::new("prog")
1919    ///         .arg(Arg::new("color").long("color")
1920    ///             .value_name("WHEN")
1921    ///             .value_parser(["always", "auto", "never"])
1922    ///             .default_value("auto")
1923    ///             .num_args(0..=1)
1924    ///             .require_equals(true)
1925    ///             .default_missing_value("always")
1926    ///             .help("Specify WHEN to colorize output.")
1927    ///         )
1928    /// }
1929    ///
1930    /// // first, we'll provide no arguments
1931    /// let m  = cli().get_matches_from(vec![
1932    ///         "prog"
1933    ///     ]);
1934    /// assert_eq!(m.get_one::<String>("color").unwrap(), "auto");
1935    /// assert_eq!(m.value_source("color"), Some(ValueSource::DefaultValue));
1936    ///
1937    /// // next, we'll provide a runtime value to override the default (as usually done).
1938    /// let m  = cli().get_matches_from(vec![
1939    ///         "prog", "--color=never"
1940    ///     ]);
1941    /// assert_eq!(m.get_one::<String>("color").unwrap(), "never");
1942    /// assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine));
1943    ///
1944    /// // finally, we will use the shortcut and only provide the argument without a value.
1945    /// let m  = cli().get_matches_from(vec![
1946    ///         "prog", "--color"
1947    ///     ]);
1948    /// assert_eq!(m.get_one::<String>("color").unwrap(), "always");
1949    /// assert_eq!(m.value_source("color"), Some(ValueSource::CommandLine));
1950    /// ```
1951    ///
1952    /// For bool literals:
1953    /// ```rust
1954    /// # use clap_builder as clap;
1955    /// # use clap::{Command, Arg, parser::ValueSource, value_parser};
1956    /// fn cli() -> Command {
1957    ///     Command::new("prog")
1958    ///         .arg(Arg::new("create").long("create")
1959    ///             .value_name("BOOL")
1960    ///             .value_parser(value_parser!(bool))
1961    ///             .num_args(0..=1)
1962    ///             .require_equals(true)
1963    ///             .default_missing_value("true")
1964    ///         )
1965    /// }
1966    ///
1967    /// // first, we'll provide no arguments
1968    /// let m  = cli().get_matches_from(vec![
1969    ///         "prog"
1970    ///     ]);
1971    /// assert_eq!(m.get_one::<bool>("create").copied(), None);
1972    ///
1973    /// // next, we'll provide a runtime value to override the default (as usually done).
1974    /// let m  = cli().get_matches_from(vec![
1975    ///         "prog", "--create=false"
1976    ///     ]);
1977    /// assert_eq!(m.get_one::<bool>("create").copied(), Some(false));
1978    /// assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine));
1979    ///
1980    /// // finally, we will use the shortcut and only provide the argument without a value.
1981    /// let m  = cli().get_matches_from(vec![
1982    ///         "prog", "--create"
1983    ///     ]);
1984    /// assert_eq!(m.get_one::<bool>("create").copied(), Some(true));
1985    /// assert_eq!(m.value_source("create"), Some(ValueSource::CommandLine));
1986    /// ```
1987    ///
1988    /// [`Arg::action(ArgAction::Set)`]: Arg::action()
1989    /// [`Arg::default_value`]: Arg::default_value()
1990    #[inline]
1991    #[must_use]
1992    pub fn default_missing_value(mut self, val: impl IntoResettable<OsStr>) -> Self {
1993        if let Some(val) = val.into_resettable().into_option() {
1994            self.default_missing_values_os([val])
1995        } else {
1996            self.default_missing_vals.clear();
1997            self
1998        }
1999    }
2000
2001    /// Value for the argument when the flag is present but no value is specified.
2002    ///
2003    /// See [`Arg::default_missing_value`].
2004    ///
2005    /// [`Arg::default_missing_value`]: Arg::default_missing_value()
2006    /// [`OsStr`]: std::ffi::OsStr
2007    #[inline]
2008    #[must_use]
2009    pub fn default_missing_value_os(self, val: impl Into<OsStr>) -> Self {
2010        self.default_missing_values_os([val])
2011    }
2012
2013    /// Value for the argument when the flag is present but no value is specified.
2014    ///
2015    /// See [`Arg::default_missing_value`].
2016    ///
2017    /// [`Arg::default_missing_value`]: Arg::default_missing_value()
2018    #[inline]
2019    #[must_use]
2020    pub fn default_missing_values(self, vals: impl IntoIterator<Item = impl Into<OsStr>>) -> Self {
2021        self.default_missing_values_os(vals)
2022    }
2023
2024    /// Value for the argument when the flag is present but no value is specified.
2025    ///
2026    /// See [`Arg::default_missing_values`].
2027    ///
2028    /// [`Arg::default_missing_values`]: Arg::default_missing_values()
2029    /// [`OsStr`]: std::ffi::OsStr
2030    #[inline]
2031    #[must_use]
2032    pub fn default_missing_values_os(
2033        mut self,
2034        vals: impl IntoIterator<Item = impl Into<OsStr>>,
2035    ) -> Self {
2036        self.default_missing_vals = vals.into_iter().map(|s| s.into()).collect();
2037        self
2038    }
2039
2040    /// Read from `name` environment variable when argument is not present.
2041    ///
2042    /// If it is not present in the environment, then default
2043    /// rules will apply.
2044    ///
2045    /// If user sets the argument in the environment:
2046    /// - When [`Arg::action(ArgAction::Set)`] is not set, the flag is considered raised.
2047    /// - When [`Arg::action(ArgAction::Set)`] is set,
2048    ///   [`ArgMatches::get_one`][crate::ArgMatches::get_one] will
2049    ///   return value of the environment variable.
2050    ///
2051    /// If user doesn't set the argument in the environment:
2052    /// - When [`Arg::action(ArgAction::Set)`] is not set, the flag is considered off.
2053    /// - When [`Arg::action(ArgAction::Set)`] is set,
2054    ///   [`ArgMatches::get_one`][crate::ArgMatches::get_one] will
2055    ///   return the default specified.
2056    ///
2057    /// Like with command-line values, this will be split by [`Arg::value_delimiter`].
2058    ///
2059    /// # Examples
2060    ///
2061    /// In this example, we show the variable coming from the environment:
2062    ///
2063    /// ```rust
2064    /// # use clap_builder as clap;
2065    /// # use std::env;
2066    /// # use clap::{Command, Arg, ArgAction};
2067    ///
2068    /// env::set_var("MY_FLAG", "env");
2069    ///
2070    /// let m = Command::new("prog")
2071    ///     .arg(Arg::new("flag")
2072    ///         .long("flag")
2073    ///         .env("MY_FLAG")
2074    ///         .action(ArgAction::Set))
2075    ///     .get_matches_from(vec![
2076    ///         "prog"
2077    ///     ]);
2078    ///
2079    /// assert_eq!(m.get_one::<String>("flag").unwrap(), "env");
2080    /// ```
2081    ///
2082    /// In this example, because `prog` is a flag that accepts an optional, case-insensitive
2083    /// boolean literal.
2084    ///
2085    /// Note that the value parser controls how flags are parsed.  In this case we've selected
2086    /// [`FalseyValueParser`][crate::builder::FalseyValueParser].  A `false` literal is `n`, `no`,
2087    /// `f`, `false`, `off` or `0`.  An absent environment variable will also be considered as
2088    /// `false`.  Anything else will considered as `true`.
2089    ///
2090    /// ```rust
2091    /// # use clap_builder as clap;
2092    /// # use std::env;
2093    /// # use clap::{Command, Arg, ArgAction};
2094    /// # use clap::builder::FalseyValueParser;
2095    ///
2096    /// env::set_var("TRUE_FLAG", "true");
2097    /// env::set_var("FALSE_FLAG", "0");
2098    ///
2099    /// let m = Command::new("prog")
2100    ///     .arg(Arg::new("true_flag")
2101    ///         .long("true_flag")
2102    ///         .action(ArgAction::SetTrue)
2103    ///         .value_parser(FalseyValueParser::new())
2104    ///         .env("TRUE_FLAG"))
2105    ///     .arg(Arg::new("false_flag")
2106    ///         .long("false_flag")
2107    ///         .action(ArgAction::SetTrue)
2108    ///         .value_parser(FalseyValueParser::new())
2109    ///         .env("FALSE_FLAG"))
2110    ///     .arg(Arg::new("absent_flag")
2111    ///         .long("absent_flag")
2112    ///         .action(ArgAction::SetTrue)
2113    ///         .value_parser(FalseyValueParser::new())
2114    ///         .env("ABSENT_FLAG"))
2115    ///     .get_matches_from(vec![
2116    ///         "prog"
2117    ///     ]);
2118    ///
2119    /// assert!(m.get_flag("true_flag"));
2120    /// assert!(!m.get_flag("false_flag"));
2121    /// assert!(!m.get_flag("absent_flag"));
2122    /// ```
2123    ///
2124    /// In this example, we show the variable coming from an option on the CLI:
2125    ///
2126    /// ```rust
2127    /// # use clap_builder as clap;
2128    /// # use std::env;
2129    /// # use clap::{Command, Arg, ArgAction};
2130    ///
2131    /// env::set_var("MY_FLAG", "env");
2132    ///
2133    /// let m = Command::new("prog")
2134    ///     .arg(Arg::new("flag")
2135    ///         .long("flag")
2136    ///         .env("MY_FLAG")
2137    ///         .action(ArgAction::Set))
2138    ///     .get_matches_from(vec![
2139    ///         "prog", "--flag", "opt"
2140    ///     ]);
2141    ///
2142    /// assert_eq!(m.get_one::<String>("flag").unwrap(), "opt");
2143    /// ```
2144    ///
2145    /// In this example, we show the variable coming from the environment even with the
2146    /// presence of a default:
2147    ///
2148    /// ```rust
2149    /// # use clap_builder as clap;
2150    /// # use std::env;
2151    /// # use clap::{Command, Arg, ArgAction};
2152    ///
2153    /// env::set_var("MY_FLAG", "env");
2154    ///
2155    /// let m = Command::new("prog")
2156    ///     .arg(Arg::new("flag")
2157    ///         .long("flag")
2158    ///         .env("MY_FLAG")
2159    ///         .action(ArgAction::Set)
2160    ///         .default_value("default"))
2161    ///     .get_matches_from(vec![
2162    ///         "prog"
2163    ///     ]);
2164    ///
2165    /// assert_eq!(m.get_one::<String>("flag").unwrap(), "env");
2166    /// ```
2167    ///
2168    /// In this example, we show the use of multiple values in a single environment variable:
2169    ///
2170    /// ```rust
2171    /// # use clap_builder as clap;
2172    /// # use std::env;
2173    /// # use clap::{Command, Arg, ArgAction};
2174    ///
2175    /// env::set_var("MY_FLAG_MULTI", "env1,env2");
2176    ///
2177    /// let m = Command::new("prog")
2178    ///     .arg(Arg::new("flag")
2179    ///         .long("flag")
2180    ///         .env("MY_FLAG_MULTI")
2181    ///         .action(ArgAction::Set)
2182    ///         .num_args(1..)
2183    ///         .value_delimiter(','))
2184    ///     .get_matches_from(vec![
2185    ///         "prog"
2186    ///     ]);
2187    ///
2188    /// assert_eq!(m.get_many::<String>("flag").unwrap().collect::<Vec<_>>(), vec!["env1", "env2"]);
2189    /// ```
2190    /// [`Arg::action(ArgAction::Set)`]: Arg::action()
2191    /// [`Arg::value_delimiter(',')`]: Arg::value_delimiter()
2192    #[cfg(feature = "env")]
2193    #[inline]
2194    #[must_use]
2195    pub fn env(mut self, name: impl IntoResettable<OsStr>) -> Self {
2196        if let Some(name) = name.into_resettable().into_option() {
2197            let value = env::var_os(&name);
2198            self.env = Some((name, value));
2199        } else {
2200            self.env = None;
2201        }
2202        self
2203    }
2204
2205    #[cfg(feature = "env")]
2206    #[doc(hidden)]
2207    #[cfg_attr(
2208        feature = "deprecated",
2209        deprecated(since = "4.0.0", note = "Replaced with `Arg::env`")
2210    )]
2211    pub fn env_os(self, name: impl Into<OsStr>) -> Self {
2212        self.env(name)
2213    }
2214}
2215
2216/// # Help
2217impl Arg {
2218    /// Sets the description of the argument for short help (`-h`).
2219    ///
2220    /// Typically, this is a short (one line) description of the arg.
2221    ///
2222    /// If [`Arg::long_help`] is not specified, this message will be displayed for `--help`.
2223    ///
2224    /// <div class="warning">
2225    ///
2226    /// **NOTE:** Only `Arg::help` is used in completion script generation in order to be concise
2227    ///
2228    /// </div>
2229    ///
2230    /// # Examples
2231    ///
2232    /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to
2233    /// include a newline in the help text and have the following text be properly aligned with all
2234    /// the other help text.
2235    ///
2236    /// Setting `help` displays a short message to the side of the argument when the user passes
2237    /// `-h` or `--help` (by default).
2238    ///
2239    /// ```rust
2240    /// # #[cfg(feature = "help")] {
2241    /// # use clap_builder as clap;
2242    /// # use clap::{Command, Arg};
2243    /// let m = Command::new("prog")
2244    ///     .arg(Arg::new("cfg")
2245    ///         .long("config")
2246    ///         .help("Some help text describing the --config arg"))
2247    ///     .get_matches_from(vec![
2248    ///         "prog", "--help"
2249    ///     ]);
2250    /// # }
2251    /// ```
2252    ///
2253    /// The above example displays
2254    ///
2255    /// ```notrust
2256    /// helptest
2257    ///
2258    /// Usage: helptest [OPTIONS]
2259    ///
2260    /// Options:
2261    ///     --config     Some help text describing the --config arg
2262    /// -h, --help       Print help information
2263    /// -V, --version    Print version information
2264    /// ```
2265    /// [`Arg::long_help`]: Arg::long_help()
2266    #[inline]
2267    #[must_use]
2268    pub fn help(mut self, h: impl IntoResettable<StyledStr>) -> Self {
2269        self.help = h.into_resettable().into_option();
2270        self
2271    }
2272
2273    /// Sets the description of the argument for long help (`--help`).
2274    ///
2275    /// Typically this a more detailed (multi-line) message
2276    /// that describes the arg.
2277    ///
2278    /// If [`Arg::help`] is not specified, this message will be displayed for `-h`.
2279    ///
2280    /// <div class="warning">
2281    ///
2282    /// **NOTE:** Only [`Arg::help`] is used in completion script generation in order to be concise
2283    ///
2284    /// </div>
2285    ///
2286    /// # Examples
2287    ///
2288    /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to
2289    /// include a newline in the help text and have the following text be properly aligned with all
2290    /// the other help text.
2291    ///
2292    /// Setting `help` displays a short message to the side of the argument when the user passes
2293    /// `-h` or `--help` (by default).
2294    ///
2295    /// ```rust
2296    /// # #[cfg(feature = "help")] {
2297    /// # use clap_builder as clap;
2298    /// # use clap::{Command, Arg};
2299    /// let m = Command::new("prog")
2300    ///     .arg(Arg::new("cfg")
2301    ///         .long("config")
2302    ///         .long_help(
2303    /// "The config file used by the myprog must be in JSON format
2304    /// with only valid keys and may not contain other nonsense
2305    /// that cannot be read by this program. Obviously I'm going on
2306    /// and on, so I'll stop now."))
2307    ///     .get_matches_from(vec![
2308    ///         "prog", "--help"
2309    ///     ]);
2310    /// # }
2311    /// ```
2312    ///
2313    /// The above example displays
2314    ///
2315    /// ```text
2316    /// prog
2317    ///
2318    /// Usage: prog [OPTIONS]
2319    ///
2320    /// Options:
2321    ///         --config
2322    ///             The config file used by the myprog must be in JSON format
2323    ///             with only valid keys and may not contain other nonsense
2324    ///             that cannot be read by this program. Obviously I'm going on
2325    ///             and on, so I'll stop now.
2326    ///
2327    ///     -h, --help
2328    ///             Print help information
2329    ///
2330    ///     -V, --version
2331    ///             Print version information
2332    /// ```
2333    /// [`Arg::help`]: Arg::help()
2334    #[inline]
2335    #[must_use]
2336    pub fn long_help(mut self, h: impl IntoResettable<StyledStr>) -> Self {
2337        self.long_help = h.into_resettable().into_option();
2338        self
2339    }
2340
2341    /// Allows custom ordering of args within the help message.
2342    ///
2343    /// `Arg`s with a lower value will be displayed first in the help message.
2344    /// Those with the same display order will be sorted.
2345    ///
2346    /// `Arg`s are automatically assigned a display order based on the order they are added to the
2347    /// [`Command`][crate::Command].
2348    /// Overriding this is helpful when the order arguments are added in isn't the same as the
2349    /// display order, whether in one-off cases or to automatically sort arguments.
2350    ///
2351    /// To change, see [`Command::next_display_order`][crate::Command::next_display_order].
2352    ///
2353    /// <div class="warning">
2354    ///
2355    /// **NOTE:** This setting is ignored for [positional arguments] which are always displayed in
2356    /// [index] order.
2357    ///
2358    /// </div>
2359    ///
2360    /// # Examples
2361    ///
2362    /// ```rust
2363    /// # #[cfg(feature = "help")] {
2364    /// # use clap_builder as clap;
2365    /// # use clap::{Command, Arg, ArgAction};
2366    /// let m = Command::new("prog")
2367    ///     .arg(Arg::new("boat")
2368    ///         .short('b')
2369    ///         .long("boat")
2370    ///         .action(ArgAction::Set)
2371    ///         .display_order(0)  // Sort
2372    ///         .help("Some help and text"))
2373    ///     .arg(Arg::new("airplane")
2374    ///         .short('a')
2375    ///         .long("airplane")
2376    ///         .action(ArgAction::Set)
2377    ///         .display_order(0)  // Sort
2378    ///         .help("I should be first!"))
2379    ///     .arg(Arg::new("custom-help")
2380    ///         .short('?')
2381    ///         .action(ArgAction::Help)
2382    ///         .display_order(100)  // Don't sort
2383    ///         .help("Alt help"))
2384    ///     .get_matches_from(vec![
2385    ///         "prog", "--help"
2386    ///     ]);
2387    /// # }
2388    /// ```
2389    ///
2390    /// The above example displays the following help message
2391    ///
2392    /// ```text
2393    /// cust-ord
2394    ///
2395    /// Usage: cust-ord [OPTIONS]
2396    ///
2397    /// Options:
2398    ///     -a, --airplane <airplane>    I should be first!
2399    ///     -b, --boat <boar>            Some help and text
2400    ///     -h, --help                   Print help information
2401    ///     -?                           Alt help
2402    /// ```
2403    /// [positional arguments]: Arg::index()
2404    /// [index]: Arg::index()
2405    #[inline]
2406    #[must_use]
2407    pub fn display_order(mut self, ord: impl IntoResettable<usize>) -> Self {
2408        self.disp_ord = ord.into_resettable().into_option();
2409        self
2410    }
2411
2412    /// Override the [current] help section.
2413    ///
2414    /// [current]: crate::Command::next_help_heading
2415    #[inline]
2416    #[must_use]
2417    pub fn help_heading(mut self, heading: impl IntoResettable<Str>) -> Self {
2418        self.help_heading = Some(heading.into_resettable().into_option());
2419        self
2420    }
2421
2422    /// Render the [help][Arg::help] on the line after the argument.
2423    ///
2424    /// This can be helpful for arguments with very long or complex help messages.
2425    /// This can also be helpful for arguments with very long flag names, or many/long value names.
2426    ///
2427    /// <div class="warning">
2428    ///
2429    /// **NOTE:** To apply this setting to all arguments and subcommands, consider using
2430    /// [`crate::Command::next_line_help`]
2431    ///
2432    /// </div>
2433    ///
2434    /// # Examples
2435    ///
2436    /// ```rust
2437    /// # #[cfg(feature = "help")] {
2438    /// # use clap_builder as clap;
2439    /// # use clap::{Command, Arg, ArgAction};
2440    /// let m = Command::new("prog")
2441    ///     .arg(Arg::new("opt")
2442    ///         .long("long-option-flag")
2443    ///         .short('o')
2444    ///         .action(ArgAction::Set)
2445    ///         .next_line_help(true)
2446    ///         .value_names(["value1", "value2"])
2447    ///         .help("Some really long help and complex\n\
2448    ///                help that makes more sense to be\n\
2449    ///                on a line after the option"))
2450    ///     .get_matches_from(vec![
2451    ///         "prog", "--help"
2452    ///     ]);
2453    /// # }
2454    /// ```
2455    ///
2456    /// The above example displays the following help message
2457    ///
2458    /// ```text
2459    /// nlh
2460    ///
2461    /// Usage: nlh [OPTIONS]
2462    ///
2463    /// Options:
2464    ///     -h, --help       Print help information
2465    ///     -V, --version    Print version information
2466    ///     -o, --long-option-flag <value1> <value2>
2467    ///         Some really long help and complex
2468    ///         help that makes more sense to be
2469    ///         on a line after the option
2470    /// ```
2471    #[inline]
2472    #[must_use]
2473    pub fn next_line_help(self, yes: bool) -> Self {
2474        if yes {
2475            self.setting(ArgSettings::NextLineHelp)
2476        } else {
2477            self.unset_setting(ArgSettings::NextLineHelp)
2478        }
2479    }
2480
2481    /// Do not display the argument in help message.
2482    ///
2483    /// <div class="warning">
2484    ///
2485    /// **NOTE:** This does **not** hide the argument from usage strings on error
2486    ///
2487    /// </div>
2488    ///
2489    /// # Examples
2490    ///
2491    /// Setting `Hidden` will hide the argument when displaying help text
2492    ///
2493    /// ```rust
2494    /// # #[cfg(feature = "help")] {
2495    /// # use clap_builder as clap;
2496    /// # use clap::{Command, Arg};
2497    /// let m = Command::new("prog")
2498    ///     .arg(Arg::new("cfg")
2499    ///         .long("config")
2500    ///         .hide(true)
2501    ///         .help("Some help text describing the --config arg"))
2502    ///     .get_matches_from(vec![
2503    ///         "prog", "--help"
2504    ///     ]);
2505    /// # }
2506    /// ```
2507    ///
2508    /// The above example displays
2509    ///
2510    /// ```text
2511    /// helptest
2512    ///
2513    /// Usage: helptest [OPTIONS]
2514    ///
2515    /// Options:
2516    /// -h, --help       Print help information
2517    /// -V, --version    Print version information
2518    /// ```
2519    #[inline]
2520    #[must_use]
2521    pub fn hide(self, yes: bool) -> Self {
2522        if yes {
2523            self.setting(ArgSettings::Hidden)
2524        } else {
2525            self.unset_setting(ArgSettings::Hidden)
2526        }
2527    }
2528
2529    /// Do not display the [possible values][crate::builder::ValueParser::possible_values] in the help message.
2530    ///
2531    /// This is useful for args with many values, or ones which are explained elsewhere in the
2532    /// help text.
2533    ///
2534    /// To set this for all arguments, see
2535    /// [`Command::hide_possible_values`][crate::Command::hide_possible_values].
2536    ///
2537    /// <div class="warning">
2538    ///
2539    /// **NOTE:** Setting this requires [taking values][Arg::num_args]
2540    ///
2541    /// </div>
2542    ///
2543    /// # Examples
2544    ///
2545    /// ```rust
2546    /// # use clap_builder as clap;
2547    /// # use clap::{Command, Arg, ArgAction};
2548    /// let m = Command::new("prog")
2549    ///     .arg(Arg::new("mode")
2550    ///         .long("mode")
2551    ///         .value_parser(["fast", "slow"])
2552    ///         .action(ArgAction::Set)
2553    ///         .hide_possible_values(true));
2554    /// ```
2555    /// If we were to run the above program with `--help` the `[values: fast, slow]` portion of
2556    /// the help text would be omitted.
2557    #[inline]
2558    #[must_use]
2559    pub fn hide_possible_values(self, yes: bool) -> Self {
2560        if yes {
2561            self.setting(ArgSettings::HidePossibleValues)
2562        } else {
2563            self.unset_setting(ArgSettings::HidePossibleValues)
2564        }
2565    }
2566
2567    /// Do not display the default value of the argument in the help message.
2568    ///
2569    /// This is useful when default behavior of an arg is explained elsewhere in the help text.
2570    ///
2571    /// <div class="warning">
2572    ///
2573    /// **NOTE:** Setting this requires [taking values][Arg::num_args]
2574    ///
2575    /// </div>
2576    ///
2577    /// # Examples
2578    ///
2579    /// ```rust
2580    /// # use clap_builder as clap;
2581    /// # use clap::{Command, Arg, ArgAction};
2582    /// let m = Command::new("connect")
2583    ///     .arg(Arg::new("host")
2584    ///         .long("host")
2585    ///         .default_value("localhost")
2586    ///         .action(ArgAction::Set)
2587    ///         .hide_default_value(true));
2588    ///
2589    /// ```
2590    ///
2591    /// If we were to run the above program with `--help` the `[default: localhost]` portion of
2592    /// the help text would be omitted.
2593    #[inline]
2594    #[must_use]
2595    pub fn hide_default_value(self, yes: bool) -> Self {
2596        if yes {
2597            self.setting(ArgSettings::HideDefaultValue)
2598        } else {
2599            self.unset_setting(ArgSettings::HideDefaultValue)
2600        }
2601    }
2602
2603    /// Do not display in help the environment variable name.
2604    ///
2605    /// This is useful when the variable option is explained elsewhere in the help text.
2606    ///
2607    /// # Examples
2608    ///
2609    /// ```rust
2610    /// # use clap_builder as clap;
2611    /// # use clap::{Command, Arg, ArgAction};
2612    /// let m = Command::new("prog")
2613    ///     .arg(Arg::new("mode")
2614    ///         .long("mode")
2615    ///         .env("MODE")
2616    ///         .action(ArgAction::Set)
2617    ///         .hide_env(true));
2618    /// ```
2619    ///
2620    /// If we were to run the above program with `--help` the `[env: MODE]` portion of the help
2621    /// text would be omitted.
2622    #[cfg(feature = "env")]
2623    #[inline]
2624    #[must_use]
2625    pub fn hide_env(self, yes: bool) -> Self {
2626        if yes {
2627            self.setting(ArgSettings::HideEnv)
2628        } else {
2629            self.unset_setting(ArgSettings::HideEnv)
2630        }
2631    }
2632
2633    /// Do not display in help any values inside the associated ENV variables for the argument.
2634    ///
2635    /// This is useful when ENV vars contain sensitive values.
2636    ///
2637    /// # Examples
2638    ///
2639    /// ```rust
2640    /// # use clap_builder as clap;
2641    /// # use clap::{Command, Arg, ArgAction};
2642    /// let m = Command::new("connect")
2643    ///     .arg(Arg::new("host")
2644    ///         .long("host")
2645    ///         .env("CONNECT")
2646    ///         .action(ArgAction::Set)
2647    ///         .hide_env_values(true));
2648    ///
2649    /// ```
2650    ///
2651    /// If we were to run the above program with `$ CONNECT=super_secret connect --help` the
2652    /// `[default: CONNECT=super_secret]` portion of the help text would be omitted.
2653    #[cfg(feature = "env")]
2654    #[inline]
2655    #[must_use]
2656    pub fn hide_env_values(self, yes: bool) -> Self {
2657        if yes {
2658            self.setting(ArgSettings::HideEnvValues)
2659        } else {
2660            self.unset_setting(ArgSettings::HideEnvValues)
2661        }
2662    }
2663
2664    /// Hides an argument from short help (`-h`).
2665    ///
2666    /// <div class="warning">
2667    ///
2668    /// **NOTE:** This does **not** hide the argument from usage strings on error
2669    ///
2670    /// </div>
2671    ///
2672    /// <div class="warning">
2673    ///
2674    /// **NOTE:** Setting this option will cause next-line-help output style to be used
2675    /// when long help (`--help`) is called.
2676    ///
2677    /// </div>
2678    ///
2679    /// # Examples
2680    ///
2681    /// ```rust
2682    /// # use clap_builder as clap;
2683    /// # use clap::{Command, Arg};
2684    /// Arg::new("debug")
2685    ///     .hide_short_help(true);
2686    /// ```
2687    ///
2688    /// Setting `hide_short_help(true)` will hide the argument when displaying short help text
2689    ///
2690    /// ```rust
2691    /// # #[cfg(feature = "help")] {
2692    /// # use clap_builder as clap;
2693    /// # use clap::{Command, Arg};
2694    /// let m = Command::new("prog")
2695    ///     .arg(Arg::new("cfg")
2696    ///         .long("config")
2697    ///         .hide_short_help(true)
2698    ///         .help("Some help text describing the --config arg"))
2699    ///     .get_matches_from(vec![
2700    ///         "prog", "-h"
2701    ///     ]);
2702    /// # }
2703    /// ```
2704    ///
2705    /// The above example displays
2706    ///
2707    /// ```text
2708    /// helptest
2709    ///
2710    /// Usage: helptest [OPTIONS]
2711    ///
2712    /// Options:
2713    /// -h, --help       Print help information
2714    /// -V, --version    Print version information
2715    /// ```
2716    ///
2717    /// However, when --help is called
2718    ///
2719    /// ```rust
2720    /// # #[cfg(feature = "help")] {
2721    /// # use clap_builder as clap;
2722    /// # use clap::{Command, Arg};
2723    /// let m = Command::new("prog")
2724    ///     .arg(Arg::new("cfg")
2725    ///         .long("config")
2726    ///         .hide_short_help(true)
2727    ///         .help("Some help text describing the --config arg"))
2728    ///     .get_matches_from(vec![
2729    ///         "prog", "--help"
2730    ///     ]);
2731    /// # }
2732    /// ```
2733    ///
2734    /// Then the following would be displayed
2735    ///
2736    /// ```text
2737    /// helptest
2738    ///
2739    /// Usage: helptest [OPTIONS]
2740    ///
2741    /// Options:
2742    ///     --config     Some help text describing the --config arg
2743    /// -h, --help       Print help information
2744    /// -V, --version    Print version information
2745    /// ```
2746    #[inline]
2747    #[must_use]
2748    pub fn hide_short_help(self, yes: bool) -> Self {
2749        if yes {
2750            self.setting(ArgSettings::HiddenShortHelp)
2751        } else {
2752            self.unset_setting(ArgSettings::HiddenShortHelp)
2753        }
2754    }
2755
2756    /// Hides an argument from long help (`--help`).
2757    ///
2758    /// <div class="warning">
2759    ///
2760    /// **NOTE:** This does **not** hide the argument from usage strings on error
2761    ///
2762    /// </div>
2763    ///
2764    /// <div class="warning">
2765    ///
2766    /// **NOTE:** Setting this option will cause next-line-help output style to be used
2767    /// when long help (`--help`) is called.
2768    ///
2769    /// </div>
2770    ///
2771    /// # Examples
2772    ///
2773    /// Setting `hide_long_help(true)` will hide the argument when displaying long help text
2774    ///
2775    /// ```rust
2776    /// # #[cfg(feature = "help")] {
2777    /// # use clap_builder as clap;
2778    /// # use clap::{Command, Arg};
2779    /// let m = Command::new("prog")
2780    ///     .arg(Arg::new("cfg")
2781    ///         .long("config")
2782    ///         .hide_long_help(true)
2783    ///         .help("Some help text describing the --config arg"))
2784    ///     .get_matches_from(vec![
2785    ///         "prog", "--help"
2786    ///     ]);
2787    /// # }
2788    /// ```
2789    ///
2790    /// The above example displays
2791    ///
2792    /// ```text
2793    /// helptest
2794    ///
2795    /// Usage: helptest [OPTIONS]
2796    ///
2797    /// Options:
2798    /// -h, --help       Print help information
2799    /// -V, --version    Print version information
2800    /// ```
2801    ///
2802    /// However, when -h is called
2803    ///
2804    /// ```rust
2805    /// # #[cfg(feature = "help")] {
2806    /// # use clap_builder as clap;
2807    /// # use clap::{Command, Arg};
2808    /// let m = Command::new("prog")
2809    ///     .arg(Arg::new("cfg")
2810    ///         .long("config")
2811    ///         .hide_long_help(true)
2812    ///         .help("Some help text describing the --config arg"))
2813    ///     .get_matches_from(vec![
2814    ///         "prog", "-h"
2815    ///     ]);
2816    /// # }
2817    /// ```
2818    ///
2819    /// Then the following would be displayed
2820    ///
2821    /// ```text
2822    /// helptest
2823    ///
2824    /// Usage: helptest [OPTIONS]
2825    ///
2826    /// OPTIONS:
2827    ///     --config     Some help text describing the --config arg
2828    /// -h, --help       Print help information
2829    /// -V, --version    Print version information
2830    /// ```
2831    #[inline]
2832    #[must_use]
2833    pub fn hide_long_help(self, yes: bool) -> Self {
2834        if yes {
2835            self.setting(ArgSettings::HiddenLongHelp)
2836        } else {
2837            self.unset_setting(ArgSettings::HiddenLongHelp)
2838        }
2839    }
2840}
2841
2842/// # Advanced Argument Relations
2843impl Arg {
2844    /// The name of the [`ArgGroup`] the argument belongs to.
2845    ///
2846    /// # Examples
2847    ///
2848    /// ```rust
2849    /// # use clap_builder as clap;
2850    /// # use clap::{Command, Arg, ArgAction};
2851    /// Arg::new("debug")
2852    ///     .long("debug")
2853    ///     .action(ArgAction::SetTrue)
2854    ///     .group("mode")
2855    /// # ;
2856    /// ```
2857    ///
2858    /// Multiple arguments can be a member of a single group and then the group checked as if it
2859    /// was one of said arguments.
2860    ///
2861    /// ```rust
2862    /// # use clap_builder as clap;
2863    /// # use clap::{Command, Arg, ArgAction};
2864    /// let m = Command::new("prog")
2865    ///     .arg(Arg::new("debug")
2866    ///         .long("debug")
2867    ///         .action(ArgAction::SetTrue)
2868    ///         .group("mode"))
2869    ///     .arg(Arg::new("verbose")
2870    ///         .long("verbose")
2871    ///         .action(ArgAction::SetTrue)
2872    ///         .group("mode"))
2873    ///     .get_matches_from(vec![
2874    ///         "prog", "--debug"
2875    ///     ]);
2876    /// assert!(m.contains_id("mode"));
2877    /// ```
2878    ///
2879    /// [`ArgGroup`]: crate::ArgGroup
2880    #[must_use]
2881    pub fn group(mut self, group_id: impl IntoResettable<Id>) -> Self {
2882        if let Some(group_id) = group_id.into_resettable().into_option() {
2883            self.groups.push(group_id);
2884        } else {
2885            self.groups.clear();
2886        }
2887        self
2888    }
2889
2890    /// The names of [`ArgGroup`]'s the argument belongs to.
2891    ///
2892    /// # Examples
2893    ///
2894    /// ```rust
2895    /// # use clap_builder as clap;
2896    /// # use clap::{Command, Arg, ArgAction};
2897    /// Arg::new("debug")
2898    ///     .long("debug")
2899    ///     .action(ArgAction::SetTrue)
2900    ///     .groups(["mode", "verbosity"])
2901    /// # ;
2902    /// ```
2903    ///
2904    /// Arguments can be members of multiple groups and then the group checked as if it
2905    /// was one of said arguments.
2906    ///
2907    /// ```rust
2908    /// # use clap_builder as clap;
2909    /// # use clap::{Command, Arg, ArgAction};
2910    /// let m = Command::new("prog")
2911    ///     .arg(Arg::new("debug")
2912    ///         .long("debug")
2913    ///         .action(ArgAction::SetTrue)
2914    ///         .groups(["mode", "verbosity"]))
2915    ///     .arg(Arg::new("verbose")
2916    ///         .long("verbose")
2917    ///         .action(ArgAction::SetTrue)
2918    ///         .groups(["mode", "verbosity"]))
2919    ///     .get_matches_from(vec![
2920    ///         "prog", "--debug"
2921    ///     ]);
2922    /// assert!(m.contains_id("mode"));
2923    /// assert!(m.contains_id("verbosity"));
2924    /// ```
2925    ///
2926    /// [`ArgGroup`]: crate::ArgGroup
2927    #[must_use]
2928    pub fn groups(mut self, group_ids: impl IntoIterator<Item = impl Into<Id>>) -> Self {
2929        self.groups.extend(group_ids.into_iter().map(Into::into));
2930        self
2931    }
2932
2933    /// Specifies the value of the argument if `arg` has been used at runtime.
2934    ///
2935    /// If `default` is set to `None`, `default_value` will be removed.
2936    ///
2937    /// Like with command-line values, this will be split by [`Arg::value_delimiter`].
2938    ///
2939    /// <div class="warning">
2940    ///
2941    /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value`] but slightly
2942    /// different. `Arg::default_value` *only* takes effect when the user has not provided this arg
2943    /// at runtime. This setting however only takes effect when the user has not provided a value at
2944    /// runtime **and** these other conditions are met as well. If you have set `Arg::default_value`
2945    /// and `Arg::default_value_if`, and the user **did not** provide this arg at runtime, nor were
2946    /// the conditions met for `Arg::default_value_if`, the `Arg::default_value` will be applied.
2947    ///
2948    /// </div>
2949    ///
2950    /// # Examples
2951    ///
2952    /// First we use the default value only if another arg is present at runtime.
2953    ///
2954    /// ```rust
2955    /// # use clap_builder as clap;
2956    /// # use clap::{Command, Arg, ArgAction};
2957    /// # use clap::builder::{ArgPredicate};
2958    /// let m = Command::new("prog")
2959    ///     .arg(Arg::new("flag")
2960    ///         .long("flag")
2961    ///         .action(ArgAction::SetTrue))
2962    ///     .arg(Arg::new("other")
2963    ///         .long("other")
2964    ///         .default_value_if("flag", ArgPredicate::IsPresent, Some("default")))
2965    ///     .get_matches_from(vec![
2966    ///         "prog", "--flag"
2967    ///     ]);
2968    ///
2969    /// assert_eq!(m.get_one::<String>("other").unwrap(), "default");
2970    /// ```
2971    ///
2972    /// Next we run the same test, but without providing `--flag`.
2973    ///
2974    /// ```rust
2975    /// # use clap_builder as clap;
2976    /// # use clap::{Command, Arg, ArgAction};
2977    /// let m = Command::new("prog")
2978    ///     .arg(Arg::new("flag")
2979    ///         .long("flag")
2980    ///         .action(ArgAction::SetTrue))
2981    ///     .arg(Arg::new("other")
2982    ///         .long("other")
2983    ///         .default_value_if("flag", "true", Some("default")))
2984    ///     .get_matches_from(vec![
2985    ///         "prog"
2986    ///     ]);
2987    ///
2988    /// assert_eq!(m.get_one::<String>("other"), None);
2989    /// ```
2990    ///
2991    /// Now lets only use the default value if `--opt` contains the value `special`.
2992    ///
2993    /// ```rust
2994    /// # use clap_builder as clap;
2995    /// # use clap::{Command, Arg, ArgAction};
2996    /// let m = Command::new("prog")
2997    ///     .arg(Arg::new("opt")
2998    ///         .action(ArgAction::Set)
2999    ///         .long("opt"))
3000    ///     .arg(Arg::new("other")
3001    ///         .long("other")
3002    ///         .default_value_if("opt", "special", Some("default")))
3003    ///     .get_matches_from(vec![
3004    ///         "prog", "--opt", "special"
3005    ///     ]);
3006    ///
3007    /// assert_eq!(m.get_one::<String>("other").unwrap(), "default");
3008    /// ```
3009    ///
3010    /// We can run the same test and provide any value *other than* `special` and we won't get a
3011    /// default value.
3012    ///
3013    /// ```rust
3014    /// # use clap_builder as clap;
3015    /// # use clap::{Command, Arg, ArgAction};
3016    /// let m = Command::new("prog")
3017    ///     .arg(Arg::new("opt")
3018    ///         .action(ArgAction::Set)
3019    ///         .long("opt"))
3020    ///     .arg(Arg::new("other")
3021    ///         .long("other")
3022    ///         .default_value_if("opt", "special", Some("default")))
3023    ///     .get_matches_from(vec![
3024    ///         "prog", "--opt", "hahaha"
3025    ///     ]);
3026    ///
3027    /// assert_eq!(m.get_one::<String>("other"), None);
3028    /// ```
3029    ///
3030    /// If we want to unset the default value for an Arg based on the presence or
3031    /// value of some other Arg.
3032    ///
3033    /// ```rust
3034    /// # use clap_builder as clap;
3035    /// # use clap::{Command, Arg, ArgAction};
3036    /// let m = Command::new("prog")
3037    ///     .arg(Arg::new("flag")
3038    ///         .long("flag")
3039    ///         .action(ArgAction::SetTrue))
3040    ///     .arg(Arg::new("other")
3041    ///         .long("other")
3042    ///         .default_value("default")
3043    ///         .default_value_if("flag", "true", None))
3044    ///     .get_matches_from(vec![
3045    ///         "prog", "--flag"
3046    ///     ]);
3047    ///
3048    /// assert_eq!(m.get_one::<String>("other"), None);
3049    /// ```
3050    /// [`Arg::action(ArgAction::Set)`]: Arg::action()
3051    /// [`Arg::default_value`]: Arg::default_value()
3052    #[must_use]
3053    pub fn default_value_if(
3054        mut self,
3055        arg_id: impl Into<Id>,
3056        predicate: impl Into<ArgPredicate>,
3057        default: impl IntoResettable<OsStr>,
3058    ) -> Self {
3059        self.default_vals_ifs.push((
3060            arg_id.into(),
3061            predicate.into(),
3062            default.into_resettable().into_option(),
3063        ));
3064        self
3065    }
3066
3067    #[must_use]
3068    #[doc(hidden)]
3069    #[cfg_attr(
3070        feature = "deprecated",
3071        deprecated(since = "4.0.0", note = "Replaced with `Arg::default_value_if`")
3072    )]
3073    pub fn default_value_if_os(
3074        self,
3075        arg_id: impl Into<Id>,
3076        predicate: impl Into<ArgPredicate>,
3077        default: impl IntoResettable<OsStr>,
3078    ) -> Self {
3079        self.default_value_if(arg_id, predicate, default)
3080    }
3081
3082    /// Specifies multiple values and conditions in the same manner as [`Arg::default_value_if`].
3083    ///
3084    /// The method takes a slice of tuples in the `(arg, predicate, default)` format.
3085    ///
3086    /// Like with command-line values, this will be split by [`Arg::value_delimiter`].
3087    ///
3088    /// <div class="warning">
3089    ///
3090    /// **NOTE**: The conditions are stored in order and evaluated in the same order. I.e. the first
3091    /// if multiple conditions are true, the first one found will be applied and the ultimate value.
3092    ///
3093    /// </div>
3094    ///
3095    /// # Examples
3096    ///
3097    /// First we use the default value only if another arg is present at runtime.
3098    ///
3099    /// ```rust
3100    /// # use clap_builder as clap;
3101    /// # use clap::{Command, Arg, ArgAction};
3102    /// let m = Command::new("prog")
3103    ///     .arg(Arg::new("flag")
3104    ///         .long("flag")
3105    ///         .action(ArgAction::SetTrue))
3106    ///     .arg(Arg::new("opt")
3107    ///         .long("opt")
3108    ///         .action(ArgAction::Set))
3109    ///     .arg(Arg::new("other")
3110    ///         .long("other")
3111    ///         .default_value_ifs([
3112    ///             ("flag", "true", Some("default")),
3113    ///             ("opt", "channal", Some("chan")),
3114    ///         ]))
3115    ///     .get_matches_from(vec![
3116    ///         "prog", "--opt", "channal"
3117    ///     ]);
3118    ///
3119    /// assert_eq!(m.get_one::<String>("other").unwrap(), "chan");
3120    /// ```
3121    ///
3122    /// Next we run the same test, but without providing `--flag`.
3123    ///
3124    /// ```rust
3125    /// # use clap_builder as clap;
3126    /// # use clap::{Command, Arg, ArgAction};
3127    /// let m = Command::new("prog")
3128    ///     .arg(Arg::new("flag")
3129    ///         .long("flag")
3130    ///         .action(ArgAction::SetTrue))
3131    ///     .arg(Arg::new("other")
3132    ///         .long("other")
3133    ///         .default_value_ifs([
3134    ///             ("flag", "true", Some("default")),
3135    ///             ("opt", "channal", Some("chan")),
3136    ///         ]))
3137    ///     .get_matches_from(vec![
3138    ///         "prog"
3139    ///     ]);
3140    ///
3141    /// assert_eq!(m.get_one::<String>("other"), None);
3142    /// ```
3143    ///
3144    /// We can also see that these values are applied in order, and if more than one condition is
3145    /// true, only the first evaluated "wins"
3146    ///
3147    /// ```rust
3148    /// # use clap_builder as clap;
3149    /// # use clap::{Command, Arg, ArgAction};
3150    /// # use clap::builder::ArgPredicate;
3151    /// let m = Command::new("prog")
3152    ///     .arg(Arg::new("flag")
3153    ///         .long("flag")
3154    ///         .action(ArgAction::SetTrue))
3155    ///     .arg(Arg::new("opt")
3156    ///         .long("opt")
3157    ///         .action(ArgAction::Set))
3158    ///     .arg(Arg::new("other")
3159    ///         .long("other")
3160    ///         .default_value_ifs([
3161    ///             ("flag", ArgPredicate::IsPresent, Some("default")),
3162    ///             ("opt", ArgPredicate::Equals("channal".into()), Some("chan")),
3163    ///         ]))
3164    ///     .get_matches_from(vec![
3165    ///         "prog", "--opt", "channal", "--flag"
3166    ///     ]);
3167    ///
3168    /// assert_eq!(m.get_one::<String>("other").unwrap(), "default");
3169    /// ```
3170    /// [`Arg::action(ArgAction::Set)`]: Arg::action()
3171    /// [`Arg::default_value_if`]: Arg::default_value_if()
3172    #[must_use]
3173    pub fn default_value_ifs(
3174        mut self,
3175        ifs: impl IntoIterator<
3176            Item = (
3177                impl Into<Id>,
3178                impl Into<ArgPredicate>,
3179                impl IntoResettable<OsStr>,
3180            ),
3181        >,
3182    ) -> Self {
3183        for (arg, predicate, default) in ifs {
3184            self = self.default_value_if(arg, predicate, default);
3185        }
3186        self
3187    }
3188
3189    #[must_use]
3190    #[doc(hidden)]
3191    #[cfg_attr(
3192        feature = "deprecated",
3193        deprecated(since = "4.0.0", note = "Replaced with `Arg::default_value_ifs`")
3194    )]
3195    pub fn default_value_ifs_os(
3196        self,
3197        ifs: impl IntoIterator<
3198            Item = (
3199                impl Into<Id>,
3200                impl Into<ArgPredicate>,
3201                impl IntoResettable<OsStr>,
3202            ),
3203        >,
3204    ) -> Self {
3205        self.default_value_ifs(ifs)
3206    }
3207
3208    /// Set this arg as [required] as long as the specified argument is not present at runtime.
3209    ///
3210    /// <div class="warning">
3211    ///
3212    /// **TIP:** Using `Arg::required_unless_present` implies [`Arg::required`] and is therefore not
3213    /// mandatory to also set.
3214    ///
3215    /// </div>
3216    ///
3217    /// # Examples
3218    ///
3219    /// ```rust
3220    /// # use clap_builder as clap;
3221    /// # use clap::Arg;
3222    /// Arg::new("config")
3223    ///     .required_unless_present("debug")
3224    /// # ;
3225    /// ```
3226    ///
3227    /// In the following example, the required argument is *not* provided,
3228    /// but it's not an error because the `unless` arg has been supplied.
3229    ///
3230    /// ```rust
3231    /// # use clap_builder as clap;
3232    /// # use clap::{Command, Arg, ArgAction};
3233    /// let res = Command::new("prog")
3234    ///     .arg(Arg::new("cfg")
3235    ///         .required_unless_present("dbg")
3236    ///         .action(ArgAction::Set)
3237    ///         .long("config"))
3238    ///     .arg(Arg::new("dbg")
3239    ///         .long("debug")
3240    ///         .action(ArgAction::SetTrue))
3241    ///     .try_get_matches_from(vec![
3242    ///         "prog", "--debug"
3243    ///     ]);
3244    ///
3245    /// assert!(res.is_ok());
3246    /// ```
3247    ///
3248    /// Setting `Arg::required_unless_present(name)` and *not* supplying `name` or this arg is an error.
3249    ///
3250    /// ```rust
3251    /// # use clap_builder as clap;
3252    /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
3253    /// let res = Command::new("prog")
3254    ///     .arg(Arg::new("cfg")
3255    ///         .required_unless_present("dbg")
3256    ///         .action(ArgAction::Set)
3257    ///         .long("config"))
3258    ///     .arg(Arg::new("dbg")
3259    ///         .long("debug"))
3260    ///     .try_get_matches_from(vec![
3261    ///         "prog"
3262    ///     ]);
3263    ///
3264    /// assert!(res.is_err());
3265    /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3266    /// ```
3267    /// [required]: Arg::required()
3268    #[must_use]
3269    pub fn required_unless_present(mut self, arg_id: impl IntoResettable<Id>) -> Self {
3270        if let Some(arg_id) = arg_id.into_resettable().into_option() {
3271            self.r_unless.push(arg_id);
3272        } else {
3273            self.r_unless.clear();
3274        }
3275        self
3276    }
3277
3278    /// Sets this arg as [required] unless *all* of the specified arguments are present at runtime.
3279    ///
3280    /// In other words, parsing will succeed only if user either
3281    /// * supplies the `self` arg.
3282    /// * supplies *all* of the `names` arguments.
3283    ///
3284    /// <div class="warning">
3285    ///
3286    /// **NOTE:** If you wish for this argument to only be required unless *any of* these args are
3287    /// present see [`Arg::required_unless_present_any`]
3288    ///
3289    /// </div>
3290    ///
3291    /// # Examples
3292    ///
3293    /// ```rust
3294    /// # use clap_builder as clap;
3295    /// # use clap::Arg;
3296    /// Arg::new("config")
3297    ///     .required_unless_present_all(["cfg", "dbg"])
3298    /// # ;
3299    /// ```
3300    ///
3301    /// In the following example, the required argument is *not* provided, but it's not an error
3302    /// because *all* of the `names` args have been supplied.
3303    ///
3304    /// ```rust
3305    /// # use clap_builder as clap;
3306    /// # use clap::{Command, Arg, ArgAction};
3307    /// let res = Command::new("prog")
3308    ///     .arg(Arg::new("cfg")
3309    ///         .required_unless_present_all(["dbg", "infile"])
3310    ///         .action(ArgAction::Set)
3311    ///         .long("config"))
3312    ///     .arg(Arg::new("dbg")
3313    ///         .long("debug")
3314    ///         .action(ArgAction::SetTrue))
3315    ///     .arg(Arg::new("infile")
3316    ///         .short('i')
3317    ///         .action(ArgAction::Set))
3318    ///     .try_get_matches_from(vec![
3319    ///         "prog", "--debug", "-i", "file"
3320    ///     ]);
3321    ///
3322    /// assert!(res.is_ok());
3323    /// ```
3324    ///
3325    /// Setting [`Arg::required_unless_present_all(names)`] and *not* supplying
3326    /// either *all* of `unless` args or the `self` arg is an error.
3327    ///
3328    /// ```rust
3329    /// # use clap_builder as clap;
3330    /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
3331    /// let res = Command::new("prog")
3332    ///     .arg(Arg::new("cfg")
3333    ///         .required_unless_present_all(["dbg", "infile"])
3334    ///         .action(ArgAction::Set)
3335    ///         .long("config"))
3336    ///     .arg(Arg::new("dbg")
3337    ///         .long("debug")
3338    ///         .action(ArgAction::SetTrue))
3339    ///     .arg(Arg::new("infile")
3340    ///         .short('i')
3341    ///         .action(ArgAction::Set))
3342    ///     .try_get_matches_from(vec![
3343    ///         "prog"
3344    ///     ]);
3345    ///
3346    /// assert!(res.is_err());
3347    /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3348    /// ```
3349    /// [required]: Arg::required()
3350    /// [`Arg::required_unless_present_any`]: Arg::required_unless_present_any()
3351    /// [`Arg::required_unless_present_all(names)`]: Arg::required_unless_present_all()
3352    #[must_use]
3353    pub fn required_unless_present_all(
3354        mut self,
3355        names: impl IntoIterator<Item = impl Into<Id>>,
3356    ) -> Self {
3357        self.r_unless_all.extend(names.into_iter().map(Into::into));
3358        self
3359    }
3360
3361    /// Sets this arg as [required] unless *any* of the specified arguments are present at runtime.
3362    ///
3363    /// In other words, parsing will succeed only if user either
3364    /// * supplies the `self` arg.
3365    /// * supplies *one or more* of the `unless` arguments.
3366    ///
3367    /// <div class="warning">
3368    ///
3369    /// **NOTE:** If you wish for this argument to be required unless *all of* these args are
3370    /// present see [`Arg::required_unless_present_all`]
3371    ///
3372    /// </div>
3373    ///
3374    /// # Examples
3375    ///
3376    /// ```rust
3377    /// # use clap_builder as clap;
3378    /// # use clap::Arg;
3379    /// Arg::new("config")
3380    ///     .required_unless_present_any(["cfg", "dbg"])
3381    /// # ;
3382    /// ```
3383    ///
3384    /// Setting [`Arg::required_unless_present_any(names)`] requires that the argument be used at runtime
3385    /// *unless* *at least one of* the args in `names` are present. In the following example, the
3386    /// required argument is *not* provided, but it's not an error because one the `unless` args
3387    /// have been supplied.
3388    ///
3389    /// ```rust
3390    /// # use clap_builder as clap;
3391    /// # use clap::{Command, Arg, ArgAction};
3392    /// let res = Command::new("prog")
3393    ///     .arg(Arg::new("cfg")
3394    ///         .required_unless_present_any(["dbg", "infile"])
3395    ///         .action(ArgAction::Set)
3396    ///         .long("config"))
3397    ///     .arg(Arg::new("dbg")
3398    ///         .long("debug")
3399    ///         .action(ArgAction::SetTrue))
3400    ///     .arg(Arg::new("infile")
3401    ///         .short('i')
3402    ///         .action(ArgAction::Set))
3403    ///     .try_get_matches_from(vec![
3404    ///         "prog", "--debug"
3405    ///     ]);
3406    ///
3407    /// assert!(res.is_ok());
3408    /// ```
3409    ///
3410    /// Setting [`Arg::required_unless_present_any(names)`] and *not* supplying *at least one of* `names`
3411    /// or this arg is an error.
3412    ///
3413    /// ```rust
3414    /// # use clap_builder as clap;
3415    /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
3416    /// let res = Command::new("prog")
3417    ///     .arg(Arg::new("cfg")
3418    ///         .required_unless_present_any(["dbg", "infile"])
3419    ///         .action(ArgAction::Set)
3420    ///         .long("config"))
3421    ///     .arg(Arg::new("dbg")
3422    ///         .long("debug")
3423    ///         .action(ArgAction::SetTrue))
3424    ///     .arg(Arg::new("infile")
3425    ///         .short('i')
3426    ///         .action(ArgAction::Set))
3427    ///     .try_get_matches_from(vec![
3428    ///         "prog"
3429    ///     ]);
3430    ///
3431    /// assert!(res.is_err());
3432    /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3433    /// ```
3434    /// [required]: Arg::required()
3435    /// [`Arg::required_unless_present_any(names)`]: Arg::required_unless_present_any()
3436    /// [`Arg::required_unless_present_all`]: Arg::required_unless_present_all()
3437    #[must_use]
3438    pub fn required_unless_present_any(
3439        mut self,
3440        names: impl IntoIterator<Item = impl Into<Id>>,
3441    ) -> Self {
3442        self.r_unless.extend(names.into_iter().map(Into::into));
3443        self
3444    }
3445
3446    /// This argument is [required] only if the specified `arg` is present at runtime and its value
3447    /// equals `val`.
3448    ///
3449    /// # Examples
3450    ///
3451    /// ```rust
3452    /// # use clap_builder as clap;
3453    /// # use clap::Arg;
3454    /// Arg::new("config")
3455    ///     .required_if_eq("other_arg", "value")
3456    /// # ;
3457    /// ```
3458    ///
3459    /// ```rust
3460    /// # use clap_builder as clap;
3461    /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
3462    /// let res = Command::new("prog")
3463    ///     .arg(Arg::new("cfg")
3464    ///         .action(ArgAction::Set)
3465    ///         .required_if_eq("other", "special")
3466    ///         .long("config"))
3467    ///     .arg(Arg::new("other")
3468    ///         .long("other")
3469    ///         .action(ArgAction::Set))
3470    ///     .try_get_matches_from(vec![
3471    ///         "prog", "--other", "not-special"
3472    ///     ]);
3473    ///
3474    /// assert!(res.is_ok()); // We didn't use --other=special, so "cfg" wasn't required
3475    ///
3476    /// let res = Command::new("prog")
3477    ///     .arg(Arg::new("cfg")
3478    ///         .action(ArgAction::Set)
3479    ///         .required_if_eq("other", "special")
3480    ///         .long("config"))
3481    ///     .arg(Arg::new("other")
3482    ///         .long("other")
3483    ///         .action(ArgAction::Set))
3484    ///     .try_get_matches_from(vec![
3485    ///         "prog", "--other", "special"
3486    ///     ]);
3487    ///
3488    /// // We did use --other=special so "cfg" had become required but was missing.
3489    /// assert!(res.is_err());
3490    /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3491    ///
3492    /// let res = Command::new("prog")
3493    ///     .arg(Arg::new("cfg")
3494    ///         .action(ArgAction::Set)
3495    ///         .required_if_eq("other", "special")
3496    ///         .long("config"))
3497    ///     .arg(Arg::new("other")
3498    ///         .long("other")
3499    ///         .action(ArgAction::Set))
3500    ///     .try_get_matches_from(vec![
3501    ///         "prog", "--other", "SPECIAL"
3502    ///     ]);
3503    ///
3504    /// // By default, the comparison is case-sensitive, so "cfg" wasn't required
3505    /// assert!(res.is_ok());
3506    ///
3507    /// let res = Command::new("prog")
3508    ///     .arg(Arg::new("cfg")
3509    ///         .action(ArgAction::Set)
3510    ///         .required_if_eq("other", "special")
3511    ///         .long("config"))
3512    ///     .arg(Arg::new("other")
3513    ///         .long("other")
3514    ///         .ignore_case(true)
3515    ///         .action(ArgAction::Set))
3516    ///     .try_get_matches_from(vec![
3517    ///         "prog", "--other", "SPECIAL"
3518    ///     ]);
3519    ///
3520    /// // However, case-insensitive comparisons can be enabled.  This typically occurs when using Arg::possible_values().
3521    /// assert!(res.is_err());
3522    /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3523    /// ```
3524    /// [`Arg::requires(name)`]: Arg::requires()
3525    /// [Conflicting]: Arg::conflicts_with()
3526    /// [required]: Arg::required()
3527    #[must_use]
3528    pub fn required_if_eq(mut self, arg_id: impl Into<Id>, val: impl Into<OsStr>) -> Self {
3529        self.r_ifs.push((arg_id.into(), val.into()));
3530        self
3531    }
3532
3533    /// Specify this argument is [required] based on multiple conditions.
3534    ///
3535    /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become
3536    /// valid if one of the specified `arg`'s value equals its corresponding `val`.
3537    ///
3538    /// # Examples
3539    ///
3540    /// ```rust
3541    /// # use clap_builder as clap;
3542    /// # use clap::Arg;
3543    /// Arg::new("config")
3544    ///     .required_if_eq_any([
3545    ///         ("extra", "val"),
3546    ///         ("option", "spec")
3547    ///     ])
3548    /// # ;
3549    /// ```
3550    ///
3551    /// Setting `Arg::required_if_eq_any([(arg, val)])` makes this arg required if any of the `arg`s
3552    /// are used at runtime and it's corresponding value is equal to `val`. If the `arg`'s value is
3553    /// anything other than `val`, this argument isn't required.
3554    ///
3555    /// ```rust
3556    /// # use clap_builder as clap;
3557    /// # use clap::{Command, Arg, ArgAction};
3558    /// let res = Command::new("prog")
3559    ///     .arg(Arg::new("cfg")
3560    ///         .required_if_eq_any([
3561    ///             ("extra", "val"),
3562    ///             ("option", "spec")
3563    ///         ])
3564    ///         .action(ArgAction::Set)
3565    ///         .long("config"))
3566    ///     .arg(Arg::new("extra")
3567    ///         .action(ArgAction::Set)
3568    ///         .long("extra"))
3569    ///     .arg(Arg::new("option")
3570    ///         .action(ArgAction::Set)
3571    ///         .long("option"))
3572    ///     .try_get_matches_from(vec![
3573    ///         "prog", "--option", "other"
3574    ///     ]);
3575    ///
3576    /// assert!(res.is_ok()); // We didn't use --option=spec, or --extra=val so "cfg" isn't required
3577    /// ```
3578    ///
3579    /// Setting `Arg::required_if_eq_any([(arg, val)])` and having any of the `arg`s used with its
3580    /// value of `val` but *not* using this arg is an error.
3581    ///
3582    /// ```rust
3583    /// # use clap_builder as clap;
3584    /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
3585    /// let res = Command::new("prog")
3586    ///     .arg(Arg::new("cfg")
3587    ///         .required_if_eq_any([
3588    ///             ("extra", "val"),
3589    ///             ("option", "spec")
3590    ///         ])
3591    ///         .action(ArgAction::Set)
3592    ///         .long("config"))
3593    ///     .arg(Arg::new("extra")
3594    ///         .action(ArgAction::Set)
3595    ///         .long("extra"))
3596    ///     .arg(Arg::new("option")
3597    ///         .action(ArgAction::Set)
3598    ///         .long("option"))
3599    ///     .try_get_matches_from(vec![
3600    ///         "prog", "--option", "spec"
3601    ///     ]);
3602    ///
3603    /// assert!(res.is_err());
3604    /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3605    /// ```
3606    /// [`Arg::requires(name)`]: Arg::requires()
3607    /// [Conflicting]: Arg::conflicts_with()
3608    /// [required]: Arg::required()
3609    #[must_use]
3610    pub fn required_if_eq_any(
3611        mut self,
3612        ifs: impl IntoIterator<Item = (impl Into<Id>, impl Into<OsStr>)>,
3613    ) -> Self {
3614        self.r_ifs
3615            .extend(ifs.into_iter().map(|(id, val)| (id.into(), val.into())));
3616        self
3617    }
3618
3619    /// Specify this argument is [required] based on multiple conditions.
3620    ///
3621    /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become
3622    /// valid if every one of the specified `arg`'s value equals its corresponding `val`.
3623    ///
3624    /// # Examples
3625    ///
3626    /// ```rust
3627    /// # use clap_builder as clap;
3628    /// # use clap::Arg;
3629    /// Arg::new("config")
3630    ///     .required_if_eq_all([
3631    ///         ("extra", "val"),
3632    ///         ("option", "spec")
3633    ///     ])
3634    /// # ;
3635    /// ```
3636    ///
3637    /// Setting `Arg::required_if_eq_all([(arg, val)])` makes this arg required if all of the `arg`s
3638    /// are used at runtime and every value is equal to its corresponding `val`. If the `arg`'s value is
3639    /// anything other than `val`, this argument isn't required.
3640    ///
3641    /// ```rust
3642    /// # use clap_builder as clap;
3643    /// # use clap::{Command, Arg, ArgAction};
3644    /// let res = Command::new("prog")
3645    ///     .arg(Arg::new("cfg")
3646    ///         .required_if_eq_all([
3647    ///             ("extra", "val"),
3648    ///             ("option", "spec")
3649    ///         ])
3650    ///         .action(ArgAction::Set)
3651    ///         .long("config"))
3652    ///     .arg(Arg::new("extra")
3653    ///         .action(ArgAction::Set)
3654    ///         .long("extra"))
3655    ///     .arg(Arg::new("option")
3656    ///         .action(ArgAction::Set)
3657    ///         .long("option"))
3658    ///     .try_get_matches_from(vec![
3659    ///         "prog", "--option", "spec"
3660    ///     ]);
3661    ///
3662    /// assert!(res.is_ok()); // We didn't use --option=spec --extra=val so "cfg" isn't required
3663    /// ```
3664    ///
3665    /// Setting `Arg::required_if_eq_all([(arg, val)])` and having all of the `arg`s used with its
3666    /// value of `val` but *not* using this arg is an error.
3667    ///
3668    /// ```rust
3669    /// # use clap_builder as clap;
3670    /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
3671    /// let res = Command::new("prog")
3672    ///     .arg(Arg::new("cfg")
3673    ///         .required_if_eq_all([
3674    ///             ("extra", "val"),
3675    ///             ("option", "spec")
3676    ///         ])
3677    ///         .action(ArgAction::Set)
3678    ///         .long("config"))
3679    ///     .arg(Arg::new("extra")
3680    ///         .action(ArgAction::Set)
3681    ///         .long("extra"))
3682    ///     .arg(Arg::new("option")
3683    ///         .action(ArgAction::Set)
3684    ///         .long("option"))
3685    ///     .try_get_matches_from(vec![
3686    ///         "prog", "--extra", "val", "--option", "spec"
3687    ///     ]);
3688    ///
3689    /// assert!(res.is_err());
3690    /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3691    /// ```
3692    /// [required]: Arg::required()
3693    #[must_use]
3694    pub fn required_if_eq_all(
3695        mut self,
3696        ifs: impl IntoIterator<Item = (impl Into<Id>, impl Into<OsStr>)>,
3697    ) -> Self {
3698        self.r_ifs_all
3699            .extend(ifs.into_iter().map(|(id, val)| (id.into(), val.into())));
3700        self
3701    }
3702
3703    /// Require another argument if this arg matches the [`ArgPredicate`]
3704    ///
3705    /// This method takes `value, another_arg` pair. At runtime, clap will check
3706    /// if this arg (`self`) matches the [`ArgPredicate`].
3707    /// If it does, `another_arg` will be marked as required.
3708    ///
3709    /// # Examples
3710    ///
3711    /// ```rust
3712    /// # use clap_builder as clap;
3713    /// # use clap::Arg;
3714    /// Arg::new("config")
3715    ///     .requires_if("val", "arg")
3716    /// # ;
3717    /// ```
3718    ///
3719    /// Setting `Arg::requires_if(val, arg)` requires that the `arg` be used at runtime if the
3720    /// defining argument's value is equal to `val`. If the defining argument is anything other than
3721    /// `val`, the other argument isn't required.
3722    ///
3723    /// ```rust
3724    /// # use clap_builder as clap;
3725    /// # use clap::{Command, Arg, ArgAction};
3726    /// let res = Command::new("prog")
3727    ///     .arg(Arg::new("cfg")
3728    ///         .action(ArgAction::Set)
3729    ///         .requires_if("my.cfg", "other")
3730    ///         .long("config"))
3731    ///     .arg(Arg::new("other"))
3732    ///     .try_get_matches_from(vec![
3733    ///         "prog", "--config", "some.cfg"
3734    ///     ]);
3735    ///
3736    /// assert!(res.is_ok()); // We didn't use --config=my.cfg, so other wasn't required
3737    /// ```
3738    ///
3739    /// Setting `Arg::requires_if(val, arg)` and setting the value to `val` but *not* supplying
3740    /// `arg` is an error.
3741    ///
3742    /// ```rust
3743    /// # use clap_builder as clap;
3744    /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
3745    /// let res = Command::new("prog")
3746    ///     .arg(Arg::new("cfg")
3747    ///         .action(ArgAction::Set)
3748    ///         .requires_if("my.cfg", "input")
3749    ///         .long("config"))
3750    ///     .arg(Arg::new("input"))
3751    ///     .try_get_matches_from(vec![
3752    ///         "prog", "--config", "my.cfg"
3753    ///     ]);
3754    ///
3755    /// assert!(res.is_err());
3756    /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3757    /// ```
3758    /// [`Arg::requires(name)`]: Arg::requires()
3759    /// [Conflicting]: Arg::conflicts_with()
3760    /// [override]: Arg::overrides_with()
3761    #[must_use]
3762    pub fn requires_if(mut self, val: impl Into<ArgPredicate>, arg_id: impl Into<Id>) -> Self {
3763        self.requires.push((val.into(), arg_id.into()));
3764        self
3765    }
3766
3767    /// Allows multiple conditional requirements.
3768    ///
3769    /// The requirement will only become valid if this arg's value matches the
3770    /// [`ArgPredicate`].
3771    ///
3772    /// # Examples
3773    ///
3774    /// ```rust
3775    /// # use clap_builder as clap;
3776    /// # use clap::Arg;
3777    /// Arg::new("config")
3778    ///     .requires_ifs([
3779    ///         ("val", "arg"),
3780    ///         ("other_val", "arg2"),
3781    ///     ])
3782    /// # ;
3783    /// ```
3784    ///
3785    /// Setting `Arg::requires_ifs(["val", "arg"])` requires that the `arg` be used at runtime if the
3786    /// defining argument's value is equal to `val`. If the defining argument's value is anything other
3787    /// than `val`, `arg` isn't required.
3788    ///
3789    /// ```rust
3790    /// # use clap_builder as clap;
3791    /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
3792    /// let res = Command::new("prog")
3793    ///     .arg(Arg::new("cfg")
3794    ///         .action(ArgAction::Set)
3795    ///         .requires_ifs([
3796    ///             ("special.conf", "opt"),
3797    ///             ("other.conf", "other"),
3798    ///         ])
3799    ///         .long("config"))
3800    ///     .arg(Arg::new("opt")
3801    ///         .long("option")
3802    ///         .action(ArgAction::Set))
3803    ///     .arg(Arg::new("other"))
3804    ///     .try_get_matches_from(vec![
3805    ///         "prog", "--config", "special.conf"
3806    ///     ]);
3807    ///
3808    /// assert!(res.is_err()); // We  used --config=special.conf so --option <val> is required
3809    /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3810    /// ```
3811    ///
3812    /// Setting `Arg::requires_ifs` with [`ArgPredicate::IsPresent`] and *not* supplying all the
3813    /// arguments is an error.
3814    ///
3815    /// ```rust
3816    /// # use clap_builder as clap;
3817    /// # use clap::{Command, Arg, error::ErrorKind, ArgAction, builder::ArgPredicate};
3818    /// let res = Command::new("prog")
3819    ///     .arg(Arg::new("cfg")
3820    ///         .action(ArgAction::Set)
3821    ///         .requires_ifs([
3822    ///             (ArgPredicate::IsPresent, "input"),
3823    ///             (ArgPredicate::IsPresent, "output"),
3824    ///         ])
3825    ///         .long("config"))
3826    ///     .arg(Arg::new("input"))
3827    ///     .arg(Arg::new("output"))
3828    ///     .try_get_matches_from(vec![
3829    ///         "prog", "--config", "file.conf", "in.txt"
3830    ///     ]);
3831    ///
3832    /// assert!(res.is_err());
3833    /// // We didn't use output
3834    /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3835    /// ```
3836    ///
3837    /// [`Arg::requires(name)`]: Arg::requires()
3838    /// [Conflicting]: Arg::conflicts_with()
3839    /// [override]: Arg::overrides_with()
3840    #[must_use]
3841    pub fn requires_ifs(
3842        mut self,
3843        ifs: impl IntoIterator<Item = (impl Into<ArgPredicate>, impl Into<Id>)>,
3844    ) -> Self {
3845        self.requires
3846            .extend(ifs.into_iter().map(|(val, arg)| (val.into(), arg.into())));
3847        self
3848    }
3849
3850    #[doc(hidden)]
3851    #[cfg_attr(
3852        feature = "deprecated",
3853        deprecated(since = "4.0.0", note = "Replaced with `Arg::requires_ifs`")
3854    )]
3855    pub fn requires_all(self, ids: impl IntoIterator<Item = impl Into<Id>>) -> Self {
3856        self.requires_ifs(ids.into_iter().map(|id| (ArgPredicate::IsPresent, id)))
3857    }
3858
3859    /// This argument is mutually exclusive with the specified argument.
3860    ///
3861    /// <div class="warning">
3862    ///
3863    /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules
3864    /// only need to be set for one of the two arguments, they do not need to be set for each.
3865    ///
3866    /// </div>
3867    ///
3868    /// <div class="warning">
3869    ///
3870    /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments
3871    /// (i.e. if A conflicts with B, defining `A.conflicts_with(B)` is sufficient. You do not
3872    /// need to also do `B.conflicts_with(A)`)
3873    ///
3874    /// </div>
3875    ///
3876    /// <div class="warning">
3877    ///
3878    /// **NOTE:** [`Arg::conflicts_with_all(names)`] allows specifying an argument which conflicts with more than one argument.
3879    ///
3880    /// </div>
3881    ///
3882    /// <div class="warning">
3883    ///
3884    /// **NOTE** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument.
3885    ///
3886    /// </div>
3887    ///
3888    /// <div class="warning">
3889    ///
3890    /// **NOTE:** All arguments implicitly conflict with themselves.
3891    ///
3892    /// </div>
3893    ///
3894    /// # Examples
3895    ///
3896    /// ```rust
3897    /// # use clap_builder as clap;
3898    /// # use clap::Arg;
3899    /// Arg::new("config")
3900    ///     .conflicts_with("debug")
3901    /// # ;
3902    /// ```
3903    ///
3904    /// Setting conflicting argument, and having both arguments present at runtime is an error.
3905    ///
3906    /// ```rust
3907    /// # use clap_builder as clap;
3908    /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
3909    /// let res = Command::new("prog")
3910    ///     .arg(Arg::new("cfg")
3911    ///         .action(ArgAction::Set)
3912    ///         .conflicts_with("debug")
3913    ///         .long("config"))
3914    ///     .arg(Arg::new("debug")
3915    ///         .long("debug")
3916    ///         .action(ArgAction::SetTrue))
3917    ///     .try_get_matches_from(vec![
3918    ///         "prog", "--debug", "--config", "file.conf"
3919    ///     ]);
3920    ///
3921    /// assert!(res.is_err());
3922    /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict);
3923    /// ```
3924    ///
3925    /// [`Arg::conflicts_with_all(names)`]: Arg::conflicts_with_all()
3926    /// [`Arg::exclusive(true)`]: Arg::exclusive()
3927    #[must_use]
3928    pub fn conflicts_with(mut self, arg_id: impl IntoResettable<Id>) -> Self {
3929        if let Some(arg_id) = arg_id.into_resettable().into_option() {
3930            self.blacklist.push(arg_id);
3931        } else {
3932            self.blacklist.clear();
3933        }
3934        self
3935    }
3936
3937    /// This argument is mutually exclusive with the specified arguments.
3938    ///
3939    /// See [`Arg::conflicts_with`].
3940    ///
3941    /// <div class="warning">
3942    ///
3943    /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules
3944    /// only need to be set for one of the two arguments, they do not need to be set for each.
3945    ///
3946    /// </div>
3947    ///
3948    /// <div class="warning">
3949    ///
3950    /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments
3951    /// (i.e. if A conflicts with B, defining `A.conflicts_with(B)` is sufficient. You do not need
3952    /// need to also do `B.conflicts_with(A)`)
3953    ///
3954    /// </div>
3955    ///
3956    /// <div class="warning">
3957    ///
3958    /// **NOTE:** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument.
3959    ///
3960    /// </div>
3961    ///
3962    /// # Examples
3963    ///
3964    /// ```rust
3965    /// # use clap_builder as clap;
3966    /// # use clap::Arg;
3967    /// Arg::new("config")
3968    ///     .conflicts_with_all(["debug", "input"])
3969    /// # ;
3970    /// ```
3971    ///
3972    /// Setting conflicting argument, and having any of the arguments present at runtime with a
3973    /// conflicting argument is an error.
3974    ///
3975    /// ```rust
3976    /// # use clap_builder as clap;
3977    /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
3978    /// let res = Command::new("prog")
3979    ///     .arg(Arg::new("cfg")
3980    ///         .action(ArgAction::Set)
3981    ///         .conflicts_with_all(["debug", "input"])
3982    ///         .long("config"))
3983    ///     .arg(Arg::new("debug")
3984    ///         .long("debug"))
3985    ///     .arg(Arg::new("input"))
3986    ///     .try_get_matches_from(vec![
3987    ///         "prog", "--config", "file.conf", "file.txt"
3988    ///     ]);
3989    ///
3990    /// assert!(res.is_err());
3991    /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict);
3992    /// ```
3993    /// [`Arg::conflicts_with`]: Arg::conflicts_with()
3994    /// [`Arg::exclusive(true)`]: Arg::exclusive()
3995    #[must_use]
3996    pub fn conflicts_with_all(mut self, names: impl IntoIterator<Item = impl Into<Id>>) -> Self {
3997        self.blacklist.extend(names.into_iter().map(Into::into));
3998        self
3999    }
4000
4001    /// Sets an overridable argument.
4002    ///
4003    /// i.e. this argument and the following argument
4004    /// will override each other in POSIX style (whichever argument was specified at runtime
4005    /// **last** "wins")
4006    ///
4007    /// <div class="warning">
4008    ///
4009    /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any
4010    /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed
4011    ///
4012    /// </div>
4013    ///
4014    /// <div class="warning">
4015    ///
4016    /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with`].
4017    ///
4018    /// </div>
4019    ///
4020    /// # Examples
4021    ///
4022    /// ```rust
4023    /// # use clap_builder as clap;
4024    /// # use clap::{Command, arg};
4025    /// let m = Command::new("prog")
4026    ///     .arg(arg!(-f --flag "some flag")
4027    ///         .conflicts_with("debug"))
4028    ///     .arg(arg!(-d --debug "other flag"))
4029    ///     .arg(arg!(-c --color "third flag")
4030    ///         .overrides_with("flag"))
4031    ///     .get_matches_from(vec![
4032    ///         "prog", "-f", "-d", "-c"]);
4033    ///             //    ^~~~~~~~~~~~^~~~~ flag is overridden by color
4034    ///
4035    /// assert!(m.get_flag("color"));
4036    /// assert!(m.get_flag("debug")); // even though flag conflicts with debug, it's as if flag
4037    ///                                 // was never used because it was overridden with color
4038    /// assert!(!m.get_flag("flag"));
4039    /// ```
4040    #[must_use]
4041    pub fn overrides_with(mut self, arg_id: impl IntoResettable<Id>) -> Self {
4042        if let Some(arg_id) = arg_id.into_resettable().into_option() {
4043            self.overrides.push(arg_id);
4044        } else {
4045            self.overrides.clear();
4046        }
4047        self
4048    }
4049
4050    /// Sets multiple mutually overridable arguments by name.
4051    ///
4052    /// i.e. this argument and the following argument will override each other in POSIX style
4053    /// (whichever argument was specified at runtime **last** "wins")
4054    ///
4055    /// <div class="warning">
4056    ///
4057    /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any
4058    /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed
4059    ///
4060    /// </div>
4061    ///
4062    /// <div class="warning">
4063    ///
4064    /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with_all`].
4065    ///
4066    /// </div>
4067    ///
4068    /// # Examples
4069    ///
4070    /// ```rust
4071    /// # use clap_builder as clap;
4072    /// # use clap::{Command, arg};
4073    /// let m = Command::new("prog")
4074    ///     .arg(arg!(-f --flag "some flag")
4075    ///         .conflicts_with("color"))
4076    ///     .arg(arg!(-d --debug "other flag"))
4077    ///     .arg(arg!(-c --color "third flag")
4078    ///         .overrides_with_all(["flag", "debug"]))
4079    ///     .get_matches_from(vec![
4080    ///         "prog", "-f", "-d", "-c"]);
4081    ///             //    ^~~~~~^~~~~~~~~ flag and debug are overridden by color
4082    ///
4083    /// assert!(m.get_flag("color")); // even though flag conflicts with color, it's as if flag
4084    ///                                 // and debug were never used because they were overridden
4085    ///                                 // with color
4086    /// assert!(!m.get_flag("debug"));
4087    /// assert!(!m.get_flag("flag"));
4088    /// ```
4089    #[must_use]
4090    pub fn overrides_with_all(mut self, names: impl IntoIterator<Item = impl Into<Id>>) -> Self {
4091        self.overrides.extend(names.into_iter().map(Into::into));
4092        self
4093    }
4094}
4095
4096/// # Reflection
4097impl Arg {
4098    /// Get the name of the argument
4099    #[inline]
4100    pub fn get_id(&self) -> &Id {
4101        &self.id
4102    }
4103
4104    /// Get the help specified for this argument, if any
4105    #[inline]
4106    pub fn get_help(&self) -> Option<&StyledStr> {
4107        self.help.as_ref()
4108    }
4109
4110    /// Get the long help specified for this argument, if any
4111    ///
4112    /// # Examples
4113    ///
4114    /// ```rust
4115    /// # use clap_builder as clap;
4116    /// # use clap::Arg;
4117    /// let arg = Arg::new("foo").long_help("long help");
4118    /// assert_eq!(Some("long help".to_owned()), arg.get_long_help().map(|s| s.to_string()));
4119    /// ```
4120    ///
4121    #[inline]
4122    pub fn get_long_help(&self) -> Option<&StyledStr> {
4123        self.long_help.as_ref()
4124    }
4125
4126    /// Get the placement within help
4127    #[inline]
4128    pub fn get_display_order(&self) -> usize {
4129        self.disp_ord.unwrap_or(999)
4130    }
4131
4132    /// Get the help heading specified for this argument, if any
4133    #[inline]
4134    pub fn get_help_heading(&self) -> Option<&str> {
4135        self.help_heading
4136            .as_ref()
4137            .map(|s| s.as_deref())
4138            .unwrap_or_default()
4139    }
4140
4141    /// Get the short option name for this argument, if any
4142    #[inline]
4143    pub fn get_short(&self) -> Option<char> {
4144        self.short
4145    }
4146
4147    /// Get visible short aliases for this argument, if any
4148    #[inline]
4149    pub fn get_visible_short_aliases(&self) -> Option<Vec<char>> {
4150        if self.short_aliases.is_empty() {
4151            None
4152        } else {
4153            Some(
4154                self.short_aliases
4155                    .iter()
4156                    .filter_map(|(c, v)| if *v { Some(c) } else { None })
4157                    .copied()
4158                    .collect(),
4159            )
4160        }
4161    }
4162
4163    /// Get *all* short aliases for this argument, if any, both visible and hidden.
4164    #[inline]
4165    pub fn get_all_short_aliases(&self) -> Option<Vec<char>> {
4166        if self.short_aliases.is_empty() {
4167            None
4168        } else {
4169            Some(self.short_aliases.iter().map(|(s, _)| s).copied().collect())
4170        }
4171    }
4172
4173    /// Get the short option name and its visible aliases, if any
4174    #[inline]
4175    pub fn get_short_and_visible_aliases(&self) -> Option<Vec<char>> {
4176        let mut shorts = match self.short {
4177            Some(short) => vec![short],
4178            None => return None,
4179        };
4180        if let Some(aliases) = self.get_visible_short_aliases() {
4181            shorts.extend(aliases);
4182        }
4183        Some(shorts)
4184    }
4185
4186    /// Get the long option name for this argument, if any
4187    #[inline]
4188    pub fn get_long(&self) -> Option<&str> {
4189        self.long.as_deref()
4190    }
4191
4192    /// Get visible aliases for this argument, if any
4193    #[inline]
4194    pub fn get_visible_aliases(&self) -> Option<Vec<&str>> {
4195        if self.aliases.is_empty() {
4196            None
4197        } else {
4198            Some(
4199                self.aliases
4200                    .iter()
4201                    .filter_map(|(s, v)| if *v { Some(s.as_str()) } else { None })
4202                    .collect(),
4203            )
4204        }
4205    }
4206
4207    /// Get *all* aliases for this argument, if any, both visible and hidden.
4208    #[inline]
4209    pub fn get_all_aliases(&self) -> Option<Vec<&str>> {
4210        if self.aliases.is_empty() {
4211            None
4212        } else {
4213            Some(self.aliases.iter().map(|(s, _)| s.as_str()).collect())
4214        }
4215    }
4216
4217    /// Get the long option name and its visible aliases, if any
4218    #[inline]
4219    pub fn get_long_and_visible_aliases(&self) -> Option<Vec<&str>> {
4220        let mut longs = match self.get_long() {
4221            Some(long) => vec![long],
4222            None => return None,
4223        };
4224        if let Some(aliases) = self.get_visible_aliases() {
4225            longs.extend(aliases);
4226        }
4227        Some(longs)
4228    }
4229
4230    /// Get hidden aliases for this argument, if any
4231    #[inline]
4232    pub fn get_aliases(&self) -> Option<Vec<&str>> {
4233        if self.aliases.is_empty() {
4234            None
4235        } else {
4236            Some(
4237                self.aliases
4238                    .iter()
4239                    .filter_map(|(s, v)| if !*v { Some(s.as_str()) } else { None })
4240                    .collect(),
4241            )
4242        }
4243    }
4244
4245    /// Get the names of possible values for this argument. Only useful for user
4246    /// facing applications, such as building help messages or man files
4247    pub fn get_possible_values(&self) -> Vec<PossibleValue> {
4248        if !self.is_takes_value_set() {
4249            vec![]
4250        } else {
4251            self.get_value_parser()
4252                .possible_values()
4253                .map(|pvs| pvs.collect())
4254                .unwrap_or_default()
4255        }
4256    }
4257
4258    /// Get the names of values for this argument.
4259    #[inline]
4260    pub fn get_value_names(&self) -> Option<&[Str]> {
4261        if self.val_names.is_empty() {
4262            None
4263        } else {
4264            Some(&self.val_names)
4265        }
4266    }
4267
4268    /// Get the number of values for this argument.
4269    #[inline]
4270    pub fn get_num_args(&self) -> Option<ValueRange> {
4271        self.num_vals
4272    }
4273
4274    #[inline]
4275    pub(crate) fn get_min_vals(&self) -> usize {
4276        self.get_num_args().expect(INTERNAL_ERROR_MSG).min_values()
4277    }
4278
4279    /// Get the delimiter between multiple values
4280    #[inline]
4281    pub fn get_value_delimiter(&self) -> Option<char> {
4282        self.val_delim
4283    }
4284
4285    /// Get the value terminator for this argument. The `value_terminator` is a value
4286    /// that terminates parsing of multi-valued arguments.
4287    #[inline]
4288    pub fn get_value_terminator(&self) -> Option<&Str> {
4289        self.terminator.as_ref()
4290    }
4291
4292    /// Get the index of this argument, if any
4293    #[inline]
4294    pub fn get_index(&self) -> Option<usize> {
4295        self.index
4296    }
4297
4298    /// Get the value hint of this argument
4299    pub fn get_value_hint(&self) -> ValueHint {
4300        // HACK: we should use `Self::add` and `Self::remove` to type-check that `ArgExt` is used
4301        self.ext.get::<ValueHint>().copied().unwrap_or_else(|| {
4302            if self.is_takes_value_set() {
4303                let type_id = self.get_value_parser().type_id();
4304                if type_id == AnyValueId::of::<std::path::PathBuf>() {
4305                    ValueHint::AnyPath
4306                } else {
4307                    ValueHint::default()
4308                }
4309            } else {
4310                ValueHint::default()
4311            }
4312        })
4313    }
4314
4315    /// Get the environment variable name specified for this argument, if any
4316    ///
4317    /// # Examples
4318    ///
4319    /// ```rust
4320    /// # use clap_builder as clap;
4321    /// # use std::ffi::OsStr;
4322    /// # use clap::Arg;
4323    /// let arg = Arg::new("foo").env("ENVIRONMENT");
4324    /// assert_eq!(arg.get_env(), Some(OsStr::new("ENVIRONMENT")));
4325    /// ```
4326    #[cfg(feature = "env")]
4327    pub fn get_env(&self) -> Option<&std::ffi::OsStr> {
4328        self.env.as_ref().map(|x| x.0.as_os_str())
4329    }
4330
4331    /// Get the default values specified for this argument, if any
4332    ///
4333    /// # Examples
4334    ///
4335    /// ```rust
4336    /// # use clap_builder as clap;
4337    /// # use clap::Arg;
4338    /// let arg = Arg::new("foo").default_value("default value");
4339    /// assert_eq!(arg.get_default_values(), &["default value"]);
4340    /// ```
4341    pub fn get_default_values(&self) -> &[OsStr] {
4342        &self.default_vals
4343    }
4344
4345    /// Checks whether this argument is a positional or not.
4346    ///
4347    /// # Examples
4348    ///
4349    /// ```rust
4350    /// # use clap_builder as clap;
4351    /// # use clap::Arg;
4352    /// let arg = Arg::new("foo");
4353    /// assert_eq!(arg.is_positional(), true);
4354    ///
4355    /// let arg = Arg::new("foo").long("foo");
4356    /// assert_eq!(arg.is_positional(), false);
4357    /// ```
4358    pub fn is_positional(&self) -> bool {
4359        self.get_long().is_none() && self.get_short().is_none()
4360    }
4361
4362    /// Reports whether [`Arg::required`] is set
4363    pub fn is_required_set(&self) -> bool {
4364        self.is_set(ArgSettings::Required)
4365    }
4366
4367    pub(crate) fn is_multiple_values_set(&self) -> bool {
4368        self.get_num_args().unwrap_or_default().is_multiple()
4369    }
4370
4371    pub(crate) fn is_takes_value_set(&self) -> bool {
4372        self.get_num_args()
4373            .unwrap_or_else(|| 1.into())
4374            .takes_values()
4375    }
4376
4377    /// Report whether [`Arg::allow_hyphen_values`] is set
4378    pub fn is_allow_hyphen_values_set(&self) -> bool {
4379        self.is_set(ArgSettings::AllowHyphenValues)
4380    }
4381
4382    /// Report whether [`Arg::allow_negative_numbers`] is set
4383    pub fn is_allow_negative_numbers_set(&self) -> bool {
4384        self.is_set(ArgSettings::AllowNegativeNumbers)
4385    }
4386
4387    /// Behavior when parsing the argument
4388    pub fn get_action(&self) -> &ArgAction {
4389        const DEFAULT: ArgAction = ArgAction::Set;
4390        self.action.as_ref().unwrap_or(&DEFAULT)
4391    }
4392
4393    /// Configured parser for argument values
4394    ///
4395    /// # Example
4396    ///
4397    /// ```rust
4398    /// # use clap_builder as clap;
4399    /// let cmd = clap::Command::new("raw")
4400    ///     .arg(
4401    ///         clap::Arg::new("port")
4402    ///             .value_parser(clap::value_parser!(usize))
4403    ///     );
4404    /// let value_parser = cmd.get_arguments()
4405    ///     .find(|a| a.get_id() == "port").unwrap()
4406    ///     .get_value_parser();
4407    /// println!("{value_parser:?}");
4408    /// ```
4409    pub fn get_value_parser(&self) -> &super::ValueParser {
4410        if let Some(value_parser) = self.value_parser.as_ref() {
4411            value_parser
4412        } else {
4413            static DEFAULT: super::ValueParser = super::ValueParser::string();
4414            &DEFAULT
4415        }
4416    }
4417
4418    /// Report whether [`Arg::global`] is set
4419    pub fn is_global_set(&self) -> bool {
4420        self.is_set(ArgSettings::Global)
4421    }
4422
4423    /// Report whether [`Arg::next_line_help`] is set
4424    pub fn is_next_line_help_set(&self) -> bool {
4425        self.is_set(ArgSettings::NextLineHelp)
4426    }
4427
4428    /// Report whether [`Arg::hide`] is set
4429    pub fn is_hide_set(&self) -> bool {
4430        self.is_set(ArgSettings::Hidden)
4431    }
4432
4433    /// Report whether [`Arg::hide_default_value`] is set
4434    pub fn is_hide_default_value_set(&self) -> bool {
4435        self.is_set(ArgSettings::HideDefaultValue)
4436    }
4437
4438    /// Report whether [`Arg::hide_possible_values`] is set
4439    pub fn is_hide_possible_values_set(&self) -> bool {
4440        self.is_set(ArgSettings::HidePossibleValues)
4441    }
4442
4443    /// Report whether [`Arg::hide_env`] is set
4444    #[cfg(feature = "env")]
4445    pub fn is_hide_env_set(&self) -> bool {
4446        self.is_set(ArgSettings::HideEnv)
4447    }
4448
4449    /// Report whether [`Arg::hide_env_values`] is set
4450    #[cfg(feature = "env")]
4451    pub fn is_hide_env_values_set(&self) -> bool {
4452        self.is_set(ArgSettings::HideEnvValues)
4453    }
4454
4455    /// Report whether [`Arg::hide_short_help`] is set
4456    pub fn is_hide_short_help_set(&self) -> bool {
4457        self.is_set(ArgSettings::HiddenShortHelp)
4458    }
4459
4460    /// Report whether [`Arg::hide_long_help`] is set
4461    pub fn is_hide_long_help_set(&self) -> bool {
4462        self.is_set(ArgSettings::HiddenLongHelp)
4463    }
4464
4465    /// Report whether [`Arg::require_equals`] is set
4466    pub fn is_require_equals_set(&self) -> bool {
4467        self.is_set(ArgSettings::RequireEquals)
4468    }
4469
4470    /// Reports whether [`Arg::exclusive`] is set
4471    pub fn is_exclusive_set(&self) -> bool {
4472        self.is_set(ArgSettings::Exclusive)
4473    }
4474
4475    /// Report whether [`Arg::trailing_var_arg`] is set
4476    pub fn is_trailing_var_arg_set(&self) -> bool {
4477        self.is_set(ArgSettings::TrailingVarArg)
4478    }
4479
4480    /// Reports whether [`Arg::last`] is set
4481    pub fn is_last_set(&self) -> bool {
4482        self.is_set(ArgSettings::Last)
4483    }
4484
4485    /// Reports whether [`Arg::ignore_case`] is set
4486    pub fn is_ignore_case_set(&self) -> bool {
4487        self.is_set(ArgSettings::IgnoreCase)
4488    }
4489
4490    /// Access an [`ArgExt`]
4491    #[cfg(feature = "unstable-ext")]
4492    pub fn get<T: ArgExt + Extension>(&self) -> Option<&T> {
4493        self.ext.get::<T>()
4494    }
4495
4496    /// Remove an [`ArgExt`]
4497    #[cfg(feature = "unstable-ext")]
4498    pub fn remove<T: ArgExt + Extension>(mut self) -> Option<T> {
4499        self.ext.remove::<T>()
4500    }
4501}
4502
4503/// # Internally used only
4504impl Arg {
4505    pub(crate) fn _build(&mut self) {
4506        if self.action.is_none() {
4507            if self.num_vals == Some(ValueRange::EMPTY) {
4508                let action = ArgAction::SetTrue;
4509                self.action = Some(action);
4510            } else {
4511                let action =
4512                    if self.is_positional() && self.num_vals.unwrap_or_default().is_unbounded() {
4513                        // Allow collecting arguments interleaved with flags
4514                        //
4515                        // Bounded values are probably a group and the user should explicitly opt-in to
4516                        // Append
4517                        ArgAction::Append
4518                    } else {
4519                        ArgAction::Set
4520                    };
4521                self.action = Some(action);
4522            }
4523        }
4524        if let Some(action) = self.action.as_ref() {
4525            if let Some(default_value) = action.default_value() {
4526                if self.default_vals.is_empty() {
4527                    self.default_vals = vec![default_value.into()];
4528                }
4529            }
4530            if let Some(default_value) = action.default_missing_value() {
4531                if self.default_missing_vals.is_empty() {
4532                    self.default_missing_vals = vec![default_value.into()];
4533                }
4534            }
4535        }
4536
4537        if self.value_parser.is_none() {
4538            if let Some(default) = self.action.as_ref().and_then(|a| a.default_value_parser()) {
4539                self.value_parser = Some(default);
4540            } else {
4541                self.value_parser = Some(super::ValueParser::string());
4542            }
4543        }
4544
4545        let val_names_len = self.val_names.len();
4546        if val_names_len > 1 {
4547            self.num_vals.get_or_insert(val_names_len.into());
4548        } else {
4549            let nargs = self.get_action().default_num_args();
4550            self.num_vals.get_or_insert(nargs);
4551        }
4552    }
4553
4554    // Used for positionals when printing
4555    pub(crate) fn name_no_brackets(&self) -> String {
4556        debug!("Arg::name_no_brackets:{}", self.get_id());
4557        let delim = " ";
4558        if !self.val_names.is_empty() {
4559            debug!("Arg::name_no_brackets: val_names={:#?}", self.val_names);
4560
4561            if self.val_names.len() > 1 {
4562                self.val_names
4563                    .iter()
4564                    .map(|n| format!("<{n}>"))
4565                    .collect::<Vec<_>>()
4566                    .join(delim)
4567            } else {
4568                self.val_names
4569                    .first()
4570                    .expect(INTERNAL_ERROR_MSG)
4571                    .as_str()
4572                    .to_owned()
4573            }
4574        } else {
4575            debug!("Arg::name_no_brackets: just name");
4576            self.get_id().as_str().to_owned()
4577        }
4578    }
4579
4580    pub(crate) fn stylized(&self, styles: &Styles, required: Option<bool>) -> StyledStr {
4581        use std::fmt::Write as _;
4582        let literal = styles.get_literal();
4583
4584        let mut styled = StyledStr::new();
4585        // Write the name such --long or -l
4586        if let Some(l) = self.get_long() {
4587            let _ = write!(styled, "{literal}--{l}{literal:#}",);
4588        } else if let Some(s) = self.get_short() {
4589            let _ = write!(styled, "{literal}-{s}{literal:#}");
4590        }
4591        styled.push_styled(&self.stylize_arg_suffix(styles, required));
4592        styled
4593    }
4594
4595    pub(crate) fn stylize_arg_suffix(&self, styles: &Styles, required: Option<bool>) -> StyledStr {
4596        use std::fmt::Write as _;
4597        let literal = styles.get_literal();
4598        let placeholder = styles.get_placeholder();
4599        let mut styled = StyledStr::new();
4600
4601        let mut need_closing_bracket = false;
4602        if self.is_takes_value_set() && !self.is_positional() {
4603            let is_optional_val = self.get_min_vals() == 0;
4604            let (style, start) = if self.is_require_equals_set() {
4605                if is_optional_val {
4606                    need_closing_bracket = true;
4607                    (placeholder, "[=")
4608                } else {
4609                    (literal, "=")
4610                }
4611            } else if is_optional_val {
4612                need_closing_bracket = true;
4613                (placeholder, " [")
4614            } else {
4615                (placeholder, " ")
4616            };
4617            let _ = write!(styled, "{style}{start}{style:#}");
4618        }
4619        if self.is_takes_value_set() || self.is_positional() {
4620            let required = required.unwrap_or_else(|| self.is_required_set());
4621            let arg_val = self.render_arg_val(required);
4622            let _ = write!(styled, "{placeholder}{arg_val}{placeholder:#}",);
4623        } else if matches!(*self.get_action(), ArgAction::Count) {
4624            let _ = write!(styled, "{placeholder}...{placeholder:#}",);
4625        }
4626        if need_closing_bracket {
4627            let _ = write!(styled, "{placeholder}]{placeholder:#}",);
4628        }
4629
4630        styled
4631    }
4632
4633    /// Write the values such as `<name1> <name2>`
4634    fn render_arg_val(&self, required: bool) -> String {
4635        let mut rendered = String::new();
4636
4637        let num_vals = self.get_num_args().unwrap_or_else(|| 1.into());
4638
4639        let mut val_names = if self.val_names.is_empty() {
4640            vec![self.id.as_internal_str().to_owned()]
4641        } else {
4642            self.val_names.clone()
4643        };
4644        if val_names.len() == 1 {
4645            let min = num_vals.min_values().max(1);
4646            let val_name = val_names.pop().unwrap();
4647            val_names = vec![val_name; min];
4648        }
4649
4650        debug_assert!(self.is_takes_value_set());
4651        for (n, val_name) in val_names.iter().enumerate() {
4652            let arg_name = if self.is_positional() && (num_vals.min_values() == 0 || !required) {
4653                format!("[{val_name}]")
4654            } else {
4655                format!("<{val_name}>")
4656            };
4657
4658            if n != 0 {
4659                rendered.push(' ');
4660            }
4661            rendered.push_str(&arg_name);
4662        }
4663
4664        let mut extra_values = false;
4665        extra_values |= val_names.len() < num_vals.max_values();
4666        if self.is_positional() && matches!(*self.get_action(), ArgAction::Append) {
4667            extra_values = true;
4668        }
4669        if extra_values {
4670            rendered.push_str("...");
4671        }
4672
4673        rendered
4674    }
4675
4676    /// Either multiple values or occurrences
4677    pub(crate) fn is_multiple(&self) -> bool {
4678        self.is_multiple_values_set() || matches!(*self.get_action(), ArgAction::Append)
4679    }
4680}
4681
4682impl From<&'_ Arg> for Arg {
4683    fn from(a: &Arg) -> Self {
4684        a.clone()
4685    }
4686}
4687
4688impl PartialEq for Arg {
4689    fn eq(&self, other: &Arg) -> bool {
4690        self.get_id() == other.get_id()
4691    }
4692}
4693
4694impl PartialOrd for Arg {
4695    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
4696        Some(self.cmp(other))
4697    }
4698}
4699
4700impl Ord for Arg {
4701    fn cmp(&self, other: &Arg) -> Ordering {
4702        self.get_id().cmp(other.get_id())
4703    }
4704}
4705
4706impl Eq for Arg {}
4707
4708impl Display for Arg {
4709    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
4710        let plain = Styles::plain();
4711        self.stylized(&plain, None).fmt(f)
4712    }
4713}
4714
4715impl fmt::Debug for Arg {
4716    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
4717        let mut ds = f.debug_struct("Arg");
4718
4719        #[allow(unused_mut)]
4720        let mut ds = ds
4721            .field("id", &self.id)
4722            .field("help", &self.help)
4723            .field("long_help", &self.long_help)
4724            .field("action", &self.action)
4725            .field("value_parser", &self.value_parser)
4726            .field("blacklist", &self.blacklist)
4727            .field("settings", &self.settings)
4728            .field("overrides", &self.overrides)
4729            .field("groups", &self.groups)
4730            .field("requires", &self.requires)
4731            .field("r_ifs", &self.r_ifs)
4732            .field("r_unless", &self.r_unless)
4733            .field("short", &self.short)
4734            .field("long", &self.long)
4735            .field("aliases", &self.aliases)
4736            .field("short_aliases", &self.short_aliases)
4737            .field("disp_ord", &self.disp_ord)
4738            .field("val_names", &self.val_names)
4739            .field("num_vals", &self.num_vals)
4740            .field("val_delim", &self.val_delim)
4741            .field("default_vals", &self.default_vals)
4742            .field("default_vals_ifs", &self.default_vals_ifs)
4743            .field("terminator", &self.terminator)
4744            .field("index", &self.index)
4745            .field("help_heading", &self.help_heading)
4746            .field("default_missing_vals", &self.default_missing_vals)
4747            .field("ext", &self.ext);
4748
4749        #[cfg(feature = "env")]
4750        {
4751            ds = ds.field("env", &self.env);
4752        }
4753
4754        ds.finish()
4755    }
4756}
4757
4758/// User-provided data that can be attached to an [`Arg`]
4759#[cfg(feature = "unstable-ext")]
4760pub trait ArgExt: Extension {}
4761
4762// Flags
4763#[cfg(test)]
4764mod test {
4765    use super::Arg;
4766    use super::ArgAction;
4767
4768    #[test]
4769    fn flag_display_long() {
4770        let mut f = Arg::new("flg").long("flag").action(ArgAction::SetTrue);
4771        f._build();
4772
4773        assert_eq!(f.to_string(), "--flag");
4774    }
4775
4776    #[test]
4777    fn flag_display_short() {
4778        let mut f2 = Arg::new("flg").short('f').action(ArgAction::SetTrue);
4779        f2._build();
4780
4781        assert_eq!(f2.to_string(), "-f");
4782    }
4783
4784    #[test]
4785    fn flag_display_count() {
4786        let mut f2 = Arg::new("flg").long("flag").action(ArgAction::Count);
4787        f2._build();
4788
4789        assert_eq!(f2.to_string(), "--flag...");
4790    }
4791
4792    #[test]
4793    fn flag_display_single_alias() {
4794        let mut f = Arg::new("flg")
4795            .long("flag")
4796            .visible_alias("als")
4797            .action(ArgAction::SetTrue);
4798        f._build();
4799
4800        assert_eq!(f.to_string(), "--flag");
4801    }
4802
4803    #[test]
4804    fn flag_display_multiple_aliases() {
4805        let mut f = Arg::new("flg").short('f').action(ArgAction::SetTrue);
4806        f.aliases = vec![
4807            ("alias_not_visible".into(), false),
4808            ("f2".into(), true),
4809            ("f3".into(), true),
4810            ("f4".into(), true),
4811        ];
4812        f._build();
4813
4814        assert_eq!(f.to_string(), "-f");
4815    }
4816
4817    #[test]
4818    fn flag_display_single_short_alias() {
4819        let mut f = Arg::new("flg").short('a').action(ArgAction::SetTrue);
4820        f.short_aliases = vec![('b', true)];
4821        f._build();
4822
4823        assert_eq!(f.to_string(), "-a");
4824    }
4825
4826    #[test]
4827    fn flag_display_multiple_short_aliases() {
4828        let mut f = Arg::new("flg").short('a').action(ArgAction::SetTrue);
4829        f.short_aliases = vec![('b', false), ('c', true), ('d', true), ('e', true)];
4830        f._build();
4831
4832        assert_eq!(f.to_string(), "-a");
4833    }
4834
4835    // Options
4836
4837    #[test]
4838    fn option_display_multiple_occurrences() {
4839        let mut o = Arg::new("opt").long("option").action(ArgAction::Append);
4840        o._build();
4841
4842        assert_eq!(o.to_string(), "--option <opt>");
4843    }
4844
4845    #[test]
4846    fn option_display_multiple_values() {
4847        let mut o = Arg::new("opt")
4848            .long("option")
4849            .action(ArgAction::Set)
4850            .num_args(1..);
4851        o._build();
4852
4853        assert_eq!(o.to_string(), "--option <opt>...");
4854    }
4855
4856    #[test]
4857    fn option_display_zero_or_more_values() {
4858        let mut o = Arg::new("opt")
4859            .long("option")
4860            .action(ArgAction::Set)
4861            .num_args(0..);
4862        o._build();
4863
4864        assert_eq!(o.to_string(), "--option [<opt>...]");
4865    }
4866
4867    #[test]
4868    fn option_display_one_or_more_values() {
4869        let mut o = Arg::new("opt")
4870            .long("option")
4871            .action(ArgAction::Set)
4872            .num_args(1..);
4873        o._build();
4874
4875        assert_eq!(o.to_string(), "--option <opt>...");
4876    }
4877
4878    #[test]
4879    fn option_display_zero_or_more_values_with_value_name() {
4880        let mut o = Arg::new("opt")
4881            .short('o')
4882            .action(ArgAction::Set)
4883            .num_args(0..)
4884            .value_names(["file"]);
4885        o._build();
4886
4887        assert_eq!(o.to_string(), "-o [<file>...]");
4888    }
4889
4890    #[test]
4891    fn option_display_one_or_more_values_with_value_name() {
4892        let mut o = Arg::new("opt")
4893            .short('o')
4894            .action(ArgAction::Set)
4895            .num_args(1..)
4896            .value_names(["file"]);
4897        o._build();
4898
4899        assert_eq!(o.to_string(), "-o <file>...");
4900    }
4901
4902    #[test]
4903    fn option_display_optional_value() {
4904        let mut o = Arg::new("opt")
4905            .long("option")
4906            .action(ArgAction::Set)
4907            .num_args(0..=1);
4908        o._build();
4909
4910        assert_eq!(o.to_string(), "--option [<opt>]");
4911    }
4912
4913    #[test]
4914    fn option_display_value_names() {
4915        let mut o = Arg::new("opt")
4916            .short('o')
4917            .action(ArgAction::Set)
4918            .value_names(["file", "name"]);
4919        o._build();
4920
4921        assert_eq!(o.to_string(), "-o <file> <name>");
4922    }
4923
4924    #[test]
4925    fn option_display3() {
4926        let mut o = Arg::new("opt")
4927            .short('o')
4928            .num_args(1..)
4929            .action(ArgAction::Set)
4930            .value_names(["file", "name"]);
4931        o._build();
4932
4933        assert_eq!(o.to_string(), "-o <file> <name>...");
4934    }
4935
4936    #[test]
4937    fn option_display_single_alias() {
4938        let mut o = Arg::new("opt")
4939            .long("option")
4940            .action(ArgAction::Set)
4941            .visible_alias("als");
4942        o._build();
4943
4944        assert_eq!(o.to_string(), "--option <opt>");
4945    }
4946
4947    #[test]
4948    fn option_display_multiple_aliases() {
4949        let mut o = Arg::new("opt")
4950            .long("option")
4951            .action(ArgAction::Set)
4952            .visible_aliases(["als2", "als3", "als4"])
4953            .alias("als_not_visible");
4954        o._build();
4955
4956        assert_eq!(o.to_string(), "--option <opt>");
4957    }
4958
4959    #[test]
4960    fn option_display_single_short_alias() {
4961        let mut o = Arg::new("opt")
4962            .short('a')
4963            .action(ArgAction::Set)
4964            .visible_short_alias('b');
4965        o._build();
4966
4967        assert_eq!(o.to_string(), "-a <opt>");
4968    }
4969
4970    #[test]
4971    fn option_display_multiple_short_aliases() {
4972        let mut o = Arg::new("opt")
4973            .short('a')
4974            .action(ArgAction::Set)
4975            .visible_short_aliases(['b', 'c', 'd'])
4976            .short_alias('e');
4977        o._build();
4978
4979        assert_eq!(o.to_string(), "-a <opt>");
4980    }
4981
4982    // Positionals
4983
4984    #[test]
4985    fn positional_display_multiple_values() {
4986        let mut p = Arg::new("pos").index(1).num_args(1..);
4987        p._build();
4988
4989        assert_eq!(p.to_string(), "[pos]...");
4990    }
4991
4992    #[test]
4993    fn positional_display_multiple_values_required() {
4994        let mut p = Arg::new("pos").index(1).num_args(1..).required(true);
4995        p._build();
4996
4997        assert_eq!(p.to_string(), "<pos>...");
4998    }
4999
5000    #[test]
5001    fn positional_display_zero_or_more_values() {
5002        let mut p = Arg::new("pos").index(1).num_args(0..);
5003        p._build();
5004
5005        assert_eq!(p.to_string(), "[pos]...");
5006    }
5007
5008    #[test]
5009    fn positional_display_one_or_more_values() {
5010        let mut p = Arg::new("pos").index(1).num_args(1..);
5011        p._build();
5012
5013        assert_eq!(p.to_string(), "[pos]...");
5014    }
5015
5016    #[test]
5017    fn positional_display_one_or_more_values_required() {
5018        let mut p = Arg::new("pos").index(1).num_args(1..).required(true);
5019        p._build();
5020
5021        assert_eq!(p.to_string(), "<pos>...");
5022    }
5023
5024    #[test]
5025    fn positional_display_optional_value() {
5026        let mut p = Arg::new("pos")
5027            .index(1)
5028            .num_args(0..=1)
5029            .action(ArgAction::Set);
5030        p._build();
5031
5032        assert_eq!(p.to_string(), "[pos]");
5033    }
5034
5035    #[test]
5036    fn positional_display_multiple_occurrences() {
5037        let mut p = Arg::new("pos").index(1).action(ArgAction::Append);
5038        p._build();
5039
5040        assert_eq!(p.to_string(), "[pos]...");
5041    }
5042
5043    #[test]
5044    fn positional_display_multiple_occurrences_required() {
5045        let mut p = Arg::new("pos")
5046            .index(1)
5047            .action(ArgAction::Append)
5048            .required(true);
5049        p._build();
5050
5051        assert_eq!(p.to_string(), "<pos>...");
5052    }
5053
5054    #[test]
5055    fn positional_display_required() {
5056        let mut p = Arg::new("pos").index(1).required(true);
5057        p._build();
5058
5059        assert_eq!(p.to_string(), "<pos>");
5060    }
5061
5062    #[test]
5063    fn positional_display_val_names() {
5064        let mut p = Arg::new("pos").index(1).value_names(["file1", "file2"]);
5065        p._build();
5066
5067        assert_eq!(p.to_string(), "[file1] [file2]");
5068    }
5069
5070    #[test]
5071    fn positional_display_val_names_required() {
5072        let mut p = Arg::new("pos")
5073            .index(1)
5074            .value_names(["file1", "file2"])
5075            .required(true);
5076        p._build();
5077
5078        assert_eq!(p.to_string(), "<file1> <file2>");
5079    }
5080}