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