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<Vec<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
3065 .into_resettable()
3066 .into_option()
3067 .map(|os_str| vec![os_str]),
3068 ));
3069 self
3070 }
3071
3072 /// Specifies the values of the argument if `arg` has been used at runtime.
3073 ///
3074 /// See [`Arg::default_value_if`].
3075 ///
3076 /// # Examples
3077 ///
3078 /// ```rust
3079 /// use clap_builder::arg;
3080 /// use clap_builder::Command;
3081 /// use clap_builder::Arg;
3082 /// let r = Command::new("df")
3083 /// .arg(arg!(--opt <FILE> "some arg"))
3084 /// .arg(
3085 /// Arg::new("args")
3086 /// .long("args")
3087 /// .num_args(2)
3088 /// .default_values_if("opt", "value", ["df1","df2"]),
3089 /// )
3090 /// .try_get_matches_from(vec!["", "--opt", "value"]);
3091 ///
3092 /// let m = r.unwrap();
3093 /// assert_eq!(
3094 /// m.get_many::<String>("args").unwrap().collect::<Vec<_>>(),
3095 /// ["df1", "df2"]
3096 /// );
3097 /// ```
3098 ///
3099 /// [`Arg::default_value_if`]: Arg::default_value_if()
3100 #[must_use]
3101 pub fn default_values_if(
3102 mut self,
3103 arg_id: impl Into<Id>,
3104 predicate: impl Into<ArgPredicate>,
3105 defaults: impl IntoIterator<Item = impl Into<OsStr>>,
3106 ) -> Self {
3107 self.default_vals_ifs.push((
3108 arg_id.into(),
3109 predicate.into(),
3110 Some(defaults.into_iter().map(|item| item.into()).collect()),
3111 ));
3112 self
3113 }
3114
3115 #[must_use]
3116 #[doc(hidden)]
3117 #[cfg_attr(
3118 feature = "deprecated",
3119 deprecated(since = "4.0.0", note = "Replaced with `Arg::default_value_if`")
3120 )]
3121 pub fn default_value_if_os(
3122 self,
3123 arg_id: impl Into<Id>,
3124 predicate: impl Into<ArgPredicate>,
3125 default: impl IntoResettable<OsStr>,
3126 ) -> Self {
3127 self.default_value_if(arg_id, predicate, default)
3128 }
3129
3130 /// Specifies multiple values and conditions in the same manner as [`Arg::default_value_if`].
3131 ///
3132 /// The method takes a slice of tuples in the `(arg, predicate, default)` format.
3133 ///
3134 /// Like with command-line values, this will be split by [`Arg::value_delimiter`].
3135 ///
3136 /// <div class="warning">
3137 ///
3138 /// **NOTE**: The conditions are stored in order and evaluated in the same order. I.e. the first
3139 /// if multiple conditions are true, the first one found will be applied and the ultimate value.
3140 ///
3141 /// </div>
3142 ///
3143 /// # Examples
3144 ///
3145 /// First we use the default value only if another arg is present at runtime.
3146 ///
3147 /// ```rust
3148 /// # use clap_builder as clap;
3149 /// # use clap::{Command, Arg, ArgAction};
3150 /// let m = Command::new("prog")
3151 /// .arg(Arg::new("flag")
3152 /// .long("flag")
3153 /// .action(ArgAction::SetTrue))
3154 /// .arg(Arg::new("opt")
3155 /// .long("opt")
3156 /// .action(ArgAction::Set))
3157 /// .arg(Arg::new("other")
3158 /// .long("other")
3159 /// .default_value_ifs([
3160 /// ("flag", "true", Some("default")),
3161 /// ("opt", "channal", Some("chan")),
3162 /// ]))
3163 /// .get_matches_from(vec![
3164 /// "prog", "--opt", "channal"
3165 /// ]);
3166 ///
3167 /// assert_eq!(m.get_one::<String>("other").unwrap(), "chan");
3168 /// ```
3169 ///
3170 /// Next we run the same test, but without providing `--flag`.
3171 ///
3172 /// ```rust
3173 /// # use clap_builder as clap;
3174 /// # use clap::{Command, Arg, ArgAction};
3175 /// let m = Command::new("prog")
3176 /// .arg(Arg::new("flag")
3177 /// .long("flag")
3178 /// .action(ArgAction::SetTrue))
3179 /// .arg(Arg::new("other")
3180 /// .long("other")
3181 /// .default_value_ifs([
3182 /// ("flag", "true", Some("default")),
3183 /// ("opt", "channal", Some("chan")),
3184 /// ]))
3185 /// .get_matches_from(vec![
3186 /// "prog"
3187 /// ]);
3188 ///
3189 /// assert_eq!(m.get_one::<String>("other"), None);
3190 /// ```
3191 ///
3192 /// We can also see that these values are applied in order, and if more than one condition is
3193 /// true, only the first evaluated "wins"
3194 ///
3195 /// ```rust
3196 /// # use clap_builder as clap;
3197 /// # use clap::{Command, Arg, ArgAction};
3198 /// # use clap::builder::ArgPredicate;
3199 /// let m = Command::new("prog")
3200 /// .arg(Arg::new("flag")
3201 /// .long("flag")
3202 /// .action(ArgAction::SetTrue))
3203 /// .arg(Arg::new("opt")
3204 /// .long("opt")
3205 /// .action(ArgAction::Set))
3206 /// .arg(Arg::new("other")
3207 /// .long("other")
3208 /// .default_value_ifs([
3209 /// ("flag", ArgPredicate::IsPresent, Some("default")),
3210 /// ("opt", ArgPredicate::Equals("channal".into()), Some("chan")),
3211 /// ]))
3212 /// .get_matches_from(vec![
3213 /// "prog", "--opt", "channal", "--flag"
3214 /// ]);
3215 ///
3216 /// assert_eq!(m.get_one::<String>("other").unwrap(), "default");
3217 /// ```
3218 /// [`Arg::action(ArgAction::Set)`]: Arg::action()
3219 /// [`Arg::default_value_if`]: Arg::default_value_if()
3220 #[must_use]
3221 pub fn default_value_ifs(
3222 mut self,
3223 ifs: impl IntoIterator<
3224 Item = (
3225 impl Into<Id>,
3226 impl Into<ArgPredicate>,
3227 impl IntoResettable<OsStr>,
3228 ),
3229 >,
3230 ) -> Self {
3231 for (arg, predicate, default) in ifs {
3232 self = self.default_value_if(arg, predicate, default);
3233 }
3234 self
3235 }
3236
3237 /// Specifies multiple values and conditions in the same manner as [`Arg::default_values_if`].
3238 ///
3239 /// See [`Arg::default_values_if`].
3240 ///
3241 /// [`Arg::default_values_if`]: Arg::default_values_if()
3242 #[must_use]
3243 pub fn default_values_ifs(
3244 mut self,
3245 ifs: impl IntoIterator<
3246 Item = (
3247 impl Into<Id>,
3248 impl Into<ArgPredicate>,
3249 impl IntoIterator<Item = impl Into<OsStr>>,
3250 ),
3251 >,
3252 ) -> Self {
3253 for (arg, predicate, default) in ifs {
3254 self = self.default_values_if(arg, predicate, default);
3255 }
3256 self
3257 }
3258
3259 #[must_use]
3260 #[doc(hidden)]
3261 #[cfg_attr(
3262 feature = "deprecated",
3263 deprecated(since = "4.0.0", note = "Replaced with `Arg::default_value_ifs`")
3264 )]
3265 pub fn default_value_ifs_os(
3266 self,
3267 ifs: impl IntoIterator<
3268 Item = (
3269 impl Into<Id>,
3270 impl Into<ArgPredicate>,
3271 impl IntoResettable<OsStr>,
3272 ),
3273 >,
3274 ) -> Self {
3275 self.default_value_ifs(ifs)
3276 }
3277
3278 /// Set this arg as [required] as long as the specified argument is not present at runtime.
3279 ///
3280 /// <div class="warning">
3281 ///
3282 /// **TIP:** Using `Arg::required_unless_present` implies [`Arg::required`] and is therefore not
3283 /// mandatory to also set.
3284 ///
3285 /// </div>
3286 ///
3287 /// # Examples
3288 ///
3289 /// ```rust
3290 /// # use clap_builder as clap;
3291 /// # use clap::Arg;
3292 /// Arg::new("config")
3293 /// .required_unless_present("debug")
3294 /// # ;
3295 /// ```
3296 ///
3297 /// In the following example, the required argument is *not* provided,
3298 /// but it's not an error because the `unless` arg has been supplied.
3299 ///
3300 /// ```rust
3301 /// # use clap_builder as clap;
3302 /// # use clap::{Command, Arg, ArgAction};
3303 /// let res = Command::new("prog")
3304 /// .arg(Arg::new("cfg")
3305 /// .required_unless_present("dbg")
3306 /// .action(ArgAction::Set)
3307 /// .long("config"))
3308 /// .arg(Arg::new("dbg")
3309 /// .long("debug")
3310 /// .action(ArgAction::SetTrue))
3311 /// .try_get_matches_from(vec![
3312 /// "prog", "--debug"
3313 /// ]);
3314 ///
3315 /// assert!(res.is_ok());
3316 /// ```
3317 ///
3318 /// Setting `Arg::required_unless_present(name)` and *not* supplying `name` or this arg is an error.
3319 ///
3320 /// ```rust
3321 /// # use clap_builder as clap;
3322 /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
3323 /// let res = Command::new("prog")
3324 /// .arg(Arg::new("cfg")
3325 /// .required_unless_present("dbg")
3326 /// .action(ArgAction::Set)
3327 /// .long("config"))
3328 /// .arg(Arg::new("dbg")
3329 /// .long("debug"))
3330 /// .try_get_matches_from(vec![
3331 /// "prog"
3332 /// ]);
3333 ///
3334 /// assert!(res.is_err());
3335 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3336 /// ```
3337 /// [required]: Arg::required()
3338 #[must_use]
3339 pub fn required_unless_present(mut self, arg_id: impl IntoResettable<Id>) -> Self {
3340 if let Some(arg_id) = arg_id.into_resettable().into_option() {
3341 self.r_unless.push(arg_id);
3342 } else {
3343 self.r_unless.clear();
3344 }
3345 self
3346 }
3347
3348 /// Sets this arg as [required] unless *all* of the specified arguments are present at runtime.
3349 ///
3350 /// In other words, parsing will succeed only if user either
3351 /// * supplies the `self` arg.
3352 /// * supplies *all* of the `names` arguments.
3353 ///
3354 /// <div class="warning">
3355 ///
3356 /// **NOTE:** If you wish for this argument to only be required unless *any of* these args are
3357 /// present see [`Arg::required_unless_present_any`]
3358 ///
3359 /// </div>
3360 ///
3361 /// # Examples
3362 ///
3363 /// ```rust
3364 /// # use clap_builder as clap;
3365 /// # use clap::Arg;
3366 /// Arg::new("config")
3367 /// .required_unless_present_all(["cfg", "dbg"])
3368 /// # ;
3369 /// ```
3370 ///
3371 /// In the following example, the required argument is *not* provided, but it's not an error
3372 /// because *all* of the `names` args have been supplied.
3373 ///
3374 /// ```rust
3375 /// # use clap_builder as clap;
3376 /// # use clap::{Command, Arg, ArgAction};
3377 /// let res = Command::new("prog")
3378 /// .arg(Arg::new("cfg")
3379 /// .required_unless_present_all(["dbg", "infile"])
3380 /// .action(ArgAction::Set)
3381 /// .long("config"))
3382 /// .arg(Arg::new("dbg")
3383 /// .long("debug")
3384 /// .action(ArgAction::SetTrue))
3385 /// .arg(Arg::new("infile")
3386 /// .short('i')
3387 /// .action(ArgAction::Set))
3388 /// .try_get_matches_from(vec![
3389 /// "prog", "--debug", "-i", "file"
3390 /// ]);
3391 ///
3392 /// assert!(res.is_ok());
3393 /// ```
3394 ///
3395 /// Setting [`Arg::required_unless_present_all(names)`] and *not* supplying
3396 /// either *all* of `unless` args or the `self` arg is an error.
3397 ///
3398 /// ```rust
3399 /// # use clap_builder as clap;
3400 /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
3401 /// let res = Command::new("prog")
3402 /// .arg(Arg::new("cfg")
3403 /// .required_unless_present_all(["dbg", "infile"])
3404 /// .action(ArgAction::Set)
3405 /// .long("config"))
3406 /// .arg(Arg::new("dbg")
3407 /// .long("debug")
3408 /// .action(ArgAction::SetTrue))
3409 /// .arg(Arg::new("infile")
3410 /// .short('i')
3411 /// .action(ArgAction::Set))
3412 /// .try_get_matches_from(vec![
3413 /// "prog"
3414 /// ]);
3415 ///
3416 /// assert!(res.is_err());
3417 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3418 /// ```
3419 /// [required]: Arg::required()
3420 /// [`Arg::required_unless_present_any`]: Arg::required_unless_present_any()
3421 /// [`Arg::required_unless_present_all(names)`]: Arg::required_unless_present_all()
3422 #[must_use]
3423 pub fn required_unless_present_all(
3424 mut self,
3425 names: impl IntoIterator<Item = impl Into<Id>>,
3426 ) -> Self {
3427 self.r_unless_all.extend(names.into_iter().map(Into::into));
3428 self
3429 }
3430
3431 /// Sets this arg as [required] unless *any* of the specified arguments are present at runtime.
3432 ///
3433 /// In other words, parsing will succeed only if user either
3434 /// * supplies the `self` arg.
3435 /// * supplies *one or more* of the `unless` arguments.
3436 ///
3437 /// <div class="warning">
3438 ///
3439 /// **NOTE:** If you wish for this argument to be required unless *all of* these args are
3440 /// present see [`Arg::required_unless_present_all`]
3441 ///
3442 /// </div>
3443 ///
3444 /// # Examples
3445 ///
3446 /// ```rust
3447 /// # use clap_builder as clap;
3448 /// # use clap::Arg;
3449 /// Arg::new("config")
3450 /// .required_unless_present_any(["cfg", "dbg"])
3451 /// # ;
3452 /// ```
3453 ///
3454 /// Setting [`Arg::required_unless_present_any(names)`] requires that the argument be used at runtime
3455 /// *unless* *at least one of* the args in `names` are present. In the following example, the
3456 /// required argument is *not* provided, but it's not an error because one the `unless` args
3457 /// have been supplied.
3458 ///
3459 /// ```rust
3460 /// # use clap_builder as clap;
3461 /// # use clap::{Command, Arg, ArgAction};
3462 /// let res = Command::new("prog")
3463 /// .arg(Arg::new("cfg")
3464 /// .required_unless_present_any(["dbg", "infile"])
3465 /// .action(ArgAction::Set)
3466 /// .long("config"))
3467 /// .arg(Arg::new("dbg")
3468 /// .long("debug")
3469 /// .action(ArgAction::SetTrue))
3470 /// .arg(Arg::new("infile")
3471 /// .short('i')
3472 /// .action(ArgAction::Set))
3473 /// .try_get_matches_from(vec![
3474 /// "prog", "--debug"
3475 /// ]);
3476 ///
3477 /// assert!(res.is_ok());
3478 /// ```
3479 ///
3480 /// Setting [`Arg::required_unless_present_any(names)`] and *not* supplying *at least one of* `names`
3481 /// or this arg is an error.
3482 ///
3483 /// ```rust
3484 /// # use clap_builder as clap;
3485 /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
3486 /// let res = Command::new("prog")
3487 /// .arg(Arg::new("cfg")
3488 /// .required_unless_present_any(["dbg", "infile"])
3489 /// .action(ArgAction::Set)
3490 /// .long("config"))
3491 /// .arg(Arg::new("dbg")
3492 /// .long("debug")
3493 /// .action(ArgAction::SetTrue))
3494 /// .arg(Arg::new("infile")
3495 /// .short('i')
3496 /// .action(ArgAction::Set))
3497 /// .try_get_matches_from(vec![
3498 /// "prog"
3499 /// ]);
3500 ///
3501 /// assert!(res.is_err());
3502 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3503 /// ```
3504 /// [required]: Arg::required()
3505 /// [`Arg::required_unless_present_any(names)`]: Arg::required_unless_present_any()
3506 /// [`Arg::required_unless_present_all`]: Arg::required_unless_present_all()
3507 #[must_use]
3508 pub fn required_unless_present_any(
3509 mut self,
3510 names: impl IntoIterator<Item = impl Into<Id>>,
3511 ) -> Self {
3512 self.r_unless.extend(names.into_iter().map(Into::into));
3513 self
3514 }
3515
3516 /// This argument is [required] only if the specified `arg` is present at runtime and its value
3517 /// equals `val`.
3518 ///
3519 /// # Examples
3520 ///
3521 /// ```rust
3522 /// # use clap_builder as clap;
3523 /// # use clap::Arg;
3524 /// Arg::new("config")
3525 /// .required_if_eq("other_arg", "value")
3526 /// # ;
3527 /// ```
3528 ///
3529 /// ```rust
3530 /// # use clap_builder as clap;
3531 /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
3532 /// let res = Command::new("prog")
3533 /// .arg(Arg::new("cfg")
3534 /// .action(ArgAction::Set)
3535 /// .required_if_eq("other", "special")
3536 /// .long("config"))
3537 /// .arg(Arg::new("other")
3538 /// .long("other")
3539 /// .action(ArgAction::Set))
3540 /// .try_get_matches_from(vec![
3541 /// "prog", "--other", "not-special"
3542 /// ]);
3543 ///
3544 /// assert!(res.is_ok()); // We didn't use --other=special, so "cfg" wasn't required
3545 ///
3546 /// let res = Command::new("prog")
3547 /// .arg(Arg::new("cfg")
3548 /// .action(ArgAction::Set)
3549 /// .required_if_eq("other", "special")
3550 /// .long("config"))
3551 /// .arg(Arg::new("other")
3552 /// .long("other")
3553 /// .action(ArgAction::Set))
3554 /// .try_get_matches_from(vec![
3555 /// "prog", "--other", "special"
3556 /// ]);
3557 ///
3558 /// // We did use --other=special so "cfg" had become required but was missing.
3559 /// assert!(res.is_err());
3560 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3561 ///
3562 /// let res = Command::new("prog")
3563 /// .arg(Arg::new("cfg")
3564 /// .action(ArgAction::Set)
3565 /// .required_if_eq("other", "special")
3566 /// .long("config"))
3567 /// .arg(Arg::new("other")
3568 /// .long("other")
3569 /// .action(ArgAction::Set))
3570 /// .try_get_matches_from(vec![
3571 /// "prog", "--other", "SPECIAL"
3572 /// ]);
3573 ///
3574 /// // By default, the comparison is case-sensitive, so "cfg" wasn't required
3575 /// assert!(res.is_ok());
3576 ///
3577 /// let res = Command::new("prog")
3578 /// .arg(Arg::new("cfg")
3579 /// .action(ArgAction::Set)
3580 /// .required_if_eq("other", "special")
3581 /// .long("config"))
3582 /// .arg(Arg::new("other")
3583 /// .long("other")
3584 /// .ignore_case(true)
3585 /// .action(ArgAction::Set))
3586 /// .try_get_matches_from(vec![
3587 /// "prog", "--other", "SPECIAL"
3588 /// ]);
3589 ///
3590 /// // However, case-insensitive comparisons can be enabled. This typically occurs when using Arg::possible_values().
3591 /// assert!(res.is_err());
3592 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3593 /// ```
3594 /// [`Arg::requires(name)`]: Arg::requires()
3595 /// [Conflicting]: Arg::conflicts_with()
3596 /// [required]: Arg::required()
3597 #[must_use]
3598 pub fn required_if_eq(mut self, arg_id: impl Into<Id>, val: impl Into<OsStr>) -> Self {
3599 self.r_ifs.push((arg_id.into(), val.into()));
3600 self
3601 }
3602
3603 /// Specify this argument is [required] based on multiple conditions.
3604 ///
3605 /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become
3606 /// valid if one of the specified `arg`'s value equals its corresponding `val`.
3607 ///
3608 /// # Examples
3609 ///
3610 /// ```rust
3611 /// # use clap_builder as clap;
3612 /// # use clap::Arg;
3613 /// Arg::new("config")
3614 /// .required_if_eq_any([
3615 /// ("extra", "val"),
3616 /// ("option", "spec")
3617 /// ])
3618 /// # ;
3619 /// ```
3620 ///
3621 /// Setting `Arg::required_if_eq_any([(arg, val)])` makes this arg required if any of the `arg`s
3622 /// are used at runtime and it's corresponding value is equal to `val`. If the `arg`'s value is
3623 /// anything other than `val`, this argument isn't required.
3624 ///
3625 /// ```rust
3626 /// # use clap_builder as clap;
3627 /// # use clap::{Command, Arg, ArgAction};
3628 /// let res = Command::new("prog")
3629 /// .arg(Arg::new("cfg")
3630 /// .required_if_eq_any([
3631 /// ("extra", "val"),
3632 /// ("option", "spec")
3633 /// ])
3634 /// .action(ArgAction::Set)
3635 /// .long("config"))
3636 /// .arg(Arg::new("extra")
3637 /// .action(ArgAction::Set)
3638 /// .long("extra"))
3639 /// .arg(Arg::new("option")
3640 /// .action(ArgAction::Set)
3641 /// .long("option"))
3642 /// .try_get_matches_from(vec![
3643 /// "prog", "--option", "other"
3644 /// ]);
3645 ///
3646 /// assert!(res.is_ok()); // We didn't use --option=spec, or --extra=val so "cfg" isn't required
3647 /// ```
3648 ///
3649 /// Setting `Arg::required_if_eq_any([(arg, val)])` and having any of the `arg`s used with its
3650 /// value of `val` but *not* using this arg is an error.
3651 ///
3652 /// ```rust
3653 /// # use clap_builder as clap;
3654 /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
3655 /// let res = Command::new("prog")
3656 /// .arg(Arg::new("cfg")
3657 /// .required_if_eq_any([
3658 /// ("extra", "val"),
3659 /// ("option", "spec")
3660 /// ])
3661 /// .action(ArgAction::Set)
3662 /// .long("config"))
3663 /// .arg(Arg::new("extra")
3664 /// .action(ArgAction::Set)
3665 /// .long("extra"))
3666 /// .arg(Arg::new("option")
3667 /// .action(ArgAction::Set)
3668 /// .long("option"))
3669 /// .try_get_matches_from(vec![
3670 /// "prog", "--option", "spec"
3671 /// ]);
3672 ///
3673 /// assert!(res.is_err());
3674 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3675 /// ```
3676 /// [`Arg::requires(name)`]: Arg::requires()
3677 /// [Conflicting]: Arg::conflicts_with()
3678 /// [required]: Arg::required()
3679 #[must_use]
3680 pub fn required_if_eq_any(
3681 mut self,
3682 ifs: impl IntoIterator<Item = (impl Into<Id>, impl Into<OsStr>)>,
3683 ) -> Self {
3684 self.r_ifs
3685 .extend(ifs.into_iter().map(|(id, val)| (id.into(), val.into())));
3686 self
3687 }
3688
3689 /// Specify this argument is [required] based on multiple conditions.
3690 ///
3691 /// The conditions are set up in a `(arg, val)` style tuple. The requirement will only become
3692 /// valid if every one of the specified `arg`'s value equals its corresponding `val`.
3693 ///
3694 /// # Examples
3695 ///
3696 /// ```rust
3697 /// # use clap_builder as clap;
3698 /// # use clap::Arg;
3699 /// Arg::new("config")
3700 /// .required_if_eq_all([
3701 /// ("extra", "val"),
3702 /// ("option", "spec")
3703 /// ])
3704 /// # ;
3705 /// ```
3706 ///
3707 /// Setting `Arg::required_if_eq_all([(arg, val)])` makes this arg required if all of the `arg`s
3708 /// are used at runtime and every value is equal to its corresponding `val`. If the `arg`'s value is
3709 /// anything other than `val`, this argument isn't required.
3710 ///
3711 /// ```rust
3712 /// # use clap_builder as clap;
3713 /// # use clap::{Command, Arg, ArgAction};
3714 /// let res = Command::new("prog")
3715 /// .arg(Arg::new("cfg")
3716 /// .required_if_eq_all([
3717 /// ("extra", "val"),
3718 /// ("option", "spec")
3719 /// ])
3720 /// .action(ArgAction::Set)
3721 /// .long("config"))
3722 /// .arg(Arg::new("extra")
3723 /// .action(ArgAction::Set)
3724 /// .long("extra"))
3725 /// .arg(Arg::new("option")
3726 /// .action(ArgAction::Set)
3727 /// .long("option"))
3728 /// .try_get_matches_from(vec![
3729 /// "prog", "--option", "spec"
3730 /// ]);
3731 ///
3732 /// assert!(res.is_ok()); // We didn't use --option=spec --extra=val so "cfg" isn't required
3733 /// ```
3734 ///
3735 /// Setting `Arg::required_if_eq_all([(arg, val)])` and having all of the `arg`s used with its
3736 /// value of `val` but *not* using this arg is an error.
3737 ///
3738 /// ```rust
3739 /// # use clap_builder as clap;
3740 /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
3741 /// let res = Command::new("prog")
3742 /// .arg(Arg::new("cfg")
3743 /// .required_if_eq_all([
3744 /// ("extra", "val"),
3745 /// ("option", "spec")
3746 /// ])
3747 /// .action(ArgAction::Set)
3748 /// .long("config"))
3749 /// .arg(Arg::new("extra")
3750 /// .action(ArgAction::Set)
3751 /// .long("extra"))
3752 /// .arg(Arg::new("option")
3753 /// .action(ArgAction::Set)
3754 /// .long("option"))
3755 /// .try_get_matches_from(vec![
3756 /// "prog", "--extra", "val", "--option", "spec"
3757 /// ]);
3758 ///
3759 /// assert!(res.is_err());
3760 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3761 /// ```
3762 /// [required]: Arg::required()
3763 #[must_use]
3764 pub fn required_if_eq_all(
3765 mut self,
3766 ifs: impl IntoIterator<Item = (impl Into<Id>, impl Into<OsStr>)>,
3767 ) -> Self {
3768 self.r_ifs_all
3769 .extend(ifs.into_iter().map(|(id, val)| (id.into(), val.into())));
3770 self
3771 }
3772
3773 /// Require another argument if this arg matches the [`ArgPredicate`]
3774 ///
3775 /// This method takes `value, another_arg` pair. At runtime, clap will check
3776 /// if this arg (`self`) matches the [`ArgPredicate`].
3777 /// If it does, `another_arg` will be marked as required.
3778 ///
3779 /// # Examples
3780 ///
3781 /// ```rust
3782 /// # use clap_builder as clap;
3783 /// # use clap::Arg;
3784 /// Arg::new("config")
3785 /// .requires_if("val", "arg")
3786 /// # ;
3787 /// ```
3788 ///
3789 /// Setting `Arg::requires_if(val, arg)` requires that the `arg` be used at runtime if the
3790 /// defining argument's value is equal to `val`. If the defining argument is anything other than
3791 /// `val`, the other argument isn't required.
3792 ///
3793 /// ```rust
3794 /// # use clap_builder as clap;
3795 /// # use clap::{Command, Arg, ArgAction};
3796 /// let res = Command::new("prog")
3797 /// .arg(Arg::new("cfg")
3798 /// .action(ArgAction::Set)
3799 /// .requires_if("my.cfg", "other")
3800 /// .long("config"))
3801 /// .arg(Arg::new("other"))
3802 /// .try_get_matches_from(vec![
3803 /// "prog", "--config", "some.cfg"
3804 /// ]);
3805 ///
3806 /// assert!(res.is_ok()); // We didn't use --config=my.cfg, so other wasn't required
3807 /// ```
3808 ///
3809 /// Setting `Arg::requires_if(val, arg)` and setting the value to `val` but *not* supplying
3810 /// `arg` is an error.
3811 ///
3812 /// ```rust
3813 /// # use clap_builder as clap;
3814 /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
3815 /// let res = Command::new("prog")
3816 /// .arg(Arg::new("cfg")
3817 /// .action(ArgAction::Set)
3818 /// .requires_if("my.cfg", "input")
3819 /// .long("config"))
3820 /// .arg(Arg::new("input"))
3821 /// .try_get_matches_from(vec![
3822 /// "prog", "--config", "my.cfg"
3823 /// ]);
3824 ///
3825 /// assert!(res.is_err());
3826 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3827 /// ```
3828 /// [`Arg::requires(name)`]: Arg::requires()
3829 /// [Conflicting]: Arg::conflicts_with()
3830 /// [override]: Arg::overrides_with()
3831 #[must_use]
3832 pub fn requires_if(mut self, val: impl Into<ArgPredicate>, arg_id: impl Into<Id>) -> Self {
3833 self.requires.push((val.into(), arg_id.into()));
3834 self
3835 }
3836
3837 /// Allows multiple conditional requirements.
3838 ///
3839 /// The requirement will only become valid if this arg's value matches the
3840 /// [`ArgPredicate`].
3841 ///
3842 /// # Examples
3843 ///
3844 /// ```rust
3845 /// # use clap_builder as clap;
3846 /// # use clap::Arg;
3847 /// Arg::new("config")
3848 /// .requires_ifs([
3849 /// ("val", "arg"),
3850 /// ("other_val", "arg2"),
3851 /// ])
3852 /// # ;
3853 /// ```
3854 ///
3855 /// Setting `Arg::requires_ifs(["val", "arg"])` requires that the `arg` be used at runtime if the
3856 /// defining argument's value is equal to `val`. If the defining argument's value is anything other
3857 /// than `val`, `arg` isn't required.
3858 ///
3859 /// ```rust
3860 /// # use clap_builder as clap;
3861 /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
3862 /// let res = Command::new("prog")
3863 /// .arg(Arg::new("cfg")
3864 /// .action(ArgAction::Set)
3865 /// .requires_ifs([
3866 /// ("special.conf", "opt"),
3867 /// ("other.conf", "other"),
3868 /// ])
3869 /// .long("config"))
3870 /// .arg(Arg::new("opt")
3871 /// .long("option")
3872 /// .action(ArgAction::Set))
3873 /// .arg(Arg::new("other"))
3874 /// .try_get_matches_from(vec![
3875 /// "prog", "--config", "special.conf"
3876 /// ]);
3877 ///
3878 /// assert!(res.is_err()); // We used --config=special.conf so --option <val> is required
3879 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3880 /// ```
3881 ///
3882 /// Setting `Arg::requires_ifs` with [`ArgPredicate::IsPresent`] and *not* supplying all the
3883 /// arguments is an error.
3884 ///
3885 /// ```rust
3886 /// # use clap_builder as clap;
3887 /// # use clap::{Command, Arg, error::ErrorKind, ArgAction, builder::ArgPredicate};
3888 /// let res = Command::new("prog")
3889 /// .arg(Arg::new("cfg")
3890 /// .action(ArgAction::Set)
3891 /// .requires_ifs([
3892 /// (ArgPredicate::IsPresent, "input"),
3893 /// (ArgPredicate::IsPresent, "output"),
3894 /// ])
3895 /// .long("config"))
3896 /// .arg(Arg::new("input"))
3897 /// .arg(Arg::new("output"))
3898 /// .try_get_matches_from(vec![
3899 /// "prog", "--config", "file.conf", "in.txt"
3900 /// ]);
3901 ///
3902 /// assert!(res.is_err());
3903 /// // We didn't use output
3904 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
3905 /// ```
3906 ///
3907 /// [`Arg::requires(name)`]: Arg::requires()
3908 /// [Conflicting]: Arg::conflicts_with()
3909 /// [override]: Arg::overrides_with()
3910 #[must_use]
3911 pub fn requires_ifs(
3912 mut self,
3913 ifs: impl IntoIterator<Item = (impl Into<ArgPredicate>, impl Into<Id>)>,
3914 ) -> Self {
3915 self.requires
3916 .extend(ifs.into_iter().map(|(val, arg)| (val.into(), arg.into())));
3917 self
3918 }
3919
3920 #[doc(hidden)]
3921 #[cfg_attr(
3922 feature = "deprecated",
3923 deprecated(since = "4.0.0", note = "Replaced with `Arg::requires_ifs`")
3924 )]
3925 pub fn requires_all(self, ids: impl IntoIterator<Item = impl Into<Id>>) -> Self {
3926 self.requires_ifs(ids.into_iter().map(|id| (ArgPredicate::IsPresent, id)))
3927 }
3928
3929 /// This argument is mutually exclusive with the specified argument.
3930 ///
3931 /// <div class="warning">
3932 ///
3933 /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules
3934 /// only need to be set for one of the two arguments, they do not need to be set for each.
3935 ///
3936 /// </div>
3937 ///
3938 /// <div class="warning">
3939 ///
3940 /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments
3941 /// (i.e. if A conflicts with B, defining `A.conflicts_with(B)` is sufficient. You do not
3942 /// need to also do `B.conflicts_with(A)`)
3943 ///
3944 /// </div>
3945 ///
3946 /// <div class="warning">
3947 ///
3948 /// **NOTE:** [`Arg::conflicts_with_all(names)`] allows specifying an argument which conflicts with more than one argument.
3949 ///
3950 /// </div>
3951 ///
3952 /// <div class="warning">
3953 ///
3954 /// **NOTE** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument.
3955 ///
3956 /// </div>
3957 ///
3958 /// <div class="warning">
3959 ///
3960 /// **NOTE:** All arguments implicitly conflict with themselves.
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("debug")
3971 /// # ;
3972 /// ```
3973 ///
3974 /// Setting conflicting argument, and having both arguments present at runtime is an error.
3975 ///
3976 /// ```rust
3977 /// # use clap_builder as clap;
3978 /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
3979 /// let res = Command::new("prog")
3980 /// .arg(Arg::new("cfg")
3981 /// .action(ArgAction::Set)
3982 /// .conflicts_with("debug")
3983 /// .long("config"))
3984 /// .arg(Arg::new("debug")
3985 /// .long("debug")
3986 /// .action(ArgAction::SetTrue))
3987 /// .try_get_matches_from(vec![
3988 /// "prog", "--debug", "--config", "file.conf"
3989 /// ]);
3990 ///
3991 /// assert!(res.is_err());
3992 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict);
3993 /// ```
3994 ///
3995 /// [`Arg::conflicts_with_all(names)`]: Arg::conflicts_with_all()
3996 /// [`Arg::exclusive(true)`]: Arg::exclusive()
3997 #[must_use]
3998 pub fn conflicts_with(mut self, arg_id: impl IntoResettable<Id>) -> Self {
3999 if let Some(arg_id) = arg_id.into_resettable().into_option() {
4000 self.blacklist.push(arg_id);
4001 } else {
4002 self.blacklist.clear();
4003 }
4004 self
4005 }
4006
4007 /// This argument is mutually exclusive with the specified arguments.
4008 ///
4009 /// See [`Arg::conflicts_with`].
4010 ///
4011 /// <div class="warning">
4012 ///
4013 /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules
4014 /// only need to be set for one of the two arguments, they do not need to be set for each.
4015 ///
4016 /// </div>
4017 ///
4018 /// <div class="warning">
4019 ///
4020 /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments
4021 /// (i.e. if A conflicts with B, defining `A.conflicts_with(B)` is sufficient. You do not need
4022 /// need to also do `B.conflicts_with(A)`)
4023 ///
4024 /// </div>
4025 ///
4026 /// <div class="warning">
4027 ///
4028 /// **NOTE:** [`Arg::exclusive(true)`] allows specifying an argument which conflicts with every other argument.
4029 ///
4030 /// </div>
4031 ///
4032 /// # Examples
4033 ///
4034 /// ```rust
4035 /// # use clap_builder as clap;
4036 /// # use clap::Arg;
4037 /// Arg::new("config")
4038 /// .conflicts_with_all(["debug", "input"])
4039 /// # ;
4040 /// ```
4041 ///
4042 /// Setting conflicting argument, and having any of the arguments present at runtime with a
4043 /// conflicting argument is an error.
4044 ///
4045 /// ```rust
4046 /// # use clap_builder as clap;
4047 /// # use clap::{Command, Arg, error::ErrorKind, ArgAction};
4048 /// let res = Command::new("prog")
4049 /// .arg(Arg::new("cfg")
4050 /// .action(ArgAction::Set)
4051 /// .conflicts_with_all(["debug", "input"])
4052 /// .long("config"))
4053 /// .arg(Arg::new("debug")
4054 /// .long("debug"))
4055 /// .arg(Arg::new("input"))
4056 /// .try_get_matches_from(vec![
4057 /// "prog", "--config", "file.conf", "file.txt"
4058 /// ]);
4059 ///
4060 /// assert!(res.is_err());
4061 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::ArgumentConflict);
4062 /// ```
4063 /// [`Arg::conflicts_with`]: Arg::conflicts_with()
4064 /// [`Arg::exclusive(true)`]: Arg::exclusive()
4065 #[must_use]
4066 pub fn conflicts_with_all(mut self, names: impl IntoIterator<Item = impl Into<Id>>) -> Self {
4067 self.blacklist.extend(names.into_iter().map(Into::into));
4068 self
4069 }
4070
4071 /// Sets an overridable argument.
4072 ///
4073 /// i.e. this argument and the following argument
4074 /// will override each other in POSIX style (whichever argument was specified at runtime
4075 /// **last** "wins")
4076 ///
4077 /// <div class="warning">
4078 ///
4079 /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any
4080 /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed
4081 ///
4082 /// </div>
4083 ///
4084 /// <div class="warning">
4085 ///
4086 /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with`].
4087 ///
4088 /// </div>
4089 ///
4090 /// # Examples
4091 ///
4092 /// ```rust
4093 /// # use clap_builder as clap;
4094 /// # use clap::{Command, arg};
4095 /// let m = Command::new("prog")
4096 /// .arg(arg!(-f --flag "some flag")
4097 /// .conflicts_with("debug"))
4098 /// .arg(arg!(-d --debug "other flag"))
4099 /// .arg(arg!(-c --color "third flag")
4100 /// .overrides_with("flag"))
4101 /// .get_matches_from(vec![
4102 /// "prog", "-f", "-d", "-c"]);
4103 /// // ^~~~~~~~~~~~^~~~~ flag is overridden by color
4104 ///
4105 /// assert!(m.get_flag("color"));
4106 /// assert!(m.get_flag("debug")); // even though flag conflicts with debug, it's as if flag
4107 /// // was never used because it was overridden with color
4108 /// assert!(!m.get_flag("flag"));
4109 /// ```
4110 #[must_use]
4111 pub fn overrides_with(mut self, arg_id: impl IntoResettable<Id>) -> Self {
4112 if let Some(arg_id) = arg_id.into_resettable().into_option() {
4113 self.overrides.push(arg_id);
4114 } else {
4115 self.overrides.clear();
4116 }
4117 self
4118 }
4119
4120 /// Sets multiple mutually overridable arguments by name.
4121 ///
4122 /// i.e. this argument and the following argument will override each other in POSIX style
4123 /// (whichever argument was specified at runtime **last** "wins")
4124 ///
4125 /// <div class="warning">
4126 ///
4127 /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any
4128 /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed
4129 ///
4130 /// </div>
4131 ///
4132 /// <div class="warning">
4133 ///
4134 /// **NOTE:** Overriding an argument implies they [conflict][Arg::conflicts_with_all`].
4135 ///
4136 /// </div>
4137 ///
4138 /// # Examples
4139 ///
4140 /// ```rust
4141 /// # use clap_builder as clap;
4142 /// # use clap::{Command, arg};
4143 /// let m = Command::new("prog")
4144 /// .arg(arg!(-f --flag "some flag")
4145 /// .conflicts_with("color"))
4146 /// .arg(arg!(-d --debug "other flag"))
4147 /// .arg(arg!(-c --color "third flag")
4148 /// .overrides_with_all(["flag", "debug"]))
4149 /// .get_matches_from(vec![
4150 /// "prog", "-f", "-d", "-c"]);
4151 /// // ^~~~~~^~~~~~~~~ flag and debug are overridden by color
4152 ///
4153 /// assert!(m.get_flag("color")); // even though flag conflicts with color, it's as if flag
4154 /// // and debug were never used because they were overridden
4155 /// // with color
4156 /// assert!(!m.get_flag("debug"));
4157 /// assert!(!m.get_flag("flag"));
4158 /// ```
4159 #[must_use]
4160 pub fn overrides_with_all(mut self, names: impl IntoIterator<Item = impl Into<Id>>) -> Self {
4161 self.overrides.extend(names.into_iter().map(Into::into));
4162 self
4163 }
4164}
4165
4166/// # Reflection
4167impl Arg {
4168 /// Get the name of the argument
4169 #[inline]
4170 pub fn get_id(&self) -> &Id {
4171 &self.id
4172 }
4173
4174 /// Get the help specified for this argument, if any
4175 #[inline]
4176 pub fn get_help(&self) -> Option<&StyledStr> {
4177 self.help.as_ref()
4178 }
4179
4180 /// Get the long help specified for this argument, if any
4181 ///
4182 /// # Examples
4183 ///
4184 /// ```rust
4185 /// # use clap_builder as clap;
4186 /// # use clap::Arg;
4187 /// let arg = Arg::new("foo").long_help("long help");
4188 /// assert_eq!(Some("long help".to_owned()), arg.get_long_help().map(|s| s.to_string()));
4189 /// ```
4190 ///
4191 #[inline]
4192 pub fn get_long_help(&self) -> Option<&StyledStr> {
4193 self.long_help.as_ref()
4194 }
4195
4196 /// Get the placement within help
4197 #[inline]
4198 pub fn get_display_order(&self) -> usize {
4199 self.disp_ord.unwrap_or(999)
4200 }
4201
4202 /// Get the help heading specified for this argument, if any
4203 #[inline]
4204 pub fn get_help_heading(&self) -> Option<&str> {
4205 self.help_heading
4206 .as_ref()
4207 .map(|s| s.as_deref())
4208 .unwrap_or_default()
4209 }
4210
4211 /// Get the short option name for this argument, if any
4212 #[inline]
4213 pub fn get_short(&self) -> Option<char> {
4214 self.short
4215 }
4216
4217 /// Get visible short aliases for this argument, if any
4218 #[inline]
4219 pub fn get_visible_short_aliases(&self) -> Option<Vec<char>> {
4220 if self.short_aliases.is_empty() {
4221 None
4222 } else {
4223 Some(
4224 self.short_aliases
4225 .iter()
4226 .filter_map(|(c, v)| if *v { Some(c) } else { None })
4227 .copied()
4228 .collect(),
4229 )
4230 }
4231 }
4232
4233 /// Get *all* short aliases for this argument, if any, both visible and hidden.
4234 #[inline]
4235 pub fn get_all_short_aliases(&self) -> Option<Vec<char>> {
4236 if self.short_aliases.is_empty() {
4237 None
4238 } else {
4239 Some(self.short_aliases.iter().map(|(s, _)| s).copied().collect())
4240 }
4241 }
4242
4243 /// Get the short option name and its visible aliases, if any
4244 #[inline]
4245 pub fn get_short_and_visible_aliases(&self) -> Option<Vec<char>> {
4246 let mut shorts = match self.short {
4247 Some(short) => vec![short],
4248 None => return None,
4249 };
4250 if let Some(aliases) = self.get_visible_short_aliases() {
4251 shorts.extend(aliases);
4252 }
4253 Some(shorts)
4254 }
4255
4256 /// Get the long option name for this argument, if any
4257 #[inline]
4258 pub fn get_long(&self) -> Option<&str> {
4259 self.long.as_deref()
4260 }
4261
4262 /// Get visible aliases for this argument, if any
4263 #[inline]
4264 pub fn get_visible_aliases(&self) -> Option<Vec<&str>> {
4265 if self.aliases.is_empty() {
4266 None
4267 } else {
4268 Some(
4269 self.aliases
4270 .iter()
4271 .filter_map(|(s, v)| if *v { Some(s.as_str()) } else { None })
4272 .collect(),
4273 )
4274 }
4275 }
4276
4277 /// Get *all* aliases for this argument, if any, both visible and hidden.
4278 #[inline]
4279 pub fn get_all_aliases(&self) -> Option<Vec<&str>> {
4280 if self.aliases.is_empty() {
4281 None
4282 } else {
4283 Some(self.aliases.iter().map(|(s, _)| s.as_str()).collect())
4284 }
4285 }
4286
4287 /// Get the long option name and its visible aliases, if any
4288 #[inline]
4289 pub fn get_long_and_visible_aliases(&self) -> Option<Vec<&str>> {
4290 let mut longs = match self.get_long() {
4291 Some(long) => vec![long],
4292 None => return None,
4293 };
4294 if let Some(aliases) = self.get_visible_aliases() {
4295 longs.extend(aliases);
4296 }
4297 Some(longs)
4298 }
4299
4300 /// Get hidden aliases for this argument, if any
4301 #[inline]
4302 pub fn get_aliases(&self) -> Option<Vec<&str>> {
4303 if self.aliases.is_empty() {
4304 None
4305 } else {
4306 Some(
4307 self.aliases
4308 .iter()
4309 .filter_map(|(s, v)| if !*v { Some(s.as_str()) } else { None })
4310 .collect(),
4311 )
4312 }
4313 }
4314
4315 /// Get the names of possible values for this argument. Only useful for user
4316 /// facing applications, such as building help messages or man files
4317 pub fn get_possible_values(&self) -> Vec<PossibleValue> {
4318 if !self.is_takes_value_set() {
4319 vec![]
4320 } else {
4321 self.get_value_parser()
4322 .possible_values()
4323 .map(|pvs| pvs.collect())
4324 .unwrap_or_default()
4325 }
4326 }
4327
4328 /// Get the names of values for this argument.
4329 #[inline]
4330 pub fn get_value_names(&self) -> Option<&[Str]> {
4331 if self.val_names.is_empty() {
4332 None
4333 } else {
4334 Some(&self.val_names)
4335 }
4336 }
4337
4338 /// Get the number of values for this argument.
4339 #[inline]
4340 pub fn get_num_args(&self) -> Option<ValueRange> {
4341 self.num_vals
4342 }
4343
4344 #[inline]
4345 pub(crate) fn get_min_vals(&self) -> usize {
4346 self.get_num_args().expect(INTERNAL_ERROR_MSG).min_values()
4347 }
4348
4349 /// Get the delimiter between multiple values
4350 #[inline]
4351 pub fn get_value_delimiter(&self) -> Option<char> {
4352 self.val_delim
4353 }
4354
4355 /// Get the value terminator for this argument. The `value_terminator` is a value
4356 /// that terminates parsing of multi-valued arguments.
4357 #[inline]
4358 pub fn get_value_terminator(&self) -> Option<&Str> {
4359 self.terminator.as_ref()
4360 }
4361
4362 /// Get the index of this argument, if any
4363 #[inline]
4364 pub fn get_index(&self) -> Option<usize> {
4365 self.index
4366 }
4367
4368 /// Get the value hint of this argument
4369 pub fn get_value_hint(&self) -> ValueHint {
4370 // HACK: we should use `Self::add` and `Self::remove` to type-check that `ArgExt` is used
4371 self.ext.get::<ValueHint>().copied().unwrap_or_else(|| {
4372 if self.is_takes_value_set() {
4373 let type_id = self.get_value_parser().type_id();
4374 if type_id == AnyValueId::of::<std::path::PathBuf>() {
4375 ValueHint::AnyPath
4376 } else {
4377 ValueHint::default()
4378 }
4379 } else {
4380 ValueHint::default()
4381 }
4382 })
4383 }
4384
4385 /// Get the environment variable name specified for this argument, if any
4386 ///
4387 /// # Examples
4388 ///
4389 /// ```rust
4390 /// # use clap_builder as clap;
4391 /// # use std::ffi::OsStr;
4392 /// # use clap::Arg;
4393 /// let arg = Arg::new("foo").env("ENVIRONMENT");
4394 /// assert_eq!(arg.get_env(), Some(OsStr::new("ENVIRONMENT")));
4395 /// ```
4396 #[cfg(feature = "env")]
4397 pub fn get_env(&self) -> Option<&std::ffi::OsStr> {
4398 self.env.as_ref().map(|x| x.0.as_os_str())
4399 }
4400
4401 /// Get the default values specified for this argument, if any
4402 ///
4403 /// # Examples
4404 ///
4405 /// ```rust
4406 /// # use clap_builder as clap;
4407 /// # use clap::Arg;
4408 /// let arg = Arg::new("foo").default_value("default value");
4409 /// assert_eq!(arg.get_default_values(), &["default value"]);
4410 /// ```
4411 pub fn get_default_values(&self) -> &[OsStr] {
4412 &self.default_vals
4413 }
4414
4415 /// Checks whether this argument is a positional or not.
4416 ///
4417 /// # Examples
4418 ///
4419 /// ```rust
4420 /// # use clap_builder as clap;
4421 /// # use clap::Arg;
4422 /// let arg = Arg::new("foo");
4423 /// assert_eq!(arg.is_positional(), true);
4424 ///
4425 /// let arg = Arg::new("foo").long("foo");
4426 /// assert_eq!(arg.is_positional(), false);
4427 /// ```
4428 pub fn is_positional(&self) -> bool {
4429 self.get_long().is_none() && self.get_short().is_none()
4430 }
4431
4432 /// Reports whether [`Arg::required`] is set
4433 pub fn is_required_set(&self) -> bool {
4434 self.is_set(ArgSettings::Required)
4435 }
4436
4437 pub(crate) fn is_multiple_values_set(&self) -> bool {
4438 self.get_num_args().unwrap_or_default().is_multiple()
4439 }
4440
4441 pub(crate) fn is_takes_value_set(&self) -> bool {
4442 self.get_num_args()
4443 .unwrap_or_else(|| 1.into())
4444 .takes_values()
4445 }
4446
4447 /// Report whether [`Arg::allow_hyphen_values`] is set
4448 pub fn is_allow_hyphen_values_set(&self) -> bool {
4449 self.is_set(ArgSettings::AllowHyphenValues)
4450 }
4451
4452 /// Report whether [`Arg::allow_negative_numbers`] is set
4453 pub fn is_allow_negative_numbers_set(&self) -> bool {
4454 self.is_set(ArgSettings::AllowNegativeNumbers)
4455 }
4456
4457 /// Behavior when parsing the argument
4458 pub fn get_action(&self) -> &ArgAction {
4459 const DEFAULT: ArgAction = ArgAction::Set;
4460 self.action.as_ref().unwrap_or(&DEFAULT)
4461 }
4462
4463 /// Configured parser for argument values
4464 ///
4465 /// # Example
4466 ///
4467 /// ```rust
4468 /// # use clap_builder as clap;
4469 /// let cmd = clap::Command::new("raw")
4470 /// .arg(
4471 /// clap::Arg::new("port")
4472 /// .value_parser(clap::value_parser!(usize))
4473 /// );
4474 /// let value_parser = cmd.get_arguments()
4475 /// .find(|a| a.get_id() == "port").unwrap()
4476 /// .get_value_parser();
4477 /// println!("{value_parser:?}");
4478 /// ```
4479 pub fn get_value_parser(&self) -> &super::ValueParser {
4480 if let Some(value_parser) = self.value_parser.as_ref() {
4481 value_parser
4482 } else {
4483 static DEFAULT: super::ValueParser = super::ValueParser::string();
4484 &DEFAULT
4485 }
4486 }
4487
4488 /// Report whether [`Arg::global`] is set
4489 pub fn is_global_set(&self) -> bool {
4490 self.is_set(ArgSettings::Global)
4491 }
4492
4493 /// Report whether [`Arg::next_line_help`] is set
4494 pub fn is_next_line_help_set(&self) -> bool {
4495 self.is_set(ArgSettings::NextLineHelp)
4496 }
4497
4498 /// Report whether [`Arg::hide`] is set
4499 pub fn is_hide_set(&self) -> bool {
4500 self.is_set(ArgSettings::Hidden)
4501 }
4502
4503 /// Report whether [`Arg::hide_default_value`] is set
4504 pub fn is_hide_default_value_set(&self) -> bool {
4505 self.is_set(ArgSettings::HideDefaultValue)
4506 }
4507
4508 /// Report whether [`Arg::hide_possible_values`] is set
4509 pub fn is_hide_possible_values_set(&self) -> bool {
4510 self.is_set(ArgSettings::HidePossibleValues)
4511 }
4512
4513 /// Report whether [`Arg::hide_env`] is set
4514 #[cfg(feature = "env")]
4515 pub fn is_hide_env_set(&self) -> bool {
4516 self.is_set(ArgSettings::HideEnv)
4517 }
4518
4519 /// Report whether [`Arg::hide_env_values`] is set
4520 #[cfg(feature = "env")]
4521 pub fn is_hide_env_values_set(&self) -> bool {
4522 self.is_set(ArgSettings::HideEnvValues)
4523 }
4524
4525 /// Report whether [`Arg::hide_short_help`] is set
4526 pub fn is_hide_short_help_set(&self) -> bool {
4527 self.is_set(ArgSettings::HiddenShortHelp)
4528 }
4529
4530 /// Report whether [`Arg::hide_long_help`] is set
4531 pub fn is_hide_long_help_set(&self) -> bool {
4532 self.is_set(ArgSettings::HiddenLongHelp)
4533 }
4534
4535 /// Report whether [`Arg::require_equals`] is set
4536 pub fn is_require_equals_set(&self) -> bool {
4537 self.is_set(ArgSettings::RequireEquals)
4538 }
4539
4540 /// Reports whether [`Arg::exclusive`] is set
4541 pub fn is_exclusive_set(&self) -> bool {
4542 self.is_set(ArgSettings::Exclusive)
4543 }
4544
4545 /// Report whether [`Arg::trailing_var_arg`] is set
4546 pub fn is_trailing_var_arg_set(&self) -> bool {
4547 self.is_set(ArgSettings::TrailingVarArg)
4548 }
4549
4550 /// Reports whether [`Arg::last`] is set
4551 pub fn is_last_set(&self) -> bool {
4552 self.is_set(ArgSettings::Last)
4553 }
4554
4555 /// Reports whether [`Arg::ignore_case`] is set
4556 pub fn is_ignore_case_set(&self) -> bool {
4557 self.is_set(ArgSettings::IgnoreCase)
4558 }
4559
4560 /// Access an [`ArgExt`]
4561 #[cfg(feature = "unstable-ext")]
4562 pub fn get<T: ArgExt + Extension>(&self) -> Option<&T> {
4563 self.ext.get::<T>()
4564 }
4565
4566 /// Remove an [`ArgExt`]
4567 #[cfg(feature = "unstable-ext")]
4568 pub fn remove<T: ArgExt + Extension>(mut self) -> Option<T> {
4569 self.ext.remove::<T>()
4570 }
4571}
4572
4573/// # Internally used only
4574impl Arg {
4575 pub(crate) fn _build(&mut self) {
4576 if self.action.is_none() {
4577 if self.num_vals == Some(ValueRange::EMPTY) {
4578 let action = ArgAction::SetTrue;
4579 self.action = Some(action);
4580 } else {
4581 let action =
4582 if self.is_positional() && self.num_vals.unwrap_or_default().is_unbounded() {
4583 // Allow collecting arguments interleaved with flags
4584 //
4585 // Bounded values are probably a group and the user should explicitly opt-in to
4586 // Append
4587 ArgAction::Append
4588 } else {
4589 ArgAction::Set
4590 };
4591 self.action = Some(action);
4592 }
4593 }
4594 if let Some(action) = self.action.as_ref() {
4595 if let Some(default_value) = action.default_value() {
4596 if self.default_vals.is_empty() {
4597 self.default_vals = vec![default_value.into()];
4598 }
4599 }
4600 if let Some(default_value) = action.default_missing_value() {
4601 if self.default_missing_vals.is_empty() {
4602 self.default_missing_vals = vec![default_value.into()];
4603 }
4604 }
4605 }
4606
4607 if self.value_parser.is_none() {
4608 if let Some(default) = self.action.as_ref().and_then(|a| a.default_value_parser()) {
4609 self.value_parser = Some(default);
4610 } else {
4611 self.value_parser = Some(super::ValueParser::string());
4612 }
4613 }
4614
4615 let val_names_len = self.val_names.len();
4616 if val_names_len > 1 {
4617 self.num_vals.get_or_insert(val_names_len.into());
4618 } else {
4619 let nargs = self.get_action().default_num_args();
4620 self.num_vals.get_or_insert(nargs);
4621 }
4622 }
4623
4624 // Used for positionals when printing
4625 pub(crate) fn name_no_brackets(&self) -> String {
4626 debug!("Arg::name_no_brackets:{}", self.get_id());
4627 let delim = " ";
4628 if !self.val_names.is_empty() {
4629 debug!("Arg::name_no_brackets: val_names={:#?}", self.val_names);
4630
4631 if self.val_names.len() > 1 {
4632 self.val_names
4633 .iter()
4634 .map(|n| format!("<{n}>"))
4635 .collect::<Vec<_>>()
4636 .join(delim)
4637 } else {
4638 self.val_names
4639 .first()
4640 .expect(INTERNAL_ERROR_MSG)
4641 .as_str()
4642 .to_owned()
4643 }
4644 } else {
4645 debug!("Arg::name_no_brackets: just name");
4646 self.get_id().as_str().to_owned()
4647 }
4648 }
4649
4650 pub(crate) fn stylized(&self, styles: &Styles, required: Option<bool>) -> StyledStr {
4651 use std::fmt::Write as _;
4652 let literal = styles.get_literal();
4653
4654 let mut styled = StyledStr::new();
4655 // Write the name such --long or -l
4656 if let Some(l) = self.get_long() {
4657 let _ = write!(styled, "{literal}--{l}{literal:#}",);
4658 } else if let Some(s) = self.get_short() {
4659 let _ = write!(styled, "{literal}-{s}{literal:#}");
4660 }
4661 styled.push_styled(&self.stylize_arg_suffix(styles, required));
4662 styled
4663 }
4664
4665 pub(crate) fn stylize_arg_suffix(&self, styles: &Styles, required: Option<bool>) -> StyledStr {
4666 use std::fmt::Write as _;
4667 let literal = styles.get_literal();
4668 let placeholder = styles.get_placeholder();
4669 let mut styled = StyledStr::new();
4670
4671 let mut need_closing_bracket = false;
4672 if self.is_takes_value_set() && !self.is_positional() {
4673 let is_optional_val = self.get_min_vals() == 0;
4674 let (style, start) = if self.is_require_equals_set() {
4675 if is_optional_val {
4676 need_closing_bracket = true;
4677 (placeholder, "[=")
4678 } else {
4679 (literal, "=")
4680 }
4681 } else if is_optional_val {
4682 need_closing_bracket = true;
4683 (placeholder, " [")
4684 } else {
4685 (placeholder, " ")
4686 };
4687 let _ = write!(styled, "{style}{start}{style:#}");
4688 }
4689 if self.is_takes_value_set() || self.is_positional() {
4690 let required = required.unwrap_or_else(|| self.is_required_set());
4691 let arg_val = self.render_arg_val(required);
4692 let _ = write!(styled, "{placeholder}{arg_val}{placeholder:#}",);
4693 } else if matches!(*self.get_action(), ArgAction::Count) {
4694 let _ = write!(styled, "{placeholder}...{placeholder:#}",);
4695 }
4696 if need_closing_bracket {
4697 let _ = write!(styled, "{placeholder}]{placeholder:#}",);
4698 }
4699
4700 styled
4701 }
4702
4703 /// Write the values such as `<name1> <name2>`
4704 fn render_arg_val(&self, required: bool) -> String {
4705 let mut rendered = String::new();
4706
4707 let num_vals = self.get_num_args().unwrap_or_else(|| 1.into());
4708
4709 let mut val_names = if self.val_names.is_empty() {
4710 vec![self.id.as_internal_str().to_owned()]
4711 } else {
4712 self.val_names.clone()
4713 };
4714 if val_names.len() == 1 {
4715 let min = num_vals.min_values().max(1);
4716 let val_name = val_names.pop().unwrap();
4717 val_names = vec![val_name; min];
4718 }
4719
4720 debug_assert!(self.is_takes_value_set());
4721 for (n, val_name) in val_names.iter().enumerate() {
4722 let arg_name = if self.is_positional() && (num_vals.min_values() == 0 || !required) {
4723 format!("[{val_name}]")
4724 } else {
4725 format!("<{val_name}>")
4726 };
4727
4728 if n != 0 {
4729 rendered.push(' ');
4730 }
4731 rendered.push_str(&arg_name);
4732 }
4733
4734 let mut extra_values = false;
4735 extra_values |= val_names.len() < num_vals.max_values();
4736 if self.is_positional() && matches!(*self.get_action(), ArgAction::Append) {
4737 extra_values = true;
4738 }
4739 if extra_values {
4740 rendered.push_str("...");
4741 }
4742
4743 rendered
4744 }
4745
4746 /// Either multiple values or occurrences
4747 pub(crate) fn is_multiple(&self) -> bool {
4748 self.is_multiple_values_set() || matches!(*self.get_action(), ArgAction::Append)
4749 }
4750}
4751
4752impl From<&'_ Arg> for Arg {
4753 fn from(a: &Arg) -> Self {
4754 a.clone()
4755 }
4756}
4757
4758impl PartialEq for Arg {
4759 fn eq(&self, other: &Arg) -> bool {
4760 self.get_id() == other.get_id()
4761 }
4762}
4763
4764impl PartialOrd for Arg {
4765 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
4766 Some(self.cmp(other))
4767 }
4768}
4769
4770impl Ord for Arg {
4771 fn cmp(&self, other: &Arg) -> Ordering {
4772 self.get_id().cmp(other.get_id())
4773 }
4774}
4775
4776impl Eq for Arg {}
4777
4778impl Display for Arg {
4779 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
4780 let plain = Styles::plain();
4781 self.stylized(&plain, None).fmt(f)
4782 }
4783}
4784
4785impl fmt::Debug for Arg {
4786 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
4787 let mut ds = f.debug_struct("Arg");
4788
4789 #[allow(unused_mut)]
4790 let mut ds = ds
4791 .field("id", &self.id)
4792 .field("help", &self.help)
4793 .field("long_help", &self.long_help)
4794 .field("action", &self.action)
4795 .field("value_parser", &self.value_parser)
4796 .field("blacklist", &self.blacklist)
4797 .field("settings", &self.settings)
4798 .field("overrides", &self.overrides)
4799 .field("groups", &self.groups)
4800 .field("requires", &self.requires)
4801 .field("r_ifs", &self.r_ifs)
4802 .field("r_unless", &self.r_unless)
4803 .field("short", &self.short)
4804 .field("long", &self.long)
4805 .field("aliases", &self.aliases)
4806 .field("short_aliases", &self.short_aliases)
4807 .field("disp_ord", &self.disp_ord)
4808 .field("val_names", &self.val_names)
4809 .field("num_vals", &self.num_vals)
4810 .field("val_delim", &self.val_delim)
4811 .field("default_vals", &self.default_vals)
4812 .field("default_vals_ifs", &self.default_vals_ifs)
4813 .field("terminator", &self.terminator)
4814 .field("index", &self.index)
4815 .field("help_heading", &self.help_heading)
4816 .field("default_missing_vals", &self.default_missing_vals)
4817 .field("ext", &self.ext);
4818
4819 #[cfg(feature = "env")]
4820 {
4821 ds = ds.field("env", &self.env);
4822 }
4823
4824 ds.finish()
4825 }
4826}
4827
4828/// User-provided data that can be attached to an [`Arg`]
4829#[cfg(feature = "unstable-ext")]
4830pub trait ArgExt: Extension {}
4831
4832// Flags
4833#[cfg(test)]
4834mod test {
4835 use super::Arg;
4836 use super::ArgAction;
4837
4838 #[test]
4839 fn flag_display_long() {
4840 let mut f = Arg::new("flg").long("flag").action(ArgAction::SetTrue);
4841 f._build();
4842
4843 assert_eq!(f.to_string(), "--flag");
4844 }
4845
4846 #[test]
4847 fn flag_display_short() {
4848 let mut f2 = Arg::new("flg").short('f').action(ArgAction::SetTrue);
4849 f2._build();
4850
4851 assert_eq!(f2.to_string(), "-f");
4852 }
4853
4854 #[test]
4855 fn flag_display_count() {
4856 let mut f2 = Arg::new("flg").long("flag").action(ArgAction::Count);
4857 f2._build();
4858
4859 assert_eq!(f2.to_string(), "--flag...");
4860 }
4861
4862 #[test]
4863 fn flag_display_single_alias() {
4864 let mut f = Arg::new("flg")
4865 .long("flag")
4866 .visible_alias("als")
4867 .action(ArgAction::SetTrue);
4868 f._build();
4869
4870 assert_eq!(f.to_string(), "--flag");
4871 }
4872
4873 #[test]
4874 fn flag_display_multiple_aliases() {
4875 let mut f = Arg::new("flg").short('f').action(ArgAction::SetTrue);
4876 f.aliases = vec![
4877 ("alias_not_visible".into(), false),
4878 ("f2".into(), true),
4879 ("f3".into(), true),
4880 ("f4".into(), true),
4881 ];
4882 f._build();
4883
4884 assert_eq!(f.to_string(), "-f");
4885 }
4886
4887 #[test]
4888 fn flag_display_single_short_alias() {
4889 let mut f = Arg::new("flg").short('a').action(ArgAction::SetTrue);
4890 f.short_aliases = vec![('b', true)];
4891 f._build();
4892
4893 assert_eq!(f.to_string(), "-a");
4894 }
4895
4896 #[test]
4897 fn flag_display_multiple_short_aliases() {
4898 let mut f = Arg::new("flg").short('a').action(ArgAction::SetTrue);
4899 f.short_aliases = vec![('b', false), ('c', true), ('d', true), ('e', true)];
4900 f._build();
4901
4902 assert_eq!(f.to_string(), "-a");
4903 }
4904
4905 // Options
4906
4907 #[test]
4908 fn option_display_multiple_occurrences() {
4909 let mut o = Arg::new("opt").long("option").action(ArgAction::Append);
4910 o._build();
4911
4912 assert_eq!(o.to_string(), "--option <opt>");
4913 }
4914
4915 #[test]
4916 fn option_display_multiple_values() {
4917 let mut o = Arg::new("opt")
4918 .long("option")
4919 .action(ArgAction::Set)
4920 .num_args(1..);
4921 o._build();
4922
4923 assert_eq!(o.to_string(), "--option <opt>...");
4924 }
4925
4926 #[test]
4927 fn option_display_zero_or_more_values() {
4928 let mut o = Arg::new("opt")
4929 .long("option")
4930 .action(ArgAction::Set)
4931 .num_args(0..);
4932 o._build();
4933
4934 assert_eq!(o.to_string(), "--option [<opt>...]");
4935 }
4936
4937 #[test]
4938 fn option_display_one_or_more_values() {
4939 let mut o = Arg::new("opt")
4940 .long("option")
4941 .action(ArgAction::Set)
4942 .num_args(1..);
4943 o._build();
4944
4945 assert_eq!(o.to_string(), "--option <opt>...");
4946 }
4947
4948 #[test]
4949 fn option_display_zero_or_more_values_with_value_name() {
4950 let mut o = Arg::new("opt")
4951 .short('o')
4952 .action(ArgAction::Set)
4953 .num_args(0..)
4954 .value_names(["file"]);
4955 o._build();
4956
4957 assert_eq!(o.to_string(), "-o [<file>...]");
4958 }
4959
4960 #[test]
4961 fn option_display_one_or_more_values_with_value_name() {
4962 let mut o = Arg::new("opt")
4963 .short('o')
4964 .action(ArgAction::Set)
4965 .num_args(1..)
4966 .value_names(["file"]);
4967 o._build();
4968
4969 assert_eq!(o.to_string(), "-o <file>...");
4970 }
4971
4972 #[test]
4973 fn option_display_optional_value() {
4974 let mut o = Arg::new("opt")
4975 .long("option")
4976 .action(ArgAction::Set)
4977 .num_args(0..=1);
4978 o._build();
4979
4980 assert_eq!(o.to_string(), "--option [<opt>]");
4981 }
4982
4983 #[test]
4984 fn option_display_value_names() {
4985 let mut o = Arg::new("opt")
4986 .short('o')
4987 .action(ArgAction::Set)
4988 .value_names(["file", "name"]);
4989 o._build();
4990
4991 assert_eq!(o.to_string(), "-o <file> <name>");
4992 }
4993
4994 #[test]
4995 fn option_display3() {
4996 let mut o = Arg::new("opt")
4997 .short('o')
4998 .num_args(1..)
4999 .action(ArgAction::Set)
5000 .value_names(["file", "name"]);
5001 o._build();
5002
5003 assert_eq!(o.to_string(), "-o <file> <name>...");
5004 }
5005
5006 #[test]
5007 fn option_display_single_alias() {
5008 let mut o = Arg::new("opt")
5009 .long("option")
5010 .action(ArgAction::Set)
5011 .visible_alias("als");
5012 o._build();
5013
5014 assert_eq!(o.to_string(), "--option <opt>");
5015 }
5016
5017 #[test]
5018 fn option_display_multiple_aliases() {
5019 let mut o = Arg::new("opt")
5020 .long("option")
5021 .action(ArgAction::Set)
5022 .visible_aliases(["als2", "als3", "als4"])
5023 .alias("als_not_visible");
5024 o._build();
5025
5026 assert_eq!(o.to_string(), "--option <opt>");
5027 }
5028
5029 #[test]
5030 fn option_display_single_short_alias() {
5031 let mut o = Arg::new("opt")
5032 .short('a')
5033 .action(ArgAction::Set)
5034 .visible_short_alias('b');
5035 o._build();
5036
5037 assert_eq!(o.to_string(), "-a <opt>");
5038 }
5039
5040 #[test]
5041 fn option_display_multiple_short_aliases() {
5042 let mut o = Arg::new("opt")
5043 .short('a')
5044 .action(ArgAction::Set)
5045 .visible_short_aliases(['b', 'c', 'd'])
5046 .short_alias('e');
5047 o._build();
5048
5049 assert_eq!(o.to_string(), "-a <opt>");
5050 }
5051
5052 // Positionals
5053
5054 #[test]
5055 fn positional_display_multiple_values() {
5056 let mut p = Arg::new("pos").index(1).num_args(1..);
5057 p._build();
5058
5059 assert_eq!(p.to_string(), "[pos]...");
5060 }
5061
5062 #[test]
5063 fn positional_display_multiple_values_required() {
5064 let mut p = Arg::new("pos").index(1).num_args(1..).required(true);
5065 p._build();
5066
5067 assert_eq!(p.to_string(), "<pos>...");
5068 }
5069
5070 #[test]
5071 fn positional_display_zero_or_more_values() {
5072 let mut p = Arg::new("pos").index(1).num_args(0..);
5073 p._build();
5074
5075 assert_eq!(p.to_string(), "[pos]...");
5076 }
5077
5078 #[test]
5079 fn positional_display_one_or_more_values() {
5080 let mut p = Arg::new("pos").index(1).num_args(1..);
5081 p._build();
5082
5083 assert_eq!(p.to_string(), "[pos]...");
5084 }
5085
5086 #[test]
5087 fn positional_display_one_or_more_values_required() {
5088 let mut p = Arg::new("pos").index(1).num_args(1..).required(true);
5089 p._build();
5090
5091 assert_eq!(p.to_string(), "<pos>...");
5092 }
5093
5094 #[test]
5095 fn positional_display_optional_value() {
5096 let mut p = Arg::new("pos")
5097 .index(1)
5098 .num_args(0..=1)
5099 .action(ArgAction::Set);
5100 p._build();
5101
5102 assert_eq!(p.to_string(), "[pos]");
5103 }
5104
5105 #[test]
5106 fn positional_display_multiple_occurrences() {
5107 let mut p = Arg::new("pos").index(1).action(ArgAction::Append);
5108 p._build();
5109
5110 assert_eq!(p.to_string(), "[pos]...");
5111 }
5112
5113 #[test]
5114 fn positional_display_multiple_occurrences_required() {
5115 let mut p = Arg::new("pos")
5116 .index(1)
5117 .action(ArgAction::Append)
5118 .required(true);
5119 p._build();
5120
5121 assert_eq!(p.to_string(), "<pos>...");
5122 }
5123
5124 #[test]
5125 fn positional_display_required() {
5126 let mut p = Arg::new("pos").index(1).required(true);
5127 p._build();
5128
5129 assert_eq!(p.to_string(), "<pos>");
5130 }
5131
5132 #[test]
5133 fn positional_display_val_names() {
5134 let mut p = Arg::new("pos").index(1).value_names(["file1", "file2"]);
5135 p._build();
5136
5137 assert_eq!(p.to_string(), "[file1] [file2]");
5138 }
5139
5140 #[test]
5141 fn positional_display_val_names_required() {
5142 let mut p = Arg::new("pos")
5143 .index(1)
5144 .value_names(["file1", "file2"])
5145 .required(true);
5146 p._build();
5147
5148 assert_eq!(p.to_string(), "<file1> <file2>");
5149 }
5150}