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