1 #[cfg(feature = "yaml")] 2 use std::collections::BTreeMap; 3 use std::rc::Rc; 4 use std::ffi::{OsStr, OsString}; 5 #[cfg(any(target_os = "windows", target_arch = "wasm32"))] 6 use osstringext::OsStrExt3; 7 #[cfg(not(any(target_os = "windows", target_arch = "wasm32")))] 8 use std::os::unix::ffi::OsStrExt; 9 use std::env; 10 11 #[cfg(feature = "yaml")] 12 use yaml_rust::Yaml; 13 use map::VecMap; 14 15 use usage_parser::UsageParser; 16 use args::settings::ArgSettings; 17 use args::arg_builder::{Base, Switched, Valued}; 18 19 /// The abstract representation of a command line argument. Used to set all the options and 20 /// relationships that define a valid argument for the program. 21 /// 22 /// There are two methods for constructing [`Arg`]s, using the builder pattern and setting options 23 /// manually, or using a usage string which is far less verbose but has fewer options. You can also 24 /// use a combination of the two methods to achieve the best of both worlds. 25 /// 26 /// # Examples 27 /// 28 /// ```rust 29 /// # use clap::Arg; 30 /// // Using the traditional builder pattern and setting each option manually 31 /// let cfg = Arg::with_name("config") 32 /// .short("c") 33 /// .long("config") 34 /// .takes_value(true) 35 /// .value_name("FILE") 36 /// .help("Provides a config file to myprog"); 37 /// // Using a usage string (setting a similar argument to the one above) 38 /// let input = Arg::from_usage("-i, --input=[FILE] 'Provides an input file to the program'"); 39 /// ``` 40 /// [`Arg`]: ./struct.Arg.html 41 #[allow(missing_debug_implementations)] 42 #[derive(Default, Clone)] 43 pub struct Arg<'a, 'b> 44 where 45 'a: 'b, 46 { 47 #[doc(hidden)] pub b: Base<'a, 'b>, 48 #[doc(hidden)] pub s: Switched<'b>, 49 #[doc(hidden)] pub v: Valued<'a, 'b>, 50 #[doc(hidden)] pub index: Option<u64>, 51 #[doc(hidden)] pub r_ifs: Option<Vec<(&'a str, &'b str)>>, 52 } 53 54 impl<'a, 'b> Arg<'a, 'b> { 55 /// Creates a new instance of [`Arg`] using a unique string name. The name will be used to get 56 /// information about whether or not the argument was used at runtime, get values, set 57 /// relationships with other args, etc.. 58 /// 59 /// **NOTE:** In the case of arguments that take values (i.e. [`Arg::takes_value(true)`]) 60 /// and positional arguments (i.e. those without a preceding `-` or `--`) the name will also 61 /// be displayed when the user prints the usage/help information of the program. 62 /// 63 /// # Examples 64 /// 65 /// ```rust 66 /// # use clap::{App, Arg}; 67 /// Arg::with_name("config") 68 /// # ; 69 /// ``` 70 /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value 71 /// [`Arg`]: ./struct.Arg.html with_name(n: &'a str) -> Self72 pub fn with_name(n: &'a str) -> Self { 73 Arg { 74 b: Base::new(n), 75 ..Default::default() 76 } 77 } 78 79 /// Creates a new instance of [`Arg`] from a .yml (YAML) file. 80 /// 81 /// # Examples 82 /// 83 /// ```ignore 84 /// # #[macro_use] 85 /// # extern crate clap; 86 /// # use clap::Arg; 87 /// # fn main() { 88 /// let yml = load_yaml!("arg.yml"); 89 /// let arg = Arg::from_yaml(yml); 90 /// # } 91 /// ``` 92 /// [`Arg`]: ./struct.Arg.html 93 #[cfg(feature = "yaml")] from_yaml(y: &BTreeMap<Yaml, Yaml>) -> Arg94 pub fn from_yaml(y: &BTreeMap<Yaml, Yaml>) -> Arg { 95 // We WANT this to panic on error...so expect() is good. 96 let name_yml = y.keys().nth(0).unwrap(); 97 let name_str = name_yml.as_str().unwrap(); 98 let mut a = Arg::with_name(name_str); 99 let arg_settings = y.get(name_yml).unwrap().as_hash().unwrap(); 100 101 for (k, v) in arg_settings.iter() { 102 a = match k.as_str().unwrap() { 103 "short" => yaml_to_str!(a, v, short), 104 "long" => yaml_to_str!(a, v, long), 105 "aliases" => yaml_vec_or_str!(v, a, alias), 106 "help" => yaml_to_str!(a, v, help), 107 "long_help" => yaml_to_str!(a, v, long_help), 108 "required" => yaml_to_bool!(a, v, required), 109 "required_if" => yaml_tuple2!(a, v, required_if), 110 "required_ifs" => yaml_tuple2!(a, v, required_if), 111 "takes_value" => yaml_to_bool!(a, v, takes_value), 112 "index" => yaml_to_u64!(a, v, index), 113 "global" => yaml_to_bool!(a, v, global), 114 "multiple" => yaml_to_bool!(a, v, multiple), 115 "hidden" => yaml_to_bool!(a, v, hidden), 116 "next_line_help" => yaml_to_bool!(a, v, next_line_help), 117 "empty_values" => yaml_to_bool!(a, v, empty_values), 118 "group" => yaml_to_str!(a, v, group), 119 "number_of_values" => yaml_to_u64!(a, v, number_of_values), 120 "max_values" => yaml_to_u64!(a, v, max_values), 121 "min_values" => yaml_to_u64!(a, v, min_values), 122 "value_name" => yaml_to_str!(a, v, value_name), 123 "use_delimiter" => yaml_to_bool!(a, v, use_delimiter), 124 "allow_hyphen_values" => yaml_to_bool!(a, v, allow_hyphen_values), 125 "last" => yaml_to_bool!(a, v, last), 126 "require_delimiter" => yaml_to_bool!(a, v, require_delimiter), 127 "value_delimiter" => yaml_to_str!(a, v, value_delimiter), 128 "required_unless" => yaml_to_str!(a, v, required_unless), 129 "display_order" => yaml_to_usize!(a, v, display_order), 130 "default_value" => yaml_to_str!(a, v, default_value), 131 "default_value_if" => yaml_tuple3!(a, v, default_value_if), 132 "default_value_ifs" => yaml_tuple3!(a, v, default_value_if), 133 "env" => yaml_to_str!(a, v, env), 134 "value_names" => yaml_vec_or_str!(v, a, value_name), 135 "groups" => yaml_vec_or_str!(v, a, group), 136 "requires" => yaml_vec_or_str!(v, a, requires), 137 "requires_if" => yaml_tuple2!(a, v, requires_if), 138 "requires_ifs" => yaml_tuple2!(a, v, requires_if), 139 "conflicts_with" => yaml_vec_or_str!(v, a, conflicts_with), 140 "overrides_with" => yaml_vec_or_str!(v, a, overrides_with), 141 "possible_values" => yaml_vec_or_str!(v, a, possible_value), 142 "case_insensitive" => yaml_to_bool!(a, v, case_insensitive), 143 "required_unless_one" => yaml_vec_or_str!(v, a, required_unless), 144 "required_unless_all" => { 145 a = yaml_vec_or_str!(v, a, required_unless); 146 a.setb(ArgSettings::RequiredUnlessAll); 147 a 148 } 149 s => panic!( 150 "Unknown Arg setting '{}' in YAML file for arg '{}'", 151 s, name_str 152 ), 153 } 154 } 155 156 a 157 } 158 159 /// Creates a new instance of [`Arg`] from a usage string. Allows creation of basic settings 160 /// for the [`Arg`]. The syntax is flexible, but there are some rules to follow. 161 /// 162 /// **NOTE**: Not all settings may be set using the usage string method. Some properties are 163 /// only available via the builder pattern. 164 /// 165 /// **NOTE**: Only ASCII values are officially supported in [`Arg::from_usage`] strings. Some 166 /// UTF-8 codepoints may work just fine, but this is not guaranteed. 167 /// 168 /// # Syntax 169 /// 170 /// Usage strings typically following the form: 171 /// 172 /// ```notrust 173 /// [explicit name] [short] [long] [value names] [help string] 174 /// ``` 175 /// 176 /// This is not a hard rule as the attributes can appear in other orders. There are also 177 /// several additional sigils which denote additional settings. Below are the details of each 178 /// portion of the string. 179 /// 180 /// ### Explicit Name 181 /// 182 /// This is an optional field, if it's omitted the argument will use one of the additional 183 /// fields as the name using the following priority order: 184 /// 185 /// * Explicit Name (This always takes precedence when present) 186 /// * Long 187 /// * Short 188 /// * Value Name 189 /// 190 /// `clap` determines explicit names as the first string of characters between either `[]` or 191 /// `<>` where `[]` has the dual notation of meaning the argument is optional, and `<>` meaning 192 /// the argument is required. 193 /// 194 /// Explicit names may be followed by: 195 /// * The multiple denotation `...` 196 /// 197 /// Example explicit names as follows (`ename` for an optional argument, and `rname` for a 198 /// required argument): 199 /// 200 /// ```notrust 201 /// [ename] -s, --long 'some flag' 202 /// <rname> -r, --longer 'some other flag' 203 /// ``` 204 /// 205 /// ### Short 206 /// 207 /// This is set by placing a single character after a leading `-`. 208 /// 209 /// Shorts may be followed by 210 /// * The multiple denotation `...` 211 /// * An optional comma `,` which is cosmetic only 212 /// * Value notation 213 /// 214 /// Example shorts are as follows (`-s`, and `-r`): 215 /// 216 /// ```notrust 217 /// -s, --long 'some flag' 218 /// <rname> -r [val], --longer 'some option' 219 /// ``` 220 /// 221 /// ### Long 222 /// 223 /// This is set by placing a word (no spaces) after a leading `--`. 224 /// 225 /// Shorts may be followed by 226 /// * The multiple denotation `...` 227 /// * Value notation 228 /// 229 /// Example longs are as follows (`--some`, and `--rapid`): 230 /// 231 /// ```notrust 232 /// -s, --some 'some flag' 233 /// --rapid=[FILE] 'some option' 234 /// ``` 235 /// 236 /// ### Values (Value Notation) 237 /// 238 /// This is set by placing a word(s) between `[]` or `<>` optionally after `=` (although this 239 /// is cosmetic only and does not affect functionality). If an explicit name has **not** been 240 /// set, using `<>` will denote a required argument, and `[]` will denote an optional argument 241 /// 242 /// Values may be followed by 243 /// * The multiple denotation `...` 244 /// * More Value notation 245 /// 246 /// More than one value will also implicitly set the arguments number of values, i.e. having 247 /// two values, `--option [val1] [val2]` specifies that in order for option to be satisified it 248 /// must receive exactly two values 249 /// 250 /// Example values are as follows (`FILE`, and `SPEED`): 251 /// 252 /// ```notrust 253 /// -s, --some [FILE] 'some option' 254 /// --rapid=<SPEED>... 'some required multiple option' 255 /// ``` 256 /// 257 /// ### Help String 258 /// 259 /// The help string is denoted between a pair of single quotes `''` and may contain any 260 /// characters. 261 /// 262 /// Example help strings are as follows: 263 /// 264 /// ```notrust 265 /// -s, --some [FILE] 'some option' 266 /// --rapid=<SPEED>... 'some required multiple option' 267 /// ``` 268 /// 269 /// ### Additional Sigils 270 /// 271 /// Multiple notation `...` (three consecutive dots/periods) specifies that this argument may 272 /// be used multiple times. Do not confuse multiple occurrences (`...`) with multiple values. 273 /// `--option val1 val2` is a single occurrence with multiple values. `--flag --flag` is 274 /// multiple occurrences (and then you can obviously have instances of both as well) 275 /// 276 /// # Examples 277 /// 278 /// ```rust 279 /// # use clap::{App, Arg}; 280 /// App::new("prog") 281 /// .args(&[ 282 /// Arg::from_usage("--config <FILE> 'a required file for the configuration and no short'"), 283 /// Arg::from_usage("-d, --debug... 'turns on debugging information and allows multiples'"), 284 /// Arg::from_usage("[input] 'an optional input file to use'") 285 /// ]) 286 /// # ; 287 /// ``` 288 /// [`Arg`]: ./struct.Arg.html 289 /// [`Arg::from_usage`]: ./struct.Arg.html#method.from_usage from_usage(u: &'a str) -> Self290 pub fn from_usage(u: &'a str) -> Self { 291 let parser = UsageParser::from_usage(u); 292 parser.parse() 293 } 294 295 /// Sets the short version of the argument without the preceding `-`. 296 /// 297 /// By default `clap` automatically assigns `V` and `h` to the auto-generated `version` and 298 /// `help` arguments respectively. You may use the uppercase `V` or lowercase `h` for your own 299 /// arguments, in which case `clap` simply will not assign those to the auto-generated 300 /// `version` or `help` arguments. 301 /// 302 /// **NOTE:** Any leading `-` characters will be stripped, and only the first 303 /// non `-` character will be used as the [`short`] version 304 /// 305 /// # Examples 306 /// 307 /// To set [`short`] use a single valid UTF-8 code point. If you supply a leading `-` such as 308 /// `-c`, the `-` will be stripped. 309 /// 310 /// ```rust 311 /// # use clap::{App, Arg}; 312 /// Arg::with_name("config") 313 /// .short("c") 314 /// # ; 315 /// ``` 316 /// 317 /// Setting [`short`] allows using the argument via a single hyphen (`-`) such as `-c` 318 /// 319 /// ```rust 320 /// # use clap::{App, Arg}; 321 /// let m = App::new("prog") 322 /// .arg(Arg::with_name("config") 323 /// .short("c")) 324 /// .get_matches_from(vec![ 325 /// "prog", "-c" 326 /// ]); 327 /// 328 /// assert!(m.is_present("config")); 329 /// ``` 330 /// [`short`]: ./struct.Arg.html#method.short short<S: AsRef<str>>(mut self, s: S) -> Self331 pub fn short<S: AsRef<str>>(mut self, s: S) -> Self { 332 self.s.short = s.as_ref().trim_left_matches(|c| c == '-').chars().nth(0); 333 self 334 } 335 336 /// Sets the long version of the argument without the preceding `--`. 337 /// 338 /// By default `clap` automatically assigns `version` and `help` to the auto-generated 339 /// `version` and `help` arguments respectively. You may use the word `version` or `help` for 340 /// the long form of your own arguments, in which case `clap` simply will not assign those to 341 /// the auto-generated `version` or `help` arguments. 342 /// 343 /// **NOTE:** Any leading `-` characters will be stripped 344 /// 345 /// # Examples 346 /// 347 /// To set `long` use a word containing valid UTF-8 codepoints. If you supply a double leading 348 /// `--` such as `--config` they will be stripped. Hyphens in the middle of the word, however, 349 /// will *not* be stripped (i.e. `config-file` is allowed) 350 /// 351 /// ```rust 352 /// # use clap::{App, Arg}; 353 /// Arg::with_name("cfg") 354 /// .long("config") 355 /// # ; 356 /// ``` 357 /// 358 /// Setting `long` allows using the argument via a double hyphen (`--`) such as `--config` 359 /// 360 /// ```rust 361 /// # use clap::{App, Arg}; 362 /// let m = App::new("prog") 363 /// .arg(Arg::with_name("cfg") 364 /// .long("config")) 365 /// .get_matches_from(vec![ 366 /// "prog", "--config" 367 /// ]); 368 /// 369 /// assert!(m.is_present("cfg")); 370 /// ``` long(mut self, l: &'b str) -> Self371 pub fn long(mut self, l: &'b str) -> Self { 372 self.s.long = Some(l.trim_left_matches(|c| c == '-')); 373 self 374 } 375 376 /// Allows adding a [`Arg`] alias, which function as "hidden" arguments that 377 /// automatically dispatch as if this argument was used. This is more efficient, and easier 378 /// than creating multiple hidden arguments as one only needs to check for the existence of 379 /// this command, and not all variants. 380 /// 381 /// # Examples 382 /// 383 /// ```rust 384 /// # use clap::{App, Arg}; 385 /// let m = App::new("prog") 386 /// .arg(Arg::with_name("test") 387 /// .long("test") 388 /// .alias("alias") 389 /// .takes_value(true)) 390 /// .get_matches_from(vec![ 391 /// "prog", "--alias", "cool" 392 /// ]); 393 /// assert!(m.is_present("test")); 394 /// assert_eq!(m.value_of("test"), Some("cool")); 395 /// ``` 396 /// [`Arg`]: ./struct.Arg.html alias<S: Into<&'b str>>(mut self, name: S) -> Self397 pub fn alias<S: Into<&'b str>>(mut self, name: S) -> Self { 398 if let Some(ref mut als) = self.s.aliases { 399 als.push((name.into(), false)); 400 } else { 401 self.s.aliases = Some(vec![(name.into(), false)]); 402 } 403 self 404 } 405 406 /// Allows adding [`Arg`] aliases, which function as "hidden" arguments that 407 /// automatically dispatch as if this argument was used. This is more efficient, and easier 408 /// than creating multiple hidden subcommands as one only needs to check for the existence of 409 /// this command, and not all variants. 410 /// 411 /// # Examples 412 /// 413 /// ```rust 414 /// # use clap::{App, Arg}; 415 /// let m = App::new("prog") 416 /// .arg(Arg::with_name("test") 417 /// .long("test") 418 /// .aliases(&["do-stuff", "do-tests", "tests"]) 419 /// .help("the file to add") 420 /// .required(false)) 421 /// .get_matches_from(vec![ 422 /// "prog", "--do-tests" 423 /// ]); 424 /// assert!(m.is_present("test")); 425 /// ``` 426 /// [`Arg`]: ./struct.Arg.html aliases(mut self, names: &[&'b str]) -> Self427 pub fn aliases(mut self, names: &[&'b str]) -> Self { 428 if let Some(ref mut als) = self.s.aliases { 429 for n in names { 430 als.push((n, false)); 431 } 432 } else { 433 self.s.aliases = Some(names.iter().map(|n| (*n, false)).collect::<Vec<_>>()); 434 } 435 self 436 } 437 438 /// Allows adding a [`Arg`] alias that functions exactly like those defined with 439 /// [`Arg::alias`], except that they are visible inside the help message. 440 /// 441 /// # Examples 442 /// 443 /// ```rust 444 /// # use clap::{App, Arg}; 445 /// let m = App::new("prog") 446 /// .arg(Arg::with_name("test") 447 /// .visible_alias("something-awesome") 448 /// .long("test") 449 /// .takes_value(true)) 450 /// .get_matches_from(vec![ 451 /// "prog", "--something-awesome", "coffee" 452 /// ]); 453 /// assert!(m.is_present("test")); 454 /// assert_eq!(m.value_of("test"), Some("coffee")); 455 /// ``` 456 /// [`Arg`]: ./struct.Arg.html 457 /// [`App::alias`]: ./struct.Arg.html#method.alias visible_alias<S: Into<&'b str>>(mut self, name: S) -> Self458 pub fn visible_alias<S: Into<&'b str>>(mut self, name: S) -> Self { 459 if let Some(ref mut als) = self.s.aliases { 460 als.push((name.into(), true)); 461 } else { 462 self.s.aliases = Some(vec![(name.into(), true)]); 463 } 464 self 465 } 466 467 /// Allows adding multiple [`Arg`] aliases that functions exactly like those defined 468 /// with [`Arg::aliases`], except that they are visible inside the help message. 469 /// 470 /// # Examples 471 /// 472 /// ```rust 473 /// # use clap::{App, Arg}; 474 /// let m = App::new("prog") 475 /// .arg(Arg::with_name("test") 476 /// .long("test") 477 /// .visible_aliases(&["something", "awesome", "cool"])) 478 /// .get_matches_from(vec![ 479 /// "prog", "--awesome" 480 /// ]); 481 /// assert!(m.is_present("test")); 482 /// ``` 483 /// [`Arg`]: ./struct.Arg.html 484 /// [`App::aliases`]: ./struct.Arg.html#method.aliases visible_aliases(mut self, names: &[&'b str]) -> Self485 pub fn visible_aliases(mut self, names: &[&'b str]) -> Self { 486 if let Some(ref mut als) = self.s.aliases { 487 for n in names { 488 als.push((n, true)); 489 } 490 } else { 491 self.s.aliases = Some(names.iter().map(|n| (*n, true)).collect::<Vec<_>>()); 492 } 493 self 494 } 495 496 /// Sets the short help text of the argument that will be displayed to the user when they print 497 /// the help information with `-h`. Typically, this is a short (one line) description of the 498 /// arg. 499 /// 500 /// **NOTE:** If only `Arg::help` is provided, and not [`Arg::long_help`] but the user requests 501 /// `--help` clap will still display the contents of `help` appropriately 502 /// 503 /// **NOTE:** Only `Arg::help` is used in completion script generation in order to be concise 504 /// 505 /// # Examples 506 /// 507 /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to 508 /// include a newline in the help text and have the following text be properly aligned with all 509 /// the other help text. 510 /// 511 /// ```rust 512 /// # use clap::{App, Arg}; 513 /// Arg::with_name("config") 514 /// .help("The config file used by the myprog") 515 /// # ; 516 /// ``` 517 /// 518 /// Setting `help` displays a short message to the side of the argument when the user passes 519 /// `-h` or `--help` (by default). 520 /// 521 /// ```rust 522 /// # use clap::{App, Arg}; 523 /// let m = App::new("prog") 524 /// .arg(Arg::with_name("cfg") 525 /// .long("config") 526 /// .help("Some help text describing the --config arg")) 527 /// .get_matches_from(vec![ 528 /// "prog", "--help" 529 /// ]); 530 /// ``` 531 /// 532 /// The above example displays 533 /// 534 /// ```notrust 535 /// helptest 536 /// 537 /// USAGE: 538 /// helptest [FLAGS] 539 /// 540 /// FLAGS: 541 /// --config Some help text describing the --config arg 542 /// -h, --help Prints help information 543 /// -V, --version Prints version information 544 /// ``` 545 /// [`Arg::long_help`]: ./struct.Arg.html#method.long_help help(mut self, h: &'b str) -> Self546 pub fn help(mut self, h: &'b str) -> Self { 547 self.b.help = Some(h); 548 self 549 } 550 551 /// Sets the long help text of the argument that will be displayed to the user when they print 552 /// the help information with `--help`. Typically this a more detailed (multi-line) message 553 /// that describes the arg. 554 /// 555 /// **NOTE:** If only `long_help` is provided, and not [`Arg::help`] but the user requests `-h` 556 /// clap will still display the contents of `long_help` appropriately 557 /// 558 /// **NOTE:** Only [`Arg::help`] is used in completion script generation in order to be concise 559 /// 560 /// # Examples 561 /// 562 /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to 563 /// include a newline in the help text and have the following text be properly aligned with all 564 /// the other help text. 565 /// 566 /// ```rust 567 /// # use clap::{App, Arg}; 568 /// Arg::with_name("config") 569 /// .long_help( 570 /// "The config file used by the myprog must be in JSON format 571 /// with only valid keys and may not contain other nonsense 572 /// that cannot be read by this program. Obviously I'm going on 573 /// and on, so I'll stop now.") 574 /// # ; 575 /// ``` 576 /// 577 /// Setting `help` displays a short message to the side of the argument when the user passes 578 /// `-h` or `--help` (by default). 579 /// 580 /// ```rust 581 /// # use clap::{App, Arg}; 582 /// let m = App::new("prog") 583 /// .arg(Arg::with_name("cfg") 584 /// .long("config") 585 /// .long_help( 586 /// "The config file used by the myprog must be in JSON format 587 /// with only valid keys and may not contain other nonsense 588 /// that cannot be read by this program. Obviously I'm going on 589 /// and on, so I'll stop now.")) 590 /// .get_matches_from(vec![ 591 /// "prog", "--help" 592 /// ]); 593 /// ``` 594 /// 595 /// The above example displays 596 /// 597 /// ```notrust 598 /// helptest 599 /// 600 /// USAGE: 601 /// helptest [FLAGS] 602 /// 603 /// FLAGS: 604 /// --config 605 /// The config file used by the myprog must be in JSON format 606 /// with only valid keys and may not contain other nonsense 607 /// that cannot be read by this program. Obviously I'm going on 608 /// and on, so I'll stop now. 609 /// 610 /// -h, --help 611 /// Prints help information 612 /// 613 /// -V, --version 614 /// Prints version information 615 /// ``` 616 /// [`Arg::help`]: ./struct.Arg.html#method.help long_help(mut self, h: &'b str) -> Self617 pub fn long_help(mut self, h: &'b str) -> Self { 618 self.b.long_help = Some(h); 619 self 620 } 621 622 /// Specifies that this arg is the last, or final, positional argument (i.e. has the highest 623 /// index) and is *only* able to be accessed via the `--` syntax (i.e. `$ prog args -- 624 /// last_arg`). Even, if no other arguments are left to parse, if the user omits the `--` syntax 625 /// they will receive an [`UnknownArgument`] error. Setting an argument to `.last(true)` also 626 /// allows one to access this arg early using the `--` syntax. Accessing an arg early, even with 627 /// the `--` syntax is otherwise not possible. 628 /// 629 /// **NOTE:** This will change the usage string to look like `$ prog [FLAGS] [-- <ARG>]` if 630 /// `ARG` is marked as `.last(true)`. 631 /// 632 /// **NOTE:** This setting will imply [`AppSettings::DontCollapseArgsInUsage`] because failing 633 /// to set this can make the usage string very confusing. 634 /// 635 /// **NOTE**: This setting only applies to positional arguments, and has no affect on FLAGS / 636 /// OPTIONS 637 /// 638 /// **CAUTION:** Setting an argument to `.last(true)` *and* having child subcommands is not 639 /// recommended with the exception of *also* using [`AppSettings::ArgsNegateSubcommands`] 640 /// (or [`AppSettings::SubcommandsNegateReqs`] if the argument marked `.last(true)` is also 641 /// marked [`.required(true)`]) 642 /// 643 /// # Examples 644 /// 645 /// ```rust 646 /// # use clap::Arg; 647 /// Arg::with_name("args") 648 /// .last(true) 649 /// # ; 650 /// ``` 651 /// 652 /// Setting [`Arg::last(true)`] ensures the arg has the highest [index] of all positional args 653 /// and requires that the `--` syntax be used to access it early. 654 /// 655 /// ```rust 656 /// # use clap::{App, Arg}; 657 /// let res = App::new("prog") 658 /// .arg(Arg::with_name("first")) 659 /// .arg(Arg::with_name("second")) 660 /// .arg(Arg::with_name("third").last(true)) 661 /// .get_matches_from_safe(vec![ 662 /// "prog", "one", "--", "three" 663 /// ]); 664 /// 665 /// assert!(res.is_ok()); 666 /// let m = res.unwrap(); 667 /// assert_eq!(m.value_of("third"), Some("three")); 668 /// assert!(m.value_of("second").is_none()); 669 /// ``` 670 /// 671 /// Even if the positional argument marked `.last(true)` is the only argument left to parse, 672 /// failing to use the `--` syntax results in an error. 673 /// 674 /// ```rust 675 /// # use clap::{App, Arg, ErrorKind}; 676 /// let res = App::new("prog") 677 /// .arg(Arg::with_name("first")) 678 /// .arg(Arg::with_name("second")) 679 /// .arg(Arg::with_name("third").last(true)) 680 /// .get_matches_from_safe(vec![ 681 /// "prog", "one", "two", "three" 682 /// ]); 683 /// 684 /// assert!(res.is_err()); 685 /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); 686 /// ``` 687 /// [`Arg::last(true)`]: ./struct.Arg.html#method.last 688 /// [index]: ./struct.Arg.html#method.index 689 /// [`AppSettings::DontCollapseArgsInUsage`]: ./enum.AppSettings.html#variant.DontCollapseArgsInUsage 690 /// [`AppSettings::ArgsNegateSubcommands`]: ./enum.AppSettings.html#variant.ArgsNegateSubcommands 691 /// [`AppSettings::SubcommandsNegateReqs`]: ./enum.AppSettings.html#variant.SubcommandsNegateReqs 692 /// [`.required(true)`]: ./struct.Arg.html#method.required 693 /// [`UnknownArgument`]: ./enum.ErrorKind.html#variant.UnknownArgument last(self, l: bool) -> Self694 pub fn last(self, l: bool) -> Self { 695 if l { 696 self.set(ArgSettings::Last) 697 } else { 698 self.unset(ArgSettings::Last) 699 } 700 } 701 702 /// Sets whether or not the argument is required by default. Required by default means it is 703 /// required, when no other conflicting rules have been evaluated. Conflicting rules take 704 /// precedence over being required. **Default:** `false` 705 /// 706 /// **NOTE:** Flags (i.e. not positional, or arguments that take values) cannot be required by 707 /// default. This is simply because if a flag should be required, it should simply be implied 708 /// as no additional information is required from user. Flags by their very nature are simply 709 /// yes/no, or true/false. 710 /// 711 /// # Examples 712 /// 713 /// ```rust 714 /// # use clap::Arg; 715 /// Arg::with_name("config") 716 /// .required(true) 717 /// # ; 718 /// ``` 719 /// 720 /// Setting [`Arg::required(true)`] requires that the argument be used at runtime. 721 /// 722 /// ```rust 723 /// # use clap::{App, Arg}; 724 /// let res = App::new("prog") 725 /// .arg(Arg::with_name("cfg") 726 /// .required(true) 727 /// .takes_value(true) 728 /// .long("config")) 729 /// .get_matches_from_safe(vec![ 730 /// "prog", "--config", "file.conf" 731 /// ]); 732 /// 733 /// assert!(res.is_ok()); 734 /// ``` 735 /// 736 /// Setting [`Arg::required(true)`] and *not* supplying that argument is an error. 737 /// 738 /// ```rust 739 /// # use clap::{App, Arg, ErrorKind}; 740 /// let res = App::new("prog") 741 /// .arg(Arg::with_name("cfg") 742 /// .required(true) 743 /// .takes_value(true) 744 /// .long("config")) 745 /// .get_matches_from_safe(vec![ 746 /// "prog" 747 /// ]); 748 /// 749 /// assert!(res.is_err()); 750 /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); 751 /// ``` 752 /// [`Arg::required(true)`]: ./struct.Arg.html#method.required required(self, r: bool) -> Self753 pub fn required(self, r: bool) -> Self { 754 if r { 755 self.set(ArgSettings::Required) 756 } else { 757 self.unset(ArgSettings::Required) 758 } 759 } 760 761 /// Requires that options use the `--option=val` syntax (i.e. an equals between the option and 762 /// associated value) **Default:** `false` 763 /// 764 /// **NOTE:** This setting also removes the default of allowing empty values and implies 765 /// [`Arg::empty_values(false)`]. 766 /// 767 /// # Examples 768 /// 769 /// ```rust 770 /// # use clap::Arg; 771 /// Arg::with_name("config") 772 /// .long("config") 773 /// .takes_value(true) 774 /// .require_equals(true) 775 /// # ; 776 /// ``` 777 /// 778 /// Setting [`Arg::require_equals(true)`] requires that the option have an equals sign between 779 /// it and the associated value. 780 /// 781 /// ```rust 782 /// # use clap::{App, Arg}; 783 /// let res = App::new("prog") 784 /// .arg(Arg::with_name("cfg") 785 /// .require_equals(true) 786 /// .takes_value(true) 787 /// .long("config")) 788 /// .get_matches_from_safe(vec![ 789 /// "prog", "--config=file.conf" 790 /// ]); 791 /// 792 /// assert!(res.is_ok()); 793 /// ``` 794 /// 795 /// Setting [`Arg::require_equals(true)`] and *not* supplying the equals will cause an error 796 /// unless [`Arg::empty_values(true)`] is set. 797 /// 798 /// ```rust 799 /// # use clap::{App, Arg, ErrorKind}; 800 /// let res = App::new("prog") 801 /// .arg(Arg::with_name("cfg") 802 /// .require_equals(true) 803 /// .takes_value(true) 804 /// .long("config")) 805 /// .get_matches_from_safe(vec![ 806 /// "prog", "--config", "file.conf" 807 /// ]); 808 /// 809 /// assert!(res.is_err()); 810 /// assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue); 811 /// ``` 812 /// [`Arg::require_equals(true)`]: ./struct.Arg.html#method.require_equals 813 /// [`Arg::empty_values(true)`]: ./struct.Arg.html#method.empty_values 814 /// [`Arg::empty_values(false)`]: ./struct.Arg.html#method.empty_values require_equals(mut self, r: bool) -> Self815 pub fn require_equals(mut self, r: bool) -> Self { 816 if r { 817 self.unsetb(ArgSettings::EmptyValues); 818 self.set(ArgSettings::RequireEquals) 819 } else { 820 self.unset(ArgSettings::RequireEquals) 821 } 822 } 823 824 /// Allows values which start with a leading hyphen (`-`) 825 /// 826 /// **WARNING**: Take caution when using this setting combined with [`Arg::multiple(true)`], as 827 /// this becomes ambiguous `$ prog --arg -- -- val`. All three `--, --, val` will be values 828 /// when the user may have thought the second `--` would constitute the normal, "Only 829 /// positional args follow" idiom. To fix this, consider using [`Arg::number_of_values(1)`] 830 /// 831 /// **WARNING**: When building your CLIs, consider the effects of allowing leading hyphens and 832 /// the user passing in a value that matches a valid short. For example `prog -opt -F` where 833 /// `-F` is supposed to be a value, yet `-F` is *also* a valid short for another arg. Care should 834 /// should be taken when designing these args. This is compounded by the ability to "stack" 835 /// short args. I.e. if `-val` is supposed to be a value, but `-v`, `-a`, and `-l` are all valid 836 /// shorts. 837 /// 838 /// # Examples 839 /// 840 /// ```rust 841 /// # use clap::Arg; 842 /// Arg::with_name("pattern") 843 /// .allow_hyphen_values(true) 844 /// # ; 845 /// ``` 846 /// 847 /// ```rust 848 /// # use clap::{App, Arg}; 849 /// let m = App::new("prog") 850 /// .arg(Arg::with_name("pat") 851 /// .allow_hyphen_values(true) 852 /// .takes_value(true) 853 /// .long("pattern")) 854 /// .get_matches_from(vec![ 855 /// "prog", "--pattern", "-file" 856 /// ]); 857 /// 858 /// assert_eq!(m.value_of("pat"), Some("-file")); 859 /// ``` 860 /// 861 /// Not setting [`Arg::allow_hyphen_values(true)`] and supplying a value which starts with a 862 /// hyphen is an error. 863 /// 864 /// ```rust 865 /// # use clap::{App, Arg, ErrorKind}; 866 /// let res = App::new("prog") 867 /// .arg(Arg::with_name("pat") 868 /// .takes_value(true) 869 /// .long("pattern")) 870 /// .get_matches_from_safe(vec![ 871 /// "prog", "--pattern", "-file" 872 /// ]); 873 /// 874 /// assert!(res.is_err()); 875 /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); 876 /// ``` 877 /// [`Arg::allow_hyphen_values(true)`]: ./struct.Arg.html#method.allow_hyphen_values 878 /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple 879 /// [`Arg::number_of_values(1)`]: ./struct.Arg.html#method.number_of_values allow_hyphen_values(self, a: bool) -> Self880 pub fn allow_hyphen_values(self, a: bool) -> Self { 881 if a { 882 self.set(ArgSettings::AllowLeadingHyphen) 883 } else { 884 self.unset(ArgSettings::AllowLeadingHyphen) 885 } 886 } 887 /// Sets an arg that override this arg's required setting. (i.e. this arg will be required 888 /// unless this other argument is present). 889 /// 890 /// **Pro Tip:** Using [`Arg::required_unless`] implies [`Arg::required`] and is therefore not 891 /// mandatory to also set. 892 /// 893 /// # Examples 894 /// 895 /// ```rust 896 /// # use clap::Arg; 897 /// Arg::with_name("config") 898 /// .required_unless("debug") 899 /// # ; 900 /// ``` 901 /// 902 /// Setting [`Arg::required_unless(name)`] requires that the argument be used at runtime 903 /// *unless* `name` is present. In the following example, the required argument is *not* 904 /// provided, but it's not an error because the `unless` arg has been supplied. 905 /// 906 /// ```rust 907 /// # use clap::{App, Arg}; 908 /// let res = App::new("prog") 909 /// .arg(Arg::with_name("cfg") 910 /// .required_unless("dbg") 911 /// .takes_value(true) 912 /// .long("config")) 913 /// .arg(Arg::with_name("dbg") 914 /// .long("debug")) 915 /// .get_matches_from_safe(vec![ 916 /// "prog", "--debug" 917 /// ]); 918 /// 919 /// assert!(res.is_ok()); 920 /// ``` 921 /// 922 /// Setting [`Arg::required_unless(name)`] and *not* supplying `name` or this arg is an error. 923 /// 924 /// ```rust 925 /// # use clap::{App, Arg, ErrorKind}; 926 /// let res = App::new("prog") 927 /// .arg(Arg::with_name("cfg") 928 /// .required_unless("dbg") 929 /// .takes_value(true) 930 /// .long("config")) 931 /// .arg(Arg::with_name("dbg") 932 /// .long("debug")) 933 /// .get_matches_from_safe(vec![ 934 /// "prog" 935 /// ]); 936 /// 937 /// assert!(res.is_err()); 938 /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); 939 /// ``` 940 /// [`Arg::required_unless`]: ./struct.Arg.html#method.required_unless 941 /// [`Arg::required`]: ./struct.Arg.html#method.required 942 /// [`Arg::required_unless(name)`]: ./struct.Arg.html#method.required_unless required_unless(mut self, name: &'a str) -> Self943 pub fn required_unless(mut self, name: &'a str) -> Self { 944 if let Some(ref mut vec) = self.b.r_unless { 945 vec.push(name); 946 } else { 947 self.b.r_unless = Some(vec![name]); 948 } 949 self.required(true) 950 } 951 952 /// Sets args that override this arg's required setting. (i.e. this arg will be required unless 953 /// all these other arguments are present). 954 /// 955 /// **NOTE:** If you wish for this argument to only be required if *one of* these args are 956 /// present see [`Arg::required_unless_one`] 957 /// 958 /// # Examples 959 /// 960 /// ```rust 961 /// # use clap::Arg; 962 /// Arg::with_name("config") 963 /// .required_unless_all(&["cfg", "dbg"]) 964 /// # ; 965 /// ``` 966 /// 967 /// Setting [`Arg::required_unless_all(names)`] requires that the argument be used at runtime 968 /// *unless* *all* the args in `names` are present. In the following example, the required 969 /// argument is *not* provided, but it's not an error because all the `unless` args have been 970 /// supplied. 971 /// 972 /// ```rust 973 /// # use clap::{App, Arg}; 974 /// let res = App::new("prog") 975 /// .arg(Arg::with_name("cfg") 976 /// .required_unless_all(&["dbg", "infile"]) 977 /// .takes_value(true) 978 /// .long("config")) 979 /// .arg(Arg::with_name("dbg") 980 /// .long("debug")) 981 /// .arg(Arg::with_name("infile") 982 /// .short("i") 983 /// .takes_value(true)) 984 /// .get_matches_from_safe(vec![ 985 /// "prog", "--debug", "-i", "file" 986 /// ]); 987 /// 988 /// assert!(res.is_ok()); 989 /// ``` 990 /// 991 /// Setting [`Arg::required_unless_all(names)`] and *not* supplying *all* of `names` or this 992 /// arg is an error. 993 /// 994 /// ```rust 995 /// # use clap::{App, Arg, ErrorKind}; 996 /// let res = App::new("prog") 997 /// .arg(Arg::with_name("cfg") 998 /// .required_unless_all(&["dbg", "infile"]) 999 /// .takes_value(true) 1000 /// .long("config")) 1001 /// .arg(Arg::with_name("dbg") 1002 /// .long("debug")) 1003 /// .arg(Arg::with_name("infile") 1004 /// .short("i") 1005 /// .takes_value(true)) 1006 /// .get_matches_from_safe(vec![ 1007 /// "prog" 1008 /// ]); 1009 /// 1010 /// assert!(res.is_err()); 1011 /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); 1012 /// ``` 1013 /// [`Arg::required_unless_one`]: ./struct.Arg.html#method.required_unless_one 1014 /// [`Arg::required_unless_all(names)`]: ./struct.Arg.html#method.required_unless_all required_unless_all(mut self, names: &[&'a str]) -> Self1015 pub fn required_unless_all(mut self, names: &[&'a str]) -> Self { 1016 if let Some(ref mut vec) = self.b.r_unless { 1017 for s in names { 1018 vec.push(s); 1019 } 1020 } else { 1021 self.b.r_unless = Some(names.iter().map(|s| *s).collect::<Vec<_>>()); 1022 } 1023 self.setb(ArgSettings::RequiredUnlessAll); 1024 self.required(true) 1025 } 1026 1027 /// Sets args that override this arg's [required] setting. (i.e. this arg will be required 1028 /// unless *at least one of* these other arguments are present). 1029 /// 1030 /// **NOTE:** If you wish for this argument to only be required if *all of* these args are 1031 /// present see [`Arg::required_unless_all`] 1032 /// 1033 /// # Examples 1034 /// 1035 /// ```rust 1036 /// # use clap::Arg; 1037 /// Arg::with_name("config") 1038 /// .required_unless_all(&["cfg", "dbg"]) 1039 /// # ; 1040 /// ``` 1041 /// 1042 /// Setting [`Arg::required_unless_one(names)`] requires that the argument be used at runtime 1043 /// *unless* *at least one of* the args in `names` are present. In the following example, the 1044 /// required argument is *not* provided, but it's not an error because one the `unless` args 1045 /// have been supplied. 1046 /// 1047 /// ```rust 1048 /// # use clap::{App, Arg}; 1049 /// let res = App::new("prog") 1050 /// .arg(Arg::with_name("cfg") 1051 /// .required_unless_one(&["dbg", "infile"]) 1052 /// .takes_value(true) 1053 /// .long("config")) 1054 /// .arg(Arg::with_name("dbg") 1055 /// .long("debug")) 1056 /// .arg(Arg::with_name("infile") 1057 /// .short("i") 1058 /// .takes_value(true)) 1059 /// .get_matches_from_safe(vec![ 1060 /// "prog", "--debug" 1061 /// ]); 1062 /// 1063 /// assert!(res.is_ok()); 1064 /// ``` 1065 /// 1066 /// Setting [`Arg::required_unless_one(names)`] and *not* supplying *at least one of* `names` 1067 /// or this arg is an error. 1068 /// 1069 /// ```rust 1070 /// # use clap::{App, Arg, ErrorKind}; 1071 /// let res = App::new("prog") 1072 /// .arg(Arg::with_name("cfg") 1073 /// .required_unless_one(&["dbg", "infile"]) 1074 /// .takes_value(true) 1075 /// .long("config")) 1076 /// .arg(Arg::with_name("dbg") 1077 /// .long("debug")) 1078 /// .arg(Arg::with_name("infile") 1079 /// .short("i") 1080 /// .takes_value(true)) 1081 /// .get_matches_from_safe(vec![ 1082 /// "prog" 1083 /// ]); 1084 /// 1085 /// assert!(res.is_err()); 1086 /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); 1087 /// ``` 1088 /// [required]: ./struct.Arg.html#method.required 1089 /// [`Arg::required_unless_one(names)`]: ./struct.Arg.html#method.required_unless_one 1090 /// [`Arg::required_unless_all`]: ./struct.Arg.html#method.required_unless_all required_unless_one(mut self, names: &[&'a str]) -> Self1091 pub fn required_unless_one(mut self, names: &[&'a str]) -> Self { 1092 if let Some(ref mut vec) = self.b.r_unless { 1093 for s in names { 1094 vec.push(s); 1095 } 1096 } else { 1097 self.b.r_unless = Some(names.iter().map(|s| *s).collect::<Vec<_>>()); 1098 } 1099 self.required(true) 1100 } 1101 1102 /// Sets a conflicting argument by name. I.e. when using this argument, 1103 /// the following argument can't be present and vice versa. 1104 /// 1105 /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules 1106 /// only need to be set for one of the two arguments, they do not need to be set for each. 1107 /// 1108 /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments 1109 /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need 1110 /// need to also do B.conflicts_with(A)) 1111 /// 1112 /// # Examples 1113 /// 1114 /// ```rust 1115 /// # use clap::Arg; 1116 /// Arg::with_name("config") 1117 /// .conflicts_with("debug") 1118 /// # ; 1119 /// ``` 1120 /// 1121 /// Setting conflicting argument, and having both arguments present at runtime is an error. 1122 /// 1123 /// ```rust 1124 /// # use clap::{App, Arg, ErrorKind}; 1125 /// let res = App::new("prog") 1126 /// .arg(Arg::with_name("cfg") 1127 /// .takes_value(true) 1128 /// .conflicts_with("debug") 1129 /// .long("config")) 1130 /// .arg(Arg::with_name("debug") 1131 /// .long("debug")) 1132 /// .get_matches_from_safe(vec![ 1133 /// "prog", "--debug", "--config", "file.conf" 1134 /// ]); 1135 /// 1136 /// assert!(res.is_err()); 1137 /// assert_eq!(res.unwrap_err().kind, ErrorKind::ArgumentConflict); 1138 /// ``` conflicts_with(mut self, name: &'a str) -> Self1139 pub fn conflicts_with(mut self, name: &'a str) -> Self { 1140 if let Some(ref mut vec) = self.b.blacklist { 1141 vec.push(name); 1142 } else { 1143 self.b.blacklist = Some(vec![name]); 1144 } 1145 self 1146 } 1147 1148 /// The same as [`Arg::conflicts_with`] but allows specifying multiple two-way conlicts per 1149 /// argument. 1150 /// 1151 /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules 1152 /// only need to be set for one of the two arguments, they do not need to be set for each. 1153 /// 1154 /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments 1155 /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need 1156 /// need to also do B.conflicts_with(A)) 1157 /// 1158 /// # Examples 1159 /// 1160 /// ```rust 1161 /// # use clap::Arg; 1162 /// Arg::with_name("config") 1163 /// .conflicts_with_all(&["debug", "input"]) 1164 /// # ; 1165 /// ``` 1166 /// 1167 /// Setting conflicting argument, and having any of the arguments present at runtime with a 1168 /// conflicting argument is an error. 1169 /// 1170 /// ```rust 1171 /// # use clap::{App, Arg, ErrorKind}; 1172 /// let res = App::new("prog") 1173 /// .arg(Arg::with_name("cfg") 1174 /// .takes_value(true) 1175 /// .conflicts_with_all(&["debug", "input"]) 1176 /// .long("config")) 1177 /// .arg(Arg::with_name("debug") 1178 /// .long("debug")) 1179 /// .arg(Arg::with_name("input") 1180 /// .index(1)) 1181 /// .get_matches_from_safe(vec![ 1182 /// "prog", "--config", "file.conf", "file.txt" 1183 /// ]); 1184 /// 1185 /// assert!(res.is_err()); 1186 /// assert_eq!(res.unwrap_err().kind, ErrorKind::ArgumentConflict); 1187 /// ``` 1188 /// [`Arg::conflicts_with`]: ./struct.Arg.html#method.conflicts_with conflicts_with_all(mut self, names: &[&'a str]) -> Self1189 pub fn conflicts_with_all(mut self, names: &[&'a str]) -> Self { 1190 if let Some(ref mut vec) = self.b.blacklist { 1191 for s in names { 1192 vec.push(s); 1193 } 1194 } else { 1195 self.b.blacklist = Some(names.iter().map(|s| *s).collect::<Vec<_>>()); 1196 } 1197 self 1198 } 1199 1200 /// Sets a overridable argument by name. I.e. this argument and the following argument 1201 /// will override each other in POSIX style (whichever argument was specified at runtime 1202 /// **last** "wins") 1203 /// 1204 /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any 1205 /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed 1206 /// 1207 /// **WARNING:** Positional arguments cannot override themselves (or we would never be able 1208 /// to advance to the next positional). If a positional agument lists itself as an override, 1209 /// it is simply ignored. 1210 /// 1211 /// # Examples 1212 /// 1213 /// ```rust 1214 /// # use clap::{App, Arg}; 1215 /// let m = App::new("prog") 1216 /// .arg(Arg::from_usage("-f, --flag 'some flag'") 1217 /// .conflicts_with("debug")) 1218 /// .arg(Arg::from_usage("-d, --debug 'other flag'")) 1219 /// .arg(Arg::from_usage("-c, --color 'third flag'") 1220 /// .overrides_with("flag")) 1221 /// .get_matches_from(vec![ 1222 /// "prog", "-f", "-d", "-c"]); 1223 /// // ^~~~~~~~~~~~^~~~~ flag is overridden by color 1224 /// 1225 /// assert!(m.is_present("color")); 1226 /// assert!(m.is_present("debug")); // even though flag conflicts with debug, it's as if flag 1227 /// // was never used because it was overridden with color 1228 /// assert!(!m.is_present("flag")); 1229 /// ``` 1230 /// Care must be taken when using this setting, and having an arg override with itself. This 1231 /// is common practice when supporting things like shell aliases, config files, etc. 1232 /// However, when combined with multiple values, it can get dicy. 1233 /// Here is how clap handles such situations: 1234 /// 1235 /// When a flag overrides itself, it's as if the flag was only ever used once (essentially 1236 /// preventing a "Unexpected multiple usage" error): 1237 /// 1238 /// ```rust 1239 /// # use clap::{App, Arg}; 1240 /// let m = App::new("posix") 1241 /// .arg(Arg::from_usage("--flag 'some flag'").overrides_with("flag")) 1242 /// .get_matches_from(vec!["posix", "--flag", "--flag"]); 1243 /// assert!(m.is_present("flag")); 1244 /// assert_eq!(m.occurrences_of("flag"), 1); 1245 /// ``` 1246 /// Making a arg `multiple(true)` and override itself is essentially meaningless. Therefore 1247 /// clap ignores an override of self if it's a flag and it already accepts multiple occurrences. 1248 /// 1249 /// ``` 1250 /// # use clap::{App, Arg}; 1251 /// let m = App::new("posix") 1252 /// .arg(Arg::from_usage("--flag... 'some flag'").overrides_with("flag")) 1253 /// .get_matches_from(vec!["", "--flag", "--flag", "--flag", "--flag"]); 1254 /// assert!(m.is_present("flag")); 1255 /// assert_eq!(m.occurrences_of("flag"), 4); 1256 /// ``` 1257 /// Now notice with options (which *do not* set `multiple(true)`), it's as if only the last 1258 /// occurrence happened. 1259 /// 1260 /// ``` 1261 /// # use clap::{App, Arg}; 1262 /// let m = App::new("posix") 1263 /// .arg(Arg::from_usage("--opt [val] 'some option'").overrides_with("opt")) 1264 /// .get_matches_from(vec!["", "--opt=some", "--opt=other"]); 1265 /// assert!(m.is_present("opt")); 1266 /// assert_eq!(m.occurrences_of("opt"), 1); 1267 /// assert_eq!(m.value_of("opt"), Some("other")); 1268 /// ``` 1269 /// 1270 /// Just like flags, options with `multiple(true)` set, will ignore the "override self" setting. 1271 /// 1272 /// ``` 1273 /// # use clap::{App, Arg}; 1274 /// let m = App::new("posix") 1275 /// .arg(Arg::from_usage("--opt [val]... 'some option'") 1276 /// .overrides_with("opt")) 1277 /// .get_matches_from(vec!["", "--opt", "first", "over", "--opt", "other", "val"]); 1278 /// assert!(m.is_present("opt")); 1279 /// assert_eq!(m.occurrences_of("opt"), 2); 1280 /// assert_eq!(m.values_of("opt").unwrap().collect::<Vec<_>>(), &["first", "over", "other", "val"]); 1281 /// ``` 1282 /// 1283 /// A safe thing to do if you'd like to support an option which supports multiple values, but 1284 /// also is "overridable" by itself, is to use `use_delimiter(false)` and *not* use 1285 /// `multiple(true)` while telling users to seperate values with a comma (i.e. `val1,val2`) 1286 /// 1287 /// ``` 1288 /// # use clap::{App, Arg}; 1289 /// let m = App::new("posix") 1290 /// .arg(Arg::from_usage("--opt [val] 'some option'") 1291 /// .overrides_with("opt") 1292 /// .use_delimiter(false)) 1293 /// .get_matches_from(vec!["", "--opt=some,other", "--opt=one,two"]); 1294 /// assert!(m.is_present("opt")); 1295 /// assert_eq!(m.occurrences_of("opt"), 1); 1296 /// assert_eq!(m.values_of("opt").unwrap().collect::<Vec<_>>(), &["one,two"]); 1297 /// ``` overrides_with(mut self, name: &'a str) -> Self1298 pub fn overrides_with(mut self, name: &'a str) -> Self { 1299 if let Some(ref mut vec) = self.b.overrides { 1300 vec.push(name); 1301 } else { 1302 self.b.overrides = Some(vec![name]); 1303 } 1304 self 1305 } 1306 1307 /// Sets multiple mutually overridable arguments by name. I.e. this argument and the following 1308 /// argument will override each other in POSIX style (whichever argument was specified at 1309 /// runtime **last** "wins") 1310 /// 1311 /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any 1312 /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed 1313 /// 1314 /// # Examples 1315 /// 1316 /// ```rust 1317 /// # use clap::{App, Arg}; 1318 /// let m = App::new("prog") 1319 /// .arg(Arg::from_usage("-f, --flag 'some flag'") 1320 /// .conflicts_with("color")) 1321 /// .arg(Arg::from_usage("-d, --debug 'other flag'")) 1322 /// .arg(Arg::from_usage("-c, --color 'third flag'") 1323 /// .overrides_with_all(&["flag", "debug"])) 1324 /// .get_matches_from(vec![ 1325 /// "prog", "-f", "-d", "-c"]); 1326 /// // ^~~~~~^~~~~~~~~ flag and debug are overridden by color 1327 /// 1328 /// assert!(m.is_present("color")); // even though flag conflicts with color, it's as if flag 1329 /// // and debug were never used because they were overridden 1330 /// // with color 1331 /// assert!(!m.is_present("debug")); 1332 /// assert!(!m.is_present("flag")); 1333 /// ``` overrides_with_all(mut self, names: &[&'a str]) -> Self1334 pub fn overrides_with_all(mut self, names: &[&'a str]) -> Self { 1335 if let Some(ref mut vec) = self.b.overrides { 1336 for s in names { 1337 vec.push(s); 1338 } 1339 } else { 1340 self.b.overrides = Some(names.iter().map(|s| *s).collect::<Vec<_>>()); 1341 } 1342 self 1343 } 1344 1345 /// Sets an argument by name that is required when this one is present I.e. when 1346 /// using this argument, the following argument *must* be present. 1347 /// 1348 /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required 1349 /// 1350 /// # Examples 1351 /// 1352 /// ```rust 1353 /// # use clap::Arg; 1354 /// Arg::with_name("config") 1355 /// .requires("input") 1356 /// # ; 1357 /// ``` 1358 /// 1359 /// Setting [`Arg::requires(name)`] requires that the argument be used at runtime if the 1360 /// defining argument is used. If the defining argument isn't used, the other argument isn't 1361 /// required 1362 /// 1363 /// ```rust 1364 /// # use clap::{App, Arg}; 1365 /// let res = App::new("prog") 1366 /// .arg(Arg::with_name("cfg") 1367 /// .takes_value(true) 1368 /// .requires("input") 1369 /// .long("config")) 1370 /// .arg(Arg::with_name("input") 1371 /// .index(1)) 1372 /// .get_matches_from_safe(vec![ 1373 /// "prog" 1374 /// ]); 1375 /// 1376 /// assert!(res.is_ok()); // We didn't use cfg, so input wasn't required 1377 /// ``` 1378 /// 1379 /// Setting [`Arg::requires(name)`] and *not* supplying that argument is an error. 1380 /// 1381 /// ```rust 1382 /// # use clap::{App, Arg, ErrorKind}; 1383 /// let res = App::new("prog") 1384 /// .arg(Arg::with_name("cfg") 1385 /// .takes_value(true) 1386 /// .requires("input") 1387 /// .long("config")) 1388 /// .arg(Arg::with_name("input") 1389 /// .index(1)) 1390 /// .get_matches_from_safe(vec![ 1391 /// "prog", "--config", "file.conf" 1392 /// ]); 1393 /// 1394 /// assert!(res.is_err()); 1395 /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); 1396 /// ``` 1397 /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires 1398 /// [Conflicting]: ./struct.Arg.html#method.conflicts_with 1399 /// [override]: ./struct.Arg.html#method.overrides_with requires(mut self, name: &'a str) -> Self1400 pub fn requires(mut self, name: &'a str) -> Self { 1401 if let Some(ref mut vec) = self.b.requires { 1402 vec.push((None, name)); 1403 } else { 1404 let mut vec = vec![]; 1405 vec.push((None, name)); 1406 self.b.requires = Some(vec); 1407 } 1408 self 1409 } 1410 1411 /// Allows a conditional requirement. The requirement will only become valid if this arg's value 1412 /// equals `val`. 1413 /// 1414 /// **NOTE:** If using YAML the values should be laid out as follows 1415 /// 1416 /// ```yaml 1417 /// requires_if: 1418 /// - [val, arg] 1419 /// ``` 1420 /// 1421 /// # Examples 1422 /// 1423 /// ```rust 1424 /// # use clap::Arg; 1425 /// Arg::with_name("config") 1426 /// .requires_if("val", "arg") 1427 /// # ; 1428 /// ``` 1429 /// 1430 /// Setting [`Arg::requires_if(val, arg)`] requires that the `arg` be used at runtime if the 1431 /// defining argument's value is equal to `val`. If the defining argument is anything other than 1432 /// `val`, the other argument isn't required. 1433 /// 1434 /// ```rust 1435 /// # use clap::{App, Arg}; 1436 /// let res = App::new("prog") 1437 /// .arg(Arg::with_name("cfg") 1438 /// .takes_value(true) 1439 /// .requires_if("my.cfg", "other") 1440 /// .long("config")) 1441 /// .arg(Arg::with_name("other")) 1442 /// .get_matches_from_safe(vec![ 1443 /// "prog", "--config", "some.cfg" 1444 /// ]); 1445 /// 1446 /// assert!(res.is_ok()); // We didn't use --config=my.cfg, so other wasn't required 1447 /// ``` 1448 /// 1449 /// Setting [`Arg::requires_if(val, arg)`] and setting the value to `val` but *not* supplying 1450 /// `arg` is an error. 1451 /// 1452 /// ```rust 1453 /// # use clap::{App, Arg, ErrorKind}; 1454 /// let res = App::new("prog") 1455 /// .arg(Arg::with_name("cfg") 1456 /// .takes_value(true) 1457 /// .requires_if("my.cfg", "input") 1458 /// .long("config")) 1459 /// .arg(Arg::with_name("input")) 1460 /// .get_matches_from_safe(vec![ 1461 /// "prog", "--config", "my.cfg" 1462 /// ]); 1463 /// 1464 /// assert!(res.is_err()); 1465 /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); 1466 /// ``` 1467 /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires 1468 /// [Conflicting]: ./struct.Arg.html#method.conflicts_with 1469 /// [override]: ./struct.Arg.html#method.overrides_with requires_if(mut self, val: &'b str, arg: &'a str) -> Self1470 pub fn requires_if(mut self, val: &'b str, arg: &'a str) -> Self { 1471 if let Some(ref mut vec) = self.b.requires { 1472 vec.push((Some(val), arg)); 1473 } else { 1474 self.b.requires = Some(vec![(Some(val), arg)]); 1475 } 1476 self 1477 } 1478 1479 /// Allows multiple conditional requirements. The requirement will only become valid if this arg's value 1480 /// equals `val`. 1481 /// 1482 /// **NOTE:** If using YAML the values should be laid out as follows 1483 /// 1484 /// ```yaml 1485 /// requires_if: 1486 /// - [val, arg] 1487 /// - [val2, arg2] 1488 /// ``` 1489 /// 1490 /// # Examples 1491 /// 1492 /// ```rust 1493 /// # use clap::Arg; 1494 /// Arg::with_name("config") 1495 /// .requires_ifs(&[ 1496 /// ("val", "arg"), 1497 /// ("other_val", "arg2"), 1498 /// ]) 1499 /// # ; 1500 /// ``` 1501 /// 1502 /// Setting [`Arg::requires_ifs(&["val", "arg"])`] requires that the `arg` be used at runtime if the 1503 /// defining argument's value is equal to `val`. If the defining argument's value is anything other 1504 /// than `val`, `arg` isn't required. 1505 /// 1506 /// ```rust 1507 /// # use clap::{App, Arg, ErrorKind}; 1508 /// let res = App::new("prog") 1509 /// .arg(Arg::with_name("cfg") 1510 /// .takes_value(true) 1511 /// .requires_ifs(&[ 1512 /// ("special.conf", "opt"), 1513 /// ("other.conf", "other"), 1514 /// ]) 1515 /// .long("config")) 1516 /// .arg(Arg::with_name("opt") 1517 /// .long("option") 1518 /// .takes_value(true)) 1519 /// .arg(Arg::with_name("other")) 1520 /// .get_matches_from_safe(vec![ 1521 /// "prog", "--config", "special.conf" 1522 /// ]); 1523 /// 1524 /// assert!(res.is_err()); // We used --config=special.conf so --option <val> is required 1525 /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); 1526 /// ``` 1527 /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires 1528 /// [Conflicting]: ./struct.Arg.html#method.conflicts_with 1529 /// [override]: ./struct.Arg.html#method.overrides_with requires_ifs(mut self, ifs: &[(&'b str, &'a str)]) -> Self1530 pub fn requires_ifs(mut self, ifs: &[(&'b str, &'a str)]) -> Self { 1531 if let Some(ref mut vec) = self.b.requires { 1532 for &(val, arg) in ifs { 1533 vec.push((Some(val), arg)); 1534 } 1535 } else { 1536 let mut vec = vec![]; 1537 for &(val, arg) in ifs { 1538 vec.push((Some(val), arg)); 1539 } 1540 self.b.requires = Some(vec); 1541 } 1542 self 1543 } 1544 1545 /// Allows specifying that an argument is [required] conditionally. The requirement will only 1546 /// become valid if the specified `arg`'s value equals `val`. 1547 /// 1548 /// **NOTE:** If using YAML the values should be laid out as follows 1549 /// 1550 /// ```yaml 1551 /// required_if: 1552 /// - [arg, val] 1553 /// ``` 1554 /// 1555 /// # Examples 1556 /// 1557 /// ```rust 1558 /// # use clap::Arg; 1559 /// Arg::with_name("config") 1560 /// .required_if("other_arg", "value") 1561 /// # ; 1562 /// ``` 1563 /// 1564 /// Setting [`Arg::required_if(arg, val)`] makes this arg required if the `arg` is used at 1565 /// runtime and it's value is equal to `val`. If the `arg`'s value is anything other than `val`, 1566 /// this argument isn't required. 1567 /// 1568 /// ```rust 1569 /// # use clap::{App, Arg}; 1570 /// let res = App::new("prog") 1571 /// .arg(Arg::with_name("cfg") 1572 /// .takes_value(true) 1573 /// .required_if("other", "special") 1574 /// .long("config")) 1575 /// .arg(Arg::with_name("other") 1576 /// .long("other") 1577 /// .takes_value(true)) 1578 /// .get_matches_from_safe(vec![ 1579 /// "prog", "--other", "not-special" 1580 /// ]); 1581 /// 1582 /// assert!(res.is_ok()); // We didn't use --other=special, so "cfg" wasn't required 1583 /// ``` 1584 /// 1585 /// Setting [`Arg::required_if(arg, val)`] and having `arg` used with a value of `val` but *not* 1586 /// using this arg is an error. 1587 /// 1588 /// ```rust 1589 /// # use clap::{App, Arg, ErrorKind}; 1590 /// let res = App::new("prog") 1591 /// .arg(Arg::with_name("cfg") 1592 /// .takes_value(true) 1593 /// .required_if("other", "special") 1594 /// .long("config")) 1595 /// .arg(Arg::with_name("other") 1596 /// .long("other") 1597 /// .takes_value(true)) 1598 /// .get_matches_from_safe(vec![ 1599 /// "prog", "--other", "special" 1600 /// ]); 1601 /// 1602 /// assert!(res.is_err()); 1603 /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); 1604 /// ``` 1605 /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires 1606 /// [Conflicting]: ./struct.Arg.html#method.conflicts_with 1607 /// [required]: ./struct.Arg.html#method.required required_if(mut self, arg: &'a str, val: &'b str) -> Self1608 pub fn required_if(mut self, arg: &'a str, val: &'b str) -> Self { 1609 if let Some(ref mut vec) = self.r_ifs { 1610 vec.push((arg, val)); 1611 } else { 1612 self.r_ifs = Some(vec![(arg, val)]); 1613 } 1614 self 1615 } 1616 1617 /// Allows specifying that an argument is [required] based on multiple conditions. The 1618 /// conditions are set up in a `(arg, val)` style tuple. The requirement will only become valid 1619 /// if one of the specified `arg`'s value equals it's corresponding `val`. 1620 /// 1621 /// **NOTE:** If using YAML the values should be laid out as follows 1622 /// 1623 /// ```yaml 1624 /// required_if: 1625 /// - [arg, val] 1626 /// - [arg2, val2] 1627 /// ``` 1628 /// 1629 /// # Examples 1630 /// 1631 /// ```rust 1632 /// # use clap::Arg; 1633 /// Arg::with_name("config") 1634 /// .required_ifs(&[ 1635 /// ("extra", "val"), 1636 /// ("option", "spec") 1637 /// ]) 1638 /// # ; 1639 /// ``` 1640 /// 1641 /// Setting [`Arg::required_ifs(&[(arg, val)])`] makes this arg required if any of the `arg`s 1642 /// are used at runtime and it's corresponding value is equal to `val`. If the `arg`'s value is 1643 /// anything other than `val`, this argument isn't required. 1644 /// 1645 /// ```rust 1646 /// # use clap::{App, Arg}; 1647 /// let res = App::new("prog") 1648 /// .arg(Arg::with_name("cfg") 1649 /// .required_ifs(&[ 1650 /// ("extra", "val"), 1651 /// ("option", "spec") 1652 /// ]) 1653 /// .takes_value(true) 1654 /// .long("config")) 1655 /// .arg(Arg::with_name("extra") 1656 /// .takes_value(true) 1657 /// .long("extra")) 1658 /// .arg(Arg::with_name("option") 1659 /// .takes_value(true) 1660 /// .long("option")) 1661 /// .get_matches_from_safe(vec![ 1662 /// "prog", "--option", "other" 1663 /// ]); 1664 /// 1665 /// assert!(res.is_ok()); // We didn't use --option=spec, or --extra=val so "cfg" isn't required 1666 /// ``` 1667 /// 1668 /// Setting [`Arg::required_ifs(&[(arg, val)])`] and having any of the `arg`s used with it's 1669 /// value of `val` but *not* using this arg is an error. 1670 /// 1671 /// ```rust 1672 /// # use clap::{App, Arg, ErrorKind}; 1673 /// let res = App::new("prog") 1674 /// .arg(Arg::with_name("cfg") 1675 /// .required_ifs(&[ 1676 /// ("extra", "val"), 1677 /// ("option", "spec") 1678 /// ]) 1679 /// .takes_value(true) 1680 /// .long("config")) 1681 /// .arg(Arg::with_name("extra") 1682 /// .takes_value(true) 1683 /// .long("extra")) 1684 /// .arg(Arg::with_name("option") 1685 /// .takes_value(true) 1686 /// .long("option")) 1687 /// .get_matches_from_safe(vec![ 1688 /// "prog", "--option", "spec" 1689 /// ]); 1690 /// 1691 /// assert!(res.is_err()); 1692 /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); 1693 /// ``` 1694 /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires 1695 /// [Conflicting]: ./struct.Arg.html#method.conflicts_with 1696 /// [required]: ./struct.Arg.html#method.required required_ifs(mut self, ifs: &[(&'a str, &'b str)]) -> Self1697 pub fn required_ifs(mut self, ifs: &[(&'a str, &'b str)]) -> Self { 1698 if let Some(ref mut vec) = self.r_ifs { 1699 for r_if in ifs { 1700 vec.push((r_if.0, r_if.1)); 1701 } 1702 } else { 1703 let mut vec = vec![]; 1704 for r_if in ifs { 1705 vec.push((r_if.0, r_if.1)); 1706 } 1707 self.r_ifs = Some(vec); 1708 } 1709 self 1710 } 1711 1712 /// Sets multiple arguments by names that are required when this one is present I.e. when 1713 /// using this argument, the following arguments *must* be present. 1714 /// 1715 /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required 1716 /// by default. 1717 /// 1718 /// # Examples 1719 /// 1720 /// ```rust 1721 /// # use clap::Arg; 1722 /// Arg::with_name("config") 1723 /// .requires_all(&["input", "output"]) 1724 /// # ; 1725 /// ``` 1726 /// 1727 /// Setting [`Arg::requires_all(&[arg, arg2])`] requires that all the arguments be used at 1728 /// runtime if the defining argument is used. If the defining argument isn't used, the other 1729 /// argument isn't required 1730 /// 1731 /// ```rust 1732 /// # use clap::{App, Arg}; 1733 /// let res = App::new("prog") 1734 /// .arg(Arg::with_name("cfg") 1735 /// .takes_value(true) 1736 /// .requires("input") 1737 /// .long("config")) 1738 /// .arg(Arg::with_name("input") 1739 /// .index(1)) 1740 /// .arg(Arg::with_name("output") 1741 /// .index(2)) 1742 /// .get_matches_from_safe(vec![ 1743 /// "prog" 1744 /// ]); 1745 /// 1746 /// assert!(res.is_ok()); // We didn't use cfg, so input and output weren't required 1747 /// ``` 1748 /// 1749 /// Setting [`Arg::requires_all(&[arg, arg2])`] and *not* supplying all the arguments is an 1750 /// error. 1751 /// 1752 /// ```rust 1753 /// # use clap::{App, Arg, ErrorKind}; 1754 /// let res = App::new("prog") 1755 /// .arg(Arg::with_name("cfg") 1756 /// .takes_value(true) 1757 /// .requires_all(&["input", "output"]) 1758 /// .long("config")) 1759 /// .arg(Arg::with_name("input") 1760 /// .index(1)) 1761 /// .arg(Arg::with_name("output") 1762 /// .index(2)) 1763 /// .get_matches_from_safe(vec![ 1764 /// "prog", "--config", "file.conf", "in.txt" 1765 /// ]); 1766 /// 1767 /// assert!(res.is_err()); 1768 /// // We didn't use output 1769 /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); 1770 /// ``` 1771 /// [Conflicting]: ./struct.Arg.html#method.conflicts_with 1772 /// [override]: ./struct.Arg.html#method.overrides_with 1773 /// [`Arg::requires_all(&[arg, arg2])`]: ./struct.Arg.html#method.requires_all requires_all(mut self, names: &[&'a str]) -> Self1774 pub fn requires_all(mut self, names: &[&'a str]) -> Self { 1775 if let Some(ref mut vec) = self.b.requires { 1776 for s in names { 1777 vec.push((None, s)); 1778 } 1779 } else { 1780 let mut vec = vec![]; 1781 for s in names { 1782 vec.push((None, *s)); 1783 } 1784 self.b.requires = Some(vec); 1785 } 1786 self 1787 } 1788 1789 /// Specifies that the argument takes a value at run time. 1790 /// 1791 /// **NOTE:** values for arguments may be specified in any of the following methods 1792 /// 1793 /// * Using a space such as `-o value` or `--option value` 1794 /// * Using an equals and no space such as `-o=value` or `--option=value` 1795 /// * Use a short and no space such as `-ovalue` 1796 /// 1797 /// **NOTE:** By default, args which allow [multiple values] are delimited by commas, meaning 1798 /// `--option=val1,val2,val3` is three values for the `--option` argument. If you wish to 1799 /// change the delimiter to another character you can use [`Arg::value_delimiter(char)`], 1800 /// alternatively you can turn delimiting values **OFF** by using [`Arg::use_delimiter(false)`] 1801 /// 1802 /// # Examples 1803 /// 1804 /// ```rust 1805 /// # use clap::{App, Arg}; 1806 /// Arg::with_name("config") 1807 /// .takes_value(true) 1808 /// # ; 1809 /// ``` 1810 /// 1811 /// ```rust 1812 /// # use clap::{App, Arg}; 1813 /// let m = App::new("prog") 1814 /// .arg(Arg::with_name("mode") 1815 /// .long("mode") 1816 /// .takes_value(true)) 1817 /// .get_matches_from(vec![ 1818 /// "prog", "--mode", "fast" 1819 /// ]); 1820 /// 1821 /// assert!(m.is_present("mode")); 1822 /// assert_eq!(m.value_of("mode"), Some("fast")); 1823 /// ``` 1824 /// [`Arg::value_delimiter(char)`]: ./struct.Arg.html#method.value_delimiter 1825 /// [`Arg::use_delimiter(false)`]: ./struct.Arg.html#method.use_delimiter 1826 /// [multiple values]: ./struct.Arg.html#method.multiple takes_value(self, tv: bool) -> Self1827 pub fn takes_value(self, tv: bool) -> Self { 1828 if tv { 1829 self.set(ArgSettings::TakesValue) 1830 } else { 1831 self.unset(ArgSettings::TakesValue) 1832 } 1833 } 1834 1835 /// Specifies if the possible values of an argument should be displayed in the help text or 1836 /// not. Defaults to `false` (i.e. show possible values) 1837 /// 1838 /// This is useful for args with many values, or ones which are explained elsewhere in the 1839 /// help text. 1840 /// 1841 /// # Examples 1842 /// 1843 /// ```rust 1844 /// # use clap::{App, Arg}; 1845 /// Arg::with_name("config") 1846 /// .hide_possible_values(true) 1847 /// # ; 1848 /// ``` 1849 /// 1850 /// ```rust 1851 /// # use clap::{App, Arg}; 1852 /// let m = App::new("prog") 1853 /// .arg(Arg::with_name("mode") 1854 /// .long("mode") 1855 /// .possible_values(&["fast", "slow"]) 1856 /// .takes_value(true) 1857 /// .hide_possible_values(true)); 1858 /// 1859 /// ``` 1860 /// 1861 /// If we were to run the above program with `--help` the `[values: fast, slow]` portion of 1862 /// the help text would be omitted. hide_possible_values(self, hide: bool) -> Self1863 pub fn hide_possible_values(self, hide: bool) -> Self { 1864 if hide { 1865 self.set(ArgSettings::HidePossibleValues) 1866 } else { 1867 self.unset(ArgSettings::HidePossibleValues) 1868 } 1869 } 1870 1871 /// Specifies if the default value of an argument should be displayed in the help text or 1872 /// not. Defaults to `false` (i.e. show default value) 1873 /// 1874 /// This is useful when default behavior of an arg is explained elsewhere in the help text. 1875 /// 1876 /// # Examples 1877 /// 1878 /// ```rust 1879 /// # use clap::{App, Arg}; 1880 /// Arg::with_name("config") 1881 /// .hide_default_value(true) 1882 /// # ; 1883 /// ``` 1884 /// 1885 /// ```rust 1886 /// # use clap::{App, Arg}; 1887 /// let m = App::new("connect") 1888 /// .arg(Arg::with_name("host") 1889 /// .long("host") 1890 /// .default_value("localhost") 1891 /// .hide_default_value(true)); 1892 /// 1893 /// ``` 1894 /// 1895 /// If we were to run the above program with `--help` the `[default: localhost]` portion of 1896 /// the help text would be omitted. hide_default_value(self, hide: bool) -> Self1897 pub fn hide_default_value(self, hide: bool) -> Self { 1898 if hide { 1899 self.set(ArgSettings::HideDefaultValue) 1900 } else { 1901 self.unset(ArgSettings::HideDefaultValue) 1902 } 1903 } 1904 1905 /// Specifies the index of a positional argument **starting at** 1. 1906 /// 1907 /// **NOTE:** The index refers to position according to **other positional argument**. It does 1908 /// not define position in the argument list as a whole. 1909 /// 1910 /// **NOTE:** If no [`Arg::short`], or [`Arg::long`] have been defined, you can optionally 1911 /// leave off the `index` method, and the index will be assigned in order of evaluation. 1912 /// Utilizing the `index` method allows for setting indexes out of order 1913 /// 1914 /// **NOTE:** When utilized with [`Arg::multiple(true)`], only the **last** positional argument 1915 /// may be defined as multiple (i.e. with the highest index) 1916 /// 1917 /// # Panics 1918 /// 1919 /// Although not in this method directly, [`App`] will [`panic!`] if indexes are skipped (such 1920 /// as defining `index(1)` and `index(3)` but not `index(2)`, or a positional argument is 1921 /// defined as multiple and is not the highest index 1922 /// 1923 /// # Examples 1924 /// 1925 /// ```rust 1926 /// # use clap::{App, Arg}; 1927 /// Arg::with_name("config") 1928 /// .index(1) 1929 /// # ; 1930 /// ``` 1931 /// 1932 /// ```rust 1933 /// # use clap::{App, Arg}; 1934 /// let m = App::new("prog") 1935 /// .arg(Arg::with_name("mode") 1936 /// .index(1)) 1937 /// .arg(Arg::with_name("debug") 1938 /// .long("debug")) 1939 /// .get_matches_from(vec![ 1940 /// "prog", "--debug", "fast" 1941 /// ]); 1942 /// 1943 /// assert!(m.is_present("mode")); 1944 /// assert_eq!(m.value_of("mode"), Some("fast")); // notice index(1) means "first positional" 1945 /// // *not* first argument 1946 /// ``` 1947 /// [`Arg::short`]: ./struct.Arg.html#method.short 1948 /// [`Arg::long`]: ./struct.Arg.html#method.long 1949 /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple 1950 /// [`App`]: ./struct.App.html 1951 /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html index(mut self, idx: u64) -> Self1952 pub fn index(mut self, idx: u64) -> Self { 1953 self.index = Some(idx); 1954 self 1955 } 1956 1957 /// Specifies that the argument may appear more than once. For flags, this results 1958 /// in the number of occurrences of the flag being recorded. For example `-ddd` or `-d -d -d` 1959 /// would count as three occurrences. For options there is a distinct difference in multiple 1960 /// occurrences vs multiple values. 1961 /// 1962 /// For example, `--opt val1 val2` is one occurrence, but two values. Whereas 1963 /// `--opt val1 --opt val2` is two occurrences. 1964 /// 1965 /// **WARNING:** 1966 /// 1967 /// Setting `multiple(true)` for an [option] with no other details, allows multiple values 1968 /// **and** multiple occurrences because it isn't possible to have more occurrences than values 1969 /// for options. Because multiple values are allowed, `--option val1 val2 val3` is perfectly 1970 /// valid, be careful when designing a CLI where positional arguments are expected after a 1971 /// option which accepts multiple values, as `clap` will continue parsing *values* until it 1972 /// reaches the max or specific number of values defined, or another flag or option. 1973 /// 1974 /// **Pro Tip**: 1975 /// 1976 /// It's possible to define an option which allows multiple occurrences, but only one value per 1977 /// occurrence. To do this use [`Arg::number_of_values(1)`] in coordination with 1978 /// [`Arg::multiple(true)`]. 1979 /// 1980 /// **WARNING:** 1981 /// 1982 /// When using args with `multiple(true)` on [options] or [positionals] (i.e. those args that 1983 /// accept values) and [subcommands], one needs to consider the possibility of an argument value 1984 /// being the same as a valid subcommand. By default `clap` will parse the argument in question 1985 /// as a value *only if* a value is possible at that moment. Otherwise it will be parsed as a 1986 /// subcommand. In effect, this means using `multiple(true)` with no additional parameters and 1987 /// a possible value that coincides with a subcommand name, the subcommand cannot be called 1988 /// unless another argument is passed first. 1989 /// 1990 /// As an example, consider a CLI with an option `--ui-paths=<paths>...` and subcommand `signer` 1991 /// 1992 /// The following would be parsed as values to `--ui-paths`. 1993 /// 1994 /// ```notrust 1995 /// $ program --ui-paths path1 path2 signer 1996 /// ``` 1997 /// 1998 /// This is because `--ui-paths` accepts multiple values. `clap` will continue parsing values 1999 /// until another argument is reached and it knows `--ui-paths` is done. 2000 /// 2001 /// By adding additional parameters to `--ui-paths` we can solve this issue. Consider adding 2002 /// [`Arg::number_of_values(1)`] as discussed above. The following are all valid, and `signer` 2003 /// is parsed as both a subcommand and a value in the second case. 2004 /// 2005 /// ```notrust 2006 /// $ program --ui-paths path1 signer 2007 /// $ program --ui-paths path1 --ui-paths signer signer 2008 /// ``` 2009 /// 2010 /// # Examples 2011 /// 2012 /// ```rust 2013 /// # use clap::{App, Arg}; 2014 /// Arg::with_name("debug") 2015 /// .short("d") 2016 /// .multiple(true) 2017 /// # ; 2018 /// ``` 2019 /// An example with flags 2020 /// 2021 /// ```rust 2022 /// # use clap::{App, Arg}; 2023 /// let m = App::new("prog") 2024 /// .arg(Arg::with_name("verbose") 2025 /// .multiple(true) 2026 /// .short("v")) 2027 /// .get_matches_from(vec![ 2028 /// "prog", "-v", "-v", "-v" // note, -vvv would have same result 2029 /// ]); 2030 /// 2031 /// assert!(m.is_present("verbose")); 2032 /// assert_eq!(m.occurrences_of("verbose"), 3); 2033 /// ``` 2034 /// 2035 /// An example with options 2036 /// 2037 /// ```rust 2038 /// # use clap::{App, Arg}; 2039 /// let m = App::new("prog") 2040 /// .arg(Arg::with_name("file") 2041 /// .multiple(true) 2042 /// .takes_value(true) 2043 /// .short("F")) 2044 /// .get_matches_from(vec![ 2045 /// "prog", "-F", "file1", "file2", "file3" 2046 /// ]); 2047 /// 2048 /// assert!(m.is_present("file")); 2049 /// assert_eq!(m.occurrences_of("file"), 1); // notice only one occurrence 2050 /// let files: Vec<_> = m.values_of("file").unwrap().collect(); 2051 /// assert_eq!(files, ["file1", "file2", "file3"]); 2052 /// ``` 2053 /// This is functionally equivalent to the example above 2054 /// 2055 /// ```rust 2056 /// # use clap::{App, Arg}; 2057 /// let m = App::new("prog") 2058 /// .arg(Arg::with_name("file") 2059 /// .multiple(true) 2060 /// .takes_value(true) 2061 /// .short("F")) 2062 /// .get_matches_from(vec![ 2063 /// "prog", "-F", "file1", "-F", "file2", "-F", "file3" 2064 /// ]); 2065 /// let files: Vec<_> = m.values_of("file").unwrap().collect(); 2066 /// assert_eq!(files, ["file1", "file2", "file3"]); 2067 /// 2068 /// assert!(m.is_present("file")); 2069 /// assert_eq!(m.occurrences_of("file"), 3); // Notice 3 occurrences 2070 /// let files: Vec<_> = m.values_of("file").unwrap().collect(); 2071 /// assert_eq!(files, ["file1", "file2", "file3"]); 2072 /// ``` 2073 /// 2074 /// A common mistake is to define an option which allows multiples, and a positional argument 2075 /// 2076 /// ```rust 2077 /// # use clap::{App, Arg}; 2078 /// let m = App::new("prog") 2079 /// .arg(Arg::with_name("file") 2080 /// .multiple(true) 2081 /// .takes_value(true) 2082 /// .short("F")) 2083 /// .arg(Arg::with_name("word") 2084 /// .index(1)) 2085 /// .get_matches_from(vec![ 2086 /// "prog", "-F", "file1", "file2", "file3", "word" 2087 /// ]); 2088 /// 2089 /// assert!(m.is_present("file")); 2090 /// let files: Vec<_> = m.values_of("file").unwrap().collect(); 2091 /// assert_eq!(files, ["file1", "file2", "file3", "word"]); // wait...what?! 2092 /// assert!(!m.is_present("word")); // but we clearly used word! 2093 /// ``` 2094 /// The problem is clap doesn't know when to stop parsing values for "files". This is further 2095 /// compounded by if we'd said `word -F file1 file2` it would have worked fine, so it would 2096 /// appear to only fail sometimes...not good! 2097 /// 2098 /// A solution for the example above is to specify that `-F` only accepts one value, but is 2099 /// allowed to appear multiple times 2100 /// 2101 /// ```rust 2102 /// # use clap::{App, Arg}; 2103 /// let m = App::new("prog") 2104 /// .arg(Arg::with_name("file") 2105 /// .multiple(true) 2106 /// .takes_value(true) 2107 /// .number_of_values(1) 2108 /// .short("F")) 2109 /// .arg(Arg::with_name("word") 2110 /// .index(1)) 2111 /// .get_matches_from(vec![ 2112 /// "prog", "-F", "file1", "-F", "file2", "-F", "file3", "word" 2113 /// ]); 2114 /// 2115 /// assert!(m.is_present("file")); 2116 /// let files: Vec<_> = m.values_of("file").unwrap().collect(); 2117 /// assert_eq!(files, ["file1", "file2", "file3"]); 2118 /// assert!(m.is_present("word")); 2119 /// assert_eq!(m.value_of("word"), Some("word")); 2120 /// ``` 2121 /// As a final example, notice if we define [`Arg::number_of_values(1)`] and try to run the 2122 /// problem example above, it would have been a runtime error with a pretty message to the 2123 /// user :) 2124 /// 2125 /// ```rust 2126 /// # use clap::{App, Arg, ErrorKind}; 2127 /// let res = App::new("prog") 2128 /// .arg(Arg::with_name("file") 2129 /// .multiple(true) 2130 /// .takes_value(true) 2131 /// .number_of_values(1) 2132 /// .short("F")) 2133 /// .arg(Arg::with_name("word") 2134 /// .index(1)) 2135 /// .get_matches_from_safe(vec![ 2136 /// "prog", "-F", "file1", "file2", "file3", "word" 2137 /// ]); 2138 /// 2139 /// assert!(res.is_err()); 2140 /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); 2141 /// ``` 2142 /// [option]: ./struct.Arg.html#method.takes_value 2143 /// [options]: ./struct.Arg.html#method.takes_value 2144 /// [subcommands]: ./struct.SubCommand.html 2145 /// [positionals]: ./struct.Arg.html#method.index 2146 /// [`Arg::number_of_values(1)`]: ./struct.Arg.html#method.number_of_values 2147 /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple multiple(self, multi: bool) -> Self2148 pub fn multiple(self, multi: bool) -> Self { 2149 if multi { 2150 self.set(ArgSettings::Multiple) 2151 } else { 2152 self.unset(ArgSettings::Multiple) 2153 } 2154 } 2155 2156 /// Specifies a value that *stops* parsing multiple values of a give argument. By default when 2157 /// one sets [`multiple(true)`] on an argument, clap will continue parsing values for that 2158 /// argument until it reaches another valid argument, or one of the other more specific settings 2159 /// for multiple values is used (such as [`min_values`], [`max_values`] or 2160 /// [`number_of_values`]). 2161 /// 2162 /// **NOTE:** This setting only applies to [options] and [positional arguments] 2163 /// 2164 /// **NOTE:** When the terminator is passed in on the command line, it is **not** stored as one 2165 /// of the values 2166 /// 2167 /// # Examples 2168 /// 2169 /// ```rust 2170 /// # use clap::{App, Arg}; 2171 /// Arg::with_name("vals") 2172 /// .takes_value(true) 2173 /// .multiple(true) 2174 /// .value_terminator(";") 2175 /// # ; 2176 /// ``` 2177 /// The following example uses two arguments, a sequence of commands, and the location in which 2178 /// to perform them 2179 /// 2180 /// ```rust 2181 /// # use clap::{App, Arg}; 2182 /// let m = App::new("prog") 2183 /// .arg(Arg::with_name("cmds") 2184 /// .multiple(true) 2185 /// .allow_hyphen_values(true) 2186 /// .value_terminator(";")) 2187 /// .arg(Arg::with_name("location")) 2188 /// .get_matches_from(vec![ 2189 /// "prog", "find", "-type", "f", "-name", "special", ";", "/home/clap" 2190 /// ]); 2191 /// let cmds: Vec<_> = m.values_of("cmds").unwrap().collect(); 2192 /// assert_eq!(&cmds, &["find", "-type", "f", "-name", "special"]); 2193 /// assert_eq!(m.value_of("location"), Some("/home/clap")); 2194 /// ``` 2195 /// [options]: ./struct.Arg.html#method.takes_value 2196 /// [positional arguments]: ./struct.Arg.html#method.index 2197 /// [`multiple(true)`]: ./struct.Arg.html#method.multiple 2198 /// [`min_values`]: ./struct.Arg.html#method.min_values 2199 /// [`number_of_values`]: ./struct.Arg.html#method.number_of_values 2200 /// [`max_values`]: ./struct.Arg.html#method.max_values value_terminator(mut self, term: &'b str) -> Self2201 pub fn value_terminator(mut self, term: &'b str) -> Self { 2202 self.setb(ArgSettings::TakesValue); 2203 self.v.terminator = Some(term); 2204 self 2205 } 2206 2207 /// Specifies that an argument can be matched to all child [`SubCommand`]s. 2208 /// 2209 /// **NOTE:** Global arguments *only* propagate down, **not** up (to parent commands), however 2210 /// their values once a user uses them will be propagated back up to parents. In effect, this 2211 /// means one should *define* all global arguments at the top level, however it doesn't matter 2212 /// where the user *uses* the global argument. 2213 /// 2214 /// # Examples 2215 /// 2216 /// ```rust 2217 /// # use clap::{App, Arg}; 2218 /// Arg::with_name("debug") 2219 /// .short("d") 2220 /// .global(true) 2221 /// # ; 2222 /// ``` 2223 /// 2224 /// For example, assume an application with two subcommands, and you'd like to define a 2225 /// `--verbose` flag that can be called on any of the subcommands and parent, but you don't 2226 /// want to clutter the source with three duplicate [`Arg`] definitions. 2227 /// 2228 /// ```rust 2229 /// # use clap::{App, Arg, SubCommand}; 2230 /// let m = App::new("prog") 2231 /// .arg(Arg::with_name("verb") 2232 /// .long("verbose") 2233 /// .short("v") 2234 /// .global(true)) 2235 /// .subcommand(SubCommand::with_name("test")) 2236 /// .subcommand(SubCommand::with_name("do-stuff")) 2237 /// .get_matches_from(vec![ 2238 /// "prog", "do-stuff", "--verbose" 2239 /// ]); 2240 /// 2241 /// assert_eq!(m.subcommand_name(), Some("do-stuff")); 2242 /// let sub_m = m.subcommand_matches("do-stuff").unwrap(); 2243 /// assert!(sub_m.is_present("verb")); 2244 /// ``` 2245 /// [`SubCommand`]: ./struct.SubCommand.html 2246 /// [required]: ./struct.Arg.html#method.required 2247 /// [`ArgMatches`]: ./struct.ArgMatches.html 2248 /// [`ArgMatches::is_present("flag")`]: ./struct.ArgMatches.html#method.is_present 2249 /// [`Arg`]: ./struct.Arg.html global(self, g: bool) -> Self2250 pub fn global(self, g: bool) -> Self { 2251 if g { 2252 self.set(ArgSettings::Global) 2253 } else { 2254 self.unset(ArgSettings::Global) 2255 } 2256 } 2257 2258 /// Allows an argument to accept explicitly empty values. An empty value must be specified at 2259 /// the command line with an explicit `""`, or `''` 2260 /// 2261 /// **NOTE:** Defaults to `true` (Explicitly empty values are allowed) 2262 /// 2263 /// **NOTE:** Implicitly sets [`Arg::takes_value(true)`] when set to `false` 2264 /// 2265 /// # Examples 2266 /// 2267 /// ```rust 2268 /// # use clap::{App, Arg}; 2269 /// Arg::with_name("file") 2270 /// .long("file") 2271 /// .empty_values(false) 2272 /// # ; 2273 /// ``` 2274 /// The default is to allow empty values, such as `--option ""` would be an empty value. But 2275 /// we can change to make empty values become an error. 2276 /// 2277 /// ```rust 2278 /// # use clap::{App, Arg, ErrorKind}; 2279 /// let res = App::new("prog") 2280 /// .arg(Arg::with_name("cfg") 2281 /// .long("config") 2282 /// .short("v") 2283 /// .empty_values(false)) 2284 /// .get_matches_from_safe(vec![ 2285 /// "prog", "--config=" 2286 /// ]); 2287 /// 2288 /// assert!(res.is_err()); 2289 /// assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue); 2290 /// ``` 2291 /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value empty_values(mut self, ev: bool) -> Self2292 pub fn empty_values(mut self, ev: bool) -> Self { 2293 if ev { 2294 self.set(ArgSettings::EmptyValues) 2295 } else { 2296 self = self.set(ArgSettings::TakesValue); 2297 self.unset(ArgSettings::EmptyValues) 2298 } 2299 } 2300 2301 /// Hides an argument from help message output. 2302 /// 2303 /// **NOTE:** Implicitly sets [`Arg::hidden_short_help(true)`] and [`Arg::hidden_long_help(true)`] 2304 /// when set to true 2305 /// 2306 /// **NOTE:** This does **not** hide the argument from usage strings on error 2307 /// 2308 /// # Examples 2309 /// 2310 /// ```rust 2311 /// # use clap::{App, Arg}; 2312 /// Arg::with_name("debug") 2313 /// .hidden(true) 2314 /// # ; 2315 /// ``` 2316 /// Setting `hidden(true)` will hide the argument when displaying help text 2317 /// 2318 /// ```rust 2319 /// # use clap::{App, Arg}; 2320 /// let m = App::new("prog") 2321 /// .arg(Arg::with_name("cfg") 2322 /// .long("config") 2323 /// .hidden(true) 2324 /// .help("Some help text describing the --config arg")) 2325 /// .get_matches_from(vec![ 2326 /// "prog", "--help" 2327 /// ]); 2328 /// ``` 2329 /// 2330 /// The above example displays 2331 /// 2332 /// ```notrust 2333 /// helptest 2334 /// 2335 /// USAGE: 2336 /// helptest [FLAGS] 2337 /// 2338 /// FLAGS: 2339 /// -h, --help Prints help information 2340 /// -V, --version Prints version information 2341 /// ``` 2342 /// [`Arg::hidden_short_help(true)`]: ./struct.Arg.html#method.hidden_short_help 2343 /// [`Arg::hidden_long_help(true)`]: ./struct.Arg.html#method.hidden_long_help hidden(self, h: bool) -> Self2344 pub fn hidden(self, h: bool) -> Self { 2345 if h { 2346 self.set(ArgSettings::Hidden) 2347 } else { 2348 self.unset(ArgSettings::Hidden) 2349 } 2350 } 2351 2352 /// Specifies a list of possible values for this argument. At runtime, `clap` verifies that 2353 /// only one of the specified values was used, or fails with an error message. 2354 /// 2355 /// **NOTE:** This setting only applies to [options] and [positional arguments] 2356 /// 2357 /// # Examples 2358 /// 2359 /// ```rust 2360 /// # use clap::{App, Arg}; 2361 /// Arg::with_name("mode") 2362 /// .takes_value(true) 2363 /// .possible_values(&["fast", "slow", "medium"]) 2364 /// # ; 2365 /// ``` 2366 /// 2367 /// ```rust 2368 /// # use clap::{App, Arg}; 2369 /// let m = App::new("prog") 2370 /// .arg(Arg::with_name("mode") 2371 /// .long("mode") 2372 /// .takes_value(true) 2373 /// .possible_values(&["fast", "slow", "medium"])) 2374 /// .get_matches_from(vec![ 2375 /// "prog", "--mode", "fast" 2376 /// ]); 2377 /// assert!(m.is_present("mode")); 2378 /// assert_eq!(m.value_of("mode"), Some("fast")); 2379 /// ``` 2380 /// 2381 /// The next example shows a failed parse from using a value which wasn't defined as one of the 2382 /// possible values. 2383 /// 2384 /// ```rust 2385 /// # use clap::{App, Arg, ErrorKind}; 2386 /// let res = App::new("prog") 2387 /// .arg(Arg::with_name("mode") 2388 /// .long("mode") 2389 /// .takes_value(true) 2390 /// .possible_values(&["fast", "slow", "medium"])) 2391 /// .get_matches_from_safe(vec![ 2392 /// "prog", "--mode", "wrong" 2393 /// ]); 2394 /// assert!(res.is_err()); 2395 /// assert_eq!(res.unwrap_err().kind, ErrorKind::InvalidValue); 2396 /// ``` 2397 /// [options]: ./struct.Arg.html#method.takes_value 2398 /// [positional arguments]: ./struct.Arg.html#method.index possible_values(mut self, names: &[&'b str]) -> Self2399 pub fn possible_values(mut self, names: &[&'b str]) -> Self { 2400 if let Some(ref mut vec) = self.v.possible_vals { 2401 for s in names { 2402 vec.push(s); 2403 } 2404 } else { 2405 self.v.possible_vals = Some(names.iter().map(|s| *s).collect::<Vec<_>>()); 2406 } 2407 self 2408 } 2409 2410 /// Specifies a possible value for this argument, one at a time. At runtime, `clap` verifies 2411 /// that only one of the specified values was used, or fails with error message. 2412 /// 2413 /// **NOTE:** This setting only applies to [options] and [positional arguments] 2414 /// 2415 /// # Examples 2416 /// 2417 /// ```rust 2418 /// # use clap::{App, Arg}; 2419 /// Arg::with_name("mode") 2420 /// .takes_value(true) 2421 /// .possible_value("fast") 2422 /// .possible_value("slow") 2423 /// .possible_value("medium") 2424 /// # ; 2425 /// ``` 2426 /// 2427 /// ```rust 2428 /// # use clap::{App, Arg}; 2429 /// let m = App::new("prog") 2430 /// .arg(Arg::with_name("mode") 2431 /// .long("mode") 2432 /// .takes_value(true) 2433 /// .possible_value("fast") 2434 /// .possible_value("slow") 2435 /// .possible_value("medium")) 2436 /// .get_matches_from(vec![ 2437 /// "prog", "--mode", "fast" 2438 /// ]); 2439 /// assert!(m.is_present("mode")); 2440 /// assert_eq!(m.value_of("mode"), Some("fast")); 2441 /// ``` 2442 /// 2443 /// The next example shows a failed parse from using a value which wasn't defined as one of the 2444 /// possible values. 2445 /// 2446 /// ```rust 2447 /// # use clap::{App, Arg, ErrorKind}; 2448 /// let res = App::new("prog") 2449 /// .arg(Arg::with_name("mode") 2450 /// .long("mode") 2451 /// .takes_value(true) 2452 /// .possible_value("fast") 2453 /// .possible_value("slow") 2454 /// .possible_value("medium")) 2455 /// .get_matches_from_safe(vec![ 2456 /// "prog", "--mode", "wrong" 2457 /// ]); 2458 /// assert!(res.is_err()); 2459 /// assert_eq!(res.unwrap_err().kind, ErrorKind::InvalidValue); 2460 /// ``` 2461 /// [options]: ./struct.Arg.html#method.takes_value 2462 /// [positional arguments]: ./struct.Arg.html#method.index possible_value(mut self, name: &'b str) -> Self2463 pub fn possible_value(mut self, name: &'b str) -> Self { 2464 if let Some(ref mut vec) = self.v.possible_vals { 2465 vec.push(name); 2466 } else { 2467 self.v.possible_vals = Some(vec![name]); 2468 } 2469 self 2470 } 2471 2472 /// When used with [`Arg::possible_values`] it allows the argument value to pass validation even if 2473 /// the case differs from that of the specified `possible_value`. 2474 /// 2475 /// **Pro Tip:** Use this setting with [`arg_enum!`] 2476 /// 2477 /// # Examples 2478 /// 2479 /// ```rust 2480 /// # use clap::{App, Arg}; 2481 /// # use std::ascii::AsciiExt; 2482 /// let m = App::new("pv") 2483 /// .arg(Arg::with_name("option") 2484 /// .long("--option") 2485 /// .takes_value(true) 2486 /// .possible_value("test123") 2487 /// .case_insensitive(true)) 2488 /// .get_matches_from(vec![ 2489 /// "pv", "--option", "TeSt123", 2490 /// ]); 2491 /// 2492 /// assert!(m.value_of("option").unwrap().eq_ignore_ascii_case("test123")); 2493 /// ``` 2494 /// 2495 /// This setting also works when multiple values can be defined: 2496 /// 2497 /// ```rust 2498 /// # use clap::{App, Arg}; 2499 /// let m = App::new("pv") 2500 /// .arg(Arg::with_name("option") 2501 /// .short("-o") 2502 /// .long("--option") 2503 /// .takes_value(true) 2504 /// .possible_value("test123") 2505 /// .possible_value("test321") 2506 /// .multiple(true) 2507 /// .case_insensitive(true)) 2508 /// .get_matches_from(vec![ 2509 /// "pv", "--option", "TeSt123", "teST123", "tESt321" 2510 /// ]); 2511 /// 2512 /// let matched_vals = m.values_of("option").unwrap().collect::<Vec<_>>(); 2513 /// assert_eq!(&*matched_vals, &["TeSt123", "teST123", "tESt321"]); 2514 /// ``` 2515 /// [`Arg::case_insensitive(true)`]: ./struct.Arg.html#method.possible_values 2516 /// [`arg_enum!`]: ./macro.arg_enum.html case_insensitive(self, ci: bool) -> Self2517 pub fn case_insensitive(self, ci: bool) -> Self { 2518 if ci { 2519 self.set(ArgSettings::CaseInsensitive) 2520 } else { 2521 self.unset(ArgSettings::CaseInsensitive) 2522 } 2523 } 2524 2525 /// Specifies the name of the [`ArgGroup`] the argument belongs to. 2526 /// 2527 /// # Examples 2528 /// 2529 /// ```rust 2530 /// # use clap::{App, Arg}; 2531 /// Arg::with_name("debug") 2532 /// .long("debug") 2533 /// .group("mode") 2534 /// # ; 2535 /// ``` 2536 /// 2537 /// Multiple arguments can be a member of a single group and then the group checked as if it 2538 /// was one of said arguments. 2539 /// 2540 /// ```rust 2541 /// # use clap::{App, Arg}; 2542 /// let m = App::new("prog") 2543 /// .arg(Arg::with_name("debug") 2544 /// .long("debug") 2545 /// .group("mode")) 2546 /// .arg(Arg::with_name("verbose") 2547 /// .long("verbose") 2548 /// .group("mode")) 2549 /// .get_matches_from(vec![ 2550 /// "prog", "--debug" 2551 /// ]); 2552 /// assert!(m.is_present("mode")); 2553 /// ``` 2554 /// [`ArgGroup`]: ./struct.ArgGroup.html group(mut self, name: &'a str) -> Self2555 pub fn group(mut self, name: &'a str) -> Self { 2556 if let Some(ref mut vec) = self.b.groups { 2557 vec.push(name); 2558 } else { 2559 self.b.groups = Some(vec![name]); 2560 } 2561 self 2562 } 2563 2564 /// Specifies the names of multiple [`ArgGroup`]'s the argument belongs to. 2565 /// 2566 /// # Examples 2567 /// 2568 /// ```rust 2569 /// # use clap::{App, Arg}; 2570 /// Arg::with_name("debug") 2571 /// .long("debug") 2572 /// .groups(&["mode", "verbosity"]) 2573 /// # ; 2574 /// ``` 2575 /// 2576 /// Arguments can be members of multiple groups and then the group checked as if it 2577 /// was one of said arguments. 2578 /// 2579 /// ```rust 2580 /// # use clap::{App, Arg}; 2581 /// let m = App::new("prog") 2582 /// .arg(Arg::with_name("debug") 2583 /// .long("debug") 2584 /// .groups(&["mode", "verbosity"])) 2585 /// .arg(Arg::with_name("verbose") 2586 /// .long("verbose") 2587 /// .groups(&["mode", "verbosity"])) 2588 /// .get_matches_from(vec![ 2589 /// "prog", "--debug" 2590 /// ]); 2591 /// assert!(m.is_present("mode")); 2592 /// assert!(m.is_present("verbosity")); 2593 /// ``` 2594 /// [`ArgGroup`]: ./struct.ArgGroup.html groups(mut self, names: &[&'a str]) -> Self2595 pub fn groups(mut self, names: &[&'a str]) -> Self { 2596 if let Some(ref mut vec) = self.b.groups { 2597 for s in names { 2598 vec.push(s); 2599 } 2600 } else { 2601 self.b.groups = Some(names.into_iter().map(|s| *s).collect::<Vec<_>>()); 2602 } 2603 self 2604 } 2605 2606 /// Specifies how many values are required to satisfy this argument. For example, if you had a 2607 /// `-f <file>` argument where you wanted exactly 3 'files' you would set 2608 /// `.number_of_values(3)`, and this argument wouldn't be satisfied unless the user provided 2609 /// 3 and only 3 values. 2610 /// 2611 /// **NOTE:** Does *not* require [`Arg::multiple(true)`] to be set. Setting 2612 /// [`Arg::multiple(true)`] would allow `-f <file> <file> <file> -f <file> <file> <file>` where 2613 /// as *not* setting [`Arg::multiple(true)`] would only allow one occurrence of this argument. 2614 /// 2615 /// # Examples 2616 /// 2617 /// ```rust 2618 /// # use clap::{App, Arg}; 2619 /// Arg::with_name("file") 2620 /// .short("f") 2621 /// .number_of_values(3) 2622 /// # ; 2623 /// ``` 2624 /// 2625 /// Not supplying the correct number of values is an error 2626 /// 2627 /// ```rust 2628 /// # use clap::{App, Arg, ErrorKind}; 2629 /// let res = App::new("prog") 2630 /// .arg(Arg::with_name("file") 2631 /// .takes_value(true) 2632 /// .number_of_values(2) 2633 /// .short("F")) 2634 /// .get_matches_from_safe(vec![ 2635 /// "prog", "-F", "file1" 2636 /// ]); 2637 /// 2638 /// assert!(res.is_err()); 2639 /// assert_eq!(res.unwrap_err().kind, ErrorKind::WrongNumberOfValues); 2640 /// ``` 2641 /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple number_of_values(mut self, qty: u64) -> Self2642 pub fn number_of_values(mut self, qty: u64) -> Self { 2643 self.setb(ArgSettings::TakesValue); 2644 self.v.num_vals = Some(qty); 2645 self 2646 } 2647 2648 /// Allows one to perform a custom validation on the argument value. You provide a closure 2649 /// which accepts a [`String`] value, and return a [`Result`] where the [`Err(String)`] is a 2650 /// message displayed to the user. 2651 /// 2652 /// **NOTE:** The error message does *not* need to contain the `error:` portion, only the 2653 /// message as all errors will appear as 2654 /// `error: Invalid value for '<arg>': <YOUR MESSAGE>` where `<arg>` is replaced by the actual 2655 /// arg, and `<YOUR MESSAGE>` is the `String` you return as the error. 2656 /// 2657 /// **NOTE:** There is a small performance hit for using validators, as they are implemented 2658 /// with [`Rc`] pointers. And the value to be checked will be allocated an extra time in order 2659 /// to to be passed to the closure. This performance hit is extremely minimal in the grand 2660 /// scheme of things. 2661 /// 2662 /// # Examples 2663 /// 2664 /// ```rust 2665 /// # use clap::{App, Arg}; 2666 /// fn has_at(v: String) -> Result<(), String> { 2667 /// if v.contains("@") { return Ok(()); } 2668 /// Err(String::from("The value did not contain the required @ sigil")) 2669 /// } 2670 /// let res = App::new("prog") 2671 /// .arg(Arg::with_name("file") 2672 /// .index(1) 2673 /// .validator(has_at)) 2674 /// .get_matches_from_safe(vec![ 2675 /// "prog", "some@file" 2676 /// ]); 2677 /// assert!(res.is_ok()); 2678 /// assert_eq!(res.unwrap().value_of("file"), Some("some@file")); 2679 /// ``` 2680 /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html 2681 /// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html 2682 /// [`Err(String)`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err 2683 /// [`Rc`]: https://doc.rust-lang.org/std/rc/struct.Rc.html validator<F>(mut self, f: F) -> Self where F: Fn(String) -> Result<(), String> + 'static,2684 pub fn validator<F>(mut self, f: F) -> Self 2685 where 2686 F: Fn(String) -> Result<(), String> + 'static, 2687 { 2688 self.v.validator = Some(Rc::new(f)); 2689 self 2690 } 2691 2692 /// Works identically to Validator but is intended to be used with values that could 2693 /// contain non UTF-8 formatted strings. 2694 /// 2695 /// # Examples 2696 /// 2697 #[cfg_attr(not(unix), doc = " ```ignore")] 2698 #[cfg_attr(unix, doc = " ```rust")] 2699 /// # use clap::{App, Arg}; 2700 /// # use std::ffi::{OsStr, OsString}; 2701 /// # use std::os::unix::ffi::OsStrExt; 2702 /// fn has_ampersand(v: &OsStr) -> Result<(), OsString> { 2703 /// if v.as_bytes().iter().any(|b| *b == b'&') { return Ok(()); } 2704 /// Err(OsString::from("The value did not contain the required & sigil")) 2705 /// } 2706 /// let res = App::new("prog") 2707 /// .arg(Arg::with_name("file") 2708 /// .index(1) 2709 /// .validator_os(has_ampersand)) 2710 /// .get_matches_from_safe(vec![ 2711 /// "prog", "Fish & chips" 2712 /// ]); 2713 /// assert!(res.is_ok()); 2714 /// assert_eq!(res.unwrap().value_of("file"), Some("Fish & chips")); 2715 /// ``` 2716 /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html 2717 /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html 2718 /// [`OsString`]: https://doc.rust-lang.org/std/ffi/struct.OsString.html 2719 /// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html 2720 /// [`Err(String)`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err 2721 /// [`Rc`]: https://doc.rust-lang.org/std/rc/struct.Rc.html validator_os<F>(mut self, f: F) -> Self where F: Fn(&OsStr) -> Result<(), OsString> + 'static,2722 pub fn validator_os<F>(mut self, f: F) -> Self 2723 where 2724 F: Fn(&OsStr) -> Result<(), OsString> + 'static, 2725 { 2726 self.v.validator_os = Some(Rc::new(f)); 2727 self 2728 } 2729 2730 /// Specifies the *maximum* number of values are for this argument. For example, if you had a 2731 /// `-f <file>` argument where you wanted up to 3 'files' you would set `.max_values(3)`, and 2732 /// this argument would be satisfied if the user provided, 1, 2, or 3 values. 2733 /// 2734 /// **NOTE:** This does *not* implicitly set [`Arg::multiple(true)`]. This is because 2735 /// `-o val -o val` is multiple occurrences but a single value and `-o val1 val2` is a single 2736 /// occurrence with multiple values. For positional arguments this **does** set 2737 /// [`Arg::multiple(true)`] because there is no way to determine the difference between multiple 2738 /// occurrences and multiple values. 2739 /// 2740 /// # Examples 2741 /// 2742 /// ```rust 2743 /// # use clap::{App, Arg}; 2744 /// Arg::with_name("file") 2745 /// .short("f") 2746 /// .max_values(3) 2747 /// # ; 2748 /// ``` 2749 /// 2750 /// Supplying less than the maximum number of values is allowed 2751 /// 2752 /// ```rust 2753 /// # use clap::{App, Arg}; 2754 /// let res = App::new("prog") 2755 /// .arg(Arg::with_name("file") 2756 /// .takes_value(true) 2757 /// .max_values(3) 2758 /// .short("F")) 2759 /// .get_matches_from_safe(vec![ 2760 /// "prog", "-F", "file1", "file2" 2761 /// ]); 2762 /// 2763 /// assert!(res.is_ok()); 2764 /// let m = res.unwrap(); 2765 /// let files: Vec<_> = m.values_of("file").unwrap().collect(); 2766 /// assert_eq!(files, ["file1", "file2"]); 2767 /// ``` 2768 /// 2769 /// Supplying more than the maximum number of values is an error 2770 /// 2771 /// ```rust 2772 /// # use clap::{App, Arg, ErrorKind}; 2773 /// let res = App::new("prog") 2774 /// .arg(Arg::with_name("file") 2775 /// .takes_value(true) 2776 /// .max_values(2) 2777 /// .short("F")) 2778 /// .get_matches_from_safe(vec![ 2779 /// "prog", "-F", "file1", "file2", "file3" 2780 /// ]); 2781 /// 2782 /// assert!(res.is_err()); 2783 /// assert_eq!(res.unwrap_err().kind, ErrorKind::TooManyValues); 2784 /// ``` 2785 /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple max_values(mut self, qty: u64) -> Self2786 pub fn max_values(mut self, qty: u64) -> Self { 2787 self.setb(ArgSettings::TakesValue); 2788 self.v.max_vals = Some(qty); 2789 self 2790 } 2791 2792 /// Specifies the *minimum* number of values for this argument. For example, if you had a 2793 /// `-f <file>` argument where you wanted at least 2 'files' you would set 2794 /// `.min_values(2)`, and this argument would be satisfied if the user provided, 2 or more 2795 /// values. 2796 /// 2797 /// **NOTE:** This does not implicitly set [`Arg::multiple(true)`]. This is because 2798 /// `-o val -o val` is multiple occurrences but a single value and `-o val1 val2` is a single 2799 /// occurrence with multiple values. For positional arguments this **does** set 2800 /// [`Arg::multiple(true)`] because there is no way to determine the difference between multiple 2801 /// occurrences and multiple values. 2802 /// 2803 /// # Examples 2804 /// 2805 /// ```rust 2806 /// # use clap::{App, Arg}; 2807 /// Arg::with_name("file") 2808 /// .short("f") 2809 /// .min_values(3) 2810 /// # ; 2811 /// ``` 2812 /// 2813 /// Supplying more than the minimum number of values is allowed 2814 /// 2815 /// ```rust 2816 /// # use clap::{App, Arg}; 2817 /// let res = App::new("prog") 2818 /// .arg(Arg::with_name("file") 2819 /// .takes_value(true) 2820 /// .min_values(2) 2821 /// .short("F")) 2822 /// .get_matches_from_safe(vec![ 2823 /// "prog", "-F", "file1", "file2", "file3" 2824 /// ]); 2825 /// 2826 /// assert!(res.is_ok()); 2827 /// let m = res.unwrap(); 2828 /// let files: Vec<_> = m.values_of("file").unwrap().collect(); 2829 /// assert_eq!(files, ["file1", "file2", "file3"]); 2830 /// ``` 2831 /// 2832 /// Supplying less than the minimum number of values is an error 2833 /// 2834 /// ```rust 2835 /// # use clap::{App, Arg, ErrorKind}; 2836 /// let res = App::new("prog") 2837 /// .arg(Arg::with_name("file") 2838 /// .takes_value(true) 2839 /// .min_values(2) 2840 /// .short("F")) 2841 /// .get_matches_from_safe(vec![ 2842 /// "prog", "-F", "file1" 2843 /// ]); 2844 /// 2845 /// assert!(res.is_err()); 2846 /// assert_eq!(res.unwrap_err().kind, ErrorKind::TooFewValues); 2847 /// ``` 2848 /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple min_values(mut self, qty: u64) -> Self2849 pub fn min_values(mut self, qty: u64) -> Self { 2850 self.v.min_vals = Some(qty); 2851 self.set(ArgSettings::TakesValue) 2852 } 2853 2854 /// Specifies whether or not an argument should allow grouping of multiple values via a 2855 /// delimiter. I.e. should `--option=val1,val2,val3` be parsed as three values (`val1`, `val2`, 2856 /// and `val3`) or as a single value (`val1,val2,val3`). Defaults to using `,` (comma) as the 2857 /// value delimiter for all arguments that accept values (options and positional arguments) 2858 /// 2859 /// **NOTE:** The default is `false`. When set to `true` the default [`Arg::value_delimiter`] 2860 /// is the comma `,`. 2861 /// 2862 /// # Examples 2863 /// 2864 /// The following example shows the default behavior. 2865 /// 2866 /// ```rust 2867 /// # use clap::{App, Arg}; 2868 /// let delims = App::new("prog") 2869 /// .arg(Arg::with_name("option") 2870 /// .long("option") 2871 /// .use_delimiter(true) 2872 /// .takes_value(true)) 2873 /// .get_matches_from(vec![ 2874 /// "prog", "--option=val1,val2,val3", 2875 /// ]); 2876 /// 2877 /// assert!(delims.is_present("option")); 2878 /// assert_eq!(delims.occurrences_of("option"), 1); 2879 /// assert_eq!(delims.values_of("option").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]); 2880 /// ``` 2881 /// The next example shows the difference when turning delimiters off. This is the default 2882 /// behavior 2883 /// 2884 /// ```rust 2885 /// # use clap::{App, Arg}; 2886 /// let nodelims = App::new("prog") 2887 /// .arg(Arg::with_name("option") 2888 /// .long("option") 2889 /// .use_delimiter(false) 2890 /// .takes_value(true)) 2891 /// .get_matches_from(vec![ 2892 /// "prog", "--option=val1,val2,val3", 2893 /// ]); 2894 /// 2895 /// assert!(nodelims.is_present("option")); 2896 /// assert_eq!(nodelims.occurrences_of("option"), 1); 2897 /// assert_eq!(nodelims.value_of("option").unwrap(), "val1,val2,val3"); 2898 /// ``` 2899 /// [`Arg::value_delimiter`]: ./struct.Arg.html#method.value_delimiter use_delimiter(mut self, d: bool) -> Self2900 pub fn use_delimiter(mut self, d: bool) -> Self { 2901 if d { 2902 if self.v.val_delim.is_none() { 2903 self.v.val_delim = Some(','); 2904 } 2905 self.setb(ArgSettings::TakesValue); 2906 self.setb(ArgSettings::UseValueDelimiter); 2907 self.unset(ArgSettings::ValueDelimiterNotSet) 2908 } else { 2909 self.v.val_delim = None; 2910 self.unsetb(ArgSettings::UseValueDelimiter); 2911 self.unset(ArgSettings::ValueDelimiterNotSet) 2912 } 2913 } 2914 2915 /// Specifies that *multiple values* may only be set using the delimiter. This means if an 2916 /// if an option is encountered, and no delimiter is found, it automatically assumed that no 2917 /// additional values for that option follow. This is unlike the default, where it is generally 2918 /// assumed that more values will follow regardless of whether or not a delimiter is used. 2919 /// 2920 /// **NOTE:** The default is `false`. 2921 /// 2922 /// **NOTE:** Setting this to true implies [`Arg::use_delimiter(true)`] 2923 /// 2924 /// **NOTE:** It's a good idea to inform the user that use of a delimiter is required, either 2925 /// through help text or other means. 2926 /// 2927 /// # Examples 2928 /// 2929 /// These examples demonstrate what happens when `require_delimiter(true)` is used. Notice 2930 /// everything works in this first example, as we use a delimiter, as expected. 2931 /// 2932 /// ```rust 2933 /// # use clap::{App, Arg}; 2934 /// let delims = App::new("prog") 2935 /// .arg(Arg::with_name("opt") 2936 /// .short("o") 2937 /// .takes_value(true) 2938 /// .multiple(true) 2939 /// .require_delimiter(true)) 2940 /// .get_matches_from(vec![ 2941 /// "prog", "-o", "val1,val2,val3", 2942 /// ]); 2943 /// 2944 /// assert!(delims.is_present("opt")); 2945 /// assert_eq!(delims.values_of("opt").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]); 2946 /// ``` 2947 /// In this next example, we will *not* use a delimiter. Notice it's now an error. 2948 /// 2949 /// ```rust 2950 /// # use clap::{App, Arg, ErrorKind}; 2951 /// let res = App::new("prog") 2952 /// .arg(Arg::with_name("opt") 2953 /// .short("o") 2954 /// .takes_value(true) 2955 /// .multiple(true) 2956 /// .require_delimiter(true)) 2957 /// .get_matches_from_safe(vec![ 2958 /// "prog", "-o", "val1", "val2", "val3", 2959 /// ]); 2960 /// 2961 /// assert!(res.is_err()); 2962 /// let err = res.unwrap_err(); 2963 /// assert_eq!(err.kind, ErrorKind::UnknownArgument); 2964 /// ``` 2965 /// What's happening is `-o` is getting `val1`, and because delimiters are required yet none 2966 /// were present, it stops parsing `-o`. At this point it reaches `val2` and because no 2967 /// positional arguments have been defined, it's an error of an unexpected argument. 2968 /// 2969 /// In this final example, we contrast the above with `clap`'s default behavior where the above 2970 /// is *not* an error. 2971 /// 2972 /// ```rust 2973 /// # use clap::{App, Arg}; 2974 /// let delims = App::new("prog") 2975 /// .arg(Arg::with_name("opt") 2976 /// .short("o") 2977 /// .takes_value(true) 2978 /// .multiple(true)) 2979 /// .get_matches_from(vec![ 2980 /// "prog", "-o", "val1", "val2", "val3", 2981 /// ]); 2982 /// 2983 /// assert!(delims.is_present("opt")); 2984 /// assert_eq!(delims.values_of("opt").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]); 2985 /// ``` 2986 /// [`Arg::use_delimiter(true)`]: ./struct.Arg.html#method.use_delimiter require_delimiter(mut self, d: bool) -> Self2987 pub fn require_delimiter(mut self, d: bool) -> Self { 2988 if d { 2989 self = self.use_delimiter(true); 2990 self.unsetb(ArgSettings::ValueDelimiterNotSet); 2991 self.setb(ArgSettings::UseValueDelimiter); 2992 self.set(ArgSettings::RequireDelimiter) 2993 } else { 2994 self = self.use_delimiter(false); 2995 self.unsetb(ArgSettings::UseValueDelimiter); 2996 self.unset(ArgSettings::RequireDelimiter) 2997 } 2998 } 2999 3000 /// Specifies the separator to use when values are clumped together, defaults to `,` (comma). 3001 /// 3002 /// **NOTE:** implicitly sets [`Arg::use_delimiter(true)`] 3003 /// 3004 /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] 3005 /// 3006 /// # Examples 3007 /// 3008 /// ```rust 3009 /// # use clap::{App, Arg}; 3010 /// let m = App::new("prog") 3011 /// .arg(Arg::with_name("config") 3012 /// .short("c") 3013 /// .long("config") 3014 /// .value_delimiter(";")) 3015 /// .get_matches_from(vec![ 3016 /// "prog", "--config=val1;val2;val3" 3017 /// ]); 3018 /// 3019 /// assert_eq!(m.values_of("config").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]) 3020 /// ``` 3021 /// [`Arg::use_delimiter(true)`]: ./struct.Arg.html#method.use_delimiter 3022 /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value value_delimiter(mut self, d: &str) -> Self3023 pub fn value_delimiter(mut self, d: &str) -> Self { 3024 self.unsetb(ArgSettings::ValueDelimiterNotSet); 3025 self.setb(ArgSettings::TakesValue); 3026 self.setb(ArgSettings::UseValueDelimiter); 3027 self.v.val_delim = Some( 3028 d.chars() 3029 .nth(0) 3030 .expect("Failed to get value_delimiter from arg"), 3031 ); 3032 self 3033 } 3034 3035 /// Specify multiple names for values of option arguments. These names are cosmetic only, used 3036 /// for help and usage strings only. The names are **not** used to access arguments. The values 3037 /// of the arguments are accessed in numeric order (i.e. if you specify two names `one` and 3038 /// `two` `one` will be the first matched value, `two` will be the second). 3039 /// 3040 /// This setting can be very helpful when describing the type of input the user should be 3041 /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to 3042 /// use all capital letters for the value name. 3043 /// 3044 /// **Pro Tip:** It may help to use [`Arg::next_line_help(true)`] if there are long, or 3045 /// multiple value names in order to not throw off the help text alignment of all options. 3046 /// 3047 /// **NOTE:** This implicitly sets [`Arg::number_of_values`] if the number of value names is 3048 /// greater than one. I.e. be aware that the number of "names" you set for the values, will be 3049 /// the *exact* number of values required to satisfy this argument 3050 /// 3051 /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] 3052 /// 3053 /// **NOTE:** Does *not* require or imply [`Arg::multiple(true)`]. 3054 /// 3055 /// # Examples 3056 /// 3057 /// ```rust 3058 /// # use clap::{App, Arg}; 3059 /// Arg::with_name("speed") 3060 /// .short("s") 3061 /// .value_names(&["fast", "slow"]) 3062 /// # ; 3063 /// ``` 3064 /// 3065 /// ```rust 3066 /// # use clap::{App, Arg}; 3067 /// let m = App::new("prog") 3068 /// .arg(Arg::with_name("io") 3069 /// .long("io-files") 3070 /// .value_names(&["INFILE", "OUTFILE"])) 3071 /// .get_matches_from(vec![ 3072 /// "prog", "--help" 3073 /// ]); 3074 /// ``` 3075 /// Running the above program produces the following output 3076 /// 3077 /// ```notrust 3078 /// valnames 3079 /// 3080 /// USAGE: 3081 /// valnames [FLAGS] [OPTIONS] 3082 /// 3083 /// FLAGS: 3084 /// -h, --help Prints help information 3085 /// -V, --version Prints version information 3086 /// 3087 /// OPTIONS: 3088 /// --io-files <INFILE> <OUTFILE> Some help text 3089 /// ``` 3090 /// [`Arg::next_line_help(true)`]: ./struct.Arg.html#method.next_line_help 3091 /// [`Arg::number_of_values`]: ./struct.Arg.html#method.number_of_values 3092 /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value 3093 /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple value_names(mut self, names: &[&'b str]) -> Self3094 pub fn value_names(mut self, names: &[&'b str]) -> Self { 3095 self.setb(ArgSettings::TakesValue); 3096 if self.is_set(ArgSettings::ValueDelimiterNotSet) { 3097 self.unsetb(ArgSettings::ValueDelimiterNotSet); 3098 self.setb(ArgSettings::UseValueDelimiter); 3099 } 3100 if let Some(ref mut vals) = self.v.val_names { 3101 let mut l = vals.len(); 3102 for s in names { 3103 vals.insert(l, s); 3104 l += 1; 3105 } 3106 } else { 3107 let mut vm = VecMap::new(); 3108 for (i, n) in names.iter().enumerate() { 3109 vm.insert(i, *n); 3110 } 3111 self.v.val_names = Some(vm); 3112 } 3113 self 3114 } 3115 3116 /// Specifies the name for value of [option] or [positional] arguments inside of help 3117 /// documentation. This name is cosmetic only, the name is **not** used to access arguments. 3118 /// This setting can be very helpful when describing the type of input the user should be 3119 /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to 3120 /// use all capital letters for the value name. 3121 /// 3122 /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] 3123 /// 3124 /// # Examples 3125 /// 3126 /// ```rust 3127 /// # use clap::{App, Arg}; 3128 /// Arg::with_name("cfg") 3129 /// .long("config") 3130 /// .value_name("FILE") 3131 /// # ; 3132 /// ``` 3133 /// 3134 /// ```rust 3135 /// # use clap::{App, Arg}; 3136 /// let m = App::new("prog") 3137 /// .arg(Arg::with_name("config") 3138 /// .long("config") 3139 /// .value_name("FILE")) 3140 /// .get_matches_from(vec![ 3141 /// "prog", "--help" 3142 /// ]); 3143 /// ``` 3144 /// Running the above program produces the following output 3145 /// 3146 /// ```notrust 3147 /// valnames 3148 /// 3149 /// USAGE: 3150 /// valnames [FLAGS] [OPTIONS] 3151 /// 3152 /// FLAGS: 3153 /// -h, --help Prints help information 3154 /// -V, --version Prints version information 3155 /// 3156 /// OPTIONS: 3157 /// --config <FILE> Some help text 3158 /// ``` 3159 /// [option]: ./struct.Arg.html#method.takes_value 3160 /// [positional]: ./struct.Arg.html#method.index 3161 /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value value_name(mut self, name: &'b str) -> Self3162 pub fn value_name(mut self, name: &'b str) -> Self { 3163 self.setb(ArgSettings::TakesValue); 3164 if let Some(ref mut vals) = self.v.val_names { 3165 let l = vals.len(); 3166 vals.insert(l, name); 3167 } else { 3168 let mut vm = VecMap::new(); 3169 vm.insert(0, name); 3170 self.v.val_names = Some(vm); 3171 } 3172 self 3173 } 3174 3175 /// Specifies the value of the argument when *not* specified at runtime. 3176 /// 3177 /// **NOTE:** If the user *does not* use this argument at runtime, [`ArgMatches::occurrences_of`] 3178 /// will return `0` even though the [`ArgMatches::value_of`] will return the default specified. 3179 /// 3180 /// **NOTE:** If the user *does not* use this argument at runtime [`ArgMatches::is_present`] will 3181 /// still return `true`. If you wish to determine whether the argument was used at runtime or 3182 /// not, consider [`ArgMatches::occurrences_of`] which will return `0` if the argument was *not* 3183 /// used at runtime. 3184 /// 3185 /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value_if`] but slightly 3186 /// different. `Arg::default_value` *only* takes affect when the user has not provided this arg 3187 /// at runtime. `Arg::default_value_if` however only takes affect when the user has not provided 3188 /// a value at runtime **and** these other conditions are met as well. If you have set 3189 /// `Arg::default_value` and `Arg::default_value_if`, and the user **did not** provide a this 3190 /// arg at runtime, nor did were the conditions met for `Arg::default_value_if`, the 3191 /// `Arg::default_value` will be applied. 3192 /// 3193 /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`]. 3194 /// 3195 /// **NOTE:** This setting effectively disables `AppSettings::ArgRequiredElseHelp` if used in 3196 /// conjunction as it ensures that some argument will always be present. 3197 /// 3198 /// # Examples 3199 /// 3200 /// First we use the default value without providing any value at runtime. 3201 /// 3202 /// ```rust 3203 /// # use clap::{App, Arg}; 3204 /// let m = App::new("prog") 3205 /// .arg(Arg::with_name("opt") 3206 /// .long("myopt") 3207 /// .default_value("myval")) 3208 /// .get_matches_from(vec![ 3209 /// "prog" 3210 /// ]); 3211 /// 3212 /// assert_eq!(m.value_of("opt"), Some("myval")); 3213 /// assert!(m.is_present("opt")); 3214 /// assert_eq!(m.occurrences_of("opt"), 0); 3215 /// ``` 3216 /// 3217 /// Next we provide a value at runtime to override the default. 3218 /// 3219 /// ```rust 3220 /// # use clap::{App, Arg}; 3221 /// let m = App::new("prog") 3222 /// .arg(Arg::with_name("opt") 3223 /// .long("myopt") 3224 /// .default_value("myval")) 3225 /// .get_matches_from(vec![ 3226 /// "prog", "--myopt=non_default" 3227 /// ]); 3228 /// 3229 /// assert_eq!(m.value_of("opt"), Some("non_default")); 3230 /// assert!(m.is_present("opt")); 3231 /// assert_eq!(m.occurrences_of("opt"), 1); 3232 /// ``` 3233 /// [`ArgMatches::occurrences_of`]: ./struct.ArgMatches.html#method.occurrences_of 3234 /// [`ArgMatches::value_of`]: ./struct.ArgMatches.html#method.value_of 3235 /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value 3236 /// [`ArgMatches::is_present`]: ./struct.ArgMatches.html#method.is_present 3237 /// [`Arg::default_value_if`]: ./struct.Arg.html#method.default_value_if default_value(self, val: &'a str) -> Self3238 pub fn default_value(self, val: &'a str) -> Self { 3239 self.default_value_os(OsStr::from_bytes(val.as_bytes())) 3240 } 3241 3242 /// Provides a default value in the exact same manner as [`Arg::default_value`] 3243 /// only using [`OsStr`]s instead. 3244 /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value 3245 /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html default_value_os(mut self, val: &'a OsStr) -> Self3246 pub fn default_value_os(mut self, val: &'a OsStr) -> Self { 3247 self.setb(ArgSettings::TakesValue); 3248 self.v.default_val = Some(val); 3249 self 3250 } 3251 3252 /// Specifies the value of the argument if `arg` has been used at runtime. If `val` is set to 3253 /// `None`, `arg` only needs to be present. If `val` is set to `"some-val"` then `arg` must be 3254 /// present at runtime **and** have the value `val`. 3255 /// 3256 /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value`] but slightly 3257 /// different. `Arg::default_value` *only* takes affect when the user has not provided this arg 3258 /// at runtime. This setting however only takes affect when the user has not provided a value at 3259 /// runtime **and** these other conditions are met as well. If you have set `Arg::default_value` 3260 /// and `Arg::default_value_if`, and the user **did not** provide a this arg at runtime, nor did 3261 /// were the conditions met for `Arg::default_value_if`, the `Arg::default_value` will be 3262 /// applied. 3263 /// 3264 /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`]. 3265 /// 3266 /// **NOTE:** If using YAML the values should be laid out as follows (`None` can be represented 3267 /// as `null` in YAML) 3268 /// 3269 /// ```yaml 3270 /// default_value_if: 3271 /// - [arg, val, default] 3272 /// ``` 3273 /// 3274 /// # Examples 3275 /// 3276 /// First we use the default value only if another arg is present at runtime. 3277 /// 3278 /// ```rust 3279 /// # use clap::{App, Arg}; 3280 /// let m = App::new("prog") 3281 /// .arg(Arg::with_name("flag") 3282 /// .long("flag")) 3283 /// .arg(Arg::with_name("other") 3284 /// .long("other") 3285 /// .default_value_if("flag", None, "default")) 3286 /// .get_matches_from(vec![ 3287 /// "prog", "--flag" 3288 /// ]); 3289 /// 3290 /// assert_eq!(m.value_of("other"), Some("default")); 3291 /// ``` 3292 /// 3293 /// Next we run the same test, but without providing `--flag`. 3294 /// 3295 /// ```rust 3296 /// # use clap::{App, Arg}; 3297 /// let m = App::new("prog") 3298 /// .arg(Arg::with_name("flag") 3299 /// .long("flag")) 3300 /// .arg(Arg::with_name("other") 3301 /// .long("other") 3302 /// .default_value_if("flag", None, "default")) 3303 /// .get_matches_from(vec![ 3304 /// "prog" 3305 /// ]); 3306 /// 3307 /// assert_eq!(m.value_of("other"), None); 3308 /// ``` 3309 /// 3310 /// Now lets only use the default value if `--opt` contains the value `special`. 3311 /// 3312 /// ```rust 3313 /// # use clap::{App, Arg}; 3314 /// let m = App::new("prog") 3315 /// .arg(Arg::with_name("opt") 3316 /// .takes_value(true) 3317 /// .long("opt")) 3318 /// .arg(Arg::with_name("other") 3319 /// .long("other") 3320 /// .default_value_if("opt", Some("special"), "default")) 3321 /// .get_matches_from(vec![ 3322 /// "prog", "--opt", "special" 3323 /// ]); 3324 /// 3325 /// assert_eq!(m.value_of("other"), Some("default")); 3326 /// ``` 3327 /// 3328 /// We can run the same test and provide any value *other than* `special` and we won't get a 3329 /// default value. 3330 /// 3331 /// ```rust 3332 /// # use clap::{App, Arg}; 3333 /// let m = App::new("prog") 3334 /// .arg(Arg::with_name("opt") 3335 /// .takes_value(true) 3336 /// .long("opt")) 3337 /// .arg(Arg::with_name("other") 3338 /// .long("other") 3339 /// .default_value_if("opt", Some("special"), "default")) 3340 /// .get_matches_from(vec![ 3341 /// "prog", "--opt", "hahaha" 3342 /// ]); 3343 /// 3344 /// assert_eq!(m.value_of("other"), None); 3345 /// ``` 3346 /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value 3347 /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value default_value_if(self, arg: &'a str, val: Option<&'b str>, default: &'b str) -> Self3348 pub fn default_value_if(self, arg: &'a str, val: Option<&'b str>, default: &'b str) -> Self { 3349 self.default_value_if_os( 3350 arg, 3351 val.map(str::as_bytes).map(OsStr::from_bytes), 3352 OsStr::from_bytes(default.as_bytes()), 3353 ) 3354 } 3355 3356 /// Provides a conditional default value in the exact same manner as [`Arg::default_value_if`] 3357 /// only using [`OsStr`]s instead. 3358 /// [`Arg::default_value_if`]: ./struct.Arg.html#method.default_value_if 3359 /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html default_value_if_os( mut self, arg: &'a str, val: Option<&'b OsStr>, default: &'b OsStr, ) -> Self3360 pub fn default_value_if_os( 3361 mut self, 3362 arg: &'a str, 3363 val: Option<&'b OsStr>, 3364 default: &'b OsStr, 3365 ) -> Self { 3366 self.setb(ArgSettings::TakesValue); 3367 if let Some(ref mut vm) = self.v.default_vals_ifs { 3368 let l = vm.len(); 3369 vm.insert(l, (arg, val, default)); 3370 } else { 3371 let mut vm = VecMap::new(); 3372 vm.insert(0, (arg, val, default)); 3373 self.v.default_vals_ifs = Some(vm); 3374 } 3375 self 3376 } 3377 3378 /// Specifies multiple values and conditions in the same manner as [`Arg::default_value_if`]. 3379 /// The method takes a slice of tuples in the `(arg, Option<val>, default)` format. 3380 /// 3381 /// **NOTE**: The conditions are stored in order and evaluated in the same order. I.e. the first 3382 /// if multiple conditions are true, the first one found will be applied and the ultimate value. 3383 /// 3384 /// **NOTE:** If using YAML the values should be laid out as follows 3385 /// 3386 /// ```yaml 3387 /// default_value_if: 3388 /// - [arg, val, default] 3389 /// - [arg2, null, default2] 3390 /// ``` 3391 /// 3392 /// # Examples 3393 /// 3394 /// First we use the default value only if another arg is present at runtime. 3395 /// 3396 /// ```rust 3397 /// # use clap::{App, Arg}; 3398 /// let m = App::new("prog") 3399 /// .arg(Arg::with_name("flag") 3400 /// .long("flag")) 3401 /// .arg(Arg::with_name("opt") 3402 /// .long("opt") 3403 /// .takes_value(true)) 3404 /// .arg(Arg::with_name("other") 3405 /// .long("other") 3406 /// .default_value_ifs(&[ 3407 /// ("flag", None, "default"), 3408 /// ("opt", Some("channal"), "chan"), 3409 /// ])) 3410 /// .get_matches_from(vec![ 3411 /// "prog", "--opt", "channal" 3412 /// ]); 3413 /// 3414 /// assert_eq!(m.value_of("other"), Some("chan")); 3415 /// ``` 3416 /// 3417 /// Next we run the same test, but without providing `--flag`. 3418 /// 3419 /// ```rust 3420 /// # use clap::{App, Arg}; 3421 /// let m = App::new("prog") 3422 /// .arg(Arg::with_name("flag") 3423 /// .long("flag")) 3424 /// .arg(Arg::with_name("other") 3425 /// .long("other") 3426 /// .default_value_ifs(&[ 3427 /// ("flag", None, "default"), 3428 /// ("opt", Some("channal"), "chan"), 3429 /// ])) 3430 /// .get_matches_from(vec![ 3431 /// "prog" 3432 /// ]); 3433 /// 3434 /// assert_eq!(m.value_of("other"), None); 3435 /// ``` 3436 /// 3437 /// We can also see that these values are applied in order, and if more than one condition is 3438 /// true, only the first evaluated "wins" 3439 /// 3440 /// ```rust 3441 /// # use clap::{App, Arg}; 3442 /// let m = App::new("prog") 3443 /// .arg(Arg::with_name("flag") 3444 /// .long("flag")) 3445 /// .arg(Arg::with_name("opt") 3446 /// .long("opt") 3447 /// .takes_value(true)) 3448 /// .arg(Arg::with_name("other") 3449 /// .long("other") 3450 /// .default_value_ifs(&[ 3451 /// ("flag", None, "default"), 3452 /// ("opt", Some("channal"), "chan"), 3453 /// ])) 3454 /// .get_matches_from(vec![ 3455 /// "prog", "--opt", "channal", "--flag" 3456 /// ]); 3457 /// 3458 /// assert_eq!(m.value_of("other"), Some("default")); 3459 /// ``` 3460 /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value 3461 /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value default_value_ifs(mut self, ifs: &[(&'a str, Option<&'b str>, &'b str)]) -> Self3462 pub fn default_value_ifs(mut self, ifs: &[(&'a str, Option<&'b str>, &'b str)]) -> Self { 3463 for &(arg, val, default) in ifs { 3464 self = self.default_value_if_os( 3465 arg, 3466 val.map(str::as_bytes).map(OsStr::from_bytes), 3467 OsStr::from_bytes(default.as_bytes()), 3468 ); 3469 } 3470 self 3471 } 3472 3473 /// Provides multiple conditional default values in the exact same manner as 3474 /// [`Arg::default_value_ifs`] only using [`OsStr`]s instead. 3475 /// [`Arg::default_value_ifs`]: ./struct.Arg.html#method.default_value_ifs 3476 /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html 3477 #[cfg_attr(feature = "lints", allow(explicit_counter_loop))] default_value_ifs_os(mut self, ifs: &[(&'a str, Option<&'b OsStr>, &'b OsStr)]) -> Self3478 pub fn default_value_ifs_os(mut self, ifs: &[(&'a str, Option<&'b OsStr>, &'b OsStr)]) -> Self { 3479 for &(arg, val, default) in ifs { 3480 self = self.default_value_if_os(arg, val, default); 3481 } 3482 self 3483 } 3484 3485 /// Specifies that if the value is not passed in as an argument, that it should be retrieved 3486 /// from the environment, if available. If it is not present in the environment, then default 3487 /// rules will apply. 3488 /// 3489 /// **NOTE:** If the user *does not* use this argument at runtime, [`ArgMatches::occurrences_of`] 3490 /// will return `0` even though the [`ArgMatches::value_of`] will return the default specified. 3491 /// 3492 /// **NOTE:** If the user *does not* use this argument at runtime [`ArgMatches::is_present`] will 3493 /// return `true` if the variable is present in the environment . If you wish to determine whether 3494 /// the argument was used at runtime or not, consider [`ArgMatches::occurrences_of`] which will 3495 /// return `0` if the argument was *not* used at runtime. 3496 /// 3497 /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`]. 3498 /// 3499 /// **NOTE:** If [`Arg::multiple(true)`] is set then [`Arg::use_delimiter(true)`] should also be 3500 /// set. Otherwise, only a single argument will be returned from the environment variable. The 3501 /// default delimiter is `,` and follows all the other delimiter rules. 3502 /// 3503 /// # Examples 3504 /// 3505 /// In this example, we show the variable coming from the environment: 3506 /// 3507 /// ```rust 3508 /// # use std::env; 3509 /// # use clap::{App, Arg}; 3510 /// 3511 /// env::set_var("MY_FLAG", "env"); 3512 /// 3513 /// let m = App::new("prog") 3514 /// .arg(Arg::with_name("flag") 3515 /// .long("flag") 3516 /// .env("MY_FLAG")) 3517 /// .get_matches_from(vec![ 3518 /// "prog" 3519 /// ]); 3520 /// 3521 /// assert_eq!(m.value_of("flag"), Some("env")); 3522 /// ``` 3523 /// 3524 /// In this example, we show the variable coming from an option on the CLI: 3525 /// 3526 /// ```rust 3527 /// # use std::env; 3528 /// # use clap::{App, Arg}; 3529 /// 3530 /// env::set_var("MY_FLAG", "env"); 3531 /// 3532 /// let m = App::new("prog") 3533 /// .arg(Arg::with_name("flag") 3534 /// .long("flag") 3535 /// .env("MY_FLAG")) 3536 /// .get_matches_from(vec![ 3537 /// "prog", "--flag", "opt" 3538 /// ]); 3539 /// 3540 /// assert_eq!(m.value_of("flag"), Some("opt")); 3541 /// ``` 3542 /// 3543 /// In this example, we show the variable coming from the environment even with the 3544 /// presence of a default: 3545 /// 3546 /// ```rust 3547 /// # use std::env; 3548 /// # use clap::{App, Arg}; 3549 /// 3550 /// env::set_var("MY_FLAG", "env"); 3551 /// 3552 /// let m = App::new("prog") 3553 /// .arg(Arg::with_name("flag") 3554 /// .long("flag") 3555 /// .env("MY_FLAG") 3556 /// .default_value("default")) 3557 /// .get_matches_from(vec![ 3558 /// "prog" 3559 /// ]); 3560 /// 3561 /// assert_eq!(m.value_of("flag"), Some("env")); 3562 /// ``` 3563 /// 3564 /// In this example, we show the use of multiple values in a single environment variable: 3565 /// 3566 /// ```rust 3567 /// # use std::env; 3568 /// # use clap::{App, Arg}; 3569 /// 3570 /// env::set_var("MY_FLAG_MULTI", "env1,env2"); 3571 /// 3572 /// let m = App::new("prog") 3573 /// .arg(Arg::with_name("flag") 3574 /// .long("flag") 3575 /// .env("MY_FLAG_MULTI") 3576 /// .multiple(true) 3577 /// .use_delimiter(true)) 3578 /// .get_matches_from(vec![ 3579 /// "prog" 3580 /// ]); 3581 /// 3582 /// assert_eq!(m.values_of("flag").unwrap().collect::<Vec<_>>(), vec!["env1", "env2"]); 3583 /// ``` 3584 /// [`ArgMatches::occurrences_of`]: ./struct.ArgMatches.html#method.occurrences_of 3585 /// [`ArgMatches::value_of`]: ./struct.ArgMatches.html#method.value_of 3586 /// [`ArgMatches::is_present`]: ./struct.ArgMatches.html#method.is_present 3587 /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value 3588 /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple 3589 /// [`Arg::use_delimiter(true)`]: ./struct.Arg.html#method.use_delimiter env(self, name: &'a str) -> Self3590 pub fn env(self, name: &'a str) -> Self { 3591 self.env_os(OsStr::new(name)) 3592 } 3593 3594 /// Specifies that if the value is not passed in as an argument, that it should be retrieved 3595 /// from the environment if available in the exact same manner as [`Arg::env`] only using 3596 /// [`OsStr`]s instead. env_os(mut self, name: &'a OsStr) -> Self3597 pub fn env_os(mut self, name: &'a OsStr) -> Self { 3598 self.setb(ArgSettings::TakesValue); 3599 3600 self.v.env = Some((name, env::var_os(name))); 3601 self 3602 } 3603 3604 /// @TODO @p2 @docs @release: write docs hide_env_values(self, hide: bool) -> Self3605 pub fn hide_env_values(self, hide: bool) -> Self { 3606 if hide { 3607 self.set(ArgSettings::HideEnvValues) 3608 } else { 3609 self.unset(ArgSettings::HideEnvValues) 3610 } 3611 } 3612 3613 /// When set to `true` the help string will be displayed on the line after the argument and 3614 /// indented once. This can be helpful for arguments with very long or complex help messages. 3615 /// This can also be helpful for arguments with very long flag names, or many/long value names. 3616 /// 3617 /// **NOTE:** To apply this setting to all arguments consider using 3618 /// [`AppSettings::NextLineHelp`] 3619 /// 3620 /// # Examples 3621 /// 3622 /// ```rust 3623 /// # use clap::{App, Arg}; 3624 /// let m = App::new("prog") 3625 /// .arg(Arg::with_name("opt") 3626 /// .long("long-option-flag") 3627 /// .short("o") 3628 /// .takes_value(true) 3629 /// .value_names(&["value1", "value2"]) 3630 /// .help("Some really long help and complex\n\ 3631 /// help that makes more sense to be\n\ 3632 /// on a line after the option") 3633 /// .next_line_help(true)) 3634 /// .get_matches_from(vec![ 3635 /// "prog", "--help" 3636 /// ]); 3637 /// ``` 3638 /// 3639 /// The above example displays the following help message 3640 /// 3641 /// ```notrust 3642 /// nlh 3643 /// 3644 /// USAGE: 3645 /// nlh [FLAGS] [OPTIONS] 3646 /// 3647 /// FLAGS: 3648 /// -h, --help Prints help information 3649 /// -V, --version Prints version information 3650 /// 3651 /// OPTIONS: 3652 /// -o, --long-option-flag <value1> <value2> 3653 /// Some really long help and complex 3654 /// help that makes more sense to be 3655 /// on a line after the option 3656 /// ``` 3657 /// [`AppSettings::NextLineHelp`]: ./enum.AppSettings.html#variant.NextLineHelp next_line_help(mut self, nlh: bool) -> Self3658 pub fn next_line_help(mut self, nlh: bool) -> Self { 3659 if nlh { 3660 self.setb(ArgSettings::NextLineHelp); 3661 } else { 3662 self.unsetb(ArgSettings::NextLineHelp); 3663 } 3664 self 3665 } 3666 3667 /// Allows custom ordering of args within the help message. Args with a lower value will be 3668 /// displayed first in the help message. This is helpful when one would like to emphasise 3669 /// frequently used args, or prioritize those towards the top of the list. Duplicate values 3670 /// **are** allowed. Args with duplicate display orders will be displayed in alphabetical 3671 /// order. 3672 /// 3673 /// **NOTE:** The default is 999 for all arguments. 3674 /// 3675 /// **NOTE:** This setting is ignored for [positional arguments] which are always displayed in 3676 /// [index] order. 3677 /// 3678 /// # Examples 3679 /// 3680 /// ```rust 3681 /// # use clap::{App, Arg}; 3682 /// let m = App::new("prog") 3683 /// .arg(Arg::with_name("a") // Typically args are grouped alphabetically by name. 3684 /// // Args without a display_order have a value of 999 and are 3685 /// // displayed alphabetically with all other 999 valued args. 3686 /// .long("long-option") 3687 /// .short("o") 3688 /// .takes_value(true) 3689 /// .help("Some help and text")) 3690 /// .arg(Arg::with_name("b") 3691 /// .long("other-option") 3692 /// .short("O") 3693 /// .takes_value(true) 3694 /// .display_order(1) // In order to force this arg to appear *first* 3695 /// // all we have to do is give it a value lower than 999. 3696 /// // Any other args with a value of 1 will be displayed 3697 /// // alphabetically with this one...then 2 values, then 3, etc. 3698 /// .help("I should be first!")) 3699 /// .get_matches_from(vec![ 3700 /// "prog", "--help" 3701 /// ]); 3702 /// ``` 3703 /// 3704 /// The above example displays the following help message 3705 /// 3706 /// ```notrust 3707 /// cust-ord 3708 /// 3709 /// USAGE: 3710 /// cust-ord [FLAGS] [OPTIONS] 3711 /// 3712 /// FLAGS: 3713 /// -h, --help Prints help information 3714 /// -V, --version Prints version information 3715 /// 3716 /// OPTIONS: 3717 /// -O, --other-option <b> I should be first! 3718 /// -o, --long-option <a> Some help and text 3719 /// ``` 3720 /// [positional arguments]: ./struct.Arg.html#method.index 3721 /// [index]: ./struct.Arg.html#method.index display_order(mut self, ord: usize) -> Self3722 pub fn display_order(mut self, ord: usize) -> Self { 3723 self.s.disp_ord = ord; 3724 self 3725 } 3726 3727 /// Indicates that all parameters passed after this should not be parsed 3728 /// individually, but rather passed in their entirety. It is worth noting 3729 /// that setting this requires all values to come after a `--` to indicate they 3730 /// should all be captured. For example: 3731 /// 3732 /// ```notrust 3733 /// --foo something -- -v -v -v -b -b -b --baz -q -u -x 3734 /// ``` 3735 /// Will result in everything after `--` to be considered one raw argument. This behavior 3736 /// may not be exactly what you are expecting and using [`AppSettings::TrailingVarArg`] 3737 /// may be more appropriate. 3738 /// 3739 /// **NOTE:** Implicitly sets [`Arg::multiple(true)`], [`Arg::allow_hyphen_values(true)`], and 3740 /// [`Arg::last(true)`] when set to `true` 3741 /// 3742 /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple 3743 /// [`Arg::allow_hyphen_values(true)`]: ./struct.Arg.html#method.allow_hyphen_values 3744 /// [`Arg::last(true)`]: ./struct.Arg.html#method.last 3745 /// [`AppSettings::TrailingVarArg`]: ./enum.AppSettings.html#variant.TrailingVarArg raw(self, raw: bool) -> Self3746 pub fn raw(self, raw: bool) -> Self { 3747 self.multiple(raw).allow_hyphen_values(raw).last(raw) 3748 } 3749 3750 /// Hides an argument from short help message output. 3751 /// 3752 /// **NOTE:** This does **not** hide the argument from usage strings on error 3753 /// 3754 /// **NOTE:** Setting this option will cause next-line-help output style to be used 3755 /// when long help (`--help`) is called. 3756 /// 3757 /// # Examples 3758 /// 3759 /// ```rust 3760 /// # use clap::{App, Arg}; 3761 /// Arg::with_name("debug") 3762 /// .hidden_short_help(true) 3763 /// # ; 3764 /// ``` 3765 /// Setting `hidden_short_help(true)` will hide the argument when displaying short help text 3766 /// 3767 /// ```rust 3768 /// # use clap::{App, Arg}; 3769 /// let m = App::new("prog") 3770 /// .arg(Arg::with_name("cfg") 3771 /// .long("config") 3772 /// .hidden_short_help(true) 3773 /// .help("Some help text describing the --config arg")) 3774 /// .get_matches_from(vec![ 3775 /// "prog", "-h" 3776 /// ]); 3777 /// ``` 3778 /// 3779 /// The above example displays 3780 /// 3781 /// ```notrust 3782 /// helptest 3783 /// 3784 /// USAGE: 3785 /// helptest [FLAGS] 3786 /// 3787 /// FLAGS: 3788 /// -h, --help Prints help information 3789 /// -V, --version Prints version information 3790 /// ``` 3791 /// 3792 /// However, when --help is called 3793 /// 3794 /// ```rust 3795 /// # use clap::{App, Arg}; 3796 /// let m = App::new("prog") 3797 /// .arg(Arg::with_name("cfg") 3798 /// .long("config") 3799 /// .hidden_short_help(true) 3800 /// .help("Some help text describing the --config arg")) 3801 /// .get_matches_from(vec![ 3802 /// "prog", "--help" 3803 /// ]); 3804 /// ``` 3805 /// 3806 /// Then the following would be displayed 3807 /// 3808 /// ```notrust 3809 /// helptest 3810 /// 3811 /// USAGE: 3812 /// helptest [FLAGS] 3813 /// 3814 /// FLAGS: 3815 /// --config Some help text describing the --config arg 3816 /// -h, --help Prints help information 3817 /// -V, --version Prints version information 3818 /// ``` hidden_short_help(self, hide: bool) -> Self3819 pub fn hidden_short_help(self, hide: bool) -> Self { 3820 if hide { 3821 self.set(ArgSettings::HiddenShortHelp) 3822 } else { 3823 self.unset(ArgSettings::HiddenShortHelp) 3824 } 3825 } 3826 3827 /// Hides an argument from long help message output. 3828 /// 3829 /// **NOTE:** This does **not** hide the argument from usage strings on error 3830 /// 3831 /// **NOTE:** Setting this option will cause next-line-help output style to be used 3832 /// when long help (`--help`) is called. 3833 /// 3834 /// # Examples 3835 /// 3836 /// ```rust 3837 /// # use clap::{App, Arg}; 3838 /// Arg::with_name("debug") 3839 /// .hidden_long_help(true) 3840 /// # ; 3841 /// ``` 3842 /// Setting `hidden_long_help(true)` will hide the argument when displaying long help text 3843 /// 3844 /// ```rust 3845 /// # use clap::{App, Arg}; 3846 /// let m = App::new("prog") 3847 /// .arg(Arg::with_name("cfg") 3848 /// .long("config") 3849 /// .hidden_long_help(true) 3850 /// .help("Some help text describing the --config arg")) 3851 /// .get_matches_from(vec![ 3852 /// "prog", "--help" 3853 /// ]); 3854 /// ``` 3855 /// 3856 /// The above example displays 3857 /// 3858 /// ```notrust 3859 /// helptest 3860 /// 3861 /// USAGE: 3862 /// helptest [FLAGS] 3863 /// 3864 /// FLAGS: 3865 /// -h, --help Prints help information 3866 /// -V, --version Prints version information 3867 /// ``` 3868 /// 3869 /// However, when -h is called 3870 /// 3871 /// ```rust 3872 /// # use clap::{App, Arg}; 3873 /// let m = App::new("prog") 3874 /// .arg(Arg::with_name("cfg") 3875 /// .long("config") 3876 /// .hidden_long_help(true) 3877 /// .help("Some help text describing the --config arg")) 3878 /// .get_matches_from(vec![ 3879 /// "prog", "-h" 3880 /// ]); 3881 /// ``` 3882 /// 3883 /// Then the following would be displayed 3884 /// 3885 /// ```notrust 3886 /// helptest 3887 /// 3888 /// USAGE: 3889 /// helptest [FLAGS] 3890 /// 3891 /// FLAGS: 3892 /// --config Some help text describing the --config arg 3893 /// -h, --help Prints help information 3894 /// -V, --version Prints version information 3895 /// ``` hidden_long_help(self, hide: bool) -> Self3896 pub fn hidden_long_help(self, hide: bool) -> Self { 3897 if hide { 3898 self.set(ArgSettings::HiddenLongHelp) 3899 } else { 3900 self.unset(ArgSettings::HiddenLongHelp) 3901 } 3902 } 3903 3904 /// Checks if one of the [`ArgSettings`] settings is set for the argument. 3905 /// 3906 /// [`ArgSettings`]: ./enum.ArgSettings.html is_set(&self, s: ArgSettings) -> bool3907 pub fn is_set(&self, s: ArgSettings) -> bool { 3908 self.b.is_set(s) 3909 } 3910 3911 /// Sets one of the [`ArgSettings`] settings for the argument. 3912 /// 3913 /// [`ArgSettings`]: ./enum.ArgSettings.html set(mut self, s: ArgSettings) -> Self3914 pub fn set(mut self, s: ArgSettings) -> Self { 3915 self.setb(s); 3916 self 3917 } 3918 3919 /// Unsets one of the [`ArgSettings`] settings for the argument. 3920 /// 3921 /// [`ArgSettings`]: ./enum.ArgSettings.html unset(mut self, s: ArgSettings) -> Self3922 pub fn unset(mut self, s: ArgSettings) -> Self { 3923 self.unsetb(s); 3924 self 3925 } 3926 3927 #[doc(hidden)] setb(&mut self, s: ArgSettings)3928 pub fn setb(&mut self, s: ArgSettings) { 3929 self.b.set(s); 3930 } 3931 3932 #[doc(hidden)] unsetb(&mut self, s: ArgSettings)3933 pub fn unsetb(&mut self, s: ArgSettings) { 3934 self.b.unset(s); 3935 } 3936 } 3937 3938 impl<'a, 'b, 'z> From<&'z Arg<'a, 'b>> for Arg<'a, 'b> { from(a: &'z Arg<'a, 'b>) -> Self3939 fn from(a: &'z Arg<'a, 'b>) -> Self { 3940 Arg { 3941 b: a.b.clone(), 3942 v: a.v.clone(), 3943 s: a.s.clone(), 3944 index: a.index, 3945 r_ifs: a.r_ifs.clone(), 3946 } 3947 } 3948 } 3949 3950 impl<'n, 'e> PartialEq for Arg<'n, 'e> { eq(&self, other: &Arg<'n, 'e>) -> bool3951 fn eq(&self, other: &Arg<'n, 'e>) -> bool { 3952 self.b == other.b 3953 } 3954 } 3955