1#![cfg_attr(not(feature = "usage"), allow(unused_mut))] 2 3// Std 4use std::env; 5use std::ffi::OsString; 6use std::fmt; 7use std::io; 8use std::ops::Index; 9use std::path::Path; 10 11// Internal 12use crate::builder::app_settings::{AppFlags, AppSettings}; 13use crate::builder::arg_settings::ArgSettings; 14use crate::builder::ArgAction; 15use crate::builder::IntoResettable; 16use crate::builder::PossibleValue; 17use crate::builder::Str; 18use crate::builder::StyledStr; 19use crate::builder::{Arg, ArgGroup, ArgPredicate}; 20use crate::error::ErrorKind; 21use crate::error::Result as ClapResult; 22use crate::mkeymap::MKeyMap; 23use crate::output::fmt::Stream; 24use crate::output::{fmt::Colorizer, write_help, Usage}; 25use crate::parser::{ArgMatcher, ArgMatches, Parser}; 26use crate::util::ChildGraph; 27use crate::util::FlatMap; 28use crate::util::{color::ColorChoice, Id}; 29use crate::{Error, INTERNAL_ERROR_MSG}; 30 31#[cfg(debug_assertions)] 32use crate::builder::debug_asserts::assert_app; 33 34/// Build a command-line interface. 35/// 36/// This includes defining arguments, subcommands, parser behavior, and help output. 37/// Once all configuration is complete, 38/// the [`Command::get_matches`] family of methods starts the runtime-parsing 39/// process. These methods then return information about the user supplied 40/// arguments (or lack thereof). 41/// 42/// When deriving a [`Parser`][crate::Parser], you can use 43/// [`CommandFactory::command`][crate::CommandFactory::command] to access the 44/// `Command`. 45/// 46/// - [Basic API][crate::Command#basic-api] 47/// - [Application-wide Settings][crate::Command#application-wide-settings] 48/// - [Command-specific Settings][crate::Command#command-specific-settings] 49/// - [Subcommand-specific Settings][crate::Command#subcommand-specific-settings] 50/// - [Reflection][crate::Command#reflection] 51/// 52/// # Examples 53/// 54/// ```no_run 55/// # use clap::{Command, Arg}; 56/// let m = Command::new("My Program") 57/// .author("Me, me@mail.com") 58/// .version("1.0.2") 59/// .about("Explains in brief what the program does") 60/// .arg( 61/// Arg::new("in_file") 62/// ) 63/// .after_help("Longer explanation to appear after the options when \ 64/// displaying the help information from --help or -h") 65/// .get_matches(); 66/// 67/// // Your program logic starts here... 68/// ``` 69/// [`Command::get_matches`]: Command::get_matches() 70#[derive(Debug, Clone)] 71pub struct Command { 72 name: Str, 73 long_flag: Option<Str>, 74 short_flag: Option<char>, 75 display_name: Option<String>, 76 bin_name: Option<String>, 77 author: Option<Str>, 78 version: Option<Str>, 79 long_version: Option<Str>, 80 about: Option<StyledStr>, 81 long_about: Option<StyledStr>, 82 before_help: Option<StyledStr>, 83 before_long_help: Option<StyledStr>, 84 after_help: Option<StyledStr>, 85 after_long_help: Option<StyledStr>, 86 aliases: Vec<(Str, bool)>, // (name, visible) 87 short_flag_aliases: Vec<(char, bool)>, // (name, visible) 88 long_flag_aliases: Vec<(Str, bool)>, // (name, visible) 89 usage_str: Option<StyledStr>, 90 usage_name: Option<String>, 91 help_str: Option<StyledStr>, 92 disp_ord: Option<usize>, 93 term_w: Option<usize>, 94 max_w: Option<usize>, 95 #[cfg(feature = "help")] 96 template: Option<StyledStr>, 97 settings: AppFlags, 98 g_settings: AppFlags, 99 args: MKeyMap, 100 subcommands: Vec<Command>, 101 replacers: FlatMap<Str, Vec<Str>>, 102 groups: Vec<ArgGroup>, 103 current_help_heading: Option<Str>, 104 current_disp_ord: Option<usize>, 105 subcommand_value_name: Option<Str>, 106 subcommand_heading: Option<Str>, 107 external_value_parser: Option<super::ValueParser>, 108 long_help_exists: bool, 109} 110 111/// # Basic API 112impl Command { 113 /// Creates a new instance of an `Command`. 114 /// 115 /// It is common, but not required, to use binary name as the `name`. This 116 /// name will only be displayed to the user when they request to print 117 /// version or help and usage information. 118 /// 119 /// See also [`command!`](crate::command!) and [`crate_name!`](crate::crate_name!). 120 /// 121 /// # Examples 122 /// 123 /// ```no_run 124 /// # use clap::Command; 125 /// Command::new("My Program") 126 /// # ; 127 /// ``` 128 pub fn new(name: impl Into<Str>) -> Self { 129 /// The actual implementation of `new`, non-generic to save code size. 130 /// 131 /// If we don't do this rustc will unnecessarily generate multiple versions 132 /// of this code. 133 fn new_inner(name: Str) -> Command { 134 Command { 135 name, 136 ..Default::default() 137 } 138 } 139 140 new_inner(name.into()) 141 } 142 143 /// Adds an [argument] to the list of valid possibilities. 144 /// 145 /// # Examples 146 /// 147 /// ```no_run 148 /// # use clap::{Command, arg, Arg}; 149 /// Command::new("myprog") 150 /// // Adding a single "flag" argument with a short and help text, using Arg::new() 151 /// .arg( 152 /// Arg::new("debug") 153 /// .short('d') 154 /// .help("turns on debugging mode") 155 /// ) 156 /// // Adding a single "option" argument with a short, a long, and help text using the less 157 /// // verbose Arg::from() 158 /// .arg( 159 /// arg!(-c --config <CONFIG> "Optionally sets a config file to use") 160 /// ) 161 /// # ; 162 /// ``` 163 /// [argument]: Arg 164 #[must_use] 165 pub fn arg(mut self, a: impl Into<Arg>) -> Self { 166 let arg = a.into(); 167 self.arg_internal(arg); 168 self 169 } 170 171 fn arg_internal(&mut self, mut arg: Arg) { 172 if let Some(current_disp_ord) = self.current_disp_ord.as_mut() { 173 if !arg.is_positional() { 174 let current = *current_disp_ord; 175 arg.disp_ord.get_or_insert(current); 176 *current_disp_ord = current + 1; 177 } 178 } 179 180 arg.help_heading 181 .get_or_insert_with(|| self.current_help_heading.clone()); 182 self.args.push(arg); 183 } 184 185 /// Adds multiple [arguments] to the list of valid possibilities. 186 /// 187 /// # Examples 188 /// 189 /// ```no_run 190 /// # use clap::{Command, arg, Arg}; 191 /// Command::new("myprog") 192 /// .args([ 193 /// arg!("[debug] -d 'turns on debugging info'"), 194 /// Arg::new("input").help("the input file to use") 195 /// ]) 196 /// # ; 197 /// ``` 198 /// [arguments]: Arg 199 #[must_use] 200 pub fn args(mut self, args: impl IntoIterator<Item = impl Into<Arg>>) -> Self { 201 for arg in args { 202 self = self.arg(arg); 203 } 204 self 205 } 206 207 /// Allows one to mutate an [`Arg`] after it's been added to a [`Command`]. 208 /// 209 /// This can be useful for modifying the auto-generated help or version arguments. 210 /// 211 /// # Panics 212 /// 213 /// If the argument is undefined 214 /// 215 /// # Examples 216 /// 217 /// ```rust 218 /// # use clap::{Command, Arg, ArgAction}; 219 /// 220 /// let mut cmd = Command::new("foo") 221 /// .arg(Arg::new("bar") 222 /// .short('b') 223 /// .action(ArgAction::SetTrue)) 224 /// .mut_arg("bar", |a| a.short('B')); 225 /// 226 /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-b"]); 227 /// 228 /// // Since we changed `bar`'s short to "B" this should err as there 229 /// // is no `-b` anymore, only `-B` 230 /// 231 /// assert!(res.is_err()); 232 /// 233 /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-B"]); 234 /// assert!(res.is_ok()); 235 /// ``` 236 #[must_use] 237 #[cfg_attr(debug_assertions, track_caller)] 238 pub fn mut_arg<F>(mut self, arg_id: impl AsRef<str>, f: F) -> Self 239 where 240 F: FnOnce(Arg) -> Arg, 241 { 242 let id = arg_id.as_ref(); 243 let a = self 244 .args 245 .remove_by_name(id) 246 .unwrap_or_else(|| panic!("Argument `{id}` is undefined")); 247 248 self.args.push(f(a)); 249 self 250 } 251 252 /// Allows one to mutate a [`Command`] after it's been added as a subcommand. 253 /// 254 /// This can be useful for modifying auto-generated arguments of nested subcommands with 255 /// [`Command::mut_arg`]. 256 /// 257 /// # Panics 258 /// 259 /// If the subcommand is undefined 260 /// 261 /// # Examples 262 /// 263 /// ```rust 264 /// # use clap::Command; 265 /// 266 /// let mut cmd = Command::new("foo") 267 /// .subcommand(Command::new("bar")) 268 /// .mut_subcommand("bar", |subcmd| subcmd.disable_help_flag(true)); 269 /// 270 /// let res = cmd.try_get_matches_from_mut(vec!["foo", "bar", "--help"]); 271 /// 272 /// // Since we disabled the help flag on the "bar" subcommand, this should err. 273 /// 274 /// assert!(res.is_err()); 275 /// 276 /// let res = cmd.try_get_matches_from_mut(vec!["foo", "bar"]); 277 /// assert!(res.is_ok()); 278 /// ``` 279 #[must_use] 280 pub fn mut_subcommand<F>(mut self, name: impl AsRef<str>, f: F) -> Self 281 where 282 F: FnOnce(Self) -> Self, 283 { 284 let name = name.as_ref(); 285 let pos = self.subcommands.iter().position(|s| s.name == name); 286 287 let subcmd = if let Some(idx) = pos { 288 self.subcommands.remove(idx) 289 } else { 290 panic!("Command `{name}` is undefined") 291 }; 292 293 self.subcommands.push(f(subcmd)); 294 self 295 } 296 297 /// Adds an [`ArgGroup`] to the application. 298 /// 299 /// [`ArgGroup`]s are a family of related arguments. 300 /// By placing them in a logical group, you can build easier requirement and exclusion rules. 301 /// 302 /// Example use cases: 303 /// - Make an entire [`ArgGroup`] required, meaning that one (and *only* 304 /// one) argument from that group must be present at runtime. 305 /// - Name an [`ArgGroup`] as a conflict to another argument. 306 /// Meaning any of the arguments that belong to that group will cause a failure if present with 307 /// the conflicting argument. 308 /// - Ensure exclusion between arguments. 309 /// - Extract a value from a group instead of determining exactly which argument was used. 310 /// 311 /// # Examples 312 /// 313 /// The following example demonstrates using an [`ArgGroup`] to ensure that one, and only one, 314 /// of the arguments from the specified group is present at runtime. 315 /// 316 /// ```no_run 317 /// # use clap::{Command, arg, ArgGroup}; 318 /// Command::new("cmd") 319 /// .arg(arg!("--set-ver [ver] 'set the version manually'")) 320 /// .arg(arg!("--major 'auto increase major'")) 321 /// .arg(arg!("--minor 'auto increase minor'")) 322 /// .arg(arg!("--patch 'auto increase patch'")) 323 /// .group(ArgGroup::new("vers") 324 /// .args(["set-ver", "major", "minor","patch"]) 325 /// .required(true)) 326 /// # ; 327 /// ``` 328 #[inline] 329 #[must_use] 330 pub fn group(mut self, group: impl Into<ArgGroup>) -> Self { 331 self.groups.push(group.into()); 332 self 333 } 334 335 /// Adds multiple [`ArgGroup`]s to the [`Command`] at once. 336 /// 337 /// # Examples 338 /// 339 /// ```no_run 340 /// # use clap::{Command, arg, ArgGroup}; 341 /// Command::new("cmd") 342 /// .arg(arg!("--set-ver [ver] 'set the version manually'")) 343 /// .arg(arg!("--major 'auto increase major'")) 344 /// .arg(arg!("--minor 'auto increase minor'")) 345 /// .arg(arg!("--patch 'auto increase patch'")) 346 /// .arg(arg!("-c [FILE] 'a config file'")) 347 /// .arg(arg!("-i [IFACE] 'an interface'")) 348 /// .groups([ 349 /// ArgGroup::new("vers") 350 /// .args(["set-ver", "major", "minor","patch"]) 351 /// .required(true), 352 /// ArgGroup::new("input") 353 /// .args(["c", "i"]) 354 /// ]) 355 /// # ; 356 /// ``` 357 #[must_use] 358 pub fn groups(mut self, groups: impl IntoIterator<Item = impl Into<ArgGroup>>) -> Self { 359 for g in groups.into_iter() { 360 self = self.group(g.into()); 361 } 362 self 363 } 364 365 /// Adds a subcommand to the list of valid possibilities. 366 /// 367 /// Subcommands are effectively sub-[`Command`]s, because they can contain their own arguments, 368 /// subcommands, version, usage, etc. They also function just like [`Command`]s, in that they get 369 /// their own auto generated help, version, and usage. 370 /// 371 /// A subcommand's [`Command::name`] will be used for: 372 /// - The argument the user passes in 373 /// - Programmatically looking up the subcommand 374 /// 375 /// # Examples 376 /// 377 /// ```no_run 378 /// # use clap::{Command, arg}; 379 /// Command::new("myprog") 380 /// .subcommand(Command::new("config") 381 /// .about("Controls configuration features") 382 /// .arg(arg!("<config> 'Required configuration file to use'"))) 383 /// # ; 384 /// ``` 385 #[inline] 386 #[must_use] 387 pub fn subcommand(self, subcmd: impl Into<Command>) -> Self { 388 let subcmd = subcmd.into(); 389 self.subcommand_internal(subcmd) 390 } 391 392 fn subcommand_internal(mut self, mut subcmd: Self) -> Self { 393 if let Some(current_disp_ord) = self.current_disp_ord.as_mut() { 394 let current = *current_disp_ord; 395 subcmd.disp_ord.get_or_insert(current); 396 *current_disp_ord = current + 1; 397 } 398 self.subcommands.push(subcmd); 399 self 400 } 401 402 /// Adds multiple subcommands to the list of valid possibilities. 403 /// 404 /// # Examples 405 /// 406 /// ```rust 407 /// # use clap::{Command, Arg, }; 408 /// # Command::new("myprog") 409 /// .subcommands( [ 410 /// Command::new("config").about("Controls configuration functionality") 411 /// .arg(Arg::new("config_file")), 412 /// Command::new("debug").about("Controls debug functionality")]) 413 /// # ; 414 /// ``` 415 /// [`IntoIterator`]: std::iter::IntoIterator 416 #[must_use] 417 pub fn subcommands(mut self, subcmds: impl IntoIterator<Item = impl Into<Self>>) -> Self { 418 for subcmd in subcmds { 419 self = self.subcommand(subcmd); 420 } 421 self 422 } 423 424 /// Catch problems earlier in the development cycle. 425 /// 426 /// Most error states are handled as asserts under the assumption they are programming mistake 427 /// and not something to handle at runtime. Rather than relying on tests (manual or automated) 428 /// that exhaustively test your CLI to ensure the asserts are evaluated, this will run those 429 /// asserts in a way convenient for running as a test. 430 /// 431 /// **Note::** This will not help with asserts in [`ArgMatches`], those will need exhaustive 432 /// testing of your CLI. 433 /// 434 /// # Examples 435 /// 436 /// ```rust 437 /// # use clap::{Command, Arg, ArgAction}; 438 /// fn cmd() -> Command { 439 /// Command::new("foo") 440 /// .arg( 441 /// Arg::new("bar").short('b').action(ArgAction::SetTrue) 442 /// ) 443 /// } 444 /// 445 /// #[test] 446 /// fn verify_app() { 447 /// cmd().debug_assert(); 448 /// } 449 /// 450 /// fn main() { 451 /// let m = cmd().get_matches_from(vec!["foo", "-b"]); 452 /// println!("{}", m.get_flag("bar")); 453 /// } 454 /// ``` 455 pub fn debug_assert(mut self) { 456 self.build(); 457 } 458 459 /// Custom error message for post-parsing validation 460 /// 461 /// # Examples 462 /// 463 /// ```rust 464 /// # use clap::{Command, error::ErrorKind}; 465 /// let mut cmd = Command::new("myprog"); 466 /// let err = cmd.error(ErrorKind::InvalidValue, "Some failure case"); 467 /// ``` 468 pub fn error(&mut self, kind: ErrorKind, message: impl std::fmt::Display) -> Error { 469 Error::raw(kind, message).format(self) 470 } 471 472 /// Parse [`env::args_os`], exiting on failure. 473 /// 474 /// # Panics 475 /// 476 /// If contradictory arguments or settings exist. 477 /// 478 /// # Examples 479 /// 480 /// ```no_run 481 /// # use clap::{Command, Arg}; 482 /// let matches = Command::new("myprog") 483 /// // Args and options go here... 484 /// .get_matches(); 485 /// ``` 486 /// [`env::args_os`]: std::env::args_os() 487 /// [`Command::try_get_matches_from_mut`]: Command::try_get_matches_from_mut() 488 #[inline] 489 pub fn get_matches(self) -> ArgMatches { 490 self.get_matches_from(env::args_os()) 491 } 492 493 /// Parse [`env::args_os`], exiting on failure. 494 /// 495 /// Like [`Command::get_matches`] but doesn't consume the `Command`. 496 /// 497 /// # Panics 498 /// 499 /// If contradictory arguments or settings exist. 500 /// 501 /// # Examples 502 /// 503 /// ```no_run 504 /// # use clap::{Command, Arg}; 505 /// let mut cmd = Command::new("myprog") 506 /// // Args and options go here... 507 /// ; 508 /// let matches = cmd.get_matches_mut(); 509 /// ``` 510 /// [`env::args_os`]: std::env::args_os() 511 /// [`Command::get_matches`]: Command::get_matches() 512 pub fn get_matches_mut(&mut self) -> ArgMatches { 513 self.try_get_matches_from_mut(&mut env::args_os()) 514 .unwrap_or_else(|e| e.exit()) 515 } 516 517 /// Parse [`env::args_os`], returning a [`clap::Result`] on failure. 518 /// 519 /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are 520 /// used. It will return a [`clap::Error`], where the [`kind`] is a 521 /// [`ErrorKind::DisplayHelp`] or [`ErrorKind::DisplayVersion`] respectively. You must call 522 /// [`Error::exit`] or perform a [`std::process::exit`]. 523 /// 524 /// # Panics 525 /// 526 /// If contradictory arguments or settings exist. 527 /// 528 /// # Examples 529 /// 530 /// ```no_run 531 /// # use clap::{Command, Arg}; 532 /// let matches = Command::new("myprog") 533 /// // Args and options go here... 534 /// .try_get_matches() 535 /// .unwrap_or_else(|e| e.exit()); 536 /// ``` 537 /// [`env::args_os`]: std::env::args_os() 538 /// [`Error::exit`]: crate::Error::exit() 539 /// [`std::process::exit`]: std::process::exit() 540 /// [`clap::Result`]: Result 541 /// [`clap::Error`]: crate::Error 542 /// [`kind`]: crate::Error 543 /// [`ErrorKind::DisplayHelp`]: crate::error::ErrorKind::DisplayHelp 544 /// [`ErrorKind::DisplayVersion`]: crate::error::ErrorKind::DisplayVersion 545 #[inline] 546 pub fn try_get_matches(self) -> ClapResult<ArgMatches> { 547 // Start the parsing 548 self.try_get_matches_from(env::args_os()) 549 } 550 551 /// Parse the specified arguments, exiting on failure. 552 /// 553 /// **NOTE:** The first argument will be parsed as the binary name unless 554 /// [`Command::no_binary_name`] is used. 555 /// 556 /// # Panics 557 /// 558 /// If contradictory arguments or settings exist. 559 /// 560 /// # Examples 561 /// 562 /// ```no_run 563 /// # use clap::{Command, Arg}; 564 /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; 565 /// 566 /// let matches = Command::new("myprog") 567 /// // Args and options go here... 568 /// .get_matches_from(arg_vec); 569 /// ``` 570 /// [`Command::get_matches`]: Command::get_matches() 571 /// [`clap::Result`]: Result 572 /// [`Vec`]: std::vec::Vec 573 pub fn get_matches_from<I, T>(mut self, itr: I) -> ArgMatches 574 where 575 I: IntoIterator<Item = T>, 576 T: Into<OsString> + Clone, 577 { 578 self.try_get_matches_from_mut(itr).unwrap_or_else(|e| { 579 drop(self); 580 e.exit() 581 }) 582 } 583 584 /// Parse the specified arguments, returning a [`clap::Result`] on failure. 585 /// 586 /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are 587 /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`] 588 /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or 589 /// perform a [`std::process::exit`] yourself. 590 /// 591 /// **NOTE:** The first argument will be parsed as the binary name unless 592 /// [`Command::no_binary_name`] is used. 593 /// 594 /// # Panics 595 /// 596 /// If contradictory arguments or settings exist. 597 /// 598 /// # Examples 599 /// 600 /// ```no_run 601 /// # use clap::{Command, Arg}; 602 /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; 603 /// 604 /// let matches = Command::new("myprog") 605 /// // Args and options go here... 606 /// .try_get_matches_from(arg_vec) 607 /// .unwrap_or_else(|e| e.exit()); 608 /// ``` 609 /// [`Command::get_matches_from`]: Command::get_matches_from() 610 /// [`Command::try_get_matches`]: Command::try_get_matches() 611 /// [`Error::exit`]: crate::Error::exit() 612 /// [`std::process::exit`]: std::process::exit() 613 /// [`clap::Error`]: crate::Error 614 /// [`Error::exit`]: crate::Error::exit() 615 /// [`kind`]: crate::Error 616 /// [`ErrorKind::DisplayHelp`]: crate::error::ErrorKind::DisplayHelp 617 /// [`ErrorKind::DisplayVersion`]: crate::error::ErrorKind::DisplayVersion 618 /// [`clap::Result`]: Result 619 pub fn try_get_matches_from<I, T>(mut self, itr: I) -> ClapResult<ArgMatches> 620 where 621 I: IntoIterator<Item = T>, 622 T: Into<OsString> + Clone, 623 { 624 self.try_get_matches_from_mut(itr) 625 } 626 627 /// Parse the specified arguments, returning a [`clap::Result`] on failure. 628 /// 629 /// Like [`Command::try_get_matches_from`] but doesn't consume the `Command`. 630 /// 631 /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are 632 /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`] 633 /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or 634 /// perform a [`std::process::exit`] yourself. 635 /// 636 /// **NOTE:** The first argument will be parsed as the binary name unless 637 /// [`Command::no_binary_name`] is used. 638 /// 639 /// # Panics 640 /// 641 /// If contradictory arguments or settings exist. 642 /// 643 /// # Examples 644 /// 645 /// ```no_run 646 /// # use clap::{Command, Arg}; 647 /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; 648 /// 649 /// let mut cmd = Command::new("myprog"); 650 /// // Args and options go here... 651 /// let matches = cmd.try_get_matches_from_mut(arg_vec) 652 /// .unwrap_or_else(|e| e.exit()); 653 /// ``` 654 /// [`Command::try_get_matches_from`]: Command::try_get_matches_from() 655 /// [`clap::Result`]: Result 656 /// [`clap::Error`]: crate::Error 657 /// [`kind`]: crate::Error 658 pub fn try_get_matches_from_mut<I, T>(&mut self, itr: I) -> ClapResult<ArgMatches> 659 where 660 I: IntoIterator<Item = T>, 661 T: Into<OsString> + Clone, 662 { 663 let mut raw_args = clap_lex::RawArgs::new(itr.into_iter()); 664 let mut cursor = raw_args.cursor(); 665 666 if self.settings.is_set(AppSettings::Multicall) { 667 if let Some(argv0) = raw_args.next_os(&mut cursor) { 668 let argv0 = Path::new(&argv0); 669 if let Some(command) = argv0.file_stem().and_then(|f| f.to_str()) { 670 // Stop borrowing command so we can get another mut ref to it. 671 let command = command.to_owned(); 672 debug!( 673 "Command::try_get_matches_from_mut: Parsed command {} from argv", 674 command 675 ); 676 677 debug!("Command::try_get_matches_from_mut: Reinserting command into arguments so subcommand parser matches it"); 678 raw_args.insert(&cursor, [&command]); 679 debug!("Command::try_get_matches_from_mut: Clearing name and bin_name so that displayed command name starts with applet name"); 680 self.name = "".into(); 681 self.bin_name = None; 682 return self._do_parse(&mut raw_args, cursor); 683 } 684 } 685 }; 686 687 // Get the name of the program (argument 1 of env::args()) and determine the 688 // actual file 689 // that was used to execute the program. This is because a program called 690 // ./target/release/my_prog -a 691 // will have two arguments, './target/release/my_prog', '-a' but we don't want 692 // to display 693 // the full path when displaying help messages and such 694 if !self.settings.is_set(AppSettings::NoBinaryName) { 695 if let Some(name) = raw_args.next_os(&mut cursor) { 696 let p = Path::new(name); 697 698 if let Some(f) = p.file_name() { 699 if let Some(s) = f.to_str() { 700 if self.bin_name.is_none() { 701 self.bin_name = Some(s.to_owned()); 702 } 703 } 704 } 705 } 706 } 707 708 self._do_parse(&mut raw_args, cursor) 709 } 710 711 /// Prints the short help message (`-h`) to [`io::stdout()`]. 712 /// 713 /// See also [`Command::print_long_help`]. 714 /// 715 /// # Examples 716 /// 717 /// ```rust 718 /// # use clap::Command; 719 /// let mut cmd = Command::new("myprog"); 720 /// cmd.print_help(); 721 /// ``` 722 /// [`io::stdout()`]: std::io::stdout() 723 pub fn print_help(&mut self) -> io::Result<()> { 724 self._build_self(false); 725 let color = self.color_help(); 726 727 let mut styled = StyledStr::new(); 728 let usage = Usage::new(self); 729 write_help(&mut styled, self, &usage, false); 730 731 let c = Colorizer::new(Stream::Stdout, color).with_content(styled); 732 c.print() 733 } 734 735 /// Prints the long help message (`--help`) to [`io::stdout()`]. 736 /// 737 /// See also [`Command::print_help`]. 738 /// 739 /// # Examples 740 /// 741 /// ```rust 742 /// # use clap::Command; 743 /// let mut cmd = Command::new("myprog"); 744 /// cmd.print_long_help(); 745 /// ``` 746 /// [`io::stdout()`]: std::io::stdout() 747 /// [`BufWriter`]: std::io::BufWriter 748 /// [`-h` (short)]: Arg::help() 749 /// [`--help` (long)]: Arg::long_help() 750 pub fn print_long_help(&mut self) -> io::Result<()> { 751 self._build_self(false); 752 let color = self.color_help(); 753 754 let mut styled = StyledStr::new(); 755 let usage = Usage::new(self); 756 write_help(&mut styled, self, &usage, true); 757 758 let c = Colorizer::new(Stream::Stdout, color).with_content(styled); 759 c.print() 760 } 761 762 /// Render the short help message (`-h`) to a [`StyledStr`] 763 /// 764 /// See also [`Command::render_long_help`]. 765 /// 766 /// # Examples 767 /// 768 /// ```rust 769 /// # use clap::Command; 770 /// use std::io; 771 /// let mut cmd = Command::new("myprog"); 772 /// let mut out = io::stdout(); 773 /// let help = cmd.render_help(); 774 /// println!("{}", help); 775 /// ``` 776 /// [`io::Write`]: std::io::Write 777 /// [`-h` (short)]: Arg::help() 778 /// [`--help` (long)]: Arg::long_help() 779 pub fn render_help(&mut self) -> StyledStr { 780 self._build_self(false); 781 782 let mut styled = StyledStr::new(); 783 let usage = Usage::new(self); 784 write_help(&mut styled, self, &usage, false); 785 styled 786 } 787 788 /// Render the long help message (`--help`) to a [`StyledStr`]. 789 /// 790 /// See also [`Command::render_help`]. 791 /// 792 /// # Examples 793 /// 794 /// ```rust 795 /// # use clap::Command; 796 /// use std::io; 797 /// let mut cmd = Command::new("myprog"); 798 /// let mut out = io::stdout(); 799 /// let help = cmd.render_long_help(); 800 /// println!("{}", help); 801 /// ``` 802 /// [`io::Write`]: std::io::Write 803 /// [`-h` (short)]: Arg::help() 804 /// [`--help` (long)]: Arg::long_help() 805 pub fn render_long_help(&mut self) -> StyledStr { 806 self._build_self(false); 807 808 let mut styled = StyledStr::new(); 809 let usage = Usage::new(self); 810 write_help(&mut styled, self, &usage, true); 811 styled 812 } 813 814 #[doc(hidden)] 815 #[cfg_attr( 816 feature = "deprecated", 817 deprecated(since = "4.0.0", note = "Replaced with `Command::render_help`") 818 )] 819 pub fn write_help<W: io::Write>(&mut self, w: &mut W) -> io::Result<()> { 820 self._build_self(false); 821 822 let mut styled = StyledStr::new(); 823 let usage = Usage::new(self); 824 write_help(&mut styled, self, &usage, false); 825 ok!(write!(w, "{styled}")); 826 w.flush() 827 } 828 829 #[doc(hidden)] 830 #[cfg_attr( 831 feature = "deprecated", 832 deprecated(since = "4.0.0", note = "Replaced with `Command::render_long_help`") 833 )] 834 pub fn write_long_help<W: io::Write>(&mut self, w: &mut W) -> io::Result<()> { 835 self._build_self(false); 836 837 let mut styled = StyledStr::new(); 838 let usage = Usage::new(self); 839 write_help(&mut styled, self, &usage, true); 840 ok!(write!(w, "{styled}")); 841 w.flush() 842 } 843 844 /// Version message rendered as if the user ran `-V`. 845 /// 846 /// See also [`Command::render_long_version`]. 847 /// 848 /// ### Coloring 849 /// 850 /// This function does not try to color the message nor it inserts any [ANSI escape codes]. 851 /// 852 /// ### Examples 853 /// 854 /// ```rust 855 /// # use clap::Command; 856 /// use std::io; 857 /// let cmd = Command::new("myprog"); 858 /// println!("{}", cmd.render_version()); 859 /// ``` 860 /// [`io::Write`]: std::io::Write 861 /// [`-V` (short)]: Command::version() 862 /// [`--version` (long)]: Command::long_version() 863 /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code 864 pub fn render_version(&self) -> String { 865 self._render_version(false) 866 } 867 868 /// Version message rendered as if the user ran `--version`. 869 /// 870 /// See also [`Command::render_version`]. 871 /// 872 /// ### Coloring 873 /// 874 /// This function does not try to color the message nor it inserts any [ANSI escape codes]. 875 /// 876 /// ### Examples 877 /// 878 /// ```rust 879 /// # use clap::Command; 880 /// use std::io; 881 /// let cmd = Command::new("myprog"); 882 /// println!("{}", cmd.render_long_version()); 883 /// ``` 884 /// [`io::Write`]: std::io::Write 885 /// [`-V` (short)]: Command::version() 886 /// [`--version` (long)]: Command::long_version() 887 /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code 888 pub fn render_long_version(&self) -> String { 889 self._render_version(true) 890 } 891 892 /// Usage statement 893 /// 894 /// ### Examples 895 /// 896 /// ```rust 897 /// # use clap::Command; 898 /// use std::io; 899 /// let mut cmd = Command::new("myprog"); 900 /// println!("{}", cmd.render_usage()); 901 /// ``` 902 pub fn render_usage(&mut self) -> StyledStr { 903 self.render_usage_().unwrap_or_default() 904 } 905 906 pub(crate) fn render_usage_(&mut self) -> Option<StyledStr> { 907 // If there are global arguments, or settings we need to propagate them down to subcommands 908 // before parsing incase we run into a subcommand 909 self._build_self(false); 910 911 Usage::new(self).create_usage_with_title(&[]) 912 } 913} 914 915/// # Application-wide Settings 916/// 917/// These settings will apply to the top-level command and all subcommands, by default. Some 918/// settings can be overridden in subcommands. 919impl Command { 920 /// Specifies that the parser should not assume the first argument passed is the binary name. 921 /// 922 /// This is normally the case when using a "daemon" style mode. For shells / REPLs, see 923 /// [`Command::multicall`][Command::multicall]. 924 /// 925 /// # Examples 926 /// 927 /// ```rust 928 /// # use clap::{Command, arg}; 929 /// let m = Command::new("myprog") 930 /// .no_binary_name(true) 931 /// .arg(arg!(<cmd> ... "commands to run")) 932 /// .get_matches_from(vec!["command", "set"]); 933 /// 934 /// let cmds: Vec<_> = m.get_many::<String>("cmd").unwrap().collect(); 935 /// assert_eq!(cmds, ["command", "set"]); 936 /// ``` 937 /// [`try_get_matches_from_mut`]: crate::Command::try_get_matches_from_mut() 938 #[inline] 939 pub fn no_binary_name(self, yes: bool) -> Self { 940 if yes { 941 self.global_setting(AppSettings::NoBinaryName) 942 } else { 943 self.unset_global_setting(AppSettings::NoBinaryName) 944 } 945 } 946 947 /// Try not to fail on parse errors, like missing option values. 948 /// 949 /// **NOTE:** This choice is propagated to all child subcommands. 950 /// 951 /// # Examples 952 /// 953 /// ```rust 954 /// # use clap::{Command, arg}; 955 /// let cmd = Command::new("cmd") 956 /// .ignore_errors(true) 957 /// .arg(arg!(-c --config <FILE> "Sets a custom config file")) 958 /// .arg(arg!(-x --stuff <FILE> "Sets a custom stuff file")) 959 /// .arg(arg!(f: -f "Flag")); 960 /// 961 /// let r = cmd.try_get_matches_from(vec!["cmd", "-c", "file", "-f", "-x"]); 962 /// 963 /// assert!(r.is_ok(), "unexpected error: {:?}", r); 964 /// let m = r.unwrap(); 965 /// assert_eq!(m.get_one::<String>("config").unwrap(), "file"); 966 /// assert!(m.get_flag("f")); 967 /// assert_eq!(m.get_one::<String>("stuff"), None); 968 /// ``` 969 #[inline] 970 pub fn ignore_errors(self, yes: bool) -> Self { 971 if yes { 972 self.global_setting(AppSettings::IgnoreErrors) 973 } else { 974 self.unset_global_setting(AppSettings::IgnoreErrors) 975 } 976 } 977 978 /// Replace prior occurrences of arguments rather than error 979 /// 980 /// For any argument that would conflict with itself by default (e.g. 981 /// [`ArgAction::Set`][ArgAction::Set], it will now override itself. 982 /// 983 /// This is the equivalent to saying the `foo` arg using [`Arg::overrides_with("foo")`] for all 984 /// defined arguments. 985 /// 986 /// **NOTE:** This choice is propagated to all child subcommands. 987 /// 988 /// [`Arg::overrides_with("foo")`]: crate::Arg::overrides_with() 989 #[inline] 990 pub fn args_override_self(self, yes: bool) -> Self { 991 if yes { 992 self.global_setting(AppSettings::AllArgsOverrideSelf) 993 } else { 994 self.unset_global_setting(AppSettings::AllArgsOverrideSelf) 995 } 996 } 997 998 /// Disables the automatic delimiting of values after `--` or when [`Command::trailing_var_arg`] 999 /// was used. 1000 /// 1001 /// **NOTE:** The same thing can be done manually by setting the final positional argument to 1002 /// [`Arg::value_delimiter(None)`]. Using this setting is safer, because it's easier to locate 1003 /// when making changes. 1004 /// 1005 /// **NOTE:** This choice is propagated to all child subcommands. 1006 /// 1007 /// # Examples 1008 /// 1009 /// ```no_run 1010 /// # use clap::{Command, Arg}; 1011 /// Command::new("myprog") 1012 /// .dont_delimit_trailing_values(true) 1013 /// .get_matches(); 1014 /// ``` 1015 /// 1016 /// [`Arg::value_delimiter(None)`]: crate::Arg::value_delimiter() 1017 #[inline] 1018 pub fn dont_delimit_trailing_values(self, yes: bool) -> Self { 1019 if yes { 1020 self.global_setting(AppSettings::DontDelimitTrailingValues) 1021 } else { 1022 self.unset_global_setting(AppSettings::DontDelimitTrailingValues) 1023 } 1024 } 1025 1026 /// Sets when to color output. 1027 /// 1028 /// **NOTE:** This choice is propagated to all child subcommands. 1029 /// 1030 /// **NOTE:** Default behaviour is [`ColorChoice::Auto`]. 1031 /// 1032 /// # Examples 1033 /// 1034 /// ```no_run 1035 /// # use clap::{Command, ColorChoice}; 1036 /// Command::new("myprog") 1037 /// .color(ColorChoice::Never) 1038 /// .get_matches(); 1039 /// ``` 1040 /// [`ColorChoice::Auto`]: crate::ColorChoice::Auto 1041 #[cfg(feature = "color")] 1042 #[inline] 1043 #[must_use] 1044 pub fn color(self, color: ColorChoice) -> Self { 1045 let cmd = self 1046 .unset_global_setting(AppSettings::ColorAuto) 1047 .unset_global_setting(AppSettings::ColorAlways) 1048 .unset_global_setting(AppSettings::ColorNever); 1049 match color { 1050 ColorChoice::Auto => cmd.global_setting(AppSettings::ColorAuto), 1051 ColorChoice::Always => cmd.global_setting(AppSettings::ColorAlways), 1052 ColorChoice::Never => cmd.global_setting(AppSettings::ColorNever), 1053 } 1054 } 1055 1056 /// Sets the terminal width at which to wrap help messages. 1057 /// 1058 /// Using `0` will ignore terminal widths and use source formatting. 1059 /// 1060 /// Defaults to current terminal width when `wrap_help` feature flag is enabled. If current 1061 /// width cannot be determined, the default is 100. 1062 /// 1063 /// **NOTE:** This setting applies globally and *not* on a per-command basis. 1064 /// 1065 /// **NOTE:** This requires the [`wrap_help` feature][crate::_features] 1066 /// 1067 /// # Examples 1068 /// 1069 /// ```no_run 1070 /// # use clap::Command; 1071 /// Command::new("myprog") 1072 /// .term_width(80) 1073 /// # ; 1074 /// ``` 1075 #[inline] 1076 #[must_use] 1077 #[cfg(any(not(feature = "unstable-v5"), feature = "wrap_help"))] 1078 pub fn term_width(mut self, width: usize) -> Self { 1079 self.term_w = Some(width); 1080 self 1081 } 1082 1083 /// Limit the line length for wrapping help when using the current terminal's width. 1084 /// 1085 /// This only applies when [`term_width`][Command::term_width] is unset so that the current 1086 /// terminal's width will be used. See [`Command::term_width`] for more details. 1087 /// 1088 /// Using `0` will ignore terminal widths and use source formatting (default). 1089 /// 1090 /// **NOTE:** This setting applies globally and *not* on a per-command basis. 1091 /// 1092 /// **NOTE:** This requires the [`wrap_help` feature][crate::_features] 1093 /// 1094 /// # Examples 1095 /// 1096 /// ```no_run 1097 /// # use clap::Command; 1098 /// Command::new("myprog") 1099 /// .max_term_width(100) 1100 /// # ; 1101 /// ``` 1102 #[inline] 1103 #[must_use] 1104 #[cfg(any(not(feature = "unstable-v5"), feature = "wrap_help"))] 1105 pub fn max_term_width(mut self, w: usize) -> Self { 1106 self.max_w = Some(w); 1107 self 1108 } 1109 1110 /// Disables `-V` and `--version` flag. 1111 /// 1112 /// # Examples 1113 /// 1114 /// ```rust 1115 /// # use clap::{Command, error::ErrorKind}; 1116 /// let res = Command::new("myprog") 1117 /// .disable_version_flag(true) 1118 /// .try_get_matches_from(vec![ 1119 /// "myprog", "-V" 1120 /// ]); 1121 /// assert!(res.is_err()); 1122 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); 1123 /// ``` 1124 #[inline] 1125 pub fn disable_version_flag(self, yes: bool) -> Self { 1126 if yes { 1127 self.global_setting(AppSettings::DisableVersionFlag) 1128 } else { 1129 self.unset_global_setting(AppSettings::DisableVersionFlag) 1130 } 1131 } 1132 1133 /// Specifies to use the version of the current command for all [`subcommands`]. 1134 /// 1135 /// Defaults to `false`; subcommands have independent version strings from their parents. 1136 /// 1137 /// **NOTE:** This choice is propagated to all child subcommands. 1138 /// 1139 /// # Examples 1140 /// 1141 /// ```no_run 1142 /// # use clap::{Command, Arg}; 1143 /// Command::new("myprog") 1144 /// .version("v1.1") 1145 /// .propagate_version(true) 1146 /// .subcommand(Command::new("test")) 1147 /// .get_matches(); 1148 /// // running `$ myprog test --version` will display 1149 /// // "myprog-test v1.1" 1150 /// ``` 1151 /// 1152 /// [`subcommands`]: crate::Command::subcommand() 1153 #[inline] 1154 pub fn propagate_version(self, yes: bool) -> Self { 1155 if yes { 1156 self.global_setting(AppSettings::PropagateVersion) 1157 } else { 1158 self.unset_global_setting(AppSettings::PropagateVersion) 1159 } 1160 } 1161 1162 /// Places the help string for all arguments and subcommands on the line after them. 1163 /// 1164 /// **NOTE:** This choice is propagated to all child subcommands. 1165 /// 1166 /// # Examples 1167 /// 1168 /// ```no_run 1169 /// # use clap::{Command, Arg}; 1170 /// Command::new("myprog") 1171 /// .next_line_help(true) 1172 /// .get_matches(); 1173 /// ``` 1174 #[inline] 1175 pub fn next_line_help(self, yes: bool) -> Self { 1176 if yes { 1177 self.global_setting(AppSettings::NextLineHelp) 1178 } else { 1179 self.unset_global_setting(AppSettings::NextLineHelp) 1180 } 1181 } 1182 1183 /// Disables `-h` and `--help` flag. 1184 /// 1185 /// **NOTE:** This choice is propagated to all child subcommands. 1186 /// 1187 /// # Examples 1188 /// 1189 /// ```rust 1190 /// # use clap::{Command, error::ErrorKind}; 1191 /// let res = Command::new("myprog") 1192 /// .disable_help_flag(true) 1193 /// .try_get_matches_from(vec![ 1194 /// "myprog", "-h" 1195 /// ]); 1196 /// assert!(res.is_err()); 1197 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument); 1198 /// ``` 1199 #[inline] 1200 pub fn disable_help_flag(self, yes: bool) -> Self { 1201 if yes { 1202 self.global_setting(AppSettings::DisableHelpFlag) 1203 } else { 1204 self.unset_global_setting(AppSettings::DisableHelpFlag) 1205 } 1206 } 1207 1208 /// Disables the `help` [`subcommand`]. 1209 /// 1210 /// # Examples 1211 /// 1212 /// ```rust 1213 /// # use clap::{Command, error::ErrorKind}; 1214 /// let res = Command::new("myprog") 1215 /// .disable_help_subcommand(true) 1216 /// // Normally, creating a subcommand causes a `help` subcommand to automatically 1217 /// // be generated as well 1218 /// .subcommand(Command::new("test")) 1219 /// .try_get_matches_from(vec![ 1220 /// "myprog", "help" 1221 /// ]); 1222 /// assert!(res.is_err()); 1223 /// assert_eq!(res.unwrap_err().kind(), ErrorKind::InvalidSubcommand); 1224 /// ``` 1225 /// 1226 /// [`subcommand`]: crate::Command::subcommand() 1227 #[inline] 1228 pub fn disable_help_subcommand(self, yes: bool) -> Self { 1229 if yes { 1230 self.global_setting(AppSettings::DisableHelpSubcommand) 1231 } else { 1232 self.unset_global_setting(AppSettings::DisableHelpSubcommand) 1233 } 1234 } 1235 1236 /// Disables colorized help messages. 1237 /// 1238 /// **NOTE:** This choice is propagated to all child subcommands. 1239 /// 1240 /// # Examples 1241 /// 1242 /// ```no_run 1243 /// # use clap::Command; 1244 /// Command::new("myprog") 1245 /// .disable_colored_help(true) 1246 /// .get_matches(); 1247 /// ``` 1248 #[inline] 1249 pub fn disable_colored_help(self, yes: bool) -> Self { 1250 if yes { 1251 self.global_setting(AppSettings::DisableColoredHelp) 1252 } else { 1253 self.unset_global_setting(AppSettings::DisableColoredHelp) 1254 } 1255 } 1256 1257 /// Panic if help descriptions are omitted. 1258 /// 1259 /// **NOTE:** When deriving [`Parser`][crate::Parser], you could instead check this at 1260 /// compile-time with `#![deny(missing_docs)]` 1261 /// 1262 /// **NOTE:** This choice is propagated to all child subcommands. 1263 /// 1264 /// # Examples 1265 /// 1266 /// ```rust 1267 /// # use clap::{Command, Arg}; 1268 /// Command::new("myprog") 1269 /// .help_expected(true) 1270 /// .arg( 1271 /// Arg::new("foo").help("It does foo stuff") 1272 /// // As required via `help_expected`, a help message was supplied 1273 /// ) 1274 /// # .get_matches(); 1275 /// ``` 1276 /// 1277 /// # Panics 1278 /// 1279 /// ```rust,no_run 1280 /// # use clap::{Command, Arg}; 1281 /// Command::new("myapp") 1282 /// .help_expected(true) 1283 /// .arg( 1284 /// Arg::new("foo") 1285 /// // Someone forgot to put .about("...") here 1286 /// // Since the setting `help_expected` is activated, this will lead to 1287 /// // a panic (if you are in debug mode) 1288 /// ) 1289 /// # .get_matches(); 1290 ///``` 1291 #[inline] 1292 pub fn help_expected(self, yes: bool) -> Self { 1293 if yes { 1294 self.global_setting(AppSettings::HelpExpected) 1295 } else { 1296 self.unset_global_setting(AppSettings::HelpExpected) 1297 } 1298 } 1299 1300 #[doc(hidden)] 1301 #[cfg_attr( 1302 feature = "deprecated", 1303 deprecated(since = "4.0.0", note = "This is now the default") 1304 )] 1305 pub fn dont_collapse_args_in_usage(self, _yes: bool) -> Self { 1306 self 1307 } 1308 1309 /// Tells `clap` *not* to print possible values when displaying help information. 1310 /// 1311 /// This can be useful if there are many values, or they are explained elsewhere. 1312 /// 1313 /// To set this per argument, see 1314 /// [`Arg::hide_possible_values`][crate::Arg::hide_possible_values]. 1315 /// 1316 /// **NOTE:** This choice is propagated to all child subcommands. 1317 #[inline] 1318 pub fn hide_possible_values(self, yes: bool) -> Self { 1319 if yes { 1320 self.global_setting(AppSettings::HidePossibleValues) 1321 } else { 1322 self.unset_global_setting(AppSettings::HidePossibleValues) 1323 } 1324 } 1325 1326 /// Allow partial matches of long arguments or their [aliases]. 1327 /// 1328 /// For example, to match an argument named `--test`, one could use `--t`, `--te`, `--tes`, and 1329 /// `--test`. 1330 /// 1331 /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match 1332 /// `--te` to `--test` there could not also be another argument or alias `--temp` because both 1333 /// start with `--te` 1334 /// 1335 /// **NOTE:** This choice is propagated to all child subcommands. 1336 /// 1337 /// [aliases]: crate::Command::aliases() 1338 #[inline] 1339 pub fn infer_long_args(self, yes: bool) -> Self { 1340 if yes { 1341 self.global_setting(AppSettings::InferLongArgs) 1342 } else { 1343 self.unset_global_setting(AppSettings::InferLongArgs) 1344 } 1345 } 1346 1347 /// Allow partial matches of [subcommand] names and their [aliases]. 1348 /// 1349 /// For example, to match a subcommand named `test`, one could use `t`, `te`, `tes`, and 1350 /// `test`. 1351 /// 1352 /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match `te` 1353 /// to `test` there could not also be a subcommand or alias `temp` because both start with `te` 1354 /// 1355 /// **CAUTION:** This setting can interfere with [positional/free arguments], take care when 1356 /// designing CLIs which allow inferred subcommands and have potential positional/free 1357 /// arguments whose values could start with the same characters as subcommands. If this is the 1358 /// case, it's recommended to use settings such as [`Command::args_conflicts_with_subcommands`] in 1359 /// conjunction with this setting. 1360 /// 1361 /// **NOTE:** This choice is propagated to all child subcommands. 1362 /// 1363 /// # Examples 1364 /// 1365 /// ```no_run 1366 /// # use clap::{Command, Arg}; 1367 /// let m = Command::new("prog") 1368 /// .infer_subcommands(true) 1369 /// .subcommand(Command::new("test")) 1370 /// .get_matches_from(vec![ 1371 /// "prog", "te" 1372 /// ]); 1373 /// assert_eq!(m.subcommand_name(), Some("test")); 1374 /// ``` 1375 /// 1376 /// [subcommand]: crate::Command::subcommand() 1377 /// [positional/free arguments]: crate::Arg::index() 1378 /// [aliases]: crate::Command::aliases() 1379 #[inline] 1380 pub fn infer_subcommands(self, yes: bool) -> Self { 1381 if yes { 1382 self.global_setting(AppSettings::InferSubcommands) 1383 } else { 1384 self.unset_global_setting(AppSettings::InferSubcommands) 1385 } 1386 } 1387} 1388 1389/// # Command-specific Settings 1390/// 1391/// These apply only to the current command and are not inherited by subcommands. 1392impl Command { 1393 /// (Re)Sets the program's name. 1394 /// 1395 /// See [`Command::new`] for more details. 1396 /// 1397 /// # Examples 1398 /// 1399 /// ```ignore 1400 /// let cmd = clap::command!() 1401 /// .name("foo"); 1402 /// 1403 /// // continued logic goes here, such as `cmd.get_matches()` etc. 1404 /// ``` 1405 #[must_use] 1406 pub fn name(mut self, name: impl Into<Str>) -> Self { 1407 self.name = name.into(); 1408 self 1409 } 1410 1411 /// Overrides the runtime-determined name of the binary for help and error messages. 1412 /// 1413 /// This should only be used when absolutely necessary, such as when the binary name for your 1414 /// application is misleading, or perhaps *not* how the user should invoke your program. 1415 /// 1416 /// **Pro-tip:** When building things such as third party `cargo` 1417 /// subcommands, this setting **should** be used! 1418 /// 1419 /// **NOTE:** This *does not* change or set the name of the binary file on 1420 /// disk. It only changes what clap thinks the name is for the purposes of 1421 /// error or help messages. 1422 /// 1423 /// # Examples 1424 /// 1425 /// ```no_run 1426 /// # use clap::Command; 1427 /// Command::new("My Program") 1428 /// .bin_name("my_binary") 1429 /// # ; 1430 /// ``` 1431 #[must_use] 1432 pub fn bin_name(mut self, name: impl IntoResettable<String>) -> Self { 1433 self.bin_name = name.into_resettable().into_option(); 1434 self 1435 } 1436 1437 /// Overrides the runtime-determined display name of the program for help and error messages. 1438 /// 1439 /// # Examples 1440 /// 1441 /// ```no_run 1442 /// # use clap::Command; 1443 /// Command::new("My Program") 1444 /// .display_name("my_program") 1445 /// # ; 1446 /// ``` 1447 #[must_use] 1448 pub fn display_name(mut self, name: impl IntoResettable<String>) -> Self { 1449 self.display_name = name.into_resettable().into_option(); 1450 self 1451 } 1452 1453 /// Sets the author(s) for the help message. 1454 /// 1455 /// **Pro-tip:** Use `clap`s convenience macro [`crate_authors!`] to 1456 /// automatically set your application's author(s) to the same thing as your 1457 /// crate at compile time. 1458 /// 1459 /// **NOTE:** A custom [`help_template`][Command::help_template] is needed for author to show 1460 /// up. 1461 /// 1462 /// # Examples 1463 /// 1464 /// ```no_run 1465 /// # use clap::Command; 1466 /// Command::new("myprog") 1467 /// .author("Me, me@mymain.com") 1468 /// # ; 1469 /// ``` 1470 #[must_use] 1471 pub fn author(mut self, author: impl IntoResettable<Str>) -> Self { 1472 self.author = author.into_resettable().into_option(); 1473 self 1474 } 1475 1476 /// Sets the program's description for the short help (`-h`). 1477 /// 1478 /// If [`Command::long_about`] is not specified, this message will be displayed for `--help`. 1479 /// 1480 /// **NOTE:** Only `Command::about` (short format) is used in completion 1481 /// script generation in order to be concise. 1482 /// 1483 /// See also [`crate_description!`](crate::crate_description!). 1484 /// 1485 /// # Examples 1486 /// 1487 /// ```no_run 1488 /// # use clap::Command; 1489 /// Command::new("myprog") 1490 /// .about("Does really amazing things for great people") 1491 /// # ; 1492 /// ``` 1493 #[must_use] 1494 pub fn about(mut self, about: impl IntoResettable<StyledStr>) -> Self { 1495 self.about = about.into_resettable().into_option(); 1496 self 1497 } 1498 1499 /// Sets the program's description for the long help (`--help`). 1500 /// 1501 /// If [`Command::about`] is not specified, this message will be displayed for `-h`. 1502 /// 1503 /// **NOTE:** Only [`Command::about`] (short format) is used in completion 1504 /// script generation in order to be concise. 1505 /// 1506 /// # Examples 1507 /// 1508 /// ```no_run 1509 /// # use clap::Command; 1510 /// Command::new("myprog") 1511 /// .long_about( 1512 /// "Does really amazing things to great people. Now let's talk a little 1513 /// more in depth about how this subcommand really works. It may take about 1514 /// a few lines of text, but that's ok!") 1515 /// # ; 1516 /// ``` 1517 /// [`Command::about`]: Command::about() 1518 #[must_use] 1519 pub fn long_about(mut self, long_about: impl IntoResettable<StyledStr>) -> Self { 1520 self.long_about = long_about.into_resettable().into_option(); 1521 self 1522 } 1523 1524 /// Free-form help text for after auto-generated short help (`-h`). 1525 /// 1526 /// This is often used to describe how to use the arguments, caveats to be noted, or license 1527 /// and contact information. 1528 /// 1529 /// If [`Command::after_long_help`] is not specified, this message will be displayed for `--help`. 1530 /// 1531 /// # Examples 1532 /// 1533 /// ```no_run 1534 /// # use clap::Command; 1535 /// Command::new("myprog") 1536 /// .after_help("Does really amazing things for great people... but be careful with -R!") 1537 /// # ; 1538 /// ``` 1539 /// 1540 #[must_use] 1541 pub fn after_help(mut self, help: impl IntoResettable<StyledStr>) -> Self { 1542 self.after_help = help.into_resettable().into_option(); 1543 self 1544 } 1545 1546 /// Free-form help text for after auto-generated long help (`--help`). 1547 /// 1548 /// This is often used to describe how to use the arguments, caveats to be noted, or license 1549 /// and contact information. 1550 /// 1551 /// If [`Command::after_help`] is not specified, this message will be displayed for `-h`. 1552 /// 1553 /// # Examples 1554 /// 1555 /// ```no_run 1556 /// # use clap::Command; 1557 /// Command::new("myprog") 1558 /// .after_long_help("Does really amazing things to great people... but be careful with -R, \ 1559 /// like, for real, be careful with this!") 1560 /// # ; 1561 /// ``` 1562 #[must_use] 1563 pub fn after_long_help(mut self, help: impl IntoResettable<StyledStr>) -> Self { 1564 self.after_long_help = help.into_resettable().into_option(); 1565 self 1566 } 1567 1568 /// Free-form help text for before auto-generated short help (`-h`). 1569 /// 1570 /// This is often used for header, copyright, or license information. 1571 /// 1572 /// If [`Command::before_long_help`] is not specified, this message will be displayed for `--help`. 1573 /// 1574 /// # Examples 1575 /// 1576 /// ```no_run 1577 /// # use clap::Command; 1578 /// Command::new("myprog") 1579 /// .before_help("Some info I'd like to appear before the help info") 1580 /// # ; 1581 /// ``` 1582 #[must_use] 1583 pub fn before_help(mut self, help: impl IntoResettable<StyledStr>) -> Self { 1584 self.before_help = help.into_resettable().into_option(); 1585 self 1586 } 1587 1588 /// Free-form help text for before auto-generated long help (`--help`). 1589 /// 1590 /// This is often used for header, copyright, or license information. 1591 /// 1592 /// If [`Command::before_help`] is not specified, this message will be displayed for `-h`. 1593 /// 1594 /// # Examples 1595 /// 1596 /// ```no_run 1597 /// # use clap::Command; 1598 /// Command::new("myprog") 1599 /// .before_long_help("Some verbose and long info I'd like to appear before the help info") 1600 /// # ; 1601 /// ``` 1602 #[must_use] 1603 pub fn before_long_help(mut self, help: impl IntoResettable<StyledStr>) -> Self { 1604 self.before_long_help = help.into_resettable().into_option(); 1605 self 1606 } 1607 1608 /// Sets the version for the short version (`-V`) and help messages. 1609 /// 1610 /// If [`Command::long_version`] is not specified, this message will be displayed for `--version`. 1611 /// 1612 /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to 1613 /// automatically set your application's version to the same thing as your 1614 /// crate at compile time. 1615 /// 1616 /// # Examples 1617 /// 1618 /// ```no_run 1619 /// # use clap::Command; 1620 /// Command::new("myprog") 1621 /// .version("v0.1.24") 1622 /// # ; 1623 /// ``` 1624 #[must_use] 1625 pub fn version(mut self, ver: impl IntoResettable<Str>) -> Self { 1626 self.version = ver.into_resettable().into_option(); 1627 self 1628 } 1629 1630 /// Sets the version for the long version (`--version`) and help messages. 1631 /// 1632 /// If [`Command::version`] is not specified, this message will be displayed for `-V`. 1633 /// 1634 /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to 1635 /// automatically set your application's version to the same thing as your 1636 /// crate at compile time. 1637 /// 1638 /// # Examples 1639 /// 1640 /// ```no_run 1641 /// # use clap::Command; 1642 /// Command::new("myprog") 1643 /// .long_version( 1644 /// "v0.1.24 1645 /// commit: abcdef89726d 1646 /// revision: 123 1647 /// release: 2 1648 /// binary: myprog") 1649 /// # ; 1650 /// ``` 1651 #[must_use] 1652 pub fn long_version(mut self, ver: impl IntoResettable<Str>) -> Self { 1653 self.long_version = ver.into_resettable().into_option(); 1654 self 1655 } 1656 1657 /// Overrides the `clap` generated usage string for help and error messages. 1658 /// 1659 /// **NOTE:** Using this setting disables `clap`s "context-aware" usage 1660 /// strings. After this setting is set, this will be *the only* usage string 1661 /// displayed to the user! 1662 /// 1663 /// **NOTE:** Multiple usage lines may be present in the usage argument, but 1664 /// some rules need to be followed to ensure the usage lines are formatted 1665 /// correctly by the default help formatter: 1666 /// 1667 /// - Do not indent the first usage line. 1668 /// - Indent all subsequent usage lines with seven spaces. 1669 /// - The last line must not end with a newline. 1670 /// 1671 /// # Examples 1672 /// 1673 /// ```no_run 1674 /// # use clap::{Command, Arg}; 1675 /// Command::new("myprog") 1676 /// .override_usage("myapp [-clDas] <some_file>") 1677 /// # ; 1678 /// ``` 1679 /// 1680 /// Or for multiple usage lines: 1681 /// 1682 /// ```no_run 1683 /// # use clap::{Command, Arg}; 1684 /// Command::new("myprog") 1685 /// .override_usage( 1686 /// "myapp -X [-a] [-b] <file>\n \ 1687 /// myapp -Y [-c] <file1> <file2>\n \ 1688 /// myapp -Z [-d|-e]" 1689 /// ) 1690 /// # ; 1691 /// ``` 1692 /// 1693 /// [`ArgMatches::usage`]: ArgMatches::usage() 1694 #[must_use] 1695 pub fn override_usage(mut self, usage: impl IntoResettable<StyledStr>) -> Self { 1696 self.usage_str = usage.into_resettable().into_option(); 1697 self 1698 } 1699 1700 /// Overrides the `clap` generated help message (both `-h` and `--help`). 1701 /// 1702 /// This should only be used when the auto-generated message does not suffice. 1703 /// 1704 /// **NOTE:** This **only** replaces the help message for the current 1705 /// command, meaning if you are using subcommands, those help messages will 1706 /// still be auto-generated unless you specify a [`Command::override_help`] for 1707 /// them as well. 1708 /// 1709 /// # Examples 1710 /// 1711 /// ```no_run 1712 /// # use clap::{Command, Arg}; 1713 /// Command::new("myapp") 1714 /// .override_help("myapp v1.0\n\ 1715 /// Does awesome things\n\ 1716 /// (C) me@mail.com\n\n\ 1717 /// 1718 /// Usage: myapp <opts> <command>\n\n\ 1719 /// 1720 /// Options:\n\ 1721 /// -h, --help Display this message\n\ 1722 /// -V, --version Display version info\n\ 1723 /// -s <stuff> Do something with stuff\n\ 1724 /// -v Be verbose\n\n\ 1725 /// 1726 /// Commands:\n\ 1727 /// help Print this message\n\ 1728 /// work Do some work") 1729 /// # ; 1730 /// ``` 1731 #[must_use] 1732 pub fn override_help(mut self, help: impl IntoResettable<StyledStr>) -> Self { 1733 self.help_str = help.into_resettable().into_option(); 1734 self 1735 } 1736 1737 /// Sets the help template to be used, overriding the default format. 1738 /// 1739 /// **NOTE:** The template system is by design very simple. Therefore, the 1740 /// tags have to be written in the lowercase and without spacing. 1741 /// 1742 /// Tags are given inside curly brackets. 1743 /// 1744 /// Valid tags are: 1745 /// 1746 /// * `{name}` - Display name for the (sub-)command. 1747 /// * `{bin}` - Binary name.(deprecated) 1748 /// * `{version}` - Version number. 1749 /// * `{author}` - Author information. 1750 /// * `{author-with-newline}` - Author followed by `\n`. 1751 /// * `{author-section}` - Author preceded and followed by `\n`. 1752 /// * `{about}` - General description (from [`Command::about`] or 1753 /// [`Command::long_about`]). 1754 /// * `{about-with-newline}` - About followed by `\n`. 1755 /// * `{about-section}` - About preceded and followed by '\n'. 1756 /// * `{usage-heading}` - Automatically generated usage heading. 1757 /// * `{usage}` - Automatically generated or given usage string. 1758 /// * `{all-args}` - Help for all arguments (options, flags, positional 1759 /// arguments, and subcommands) including titles. 1760 /// * `{options}` - Help for options. 1761 /// * `{positionals}` - Help for positional arguments. 1762 /// * `{subcommands}` - Help for subcommands. 1763 /// * `{tab}` - Standard tab sized used within clap 1764 /// * `{after-help}` - Help from [`Command::after_help`] or [`Command::after_long_help`]. 1765 /// * `{before-help}` - Help from [`Command::before_help`] or [`Command::before_long_help`]. 1766 /// 1767 /// # Examples 1768 /// 1769 /// For a very brief help: 1770 /// 1771 /// ```no_run 1772 /// # use clap::Command; 1773 /// Command::new("myprog") 1774 /// .version("1.0") 1775 /// .help_template("{name} ({version}) - {usage}") 1776 /// # ; 1777 /// ``` 1778 /// 1779 /// For showing more application context: 1780 /// 1781 /// ```no_run 1782 /// # use clap::Command; 1783 /// Command::new("myprog") 1784 /// .version("1.0") 1785 /// .help_template("\ 1786 /// {before-help}{name} {version} 1787 /// {author-with-newline}{about-with-newline} 1788 /// {usage-heading} {usage} 1789 /// 1790 /// {all-args}{after-help} 1791 /// ") 1792 /// # ; 1793 /// ``` 1794 /// [`Command::about`]: Command::about() 1795 /// [`Command::long_about`]: Command::long_about() 1796 /// [`Command::after_help`]: Command::after_help() 1797 /// [`Command::after_long_help`]: Command::after_long_help() 1798 /// [`Command::before_help`]: Command::before_help() 1799 /// [`Command::before_long_help`]: Command::before_long_help() 1800 #[must_use] 1801 #[cfg(feature = "help")] 1802 pub fn help_template(mut self, s: impl IntoResettable<StyledStr>) -> Self { 1803 self.template = s.into_resettable().into_option(); 1804 self 1805 } 1806 1807 #[inline] 1808 #[must_use] 1809 pub(crate) fn setting<F>(mut self, setting: F) -> Self 1810 where 1811 F: Into<AppFlags>, 1812 { 1813 self.settings.insert(setting.into()); 1814 self 1815 } 1816 1817 #[inline] 1818 #[must_use] 1819 pub(crate) fn unset_setting<F>(mut self, setting: F) -> Self 1820 where 1821 F: Into<AppFlags>, 1822 { 1823 self.settings.remove(setting.into()); 1824 self 1825 } 1826 1827 #[inline] 1828 #[must_use] 1829 pub(crate) fn global_setting(mut self, setting: AppSettings) -> Self { 1830 self.settings.set(setting); 1831 self.g_settings.set(setting); 1832 self 1833 } 1834 1835 #[inline] 1836 #[must_use] 1837 pub(crate) fn unset_global_setting(mut self, setting: AppSettings) -> Self { 1838 self.settings.unset(setting); 1839 self.g_settings.unset(setting); 1840 self 1841 } 1842 1843 /// Set the default section heading for future args. 1844 /// 1845 /// This will be used for any arg that hasn't had [`Arg::help_heading`] called. 1846 /// 1847 /// This is useful if the default `Options` or `Arguments` headings are 1848 /// not specific enough for one's use case. 1849 /// 1850 /// For subcommands, see [`Command::subcommand_help_heading`] 1851 /// 1852 /// [`Command::arg`]: Command::arg() 1853 /// [`Arg::help_heading`]: crate::Arg::help_heading() 1854 #[inline] 1855 #[must_use] 1856 pub fn next_help_heading(mut self, heading: impl IntoResettable<Str>) -> Self { 1857 self.current_help_heading = heading.into_resettable().into_option(); 1858 self 1859 } 1860 1861 /// Change the starting value for assigning future display orders for ags. 1862 /// 1863 /// This will be used for any arg that hasn't had [`Arg::display_order`] called. 1864 #[inline] 1865 #[must_use] 1866 pub fn next_display_order(mut self, disp_ord: impl IntoResettable<usize>) -> Self { 1867 self.current_disp_ord = disp_ord.into_resettable().into_option(); 1868 self 1869 } 1870 1871 /// Replaces an argument or subcommand used on the CLI at runtime with other arguments or subcommands. 1872 /// 1873 /// **Note:** This is gated behind [`unstable-replace`](https://github.com/clap-rs/clap/issues/2836) 1874 /// 1875 /// When this method is used, `name` is removed from the CLI, and `target` 1876 /// is inserted in its place. Parsing continues as if the user typed 1877 /// `target` instead of `name`. 1878 /// 1879 /// This can be used to create "shortcuts" for subcommands, or if a 1880 /// particular argument has the semantic meaning of several other specific 1881 /// arguments and values. 1882 /// 1883 /// # Examples 1884 /// 1885 /// We'll start with the "subcommand short" example. In this example, let's 1886 /// assume we have a program with a subcommand `module` which can be invoked 1887 /// via `cmd module`. Now let's also assume `module` also has a subcommand 1888 /// called `install` which can be invoked `cmd module install`. If for some 1889 /// reason users needed to be able to reach `cmd module install` via the 1890 /// short-hand `cmd install`, we'd have several options. 1891 /// 1892 /// We *could* create another sibling subcommand to `module` called 1893 /// `install`, but then we would need to manage another subcommand and manually 1894 /// dispatch to `cmd module install` handling code. This is error prone and 1895 /// tedious. 1896 /// 1897 /// We could instead use [`Command::replace`] so that, when the user types `cmd 1898 /// install`, `clap` will replace `install` with `module install` which will 1899 /// end up getting parsed as if the user typed the entire incantation. 1900 /// 1901 /// ```rust 1902 /// # use clap::Command; 1903 /// let m = Command::new("cmd") 1904 /// .subcommand(Command::new("module") 1905 /// .subcommand(Command::new("install"))) 1906 /// .replace("install", &["module", "install"]) 1907 /// .get_matches_from(vec!["cmd", "install"]); 1908 /// 1909 /// assert!(m.subcommand_matches("module").is_some()); 1910 /// assert!(m.subcommand_matches("module").unwrap().subcommand_matches("install").is_some()); 1911 /// ``` 1912 /// 1913 /// Now let's show an argument example! 1914 /// 1915 /// Let's assume we have an application with two flags `--save-context` and 1916 /// `--save-runtime`. But often users end up needing to do *both* at the 1917 /// same time. We can add a third flag `--save-all` which semantically means 1918 /// the same thing as `cmd --save-context --save-runtime`. To implement that, 1919 /// we have several options. 1920 /// 1921 /// We could create this third argument and manually check if that argument 1922 /// and in our own consumer code handle the fact that both `--save-context` 1923 /// and `--save-runtime` *should* have been used. But again this is error 1924 /// prone and tedious. If we had code relying on checking `--save-context` 1925 /// and we forgot to update that code to *also* check `--save-all` it'd mean 1926 /// an error! 1927 /// 1928 /// Luckily we can use [`Command::replace`] so that when the user types 1929 /// `--save-all`, `clap` will replace that argument with `--save-context 1930 /// --save-runtime`, and parsing will continue like normal. Now all our code 1931 /// that was originally checking for things like `--save-context` doesn't 1932 /// need to change! 1933 /// 1934 /// ```rust 1935 /// # use clap::{Command, Arg, ArgAction}; 1936 /// let m = Command::new("cmd") 1937 /// .arg(Arg::new("save-context") 1938 /// .long("save-context") 1939 /// .action(ArgAction::SetTrue)) 1940 /// .arg(Arg::new("save-runtime") 1941 /// .long("save-runtime") 1942 /// .action(ArgAction::SetTrue)) 1943 /// .replace("--save-all", &["--save-context", "--save-runtime"]) 1944 /// .get_matches_from(vec!["cmd", "--save-all"]); 1945 /// 1946 /// assert!(m.get_flag("save-context")); 1947 /// assert!(m.get_flag("save-runtime")); 1948 /// ``` 1949 /// 1950 /// This can also be used with options, for example if our application with 1951 /// `--save-*` above also had a `--format=TYPE` option. Let's say it 1952 /// accepted `txt` or `json` values. However, when `--save-all` is used, 1953 /// only `--format=json` is allowed, or valid. We could change the example 1954 /// above to enforce this: 1955 /// 1956 /// ```rust 1957 /// # use clap::{Command, Arg, ArgAction}; 1958 /// let m = Command::new("cmd") 1959 /// .arg(Arg::new("save-context") 1960 /// .long("save-context") 1961 /// .action(ArgAction::SetTrue)) 1962 /// .arg(Arg::new("save-runtime") 1963 /// .long("save-runtime") 1964 /// .action(ArgAction::SetTrue)) 1965 /// .arg(Arg::new("format") 1966 /// .long("format") 1967 /// .action(ArgAction::Set) 1968 /// .value_parser(["txt", "json"])) 1969 /// .replace("--save-all", &["--save-context", "--save-runtime", "--format=json"]) 1970 /// .get_matches_from(vec!["cmd", "--save-all"]); 1971 /// 1972 /// assert!(m.get_flag("save-context")); 1973 /// assert!(m.get_flag("save-runtime")); 1974 /// assert_eq!(m.get_one::<String>("format").unwrap(), "json"); 1975 /// ``` 1976 /// 1977 /// [`Command::replace`]: Command::replace() 1978 #[inline] 1979 #[cfg(feature = "unstable-replace")] 1980 #[must_use] 1981 pub fn replace( 1982 mut self, 1983 name: impl Into<Str>, 1984 target: impl IntoIterator<Item = impl Into<Str>>, 1985 ) -> Self { 1986 self.replacers 1987 .insert(name.into(), target.into_iter().map(Into::into).collect()); 1988 self 1989 } 1990 1991 /// Exit gracefully if no arguments are present (e.g. `$ myprog`). 1992 /// 1993 /// **NOTE:** [`subcommands`] count as arguments 1994 /// 1995 /// # Examples 1996 /// 1997 /// ```rust 1998 /// # use clap::{Command}; 1999 /// Command::new("myprog") 2000 /// .arg_required_else_help(true); 2001 /// ``` 2002 /// 2003 /// [`subcommands`]: crate::Command::subcommand() 2004 /// [`Arg::default_value`]: crate::Arg::default_value() 2005 #[inline] 2006 pub fn arg_required_else_help(self, yes: bool) -> Self { 2007 if yes { 2008 self.setting(AppSettings::ArgRequiredElseHelp) 2009 } else { 2010 self.unset_setting(AppSettings::ArgRequiredElseHelp) 2011 } 2012 } 2013 2014 #[doc(hidden)] 2015 #[cfg_attr( 2016 feature = "deprecated", 2017 deprecated(since = "4.0.0", note = "Replaced with `Arg::allow_hyphen_values`") 2018 )] 2019 pub fn allow_hyphen_values(self, yes: bool) -> Self { 2020 if yes { 2021 self.setting(AppSettings::AllowHyphenValues) 2022 } else { 2023 self.unset_setting(AppSettings::AllowHyphenValues) 2024 } 2025 } 2026 2027 #[doc(hidden)] 2028 #[cfg_attr( 2029 feature = "deprecated", 2030 deprecated(since = "4.0.0", note = "Replaced with `Arg::allow_negative_numbers`") 2031 )] 2032 pub fn allow_negative_numbers(self, yes: bool) -> Self { 2033 if yes { 2034 self.setting(AppSettings::AllowNegativeNumbers) 2035 } else { 2036 self.unset_setting(AppSettings::AllowNegativeNumbers) 2037 } 2038 } 2039 2040 #[doc(hidden)] 2041 #[cfg_attr( 2042 feature = "deprecated", 2043 deprecated(since = "4.0.0", note = "Replaced with `Arg::trailing_var_arg`") 2044 )] 2045 pub fn trailing_var_arg(self, yes: bool) -> Self { 2046 if yes { 2047 self.setting(AppSettings::TrailingVarArg) 2048 } else { 2049 self.unset_setting(AppSettings::TrailingVarArg) 2050 } 2051 } 2052 2053 /// Allows one to implement two styles of CLIs where positionals can be used out of order. 2054 /// 2055 /// The first example is a CLI where the second to last positional argument is optional, but 2056 /// the final positional argument is required. Such as `$ prog [optional] <required>` where one 2057 /// of the two following usages is allowed: 2058 /// 2059 /// * `$ prog [optional] <required>` 2060 /// * `$ prog <required>` 2061 /// 2062 /// This would otherwise not be allowed. This is useful when `[optional]` has a default value. 2063 /// 2064 /// **Note:** when using this style of "missing positionals" the final positional *must* be 2065 /// [required] if `--` will not be used to skip to the final positional argument. 2066 /// 2067 /// **Note:** This style also only allows a single positional argument to be "skipped" without 2068 /// the use of `--`. To skip more than one, see the second example. 2069 /// 2070 /// The second example is when one wants to skip multiple optional positional arguments, and use 2071 /// of the `--` operator is OK (but not required if all arguments will be specified anyways). 2072 /// 2073 /// For example, imagine a CLI which has three positional arguments `[foo] [bar] [baz]...` where 2074 /// `baz` accepts multiple values (similar to man `ARGS...` style training arguments). 2075 /// 2076 /// With this setting the following invocations are posisble: 2077 /// 2078 /// * `$ prog foo bar baz1 baz2 baz3` 2079 /// * `$ prog foo -- baz1 baz2 baz3` 2080 /// * `$ prog -- baz1 baz2 baz3` 2081 /// 2082 /// # Examples 2083 /// 2084 /// Style number one from above: 2085 /// 2086 /// ```rust 2087 /// # use clap::{Command, Arg}; 2088 /// // Assume there is an external subcommand named "subcmd" 2089 /// let m = Command::new("myprog") 2090 /// .allow_missing_positional(true) 2091 /// .arg(Arg::new("arg1")) 2092 /// .arg(Arg::new("arg2") 2093 /// .required(true)) 2094 /// .get_matches_from(vec![ 2095 /// "prog", "other" 2096 /// ]); 2097 /// 2098 /// assert_eq!(m.get_one::<String>("arg1"), None); 2099 /// assert_eq!(m.get_one::<String>("arg2").unwrap(), "other"); 2100 /// ``` 2101 /// 2102 /// Now the same example, but using a default value for the first optional positional argument 2103 /// 2104 /// ```rust 2105 /// # use clap::{Command, Arg}; 2106 /// // Assume there is an external subcommand named "subcmd" 2107 /// let m = Command::new("myprog") 2108 /// .allow_missing_positional(true) 2109 /// .arg(Arg::new("arg1") 2110 /// .default_value("something")) 2111 /// .arg(Arg::new("arg2") 2112 /// .required(true)) 2113 /// .get_matches_from(vec![ 2114 /// "prog", "other" 2115 /// ]); 2116 /// 2117 /// assert_eq!(m.get_one::<String>("arg1").unwrap(), "something"); 2118 /// assert_eq!(m.get_one::<String>("arg2").unwrap(), "other"); 2119 /// ``` 2120 /// 2121 /// Style number two from above: 2122 /// 2123 /// ```rust 2124 /// # use clap::{Command, Arg, ArgAction}; 2125 /// // Assume there is an external subcommand named "subcmd" 2126 /// let m = Command::new("myprog") 2127 /// .allow_missing_positional(true) 2128 /// .arg(Arg::new("foo")) 2129 /// .arg(Arg::new("bar")) 2130 /// .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..)) 2131 /// .get_matches_from(vec![ 2132 /// "prog", "foo", "bar", "baz1", "baz2", "baz3" 2133 /// ]); 2134 /// 2135 /// assert_eq!(m.get_one::<String>("foo").unwrap(), "foo"); 2136 /// assert_eq!(m.get_one::<String>("bar").unwrap(), "bar"); 2137 /// assert_eq!(m.get_many::<String>("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]); 2138 /// ``` 2139 /// 2140 /// Now nofice if we don't specify `foo` or `baz` but use the `--` operator. 2141 /// 2142 /// ```rust 2143 /// # use clap::{Command, Arg, ArgAction}; 2144 /// // Assume there is an external subcommand named "subcmd" 2145 /// let m = Command::new("myprog") 2146 /// .allow_missing_positional(true) 2147 /// .arg(Arg::new("foo")) 2148 /// .arg(Arg::new("bar")) 2149 /// .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..)) 2150 /// .get_matches_from(vec![ 2151 /// "prog", "--", "baz1", "baz2", "baz3" 2152 /// ]); 2153 /// 2154 /// assert_eq!(m.get_one::<String>("foo"), None); 2155 /// assert_eq!(m.get_one::<String>("bar"), None); 2156 /// assert_eq!(m.get_many::<String>("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]); 2157 /// ``` 2158 /// 2159 /// [required]: crate::Arg::required() 2160 #[inline] 2161 pub fn allow_missing_positional(self, yes: bool) -> Self { 2162 if yes { 2163 self.setting(AppSettings::AllowMissingPositional) 2164 } else { 2165 self.unset_setting(AppSettings::AllowMissingPositional) 2166 } 2167 } 2168} 2169 2170/// # Subcommand-specific Settings 2171impl Command { 2172 /// Sets the short version of the subcommand flag without the preceding `-`. 2173 /// 2174 /// Allows the subcommand to be used as if it were an [`Arg::short`]. 2175 /// 2176 /// # Examples 2177 /// 2178 /// ``` 2179 /// # use clap::{Command, Arg, ArgAction}; 2180 /// let matches = Command::new("pacman") 2181 /// .subcommand( 2182 /// Command::new("sync").short_flag('S').arg( 2183 /// Arg::new("search") 2184 /// .short('s') 2185 /// .long("search") 2186 /// .action(ArgAction::SetTrue) 2187 /// .help("search remote repositories for matching strings"), 2188 /// ), 2189 /// ) 2190 /// .get_matches_from(vec!["pacman", "-Ss"]); 2191 /// 2192 /// assert_eq!(matches.subcommand_name().unwrap(), "sync"); 2193 /// let sync_matches = matches.subcommand_matches("sync").unwrap(); 2194 /// assert!(sync_matches.get_flag("search")); 2195 /// ``` 2196 /// [`Arg::short`]: Arg::short() 2197 #[must_use] 2198 pub fn short_flag(mut self, short: impl IntoResettable<char>) -> Self { 2199 self.short_flag = short.into_resettable().into_option(); 2200 self 2201 } 2202 2203 /// Sets the long version of the subcommand flag without the preceding `--`. 2204 /// 2205 /// Allows the subcommand to be used as if it were an [`Arg::long`]. 2206 /// 2207 /// **NOTE:** Any leading `-` characters will be stripped. 2208 /// 2209 /// # Examples 2210 /// 2211 /// To set `long_flag` use a word containing valid UTF-8 codepoints. If you supply a double leading 2212 /// `--` such as `--sync` they will be stripped. Hyphens in the middle of the word; however, 2213 /// will *not* be stripped (i.e. `sync-file` is allowed). 2214 /// 2215 /// ``` 2216 /// # use clap::{Command, Arg, ArgAction}; 2217 /// let matches = Command::new("pacman") 2218 /// .subcommand( 2219 /// Command::new("sync").long_flag("sync").arg( 2220 /// Arg::new("search") 2221 /// .short('s') 2222 /// .long("search") 2223 /// .action(ArgAction::SetTrue) 2224 /// .help("search remote repositories for matching strings"), 2225 /// ), 2226 /// ) 2227 /// .get_matches_from(vec!["pacman", "--sync", "--search"]); 2228 /// 2229 /// assert_eq!(matches.subcommand_name().unwrap(), "sync"); 2230 /// let sync_matches = matches.subcommand_matches("sync").unwrap(); 2231 /// assert!(sync_matches.get_flag("search")); 2232 /// ``` 2233 /// 2234 /// [`Arg::long`]: Arg::long() 2235 #[must_use] 2236 pub fn long_flag(mut self, long: impl Into<Str>) -> Self { 2237 self.long_flag = Some(long.into()); 2238 self 2239 } 2240 2241 /// Sets a hidden alias to this subcommand. 2242 /// 2243 /// This allows the subcommand to be accessed via *either* the original name, or this given 2244 /// alias. This is more efficient and easier than creating multiple hidden subcommands as one 2245 /// only needs to check for the existence of this command, and not all aliased variants. 2246 /// 2247 /// **NOTE:** Aliases defined with this method are *hidden* from the help 2248 /// message. If you're looking for aliases that will be displayed in the help 2249 /// message, see [`Command::visible_alias`]. 2250 /// 2251 /// **NOTE:** When using aliases and checking for the existence of a 2252 /// particular subcommand within an [`ArgMatches`] struct, one only needs to 2253 /// search for the original name and not all aliases. 2254 /// 2255 /// # Examples 2256 /// 2257 /// ```rust 2258 /// # use clap::{Command, Arg, }; 2259 /// let m = Command::new("myprog") 2260 /// .subcommand(Command::new("test") 2261 /// .alias("do-stuff")) 2262 /// .get_matches_from(vec!["myprog", "do-stuff"]); 2263 /// assert_eq!(m.subcommand_name(), Some("test")); 2264 /// ``` 2265 /// [`Command::visible_alias`]: Command::visible_alias() 2266 #[must_use] 2267 pub fn alias(mut self, name: impl IntoResettable<Str>) -> Self { 2268 if let Some(name) = name.into_resettable().into_option() { 2269 self.aliases.push((name, false)); 2270 } else { 2271 self.aliases.clear(); 2272 } 2273 self 2274 } 2275 2276 /// Add an alias, which functions as "hidden" short flag subcommand 2277 /// 2278 /// This will automatically dispatch as if this subcommand was used. This is more efficient, 2279 /// and easier than creating multiple hidden subcommands as one only needs to check for the 2280 /// existence of this command, and not all variants. 2281 /// 2282 /// # Examples 2283 /// 2284 /// ```no_run 2285 /// # use clap::{Command, Arg, }; 2286 /// let m = Command::new("myprog") 2287 /// .subcommand(Command::new("test").short_flag('t') 2288 /// .short_flag_alias('d')) 2289 /// .get_matches_from(vec!["myprog", "-d"]); 2290 /// assert_eq!(m.subcommand_name(), Some("test")); 2291 /// ``` 2292 #[must_use] 2293 pub fn short_flag_alias(mut self, name: impl IntoResettable<char>) -> Self { 2294 if let Some(name) = name.into_resettable().into_option() { 2295 debug_assert!(name != '-', "short alias name cannot be `-`"); 2296 self.short_flag_aliases.push((name, false)); 2297 } else { 2298 self.short_flag_aliases.clear(); 2299 } 2300 self 2301 } 2302 2303 /// Add an alias, which functions as a "hidden" long flag subcommand. 2304 /// 2305 /// This will automatically dispatch as if this subcommand was used. This is more efficient, 2306 /// and easier than creating multiple hidden subcommands as one only needs to check for the 2307 /// existence of this command, and not all variants. 2308 /// 2309 /// # Examples 2310 /// 2311 /// ```no_run 2312 /// # use clap::{Command, Arg, }; 2313 /// let m = Command::new("myprog") 2314 /// .subcommand(Command::new("test").long_flag("test") 2315 /// .long_flag_alias("testing")) 2316 /// .get_matches_from(vec!["myprog", "--testing"]); 2317 /// assert_eq!(m.subcommand_name(), Some("test")); 2318 /// ``` 2319 #[must_use] 2320 pub fn long_flag_alias(mut self, name: impl IntoResettable<Str>) -> Self { 2321 if let Some(name) = name.into_resettable().into_option() { 2322 self.long_flag_aliases.push((name, false)); 2323 } else { 2324 self.long_flag_aliases.clear(); 2325 } 2326 self 2327 } 2328 2329 /// Sets multiple hidden aliases to this subcommand. 2330 /// 2331 /// This allows the subcommand to be accessed via *either* the original name or any of the 2332 /// given aliases. This is more efficient, and easier than creating multiple hidden subcommands 2333 /// as one only needs to check for the existence of this command and not all aliased variants. 2334 /// 2335 /// **NOTE:** Aliases defined with this method are *hidden* from the help 2336 /// message. If looking for aliases that will be displayed in the help 2337 /// message, see [`Command::visible_aliases`]. 2338 /// 2339 /// **NOTE:** When using aliases and checking for the existence of a 2340 /// particular subcommand within an [`ArgMatches`] struct, one only needs to 2341 /// search for the original name and not all aliases. 2342 /// 2343 /// # Examples 2344 /// 2345 /// ```rust 2346 /// # use clap::{Command, Arg}; 2347 /// let m = Command::new("myprog") 2348 /// .subcommand(Command::new("test") 2349 /// .aliases(["do-stuff", "do-tests", "tests"])) 2350 /// .arg(Arg::new("input") 2351 /// .help("the file to add") 2352 /// .required(false)) 2353 /// .get_matches_from(vec!["myprog", "do-tests"]); 2354 /// assert_eq!(m.subcommand_name(), Some("test")); 2355 /// ``` 2356 /// [`Command::visible_aliases`]: Command::visible_aliases() 2357 #[must_use] 2358 pub fn aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self { 2359 self.aliases 2360 .extend(names.into_iter().map(|n| (n.into(), false))); 2361 self 2362 } 2363 2364 /// Add aliases, which function as "hidden" short flag subcommands. 2365 /// 2366 /// These will automatically dispatch as if this subcommand was used. This is more efficient, 2367 /// and easier than creating multiple hidden subcommands as one only needs to check for the 2368 /// existence of this command, and not all variants. 2369 /// 2370 /// # Examples 2371 /// 2372 /// ```rust 2373 /// # use clap::{Command, Arg, }; 2374 /// let m = Command::new("myprog") 2375 /// .subcommand(Command::new("test").short_flag('t') 2376 /// .short_flag_aliases(['a', 'b', 'c'])) 2377 /// .arg(Arg::new("input") 2378 /// .help("the file to add") 2379 /// .required(false)) 2380 /// .get_matches_from(vec!["myprog", "-a"]); 2381 /// assert_eq!(m.subcommand_name(), Some("test")); 2382 /// ``` 2383 #[must_use] 2384 pub fn short_flag_aliases(mut self, names: impl IntoIterator<Item = char>) -> Self { 2385 for s in names { 2386 debug_assert!(s != '-', "short alias name cannot be `-`"); 2387 self.short_flag_aliases.push((s, false)); 2388 } 2389 self 2390 } 2391 2392 /// Add aliases, which function as "hidden" long flag subcommands. 2393 /// 2394 /// These will automatically dispatch as if this subcommand was used. This is more efficient, 2395 /// and easier than creating multiple hidden subcommands as one only needs to check for the 2396 /// existence of this command, and not all variants. 2397 /// 2398 /// # Examples 2399 /// 2400 /// ```rust 2401 /// # use clap::{Command, Arg, }; 2402 /// let m = Command::new("myprog") 2403 /// .subcommand(Command::new("test").long_flag("test") 2404 /// .long_flag_aliases(["testing", "testall", "test_all"])) 2405 /// .arg(Arg::new("input") 2406 /// .help("the file to add") 2407 /// .required(false)) 2408 /// .get_matches_from(vec!["myprog", "--testing"]); 2409 /// assert_eq!(m.subcommand_name(), Some("test")); 2410 /// ``` 2411 #[must_use] 2412 pub fn long_flag_aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self { 2413 for s in names { 2414 self = self.long_flag_alias(s) 2415 } 2416 self 2417 } 2418 2419 /// Sets a visible alias to this subcommand. 2420 /// 2421 /// This allows the subcommand to be accessed via *either* the 2422 /// original name or the given alias. This is more efficient and easier 2423 /// than creating hidden subcommands as one only needs to check for 2424 /// the existence of this command and not all aliased variants. 2425 /// 2426 /// **NOTE:** The alias defined with this method is *visible* from the help 2427 /// message and displayed as if it were just another regular subcommand. If 2428 /// looking for an alias that will not be displayed in the help message, see 2429 /// [`Command::alias`]. 2430 /// 2431 /// **NOTE:** When using aliases and checking for the existence of a 2432 /// particular subcommand within an [`ArgMatches`] struct, one only needs to 2433 /// search for the original name and not all aliases. 2434 /// 2435 /// # Examples 2436 /// 2437 /// ```no_run 2438 /// # use clap::{Command, Arg}; 2439 /// let m = Command::new("myprog") 2440 /// .subcommand(Command::new("test") 2441 /// .visible_alias("do-stuff")) 2442 /// .get_matches_from(vec!["myprog", "do-stuff"]); 2443 /// assert_eq!(m.subcommand_name(), Some("test")); 2444 /// ``` 2445 /// [`Command::alias`]: Command::alias() 2446 #[must_use] 2447 pub fn visible_alias(mut self, name: impl IntoResettable<Str>) -> Self { 2448 if let Some(name) = name.into_resettable().into_option() { 2449 self.aliases.push((name, true)); 2450 } else { 2451 self.aliases.clear(); 2452 } 2453 self 2454 } 2455 2456 /// Add an alias, which functions as "visible" short flag subcommand 2457 /// 2458 /// This will automatically dispatch as if this subcommand was used. This is more efficient, 2459 /// and easier than creating multiple hidden subcommands as one only needs to check for the 2460 /// existence of this command, and not all variants. 2461 /// 2462 /// See also [`Command::short_flag_alias`]. 2463 /// 2464 /// # Examples 2465 /// 2466 /// ```no_run 2467 /// # use clap::{Command, Arg, }; 2468 /// let m = Command::new("myprog") 2469 /// .subcommand(Command::new("test").short_flag('t') 2470 /// .visible_short_flag_alias('d')) 2471 /// .get_matches_from(vec!["myprog", "-d"]); 2472 /// assert_eq!(m.subcommand_name(), Some("test")); 2473 /// ``` 2474 /// [`Command::short_flag_alias`]: Command::short_flag_alias() 2475 #[must_use] 2476 pub fn visible_short_flag_alias(mut self, name: impl IntoResettable<char>) -> Self { 2477 if let Some(name) = name.into_resettable().into_option() { 2478 debug_assert!(name != '-', "short alias name cannot be `-`"); 2479 self.short_flag_aliases.push((name, true)); 2480 } else { 2481 self.short_flag_aliases.clear(); 2482 } 2483 self 2484 } 2485 2486 /// Add an alias, which functions as a "visible" long flag subcommand. 2487 /// 2488 /// This will automatically dispatch as if this subcommand was used. This is more efficient, 2489 /// and easier than creating multiple hidden subcommands as one only needs to check for the 2490 /// existence of this command, and not all variants. 2491 /// 2492 /// See also [`Command::long_flag_alias`]. 2493 /// 2494 /// # Examples 2495 /// 2496 /// ```no_run 2497 /// # use clap::{Command, Arg, }; 2498 /// let m = Command::new("myprog") 2499 /// .subcommand(Command::new("test").long_flag("test") 2500 /// .visible_long_flag_alias("testing")) 2501 /// .get_matches_from(vec!["myprog", "--testing"]); 2502 /// assert_eq!(m.subcommand_name(), Some("test")); 2503 /// ``` 2504 /// [`Command::long_flag_alias`]: Command::long_flag_alias() 2505 #[must_use] 2506 pub fn visible_long_flag_alias(mut self, name: impl IntoResettable<Str>) -> Self { 2507 if let Some(name) = name.into_resettable().into_option() { 2508 self.long_flag_aliases.push((name, true)); 2509 } else { 2510 self.long_flag_aliases.clear(); 2511 } 2512 self 2513 } 2514 2515 /// Sets multiple visible aliases to this subcommand. 2516 /// 2517 /// This allows the subcommand to be accessed via *either* the 2518 /// original name or any of the given aliases. This is more efficient and easier 2519 /// than creating multiple hidden subcommands as one only needs to check for 2520 /// the existence of this command and not all aliased variants. 2521 /// 2522 /// **NOTE:** The alias defined with this method is *visible* from the help 2523 /// message and displayed as if it were just another regular subcommand. If 2524 /// looking for an alias that will not be displayed in the help message, see 2525 /// [`Command::alias`]. 2526 /// 2527 /// **NOTE:** When using aliases, and checking for the existence of a 2528 /// particular subcommand within an [`ArgMatches`] struct, one only needs to 2529 /// search for the original name and not all aliases. 2530 /// 2531 /// # Examples 2532 /// 2533 /// ```no_run 2534 /// # use clap::{Command, Arg, }; 2535 /// let m = Command::new("myprog") 2536 /// .subcommand(Command::new("test") 2537 /// .visible_aliases(["do-stuff", "tests"])) 2538 /// .get_matches_from(vec!["myprog", "do-stuff"]); 2539 /// assert_eq!(m.subcommand_name(), Some("test")); 2540 /// ``` 2541 /// [`Command::alias`]: Command::alias() 2542 #[must_use] 2543 pub fn visible_aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self { 2544 self.aliases 2545 .extend(names.into_iter().map(|n| (n.into(), true))); 2546 self 2547 } 2548 2549 /// Add aliases, which function as *visible* short flag subcommands. 2550 /// 2551 /// See [`Command::short_flag_aliases`]. 2552 /// 2553 /// # Examples 2554 /// 2555 /// ```no_run 2556 /// # use clap::{Command, Arg, }; 2557 /// let m = Command::new("myprog") 2558 /// .subcommand(Command::new("test").short_flag('b') 2559 /// .visible_short_flag_aliases(['t'])) 2560 /// .get_matches_from(vec!["myprog", "-t"]); 2561 /// assert_eq!(m.subcommand_name(), Some("test")); 2562 /// ``` 2563 /// [`Command::short_flag_aliases`]: Command::short_flag_aliases() 2564 #[must_use] 2565 pub fn visible_short_flag_aliases(mut self, names: impl IntoIterator<Item = char>) -> Self { 2566 for s in names { 2567 debug_assert!(s != '-', "short alias name cannot be `-`"); 2568 self.short_flag_aliases.push((s, true)); 2569 } 2570 self 2571 } 2572 2573 /// Add aliases, which function as *visible* long flag subcommands. 2574 /// 2575 /// See [`Command::long_flag_aliases`]. 2576 /// 2577 /// # Examples 2578 /// 2579 /// ```no_run 2580 /// # use clap::{Command, Arg, }; 2581 /// let m = Command::new("myprog") 2582 /// .subcommand(Command::new("test").long_flag("test") 2583 /// .visible_long_flag_aliases(["testing", "testall", "test_all"])) 2584 /// .get_matches_from(vec!["myprog", "--testing"]); 2585 /// assert_eq!(m.subcommand_name(), Some("test")); 2586 /// ``` 2587 /// [`Command::long_flag_aliases`]: Command::long_flag_aliases() 2588 #[must_use] 2589 pub fn visible_long_flag_aliases( 2590 mut self, 2591 names: impl IntoIterator<Item = impl Into<Str>>, 2592 ) -> Self { 2593 for s in names { 2594 self = self.visible_long_flag_alias(s); 2595 } 2596 self 2597 } 2598 2599 /// Set the placement of this subcommand within the help. 2600 /// 2601 /// Subcommands with a lower value will be displayed first in the help message. Subcommands 2602 /// with duplicate display orders will be displayed in order they are defined. 2603 /// 2604 /// This is helpful when one would like to emphasize frequently used subcommands, or prioritize 2605 /// those towards the top of the list. 2606 /// 2607 /// **NOTE:** The default is 999 for all subcommands. 2608 /// 2609 /// # Examples 2610 /// 2611 #[cfg_attr(not(feature = "help"), doc = " ```ignore")] 2612 #[cfg_attr(feature = "help", doc = " ```")] 2613 /// # use clap::{Command, }; 2614 /// let m = Command::new("cust-ord") 2615 /// .subcommand(Command::new("alpha") // typically subcommands are grouped 2616 /// // alphabetically by name. Subcommands 2617 /// // without a display_order have a value of 2618 /// // 999 and are displayed alphabetically with 2619 /// // all other 999 subcommands 2620 /// .about("Some help and text")) 2621 /// .subcommand(Command::new("beta") 2622 /// .display_order(1) // In order to force this subcommand to appear *first* 2623 /// // all we have to do is give it a value lower than 999. 2624 /// // Any other subcommands with a value of 1 will be displayed 2625 /// // alphabetically with this one...then 2 values, then 3, etc. 2626 /// .about("I should be first!")) 2627 /// .get_matches_from(vec![ 2628 /// "cust-ord", "--help" 2629 /// ]); 2630 /// ``` 2631 /// 2632 /// The above example displays the following help message 2633 /// 2634 /// ```text 2635 /// cust-ord 2636 /// 2637 /// Usage: cust-ord [OPTIONS] 2638 /// 2639 /// Commands: 2640 /// beta I should be first! 2641 /// alpha Some help and text 2642 /// 2643 /// Options: 2644 /// -h, --help Print help 2645 /// -V, --version Print version 2646 /// ``` 2647 #[inline] 2648 #[must_use] 2649 pub fn display_order(mut self, ord: impl IntoResettable<usize>) -> Self { 2650 self.disp_ord = ord.into_resettable().into_option(); 2651 self 2652 } 2653 2654 /// Specifies that this [`subcommand`] should be hidden from help messages 2655 /// 2656 /// # Examples 2657 /// 2658 /// ```rust 2659 /// # use clap::{Command, Arg}; 2660 /// Command::new("myprog") 2661 /// .subcommand( 2662 /// Command::new("test").hide(true) 2663 /// ) 2664 /// # ; 2665 /// ``` 2666 /// 2667 /// [`subcommand`]: crate::Command::subcommand() 2668 #[inline] 2669 pub fn hide(self, yes: bool) -> Self { 2670 if yes { 2671 self.setting(AppSettings::Hidden) 2672 } else { 2673 self.unset_setting(AppSettings::Hidden) 2674 } 2675 } 2676 2677 /// If no [`subcommand`] is present at runtime, error and exit gracefully. 2678 /// 2679 /// # Examples 2680 /// 2681 /// ```rust 2682 /// # use clap::{Command, error::ErrorKind}; 2683 /// let err = Command::new("myprog") 2684 /// .subcommand_required(true) 2685 /// .subcommand(Command::new("test")) 2686 /// .try_get_matches_from(vec![ 2687 /// "myprog", 2688 /// ]); 2689 /// assert!(err.is_err()); 2690 /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingSubcommand); 2691 /// # ; 2692 /// ``` 2693 /// 2694 /// [`subcommand`]: crate::Command::subcommand() 2695 pub fn subcommand_required(self, yes: bool) -> Self { 2696 if yes { 2697 self.setting(AppSettings::SubcommandRequired) 2698 } else { 2699 self.unset_setting(AppSettings::SubcommandRequired) 2700 } 2701 } 2702 2703 /// Assume unexpected positional arguments are a [`subcommand`]. 2704 /// 2705 /// Arguments will be stored in the `""` argument in the [`ArgMatches`] 2706 /// 2707 /// **NOTE:** Use this setting with caution, 2708 /// as a truly unexpected argument (i.e. one that is *NOT* an external subcommand) 2709 /// will **not** cause an error and instead be treated as a potential subcommand. 2710 /// One should check for such cases manually and inform the user appropriately. 2711 /// 2712 /// **NOTE:** A built-in subcommand will be parsed as an external subcommand when escaped with 2713 /// `--`. 2714 /// 2715 /// # Examples 2716 /// 2717 /// ```rust 2718 /// # use std::ffi::OsString; 2719 /// # use clap::Command; 2720 /// // Assume there is an external subcommand named "subcmd" 2721 /// let m = Command::new("myprog") 2722 /// .allow_external_subcommands(true) 2723 /// .get_matches_from(vec![ 2724 /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" 2725 /// ]); 2726 /// 2727 /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty 2728 /// // string argument name 2729 /// match m.subcommand() { 2730 /// Some((external, ext_m)) => { 2731 /// let ext_args: Vec<_> = ext_m.get_many::<OsString>("").unwrap().collect(); 2732 /// assert_eq!(external, "subcmd"); 2733 /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); 2734 /// }, 2735 /// _ => {}, 2736 /// } 2737 /// ``` 2738 /// 2739 /// [`subcommand`]: crate::Command::subcommand() 2740 /// [`ArgMatches`]: crate::ArgMatches 2741 /// [`ErrorKind::UnknownArgument`]: crate::error::ErrorKind::UnknownArgument 2742 pub fn allow_external_subcommands(self, yes: bool) -> Self { 2743 if yes { 2744 self.setting(AppSettings::AllowExternalSubcommands) 2745 } else { 2746 self.unset_setting(AppSettings::AllowExternalSubcommands) 2747 } 2748 } 2749 2750 /// Specifies how to parse external subcommand arguments. 2751 /// 2752 /// The default parser is for `OsString`. This can be used to switch it to `String` or another 2753 /// type. 2754 /// 2755 /// **NOTE:** Setting this requires [`Command::allow_external_subcommands`] 2756 /// 2757 /// # Examples 2758 /// 2759 #[cfg_attr(not(unix), doc = " ```ignore")] 2760 #[cfg_attr(unix, doc = " ```")] 2761 /// # use std::ffi::OsString; 2762 /// # use clap::Command; 2763 /// # use clap::value_parser; 2764 /// // Assume there is an external subcommand named "subcmd" 2765 /// let m = Command::new("myprog") 2766 /// .allow_external_subcommands(true) 2767 /// .get_matches_from(vec![ 2768 /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" 2769 /// ]); 2770 /// 2771 /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty 2772 /// // string argument name 2773 /// match m.subcommand() { 2774 /// Some((external, ext_m)) => { 2775 /// let ext_args: Vec<_> = ext_m.get_many::<OsString>("").unwrap().collect(); 2776 /// assert_eq!(external, "subcmd"); 2777 /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); 2778 /// }, 2779 /// _ => {}, 2780 /// } 2781 /// ``` 2782 /// 2783 /// ``` 2784 /// # use clap::Command; 2785 /// # use clap::value_parser; 2786 /// // Assume there is an external subcommand named "subcmd" 2787 /// let m = Command::new("myprog") 2788 /// .external_subcommand_value_parser(value_parser!(String)) 2789 /// .get_matches_from(vec![ 2790 /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" 2791 /// ]); 2792 /// 2793 /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty 2794 /// // string argument name 2795 /// match m.subcommand() { 2796 /// Some((external, ext_m)) => { 2797 /// let ext_args: Vec<_> = ext_m.get_many::<String>("").unwrap().collect(); 2798 /// assert_eq!(external, "subcmd"); 2799 /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); 2800 /// }, 2801 /// _ => {}, 2802 /// } 2803 /// ``` 2804 /// 2805 /// [`subcommands`]: crate::Command::subcommand() 2806 pub fn external_subcommand_value_parser( 2807 mut self, 2808 parser: impl IntoResettable<super::ValueParser>, 2809 ) -> Self { 2810 self.external_value_parser = parser.into_resettable().into_option(); 2811 self 2812 } 2813 2814 /// Specifies that use of an argument prevents the use of [`subcommands`]. 2815 /// 2816 /// By default `clap` allows arguments between subcommands such 2817 /// as `<cmd> [cmd_args] <subcmd> [subcmd_args] <subsubcmd> [subsubcmd_args]`. 2818 /// 2819 /// This setting disables that functionality and says that arguments can 2820 /// only follow the *final* subcommand. For instance using this setting 2821 /// makes only the following invocations possible: 2822 /// 2823 /// * `<cmd> <subcmd> <subsubcmd> [subsubcmd_args]` 2824 /// * `<cmd> <subcmd> [subcmd_args]` 2825 /// * `<cmd> [cmd_args]` 2826 /// 2827 /// # Examples 2828 /// 2829 /// ```rust 2830 /// # use clap::Command; 2831 /// Command::new("myprog") 2832 /// .args_conflicts_with_subcommands(true); 2833 /// ``` 2834 /// 2835 /// [`subcommands`]: crate::Command::subcommand() 2836 pub fn args_conflicts_with_subcommands(self, yes: bool) -> Self { 2837 if yes { 2838 self.setting(AppSettings::ArgsNegateSubcommands) 2839 } else { 2840 self.unset_setting(AppSettings::ArgsNegateSubcommands) 2841 } 2842 } 2843 2844 /// Prevent subcommands from being consumed as an arguments value. 2845 /// 2846 /// By default, if an option taking multiple values is followed by a subcommand, the 2847 /// subcommand will be parsed as another value. 2848 /// 2849 /// ```text 2850 /// cmd --foo val1 val2 subcommand 2851 /// --------- ---------- 2852 /// values another value 2853 /// ``` 2854 /// 2855 /// This setting instructs the parser to stop when encountering a subcommand instead of 2856 /// greedily consuming arguments. 2857 /// 2858 /// ```text 2859 /// cmd --foo val1 val2 subcommand 2860 /// --------- ---------- 2861 /// values subcommand 2862 /// ``` 2863 /// 2864 /// # Examples 2865 /// 2866 /// ```rust 2867 /// # use clap::{Command, Arg, ArgAction}; 2868 /// let cmd = Command::new("cmd").subcommand(Command::new("sub")).arg( 2869 /// Arg::new("arg") 2870 /// .long("arg") 2871 /// .num_args(1..) 2872 /// .action(ArgAction::Set), 2873 /// ); 2874 /// 2875 /// let matches = cmd 2876 /// .clone() 2877 /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"]) 2878 /// .unwrap(); 2879 /// assert_eq!( 2880 /// matches.get_many::<String>("arg").unwrap().collect::<Vec<_>>(), 2881 /// &["1", "2", "3", "sub"] 2882 /// ); 2883 /// assert!(matches.subcommand_matches("sub").is_none()); 2884 /// 2885 /// let matches = cmd 2886 /// .subcommand_precedence_over_arg(true) 2887 /// .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"]) 2888 /// .unwrap(); 2889 /// assert_eq!( 2890 /// matches.get_many::<String>("arg").unwrap().collect::<Vec<_>>(), 2891 /// &["1", "2", "3"] 2892 /// ); 2893 /// assert!(matches.subcommand_matches("sub").is_some()); 2894 /// ``` 2895 pub fn subcommand_precedence_over_arg(self, yes: bool) -> Self { 2896 if yes { 2897 self.setting(AppSettings::SubcommandPrecedenceOverArg) 2898 } else { 2899 self.unset_setting(AppSettings::SubcommandPrecedenceOverArg) 2900 } 2901 } 2902 2903 /// Allows [`subcommands`] to override all requirements of the parent command. 2904 /// 2905 /// For example, if you had a subcommand or top level application with a required argument 2906 /// that is only required as long as there is no subcommand present, 2907 /// using this setting would allow you to set those arguments to [`Arg::required(true)`] 2908 /// and yet receive no error so long as the user uses a valid subcommand instead. 2909 /// 2910 /// **NOTE:** This defaults to false (using subcommand does *not* negate requirements) 2911 /// 2912 /// # Examples 2913 /// 2914 /// This first example shows that it is an error to not use a required argument 2915 /// 2916 /// ```rust 2917 /// # use clap::{Command, Arg, error::ErrorKind}; 2918 /// let err = Command::new("myprog") 2919 /// .subcommand_negates_reqs(true) 2920 /// .arg(Arg::new("opt").required(true)) 2921 /// .subcommand(Command::new("test")) 2922 /// .try_get_matches_from(vec![ 2923 /// "myprog" 2924 /// ]); 2925 /// assert!(err.is_err()); 2926 /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingRequiredArgument); 2927 /// # ; 2928 /// ``` 2929 /// 2930 /// This next example shows that it is no longer error to not use a required argument if a 2931 /// valid subcommand is used. 2932 /// 2933 /// ```rust 2934 /// # use clap::{Command, Arg, error::ErrorKind}; 2935 /// let noerr = Command::new("myprog") 2936 /// .subcommand_negates_reqs(true) 2937 /// .arg(Arg::new("opt").required(true)) 2938 /// .subcommand(Command::new("test")) 2939 /// .try_get_matches_from(vec![ 2940 /// "myprog", "test" 2941 /// ]); 2942 /// assert!(noerr.is_ok()); 2943 /// # ; 2944 /// ``` 2945 /// 2946 /// [`Arg::required(true)`]: crate::Arg::required() 2947 /// [`subcommands`]: crate::Command::subcommand() 2948 pub fn subcommand_negates_reqs(self, yes: bool) -> Self { 2949 if yes { 2950 self.setting(AppSettings::SubcommandsNegateReqs) 2951 } else { 2952 self.unset_setting(AppSettings::SubcommandsNegateReqs) 2953 } 2954 } 2955 2956 /// Multiple-personality program dispatched on the binary name (`argv[0]`) 2957 /// 2958 /// A "multicall" executable is a single executable 2959 /// that contains a variety of applets, 2960 /// and decides which applet to run based on the name of the file. 2961 /// The executable can be called from different names by creating hard links 2962 /// or symbolic links to it. 2963 /// 2964 /// This is desirable for: 2965 /// - Easy distribution, a single binary that can install hardlinks to access the different 2966 /// personalities. 2967 /// - Minimal binary size by sharing common code (e.g. standard library, clap) 2968 /// - Custom shells or REPLs where there isn't a single top-level command 2969 /// 2970 /// Setting `multicall` will cause 2971 /// - `argv[0]` to be stripped to the base name and parsed as the first argument, as if 2972 /// [`Command::no_binary_name`][Command::no_binary_name] was set. 2973 /// - Help and errors to report subcommands as if they were the top-level command 2974 /// 2975 /// When the subcommand is not present, there are several strategies you may employ, depending 2976 /// on your needs: 2977 /// - Let the error percolate up normally 2978 /// - Print a specialized error message using the 2979 /// [`Error::context`][crate::Error::context] 2980 /// - Print the [help][Command::write_help] but this might be ambiguous 2981 /// - Disable `multicall` and re-parse it 2982 /// - Disable `multicall` and re-parse it with a specific subcommand 2983 /// 2984 /// When detecting the error condition, the [`ErrorKind`] isn't sufficient as a sub-subcommand 2985 /// might report the same error. Enable 2986 /// [`allow_external_subcommands`][Command::allow_external_subcommands] if you want to specifically 2987 /// get the unrecognized binary name. 2988 /// 2989 /// **NOTE:** Multicall can't be used with [`no_binary_name`] since they interpret 2990 /// the command name in incompatible ways. 2991 /// 2992 /// **NOTE:** The multicall command cannot have arguments. 2993 /// 2994 /// **NOTE:** Applets are slightly semantically different from subcommands, 2995 /// so it's recommended to use [`Command::subcommand_help_heading`] and 2996 /// [`Command::subcommand_value_name`] to change the descriptive text as above. 2997 /// 2998 /// # Examples 2999 /// 3000 /// `hostname` is an example of a multicall executable. 3001 /// Both `hostname` and `dnsdomainname` are provided by the same executable 3002 /// and which behaviour to use is based on the executable file name. 3003 /// 3004 /// This is desirable when the executable has a primary purpose 3005 /// but there is related functionality that would be convenient to provide 3006 /// and implement it to be in the same executable. 3007 /// 3008 /// The name of the cmd is essentially unused 3009 /// and may be the same as the name of a subcommand. 3010 /// 3011 /// The names of the immediate subcommands of the Command 3012 /// are matched against the basename of the first argument, 3013 /// which is conventionally the path of the executable. 3014 /// 3015 /// This does not allow the subcommand to be passed as the first non-path argument. 3016 /// 3017 /// ```rust 3018 /// # use clap::{Command, error::ErrorKind}; 3019 /// let mut cmd = Command::new("hostname") 3020 /// .multicall(true) 3021 /// .subcommand(Command::new("hostname")) 3022 /// .subcommand(Command::new("dnsdomainname")); 3023 /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/hostname", "dnsdomainname"]); 3024 /// assert!(m.is_err()); 3025 /// assert_eq!(m.unwrap_err().kind(), ErrorKind::UnknownArgument); 3026 /// let m = cmd.get_matches_from(&["/usr/bin/dnsdomainname"]); 3027 /// assert_eq!(m.subcommand_name(), Some("dnsdomainname")); 3028 /// ``` 3029 /// 3030 /// Busybox is another common example of a multicall executable 3031 /// with a subcommmand for each applet that can be run directly, 3032 /// e.g. with the `cat` applet being run by running `busybox cat`, 3033 /// or with `cat` as a link to the `busybox` binary. 3034 /// 3035 /// This is desirable when the launcher program has additional options 3036 /// or it is useful to run the applet without installing a symlink 3037 /// e.g. to test the applet without installing it 3038 /// or there may already be a command of that name installed. 3039 /// 3040 /// To make an applet usable as both a multicall link and a subcommand 3041 /// the subcommands must be defined both in the top-level Command 3042 /// and as subcommands of the "main" applet. 3043 /// 3044 /// ```rust 3045 /// # use clap::Command; 3046 /// fn applet_commands() -> [Command; 2] { 3047 /// [Command::new("true"), Command::new("false")] 3048 /// } 3049 /// let mut cmd = Command::new("busybox") 3050 /// .multicall(true) 3051 /// .subcommand( 3052 /// Command::new("busybox") 3053 /// .subcommand_value_name("APPLET") 3054 /// .subcommand_help_heading("APPLETS") 3055 /// .subcommands(applet_commands()), 3056 /// ) 3057 /// .subcommands(applet_commands()); 3058 /// // When called from the executable's canonical name 3059 /// // its applets can be matched as subcommands. 3060 /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/busybox", "true"]).unwrap(); 3061 /// assert_eq!(m.subcommand_name(), Some("busybox")); 3062 /// assert_eq!(m.subcommand().unwrap().1.subcommand_name(), Some("true")); 3063 /// // When called from a link named after an applet that applet is matched. 3064 /// let m = cmd.get_matches_from(&["/usr/bin/true"]); 3065 /// assert_eq!(m.subcommand_name(), Some("true")); 3066 /// ``` 3067 /// 3068 /// [`no_binary_name`]: crate::Command::no_binary_name 3069 /// [`Command::subcommand_value_name`]: crate::Command::subcommand_value_name 3070 /// [`Command::subcommand_help_heading`]: crate::Command::subcommand_help_heading 3071 #[inline] 3072 pub fn multicall(self, yes: bool) -> Self { 3073 if yes { 3074 self.setting(AppSettings::Multicall) 3075 } else { 3076 self.unset_setting(AppSettings::Multicall) 3077 } 3078 } 3079 3080 /// Sets the value name used for subcommands when printing usage and help. 3081 /// 3082 /// By default, this is "COMMAND". 3083 /// 3084 /// See also [`Command::subcommand_help_heading`] 3085 /// 3086 /// # Examples 3087 /// 3088 /// ```no_run 3089 /// # use clap::{Command, Arg}; 3090 /// Command::new("myprog") 3091 /// .subcommand(Command::new("sub1")) 3092 /// .print_help() 3093 /// # ; 3094 /// ``` 3095 /// 3096 /// will produce 3097 /// 3098 /// ```text 3099 /// myprog 3100 /// 3101 /// Usage: myprog [COMMAND] 3102 /// 3103 /// Commands: 3104 /// help Print this message or the help of the given subcommand(s) 3105 /// sub1 3106 /// 3107 /// Options: 3108 /// -h, --help Print help 3109 /// -V, --version Print version 3110 /// ``` 3111 /// 3112 /// but usage of `subcommand_value_name` 3113 /// 3114 /// ```no_run 3115 /// # use clap::{Command, Arg}; 3116 /// Command::new("myprog") 3117 /// .subcommand(Command::new("sub1")) 3118 /// .subcommand_value_name("THING") 3119 /// .print_help() 3120 /// # ; 3121 /// ``` 3122 /// 3123 /// will produce 3124 /// 3125 /// ```text 3126 /// myprog 3127 /// 3128 /// Usage: myprog [THING] 3129 /// 3130 /// Commands: 3131 /// help Print this message or the help of the given subcommand(s) 3132 /// sub1 3133 /// 3134 /// Options: 3135 /// -h, --help Print help 3136 /// -V, --version Print version 3137 /// ``` 3138 #[must_use] 3139 pub fn subcommand_value_name(mut self, value_name: impl IntoResettable<Str>) -> Self { 3140 self.subcommand_value_name = value_name.into_resettable().into_option(); 3141 self 3142 } 3143 3144 /// Sets the help heading used for subcommands when printing usage and help. 3145 /// 3146 /// By default, this is "Commands". 3147 /// 3148 /// See also [`Command::subcommand_value_name`] 3149 /// 3150 /// # Examples 3151 /// 3152 /// ```no_run 3153 /// # use clap::{Command, Arg}; 3154 /// Command::new("myprog") 3155 /// .subcommand(Command::new("sub1")) 3156 /// .print_help() 3157 /// # ; 3158 /// ``` 3159 /// 3160 /// will produce 3161 /// 3162 /// ```text 3163 /// myprog 3164 /// 3165 /// Usage: myprog [COMMAND] 3166 /// 3167 /// Commands: 3168 /// help Print this message or the help of the given subcommand(s) 3169 /// sub1 3170 /// 3171 /// Options: 3172 /// -h, --help Print help 3173 /// -V, --version Print version 3174 /// ``` 3175 /// 3176 /// but usage of `subcommand_help_heading` 3177 /// 3178 /// ```no_run 3179 /// # use clap::{Command, Arg}; 3180 /// Command::new("myprog") 3181 /// .subcommand(Command::new("sub1")) 3182 /// .subcommand_help_heading("Things") 3183 /// .print_help() 3184 /// # ; 3185 /// ``` 3186 /// 3187 /// will produce 3188 /// 3189 /// ```text 3190 /// myprog 3191 /// 3192 /// Usage: myprog [COMMAND] 3193 /// 3194 /// Things: 3195 /// help Print this message or the help of the given subcommand(s) 3196 /// sub1 3197 /// 3198 /// Options: 3199 /// -h, --help Print help 3200 /// -V, --version Print version 3201 /// ``` 3202 #[must_use] 3203 pub fn subcommand_help_heading(mut self, heading: impl IntoResettable<Str>) -> Self { 3204 self.subcommand_heading = heading.into_resettable().into_option(); 3205 self 3206 } 3207} 3208 3209/// # Reflection 3210impl Command { 3211 #[inline] 3212 #[cfg(feature = "usage")] 3213 pub(crate) fn get_usage_name(&self) -> Option<&str> { 3214 self.usage_name.as_deref() 3215 } 3216 3217 /// Get the name of the binary. 3218 #[inline] 3219 pub fn get_display_name(&self) -> Option<&str> { 3220 self.display_name.as_deref() 3221 } 3222 3223 /// Get the name of the binary. 3224 #[inline] 3225 pub fn get_bin_name(&self) -> Option<&str> { 3226 self.bin_name.as_deref() 3227 } 3228 3229 /// Set binary name. Uses `&mut self` instead of `self`. 3230 pub fn set_bin_name(&mut self, name: impl Into<String>) { 3231 self.bin_name = Some(name.into()); 3232 } 3233 3234 /// Get the name of the cmd. 3235 #[inline] 3236 pub fn get_name(&self) -> &str { 3237 self.name.as_str() 3238 } 3239 3240 #[inline] 3241 #[cfg(debug_assertions)] 3242 pub(crate) fn get_name_str(&self) -> &Str { 3243 &self.name 3244 } 3245 3246 /// Get the version of the cmd. 3247 #[inline] 3248 pub fn get_version(&self) -> Option<&str> { 3249 self.version.as_deref() 3250 } 3251 3252 /// Get the long version of the cmd. 3253 #[inline] 3254 pub fn get_long_version(&self) -> Option<&str> { 3255 self.long_version.as_deref() 3256 } 3257 3258 /// Get the authors of the cmd. 3259 #[inline] 3260 pub fn get_author(&self) -> Option<&str> { 3261 self.author.as_deref() 3262 } 3263 3264 /// Get the short flag of the subcommand. 3265 #[inline] 3266 pub fn get_short_flag(&self) -> Option<char> { 3267 self.short_flag 3268 } 3269 3270 /// Get the long flag of the subcommand. 3271 #[inline] 3272 pub fn get_long_flag(&self) -> Option<&str> { 3273 self.long_flag.as_deref() 3274 } 3275 3276 /// Get the help message specified via [`Command::about`]. 3277 /// 3278 /// [`Command::about`]: Command::about() 3279 #[inline] 3280 pub fn get_about(&self) -> Option<&StyledStr> { 3281 self.about.as_ref() 3282 } 3283 3284 /// Get the help message specified via [`Command::long_about`]. 3285 /// 3286 /// [`Command::long_about`]: Command::long_about() 3287 #[inline] 3288 pub fn get_long_about(&self) -> Option<&StyledStr> { 3289 self.long_about.as_ref() 3290 } 3291 3292 /// Get the custom section heading specified via [`Command::next_help_heading`]. 3293 /// 3294 /// [`Command::help_heading`]: Command::help_heading() 3295 #[inline] 3296 pub fn get_next_help_heading(&self) -> Option<&str> { 3297 self.current_help_heading.as_deref() 3298 } 3299 3300 /// Iterate through the *visible* aliases for this subcommand. 3301 #[inline] 3302 pub fn get_visible_aliases(&self) -> impl Iterator<Item = &str> + '_ { 3303 self.aliases 3304 .iter() 3305 .filter(|(_, vis)| *vis) 3306 .map(|a| a.0.as_str()) 3307 } 3308 3309 /// Iterate through the *visible* short aliases for this subcommand. 3310 #[inline] 3311 pub fn get_visible_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ { 3312 self.short_flag_aliases 3313 .iter() 3314 .filter(|(_, vis)| *vis) 3315 .map(|a| a.0) 3316 } 3317 3318 /// Iterate through the *visible* long aliases for this subcommand. 3319 #[inline] 3320 pub fn get_visible_long_flag_aliases(&self) -> impl Iterator<Item = &str> + '_ { 3321 self.long_flag_aliases 3322 .iter() 3323 .filter(|(_, vis)| *vis) 3324 .map(|a| a.0.as_str()) 3325 } 3326 3327 /// Iterate through the set of *all* the aliases for this subcommand, both visible and hidden. 3328 #[inline] 3329 pub fn get_all_aliases(&self) -> impl Iterator<Item = &str> + '_ { 3330 self.aliases.iter().map(|a| a.0.as_str()) 3331 } 3332 3333 /// Iterate through the set of *all* the short aliases for this subcommand, both visible and hidden. 3334 #[inline] 3335 pub fn get_all_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ { 3336 self.short_flag_aliases.iter().map(|a| a.0) 3337 } 3338 3339 /// Iterate through the set of *all* the long aliases for this subcommand, both visible and hidden. 3340 #[inline] 3341 pub fn get_all_long_flag_aliases(&self) -> impl Iterator<Item = &str> + '_ { 3342 self.long_flag_aliases.iter().map(|a| a.0.as_str()) 3343 } 3344 3345 #[inline] 3346 pub(crate) fn is_set(&self, s: AppSettings) -> bool { 3347 self.settings.is_set(s) || self.g_settings.is_set(s) 3348 } 3349 3350 /// Should we color the output? 3351 pub fn get_color(&self) -> ColorChoice { 3352 debug!("Command::color: Color setting..."); 3353 3354 if cfg!(feature = "color") { 3355 if self.is_set(AppSettings::ColorNever) { 3356 debug!("Never"); 3357 ColorChoice::Never 3358 } else if self.is_set(AppSettings::ColorAlways) { 3359 debug!("Always"); 3360 ColorChoice::Always 3361 } else { 3362 debug!("Auto"); 3363 ColorChoice::Auto 3364 } 3365 } else { 3366 ColorChoice::Never 3367 } 3368 } 3369 3370 /// Iterate through the set of subcommands, getting a reference to each. 3371 #[inline] 3372 pub fn get_subcommands(&self) -> impl Iterator<Item = &Command> { 3373 self.subcommands.iter() 3374 } 3375 3376 /// Iterate through the set of subcommands, getting a mutable reference to each. 3377 #[inline] 3378 pub fn get_subcommands_mut(&mut self) -> impl Iterator<Item = &mut Command> { 3379 self.subcommands.iter_mut() 3380 } 3381 3382 /// Returns `true` if this `Command` has subcommands. 3383 #[inline] 3384 pub fn has_subcommands(&self) -> bool { 3385 !self.subcommands.is_empty() 3386 } 3387 3388 /// Returns the help heading for listing subcommands. 3389 #[inline] 3390 pub fn get_subcommand_help_heading(&self) -> Option<&str> { 3391 self.subcommand_heading.as_deref() 3392 } 3393 3394 /// Returns the subcommand value name. 3395 #[inline] 3396 pub fn get_subcommand_value_name(&self) -> Option<&str> { 3397 self.subcommand_value_name.as_deref() 3398 } 3399 3400 /// Returns the help heading for listing subcommands. 3401 #[inline] 3402 pub fn get_before_help(&self) -> Option<&StyledStr> { 3403 self.before_help.as_ref() 3404 } 3405 3406 /// Returns the help heading for listing subcommands. 3407 #[inline] 3408 pub fn get_before_long_help(&self) -> Option<&StyledStr> { 3409 self.before_long_help.as_ref() 3410 } 3411 3412 /// Returns the help heading for listing subcommands. 3413 #[inline] 3414 pub fn get_after_help(&self) -> Option<&StyledStr> { 3415 self.after_help.as_ref() 3416 } 3417 3418 /// Returns the help heading for listing subcommands. 3419 #[inline] 3420 pub fn get_after_long_help(&self) -> Option<&StyledStr> { 3421 self.after_long_help.as_ref() 3422 } 3423 3424 /// Find subcommand such that its name or one of aliases equals `name`. 3425 /// 3426 /// This does not recurse through subcommands of subcommands. 3427 #[inline] 3428 pub fn find_subcommand(&self, name: impl AsRef<std::ffi::OsStr>) -> Option<&Command> { 3429 let name = name.as_ref(); 3430 self.get_subcommands().find(|s| s.aliases_to(name)) 3431 } 3432 3433 /// Find subcommand such that its name or one of aliases equals `name`, returning 3434 /// a mutable reference to the subcommand. 3435 /// 3436 /// This does not recurse through subcommands of subcommands. 3437 #[inline] 3438 pub fn find_subcommand_mut( 3439 &mut self, 3440 name: impl AsRef<std::ffi::OsStr>, 3441 ) -> Option<&mut Command> { 3442 let name = name.as_ref(); 3443 self.get_subcommands_mut().find(|s| s.aliases_to(name)) 3444 } 3445 3446 /// Iterate through the set of groups. 3447 #[inline] 3448 pub fn get_groups(&self) -> impl Iterator<Item = &ArgGroup> { 3449 self.groups.iter() 3450 } 3451 3452 /// Iterate through the set of arguments. 3453 #[inline] 3454 pub fn get_arguments(&self) -> impl Iterator<Item = &Arg> { 3455 self.args.args() 3456 } 3457 3458 /// Iterate through the *positionals* arguments. 3459 #[inline] 3460 pub fn get_positionals(&self) -> impl Iterator<Item = &Arg> { 3461 self.get_arguments().filter(|a| a.is_positional()) 3462 } 3463 3464 /// Iterate through the *options*. 3465 pub fn get_opts(&self) -> impl Iterator<Item = &Arg> { 3466 self.get_arguments() 3467 .filter(|a| a.is_takes_value_set() && !a.is_positional()) 3468 } 3469 3470 /// Get a list of all arguments the given argument conflicts with. 3471 /// 3472 /// If the provided argument is declared as global, the conflicts will be determined 3473 /// based on the propagation rules of global arguments. 3474 /// 3475 /// ### Panics 3476 /// 3477 /// If the given arg contains a conflict with an argument that is unknown to 3478 /// this `Command`. 3479 pub fn get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator 3480 { 3481 if arg.is_global_set() { 3482 self.get_global_arg_conflicts_with(arg) 3483 } else { 3484 let mut result = Vec::new(); 3485 for id in arg.blacklist.iter() { 3486 if let Some(arg) = self.find(id) { 3487 result.push(arg); 3488 } else if let Some(group) = self.find_group(id) { 3489 result.extend( 3490 self.unroll_args_in_group(&group.id) 3491 .iter() 3492 .map(|id| self.find(id).expect(INTERNAL_ERROR_MSG)), 3493 ); 3494 } else { 3495 panic!("Command::get_arg_conflicts_with: The passed arg conflicts with an arg unknown to the cmd"); 3496 } 3497 } 3498 result 3499 } 3500 } 3501 3502 // Get a unique list of all arguments of all commands and continuous subcommands the given argument conflicts with. 3503 // 3504 // This behavior follows the propagation rules of global arguments. 3505 // It is useful for finding conflicts for arguments declared as global. 3506 // 3507 // ### Panics 3508 // 3509 // If the given arg contains a conflict with an argument that is unknown to 3510 // this `Command`. 3511 fn get_global_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator 3512 { 3513 arg.blacklist 3514 .iter() 3515 .map(|id| { 3516 self.args 3517 .args() 3518 .chain( 3519 self.get_subcommands_containing(arg) 3520 .iter() 3521 .flat_map(|x| x.args.args()), 3522 ) 3523 .find(|arg| arg.get_id() == id) 3524 .expect( 3525 "Command::get_arg_conflicts_with: \ 3526 The passed arg conflicts with an arg unknown to the cmd", 3527 ) 3528 }) 3529 .collect() 3530 } 3531 3532 // Get a list of subcommands which contain the provided Argument 3533 // 3534 // This command will only include subcommands in its list for which the subcommands 3535 // parent also contains the Argument. 3536 // 3537 // This search follows the propagation rules of global arguments. 3538 // It is useful to finding subcommands, that have inherited a global argument. 3539 // 3540 // **NOTE:** In this case only Sucommand_1 will be included 3541 // Subcommand_1 (contains Arg) 3542 // Subcommand_1.1 (doesn't contain Arg) 3543 // Subcommand_1.1.1 (contains Arg) 3544 // 3545 fn get_subcommands_containing(&self, arg: &Arg) -> Vec<&Self> { 3546 let mut vec = std::vec::Vec::new(); 3547 for idx in 0..self.subcommands.len() { 3548 if self.subcommands[idx] 3549 .args 3550 .args() 3551 .any(|ar| ar.get_id() == arg.get_id()) 3552 { 3553 vec.push(&self.subcommands[idx]); 3554 vec.append(&mut self.subcommands[idx].get_subcommands_containing(arg)); 3555 } 3556 } 3557 vec 3558 } 3559 3560 /// Report whether [`Command::no_binary_name`] is set 3561 pub fn is_no_binary_name_set(&self) -> bool { 3562 self.is_set(AppSettings::NoBinaryName) 3563 } 3564 3565 /// Report whether [`Command::ignore_errors`] is set 3566 pub(crate) fn is_ignore_errors_set(&self) -> bool { 3567 self.is_set(AppSettings::IgnoreErrors) 3568 } 3569 3570 /// Report whether [`Command::dont_delimit_trailing_values`] is set 3571 pub fn is_dont_delimit_trailing_values_set(&self) -> bool { 3572 self.is_set(AppSettings::DontDelimitTrailingValues) 3573 } 3574 3575 /// Report whether [`Command::disable_version_flag`] is set 3576 pub fn is_disable_version_flag_set(&self) -> bool { 3577 self.is_set(AppSettings::DisableVersionFlag) 3578 || (self.version.is_none() && self.long_version.is_none()) 3579 } 3580 3581 /// Report whether [`Command::propagate_version`] is set 3582 pub fn is_propagate_version_set(&self) -> bool { 3583 self.is_set(AppSettings::PropagateVersion) 3584 } 3585 3586 /// Report whether [`Command::next_line_help`] is set 3587 pub fn is_next_line_help_set(&self) -> bool { 3588 self.is_set(AppSettings::NextLineHelp) 3589 } 3590 3591 /// Report whether [`Command::disable_help_flag`] is set 3592 pub fn is_disable_help_flag_set(&self) -> bool { 3593 self.is_set(AppSettings::DisableHelpFlag) 3594 } 3595 3596 /// Report whether [`Command::disable_help_subcommand`] is set 3597 pub fn is_disable_help_subcommand_set(&self) -> bool { 3598 self.is_set(AppSettings::DisableHelpSubcommand) 3599 } 3600 3601 /// Report whether [`Command::disable_colored_help`] is set 3602 pub fn is_disable_colored_help_set(&self) -> bool { 3603 self.is_set(AppSettings::DisableColoredHelp) 3604 } 3605 3606 /// Report whether [`Command::help_expected`] is set 3607 #[cfg(debug_assertions)] 3608 pub(crate) fn is_help_expected_set(&self) -> bool { 3609 self.is_set(AppSettings::HelpExpected) 3610 } 3611 3612 #[doc(hidden)] 3613 #[cfg_attr( 3614 feature = "deprecated", 3615 deprecated(since = "4.0.0", note = "This is now the default") 3616 )] 3617 pub fn is_dont_collapse_args_in_usage_set(&self) -> bool { 3618 true 3619 } 3620 3621 /// Report whether [`Command::infer_long_args`] is set 3622 pub(crate) fn is_infer_long_args_set(&self) -> bool { 3623 self.is_set(AppSettings::InferLongArgs) 3624 } 3625 3626 /// Report whether [`Command::infer_subcommands`] is set 3627 pub(crate) fn is_infer_subcommands_set(&self) -> bool { 3628 self.is_set(AppSettings::InferSubcommands) 3629 } 3630 3631 /// Report whether [`Command::arg_required_else_help`] is set 3632 pub fn is_arg_required_else_help_set(&self) -> bool { 3633 self.is_set(AppSettings::ArgRequiredElseHelp) 3634 } 3635 3636 #[doc(hidden)] 3637 #[cfg_attr( 3638 feature = "deprecated", 3639 deprecated( 3640 since = "4.0.0", 3641 note = "Replaced with `Arg::is_allow_hyphen_values_set`" 3642 ) 3643 )] 3644 pub(crate) fn is_allow_hyphen_values_set(&self) -> bool { 3645 self.is_set(AppSettings::AllowHyphenValues) 3646 } 3647 3648 #[doc(hidden)] 3649 #[cfg_attr( 3650 feature = "deprecated", 3651 deprecated( 3652 since = "4.0.0", 3653 note = "Replaced with `Arg::is_allow_negative_numbers_set`" 3654 ) 3655 )] 3656 pub fn is_allow_negative_numbers_set(&self) -> bool { 3657 self.is_set(AppSettings::AllowNegativeNumbers) 3658 } 3659 3660 #[doc(hidden)] 3661 #[cfg_attr( 3662 feature = "deprecated", 3663 deprecated(since = "4.0.0", note = "Replaced with `Arg::is_trailing_var_arg_set`") 3664 )] 3665 pub fn is_trailing_var_arg_set(&self) -> bool { 3666 self.is_set(AppSettings::TrailingVarArg) 3667 } 3668 3669 /// Report whether [`Command::allow_missing_positional`] is set 3670 pub fn is_allow_missing_positional_set(&self) -> bool { 3671 self.is_set(AppSettings::AllowMissingPositional) 3672 } 3673 3674 /// Report whether [`Command::hide`] is set 3675 pub fn is_hide_set(&self) -> bool { 3676 self.is_set(AppSettings::Hidden) 3677 } 3678 3679 /// Report whether [`Command::subcommand_required`] is set 3680 pub fn is_subcommand_required_set(&self) -> bool { 3681 self.is_set(AppSettings::SubcommandRequired) 3682 } 3683 3684 /// Report whether [`Command::allow_external_subcommands`] is set 3685 pub fn is_allow_external_subcommands_set(&self) -> bool { 3686 self.is_set(AppSettings::AllowExternalSubcommands) 3687 } 3688 3689 /// Configured parser for values passed to an external subcommand 3690 /// 3691 /// # Example 3692 /// 3693 /// ```rust 3694 /// let cmd = clap::Command::new("raw") 3695 /// .external_subcommand_value_parser(clap::value_parser!(String)); 3696 /// let value_parser = cmd.get_external_subcommand_value_parser(); 3697 /// println!("{:?}", value_parser); 3698 /// ``` 3699 pub fn get_external_subcommand_value_parser(&self) -> Option<&super::ValueParser> { 3700 if !self.is_allow_external_subcommands_set() { 3701 None 3702 } else { 3703 static DEFAULT: super::ValueParser = super::ValueParser::os_string(); 3704 Some(self.external_value_parser.as_ref().unwrap_or(&DEFAULT)) 3705 } 3706 } 3707 3708 /// Report whether [`Command::args_conflicts_with_subcommands`] is set 3709 pub fn is_args_conflicts_with_subcommands_set(&self) -> bool { 3710 self.is_set(AppSettings::ArgsNegateSubcommands) 3711 } 3712 3713 #[doc(hidden)] 3714 pub fn is_args_override_self(&self) -> bool { 3715 self.is_set(AppSettings::AllArgsOverrideSelf) 3716 } 3717 3718 /// Report whether [`Command::subcommand_precedence_over_arg`] is set 3719 pub fn is_subcommand_precedence_over_arg_set(&self) -> bool { 3720 self.is_set(AppSettings::SubcommandPrecedenceOverArg) 3721 } 3722 3723 /// Report whether [`Command::subcommand_negates_reqs`] is set 3724 pub fn is_subcommand_negates_reqs_set(&self) -> bool { 3725 self.is_set(AppSettings::SubcommandsNegateReqs) 3726 } 3727 3728 /// Report whether [`Command::multicall`] is set 3729 pub fn is_multicall_set(&self) -> bool { 3730 self.is_set(AppSettings::Multicall) 3731 } 3732} 3733 3734// Internally used only 3735impl Command { 3736 pub(crate) fn get_override_usage(&self) -> Option<&StyledStr> { 3737 self.usage_str.as_ref() 3738 } 3739 3740 pub(crate) fn get_override_help(&self) -> Option<&StyledStr> { 3741 self.help_str.as_ref() 3742 } 3743 3744 #[cfg(feature = "help")] 3745 pub(crate) fn get_help_template(&self) -> Option<&StyledStr> { 3746 self.template.as_ref() 3747 } 3748 3749 #[cfg(feature = "help")] 3750 pub(crate) fn get_term_width(&self) -> Option<usize> { 3751 self.term_w 3752 } 3753 3754 #[cfg(feature = "help")] 3755 pub(crate) fn get_max_term_width(&self) -> Option<usize> { 3756 self.max_w 3757 } 3758 3759 pub(crate) fn get_replacement(&self, key: &str) -> Option<&[Str]> { 3760 self.replacers.get(key).map(|v| v.as_slice()) 3761 } 3762 3763 pub(crate) fn get_keymap(&self) -> &MKeyMap { 3764 &self.args 3765 } 3766 3767 fn get_used_global_args(&self, matches: &ArgMatches, global_arg_vec: &mut Vec<Id>) { 3768 global_arg_vec.extend( 3769 self.args 3770 .args() 3771 .filter(|a| a.is_global_set()) 3772 .map(|ga| ga.id.clone()), 3773 ); 3774 if let Some((id, matches)) = matches.subcommand() { 3775 if let Some(used_sub) = self.find_subcommand(id) { 3776 used_sub.get_used_global_args(matches, global_arg_vec); 3777 } 3778 } 3779 } 3780 3781 fn _do_parse( 3782 &mut self, 3783 raw_args: &mut clap_lex::RawArgs, 3784 args_cursor: clap_lex::ArgCursor, 3785 ) -> ClapResult<ArgMatches> { 3786 debug!("Command::_do_parse"); 3787 3788 // If there are global arguments, or settings we need to propagate them down to subcommands 3789 // before parsing in case we run into a subcommand 3790 self._build_self(false); 3791 3792 let mut matcher = ArgMatcher::new(self); 3793 3794 // do the real parsing 3795 let mut parser = Parser::new(self); 3796 if let Err(error) = parser.get_matches_with(&mut matcher, raw_args, args_cursor) { 3797 if self.is_set(AppSettings::IgnoreErrors) { 3798 debug!("Command::_do_parse: ignoring error: {}", error); 3799 } else { 3800 return Err(error); 3801 } 3802 } 3803 3804 let mut global_arg_vec = Default::default(); 3805 self.get_used_global_args(&matcher, &mut global_arg_vec); 3806 3807 matcher.propagate_globals(&global_arg_vec); 3808 3809 Ok(matcher.into_inner()) 3810 } 3811 3812 /// Prepare for introspecting on all included [`Command`]s 3813 /// 3814 /// Call this on the top-level [`Command`] when done building and before reading state for 3815 /// cases like completions, custom help output, etc. 3816 pub fn build(&mut self) { 3817 self._build_recursive(true); 3818 self._build_bin_names_internal(); 3819 } 3820 3821 pub(crate) fn _build_recursive(&mut self, expand_help_tree: bool) { 3822 self._build_self(expand_help_tree); 3823 for subcmd in self.get_subcommands_mut() { 3824 subcmd._build_recursive(expand_help_tree); 3825 } 3826 } 3827 3828 pub(crate) fn _build_self(&mut self, expand_help_tree: bool) { 3829 debug!("Command::_build: name={:?}", self.get_name()); 3830 if !self.settings.is_set(AppSettings::Built) { 3831 // Make sure all the globally set flags apply to us as well 3832 self.settings = self.settings | self.g_settings; 3833 3834 if self.is_multicall_set() { 3835 self.settings.insert(AppSettings::SubcommandRequired.into()); 3836 self.settings.insert(AppSettings::DisableHelpFlag.into()); 3837 self.settings.insert(AppSettings::DisableVersionFlag.into()); 3838 } 3839 if !cfg!(feature = "help") && self.get_override_help().is_none() { 3840 self.settings.insert(AppSettings::DisableHelpFlag.into()); 3841 self.settings 3842 .insert(AppSettings::DisableHelpSubcommand.into()); 3843 } 3844 if self.is_set(AppSettings::ArgsNegateSubcommands) { 3845 self.settings 3846 .insert(AppSettings::SubcommandsNegateReqs.into()); 3847 } 3848 if self.external_value_parser.is_some() { 3849 self.settings 3850 .insert(AppSettings::AllowExternalSubcommands.into()); 3851 } 3852 if !self.has_subcommands() { 3853 self.settings 3854 .insert(AppSettings::DisableHelpSubcommand.into()); 3855 } 3856 3857 self._propagate(); 3858 self._check_help_and_version(expand_help_tree); 3859 self._propagate_global_args(); 3860 3861 let mut pos_counter = 1; 3862 let hide_pv = self.is_set(AppSettings::HidePossibleValues); 3863 for a in self.args.args_mut() { 3864 // Fill in the groups 3865 for g in &a.groups { 3866 if let Some(ag) = self.groups.iter_mut().find(|grp| grp.id == *g) { 3867 ag.args.push(a.get_id().clone()); 3868 } else { 3869 let mut ag = ArgGroup::new(g); 3870 ag.args.push(a.get_id().clone()); 3871 self.groups.push(ag); 3872 } 3873 } 3874 3875 // Figure out implied settings 3876 a._build(); 3877 if hide_pv && a.is_takes_value_set() { 3878 a.settings.set(ArgSettings::HidePossibleValues); 3879 } 3880 if a.is_positional() && a.index.is_none() { 3881 a.index = Some(pos_counter); 3882 pos_counter += 1; 3883 } 3884 } 3885 3886 self.args._build(); 3887 3888 #[allow(deprecated)] 3889 { 3890 let highest_idx = self 3891 .get_keymap() 3892 .keys() 3893 .filter_map(|x| { 3894 if let crate::mkeymap::KeyType::Position(n) = x { 3895 Some(*n) 3896 } else { 3897 None 3898 } 3899 }) 3900 .max() 3901 .unwrap_or(0); 3902 let is_trailing_var_arg_set = self.is_trailing_var_arg_set(); 3903 let is_allow_hyphen_values_set = self.is_allow_hyphen_values_set(); 3904 let is_allow_negative_numbers_set = self.is_allow_negative_numbers_set(); 3905 for arg in self.args.args_mut() { 3906 if is_allow_hyphen_values_set && arg.is_takes_value_set() { 3907 arg.settings.insert(ArgSettings::AllowHyphenValues.into()); 3908 } 3909 if is_allow_negative_numbers_set && arg.is_takes_value_set() { 3910 arg.settings 3911 .insert(ArgSettings::AllowNegativeNumbers.into()); 3912 } 3913 if is_trailing_var_arg_set && arg.get_index() == Some(highest_idx) { 3914 arg.settings.insert(ArgSettings::TrailingVarArg.into()); 3915 } 3916 } 3917 } 3918 3919 #[cfg(debug_assertions)] 3920 assert_app(self); 3921 self.settings.set(AppSettings::Built); 3922 } else { 3923 debug!("Command::_build: already built"); 3924 } 3925 } 3926 3927 pub(crate) fn _build_subcommand(&mut self, name: &str) -> Option<&mut Self> { 3928 use std::fmt::Write; 3929 3930 let mut mid_string = String::from(" "); 3931 #[cfg(feature = "usage")] 3932 if !self.is_subcommand_negates_reqs_set() && !self.is_args_conflicts_with_subcommands_set() 3933 { 3934 let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m) 3935 3936 for s in &reqs { 3937 mid_string.push_str(&s.to_string()); 3938 mid_string.push(' '); 3939 } 3940 } 3941 let is_multicall_set = self.is_multicall_set(); 3942 3943 let sc = some!(self.subcommands.iter_mut().find(|s| s.name == name)); 3944 3945 // Display subcommand name, short and long in usage 3946 let mut sc_names = String::new(); 3947 sc_names.push_str(sc.name.as_str()); 3948 let mut flag_subcmd = false; 3949 if let Some(l) = sc.get_long_flag() { 3950 write!(sc_names, "|--{l}").unwrap(); 3951 flag_subcmd = true; 3952 } 3953 if let Some(s) = sc.get_short_flag() { 3954 write!(sc_names, "|-{s}").unwrap(); 3955 flag_subcmd = true; 3956 } 3957 3958 if flag_subcmd { 3959 sc_names = format!("{{{sc_names}}}"); 3960 } 3961 3962 let usage_name = self 3963 .bin_name 3964 .as_ref() 3965 .map(|bin_name| format!("{bin_name}{mid_string}{sc_names}")) 3966 .unwrap_or(sc_names); 3967 sc.usage_name = Some(usage_name); 3968 3969 // bin_name should be parent's bin_name + [<reqs>] + the sc's name separated by 3970 // a space 3971 let bin_name = format!( 3972 "{}{}{}", 3973 self.bin_name.as_deref().unwrap_or_default(), 3974 if self.bin_name.is_some() { " " } else { "" }, 3975 &*sc.name 3976 ); 3977 debug!( 3978 "Command::_build_subcommand Setting bin_name of {} to {:?}", 3979 sc.name, bin_name 3980 ); 3981 sc.bin_name = Some(bin_name); 3982 3983 if sc.display_name.is_none() { 3984 let self_display_name = if is_multicall_set { 3985 self.display_name.as_deref().unwrap_or("") 3986 } else { 3987 self.display_name.as_deref().unwrap_or(&self.name) 3988 }; 3989 let display_name = format!( 3990 "{}{}{}", 3991 self_display_name, 3992 if !self_display_name.is_empty() { 3993 "-" 3994 } else { 3995 "" 3996 }, 3997 &*sc.name 3998 ); 3999 debug!( 4000 "Command::_build_subcommand Setting display_name of {} to {:?}", 4001 sc.name, display_name 4002 ); 4003 sc.display_name = Some(display_name); 4004 } 4005 4006 // Ensure all args are built and ready to parse 4007 sc._build_self(false); 4008 4009 Some(sc) 4010 } 4011 4012 fn _build_bin_names_internal(&mut self) { 4013 debug!("Command::_build_bin_names"); 4014 4015 if !self.is_set(AppSettings::BinNameBuilt) { 4016 let mut mid_string = String::from(" "); 4017 #[cfg(feature = "usage")] 4018 if !self.is_subcommand_negates_reqs_set() 4019 && !self.is_args_conflicts_with_subcommands_set() 4020 { 4021 let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m) 4022 4023 for s in &reqs { 4024 mid_string.push_str(&s.to_string()); 4025 mid_string.push(' '); 4026 } 4027 } 4028 let is_multicall_set = self.is_multicall_set(); 4029 4030 let self_bin_name = if is_multicall_set { 4031 self.bin_name.as_deref().unwrap_or("") 4032 } else { 4033 self.bin_name.as_deref().unwrap_or(&self.name) 4034 } 4035 .to_owned(); 4036 4037 for mut sc in &mut self.subcommands { 4038 debug!("Command::_build_bin_names:iter: bin_name set..."); 4039 4040 if sc.usage_name.is_none() { 4041 use std::fmt::Write; 4042 // Display subcommand name, short and long in usage 4043 let mut sc_names = String::new(); 4044 sc_names.push_str(sc.name.as_str()); 4045 let mut flag_subcmd = false; 4046 if let Some(l) = sc.get_long_flag() { 4047 write!(sc_names, "|--{l}").unwrap(); 4048 flag_subcmd = true; 4049 } 4050 if let Some(s) = sc.get_short_flag() { 4051 write!(sc_names, "|-{s}").unwrap(); 4052 flag_subcmd = true; 4053 } 4054 4055 if flag_subcmd { 4056 sc_names = format!("{{{sc_names}}}"); 4057 } 4058 4059 let usage_name = format!("{self_bin_name}{mid_string}{sc_names}"); 4060 debug!( 4061 "Command::_build_bin_names:iter: Setting usage_name of {} to {:?}", 4062 sc.name, usage_name 4063 ); 4064 sc.usage_name = Some(usage_name); 4065 } else { 4066 debug!( 4067 "Command::_build_bin_names::iter: Using existing usage_name of {} ({:?})", 4068 sc.name, sc.usage_name 4069 ); 4070 } 4071 4072 if sc.bin_name.is_none() { 4073 let bin_name = format!( 4074 "{}{}{}", 4075 self_bin_name, 4076 if !self_bin_name.is_empty() { " " } else { "" }, 4077 &*sc.name 4078 ); 4079 debug!( 4080 "Command::_build_bin_names:iter: Setting bin_name of {} to {:?}", 4081 sc.name, bin_name 4082 ); 4083 sc.bin_name = Some(bin_name); 4084 } else { 4085 debug!( 4086 "Command::_build_bin_names::iter: Using existing bin_name of {} ({:?})", 4087 sc.name, sc.bin_name 4088 ); 4089 } 4090 4091 if sc.display_name.is_none() { 4092 let self_display_name = if is_multicall_set { 4093 self.display_name.as_deref().unwrap_or("") 4094 } else { 4095 self.display_name.as_deref().unwrap_or(&self.name) 4096 }; 4097 let display_name = format!( 4098 "{}{}{}", 4099 self_display_name, 4100 if !self_display_name.is_empty() { 4101 "-" 4102 } else { 4103 "" 4104 }, 4105 &*sc.name 4106 ); 4107 debug!( 4108 "Command::_build_bin_names:iter: Setting display_name of {} to {:?}", 4109 sc.name, display_name 4110 ); 4111 sc.display_name = Some(display_name); 4112 } else { 4113 debug!( 4114 "Command::_build_bin_names::iter: Using existing display_name of {} ({:?})", 4115 sc.name, sc.display_name 4116 ); 4117 } 4118 4119 sc._build_bin_names_internal(); 4120 } 4121 self.set(AppSettings::BinNameBuilt); 4122 } else { 4123 debug!("Command::_build_bin_names: already built"); 4124 } 4125 } 4126 4127 pub(crate) fn _panic_on_missing_help(&self, help_required_globally: bool) { 4128 if self.is_set(AppSettings::HelpExpected) || help_required_globally { 4129 let args_missing_help: Vec<Id> = self 4130 .args 4131 .args() 4132 .filter(|arg| arg.get_help().is_none() && arg.get_long_help().is_none()) 4133 .map(|arg| arg.get_id().clone()) 4134 .collect(); 4135 4136 debug_assert!(args_missing_help.is_empty(), 4137 "Command::help_expected is enabled for the Command {}, but at least one of its arguments does not have either `help` or `long_help` set. List of such arguments: {}", 4138 self.name, 4139 args_missing_help.join(", ") 4140 ); 4141 } 4142 4143 for sub_app in &self.subcommands { 4144 sub_app._panic_on_missing_help(help_required_globally); 4145 } 4146 } 4147 4148 #[cfg(debug_assertions)] 4149 pub(crate) fn two_args_of<F>(&self, condition: F) -> Option<(&Arg, &Arg)> 4150 where 4151 F: Fn(&Arg) -> bool, 4152 { 4153 two_elements_of(self.args.args().filter(|a: &&Arg| condition(a))) 4154 } 4155 4156 // just in case 4157 #[allow(unused)] 4158 fn two_groups_of<F>(&self, condition: F) -> Option<(&ArgGroup, &ArgGroup)> 4159 where 4160 F: Fn(&ArgGroup) -> bool, 4161 { 4162 two_elements_of(self.groups.iter().filter(|a| condition(a))) 4163 } 4164 4165 /// Propagate global args 4166 pub(crate) fn _propagate_global_args(&mut self) { 4167 debug!("Command::_propagate_global_args:{}", self.name); 4168 4169 let autogenerated_help_subcommand = !self.is_disable_help_subcommand_set(); 4170 4171 for sc in &mut self.subcommands { 4172 if sc.get_name() == "help" && autogenerated_help_subcommand { 4173 // Avoid propagating args to the autogenerated help subtrees used in completion. 4174 // This prevents args from showing up during help completions like 4175 // `myapp help subcmd <TAB>`, which should only suggest subcommands and not args, 4176 // while still allowing args to show up properly on the generated help message. 4177 continue; 4178 } 4179 4180 for a in self.args.args().filter(|a| a.is_global_set()) { 4181 if sc.find(&a.id).is_some() { 4182 debug!( 4183 "Command::_propagate skipping {:?} to {}, already exists", 4184 a.id, 4185 sc.get_name(), 4186 ); 4187 continue; 4188 } 4189 4190 debug!( 4191 "Command::_propagate pushing {:?} to {}", 4192 a.id, 4193 sc.get_name(), 4194 ); 4195 sc.args.push(a.clone()); 4196 } 4197 } 4198 } 4199 4200 /// Propagate settings 4201 pub(crate) fn _propagate(&mut self) { 4202 debug!("Command::_propagate:{}", self.name); 4203 let mut subcommands = std::mem::take(&mut self.subcommands); 4204 for sc in &mut subcommands { 4205 self._propagate_subcommand(sc); 4206 } 4207 self.subcommands = subcommands; 4208 } 4209 4210 fn _propagate_subcommand(&self, sc: &mut Self) { 4211 // We have to create a new scope in order to tell rustc the borrow of `sc` is 4212 // done and to recursively call this method 4213 { 4214 if self.settings.is_set(AppSettings::PropagateVersion) { 4215 if let Some(version) = self.version.as_ref() { 4216 sc.version.get_or_insert_with(|| version.clone()); 4217 } 4218 if let Some(long_version) = self.long_version.as_ref() { 4219 sc.long_version.get_or_insert_with(|| long_version.clone()); 4220 } 4221 } 4222 4223 sc.settings = sc.settings | self.g_settings; 4224 sc.g_settings = sc.g_settings | self.g_settings; 4225 sc.term_w = self.term_w; 4226 sc.max_w = self.max_w; 4227 } 4228 } 4229 4230 pub(crate) fn _check_help_and_version(&mut self, expand_help_tree: bool) { 4231 debug!( 4232 "Command::_check_help_and_version:{} expand_help_tree={}", 4233 self.name, expand_help_tree 4234 ); 4235 4236 self.long_help_exists = self.long_help_exists_(); 4237 4238 if !self.is_disable_help_flag_set() { 4239 debug!("Command::_check_help_and_version: Building default --help"); 4240 let mut arg = Arg::new(Id::HELP) 4241 .short('h') 4242 .long("help") 4243 .action(ArgAction::Help); 4244 if self.long_help_exists { 4245 arg = arg 4246 .help("Print help (see more with '--help')") 4247 .long_help("Print help (see a summary with '-h')"); 4248 } else { 4249 arg = arg.help("Print help"); 4250 } 4251 // Avoiding `arg_internal` to not be sensitive to `next_help_heading` / 4252 // `next_display_order` 4253 self.args.push(arg); 4254 } 4255 if !self.is_disable_version_flag_set() { 4256 debug!("Command::_check_help_and_version: Building default --version"); 4257 let arg = Arg::new(Id::VERSION) 4258 .short('V') 4259 .long("version") 4260 .action(ArgAction::Version) 4261 .help("Print version"); 4262 // Avoiding `arg_internal` to not be sensitive to `next_help_heading` / 4263 // `next_display_order` 4264 self.args.push(arg); 4265 } 4266 4267 if !self.is_set(AppSettings::DisableHelpSubcommand) { 4268 debug!("Command::_check_help_and_version: Building help subcommand"); 4269 let help_about = "Print this message or the help of the given subcommand(s)"; 4270 4271 let mut help_subcmd = if expand_help_tree { 4272 // Slow code path to recursively clone all other subcommand subtrees under help 4273 let help_subcmd = Command::new("help") 4274 .about(help_about) 4275 .global_setting(AppSettings::DisableHelpSubcommand) 4276 .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help)); 4277 4278 let mut help_help_subcmd = Command::new("help").about(help_about); 4279 help_help_subcmd.version = None; 4280 help_help_subcmd.long_version = None; 4281 help_help_subcmd = help_help_subcmd 4282 .setting(AppSettings::DisableHelpFlag) 4283 .setting(AppSettings::DisableVersionFlag); 4284 4285 help_subcmd.subcommand(help_help_subcmd) 4286 } else { 4287 Command::new("help").about(help_about).arg( 4288 Arg::new("subcommand") 4289 .action(ArgAction::Append) 4290 .num_args(..) 4291 .value_name("COMMAND") 4292 .help("Print help for the subcommand(s)"), 4293 ) 4294 }; 4295 self._propagate_subcommand(&mut help_subcmd); 4296 4297 // The parser acts like this is set, so let's set it so we don't falsely 4298 // advertise it to the user 4299 help_subcmd.version = None; 4300 help_subcmd.long_version = None; 4301 help_subcmd = help_subcmd 4302 .setting(AppSettings::DisableHelpFlag) 4303 .setting(AppSettings::DisableVersionFlag) 4304 .unset_global_setting(AppSettings::PropagateVersion); 4305 4306 self.subcommands.push(help_subcmd); 4307 } 4308 } 4309 4310 fn _copy_subtree_for_help(&self) -> Command { 4311 let mut cmd = Command::new(self.name.clone()) 4312 .hide(self.is_hide_set()) 4313 .global_setting(AppSettings::DisableHelpFlag) 4314 .global_setting(AppSettings::DisableVersionFlag) 4315 .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help)); 4316 if self.get_about().is_some() { 4317 cmd = cmd.about(self.get_about().unwrap().clone()); 4318 } 4319 cmd 4320 } 4321 4322 pub(crate) fn _render_version(&self, use_long: bool) -> String { 4323 debug!("Command::_render_version"); 4324 4325 let ver = if use_long { 4326 self.long_version 4327 .as_deref() 4328 .or(self.version.as_deref()) 4329 .unwrap_or_default() 4330 } else { 4331 self.version 4332 .as_deref() 4333 .or(self.long_version.as_deref()) 4334 .unwrap_or_default() 4335 }; 4336 let display_name = self.get_display_name().unwrap_or_else(|| self.get_name()); 4337 format!("{display_name} {ver}\n") 4338 } 4339 4340 pub(crate) fn format_group(&self, g: &Id) -> StyledStr { 4341 let g_string = self 4342 .unroll_args_in_group(g) 4343 .iter() 4344 .filter_map(|x| self.find(x)) 4345 .map(|x| { 4346 if x.is_positional() { 4347 // Print val_name for positional arguments. e.g. <file_name> 4348 x.name_no_brackets() 4349 } else { 4350 // Print usage string for flags arguments, e.g. <--help> 4351 x.to_string() 4352 } 4353 }) 4354 .collect::<Vec<_>>() 4355 .join("|"); 4356 let mut styled = StyledStr::new(); 4357 styled.none("<"); 4358 styled.none(g_string); 4359 styled.none(">"); 4360 styled 4361 } 4362} 4363 4364/// A workaround: 4365/// <https://github.com/rust-lang/rust/issues/34511#issuecomment-373423999> 4366pub(crate) trait Captures<'a> {} 4367impl<'a, T> Captures<'a> for T {} 4368 4369// Internal Query Methods 4370impl Command { 4371 /// Iterate through the *flags* & *options* arguments. 4372 #[cfg(any(feature = "usage", feature = "help"))] 4373 pub(crate) fn get_non_positionals(&self) -> impl Iterator<Item = &Arg> { 4374 self.get_arguments().filter(|a| !a.is_positional()) 4375 } 4376 4377 pub(crate) fn find(&self, arg_id: &Id) -> Option<&Arg> { 4378 self.args.args().find(|a| a.get_id() == arg_id) 4379 } 4380 4381 #[inline] 4382 pub(crate) fn contains_short(&self, s: char) -> bool { 4383 debug_assert!( 4384 self.is_set(AppSettings::Built), 4385 "If Command::_build hasn't been called, manually search through Arg shorts" 4386 ); 4387 4388 self.args.contains(s) 4389 } 4390 4391 #[inline] 4392 pub(crate) fn set(&mut self, s: AppSettings) { 4393 self.settings.set(s) 4394 } 4395 4396 #[inline] 4397 pub(crate) fn has_positionals(&self) -> bool { 4398 self.get_positionals().next().is_some() 4399 } 4400 4401 #[cfg(any(feature = "usage", feature = "help"))] 4402 pub(crate) fn has_visible_subcommands(&self) -> bool { 4403 self.subcommands 4404 .iter() 4405 .any(|sc| sc.name != "help" && !sc.is_set(AppSettings::Hidden)) 4406 } 4407 4408 /// Check if this subcommand can be referred to as `name`. In other words, 4409 /// check if `name` is the name of this subcommand or is one of its aliases. 4410 #[inline] 4411 pub(crate) fn aliases_to(&self, name: impl AsRef<std::ffi::OsStr>) -> bool { 4412 let name = name.as_ref(); 4413 self.get_name() == name || self.get_all_aliases().any(|alias| alias == name) 4414 } 4415 4416 /// Check if this subcommand can be referred to as `name`. In other words, 4417 /// check if `name` is the name of this short flag subcommand or is one of its short flag aliases. 4418 #[inline] 4419 pub(crate) fn short_flag_aliases_to(&self, flag: char) -> bool { 4420 Some(flag) == self.short_flag 4421 || self.get_all_short_flag_aliases().any(|alias| flag == alias) 4422 } 4423 4424 /// Check if this subcommand can be referred to as `name`. In other words, 4425 /// check if `name` is the name of this long flag subcommand or is one of its long flag aliases. 4426 #[inline] 4427 pub(crate) fn long_flag_aliases_to(&self, flag: &str) -> bool { 4428 match self.long_flag.as_ref() { 4429 Some(long_flag) => { 4430 long_flag == flag || self.get_all_long_flag_aliases().any(|alias| alias == flag) 4431 } 4432 None => self.get_all_long_flag_aliases().any(|alias| alias == flag), 4433 } 4434 } 4435 4436 #[cfg(debug_assertions)] 4437 pub(crate) fn id_exists(&self, id: &Id) -> bool { 4438 self.args.args().any(|x| x.get_id() == id) || self.groups.iter().any(|x| x.id == *id) 4439 } 4440 4441 /// Iterate through the groups this arg is member of. 4442 pub(crate) fn groups_for_arg<'a>(&'a self, arg: &Id) -> impl Iterator<Item = Id> + 'a { 4443 debug!("Command::groups_for_arg: id={:?}", arg); 4444 let arg = arg.clone(); 4445 self.groups 4446 .iter() 4447 .filter(move |grp| grp.args.iter().any(|a| a == &arg)) 4448 .map(|grp| grp.id.clone()) 4449 } 4450 4451 pub(crate) fn find_group(&self, group_id: &Id) -> Option<&ArgGroup> { 4452 self.groups.iter().find(|g| g.id == *group_id) 4453 } 4454 4455 /// Iterate through all the names of all subcommands (not recursively), including aliases. 4456 /// Used for suggestions. 4457 pub(crate) fn all_subcommand_names(&self) -> impl Iterator<Item = &str> + Captures { 4458 self.get_subcommands().flat_map(|sc| { 4459 let name = sc.get_name(); 4460 let aliases = sc.get_all_aliases(); 4461 std::iter::once(name).chain(aliases) 4462 }) 4463 } 4464 4465 pub(crate) fn required_graph(&self) -> ChildGraph<Id> { 4466 let mut reqs = ChildGraph::with_capacity(5); 4467 for a in self.args.args().filter(|a| a.is_required_set()) { 4468 reqs.insert(a.get_id().clone()); 4469 } 4470 for group in &self.groups { 4471 if group.required { 4472 let idx = reqs.insert(group.id.clone()); 4473 for a in &group.requires { 4474 reqs.insert_child(idx, a.clone()); 4475 } 4476 } 4477 } 4478 4479 reqs 4480 } 4481 4482 pub(crate) fn unroll_args_in_group(&self, group: &Id) -> Vec<Id> { 4483 debug!("Command::unroll_args_in_group: group={:?}", group); 4484 let mut g_vec = vec![group]; 4485 let mut args = vec![]; 4486 4487 while let Some(g) = g_vec.pop() { 4488 for n in self 4489 .groups 4490 .iter() 4491 .find(|grp| grp.id == *g) 4492 .expect(INTERNAL_ERROR_MSG) 4493 .args 4494 .iter() 4495 { 4496 debug!("Command::unroll_args_in_group:iter: entity={:?}", n); 4497 if !args.contains(n) { 4498 if self.find(n).is_some() { 4499 debug!("Command::unroll_args_in_group:iter: this is an arg"); 4500 args.push(n.clone()) 4501 } else { 4502 debug!("Command::unroll_args_in_group:iter: this is a group"); 4503 g_vec.push(n); 4504 } 4505 } 4506 } 4507 } 4508 4509 args 4510 } 4511 4512 pub(crate) fn unroll_arg_requires<F>(&self, func: F, arg: &Id) -> Vec<Id> 4513 where 4514 F: Fn(&(ArgPredicate, Id)) -> Option<Id>, 4515 { 4516 let mut processed = vec![]; 4517 let mut r_vec = vec![arg]; 4518 let mut args = vec![]; 4519 4520 while let Some(a) = r_vec.pop() { 4521 if processed.contains(&a) { 4522 continue; 4523 } 4524 4525 processed.push(a); 4526 4527 if let Some(arg) = self.find(a) { 4528 for r in arg.requires.iter().filter_map(&func) { 4529 if let Some(req) = self.find(&r) { 4530 if !req.requires.is_empty() { 4531 r_vec.push(req.get_id()) 4532 } 4533 } 4534 args.push(r); 4535 } 4536 } 4537 } 4538 4539 args 4540 } 4541 4542 /// Find a flag subcommand name by short flag or an alias 4543 pub(crate) fn find_short_subcmd(&self, c: char) -> Option<&str> { 4544 self.get_subcommands() 4545 .find(|sc| sc.short_flag_aliases_to(c)) 4546 .map(|sc| sc.get_name()) 4547 } 4548 4549 /// Find a flag subcommand name by long flag or an alias 4550 pub(crate) fn find_long_subcmd(&self, long: &str) -> Option<&str> { 4551 self.get_subcommands() 4552 .find(|sc| sc.long_flag_aliases_to(long)) 4553 .map(|sc| sc.get_name()) 4554 } 4555 4556 #[cfg(feature = "help")] 4557 pub(crate) fn get_display_order(&self) -> usize { 4558 self.disp_ord.unwrap_or(999) 4559 } 4560 4561 pub(crate) fn write_help_err(&self, mut use_long: bool) -> StyledStr { 4562 debug!( 4563 "Command::write_help_err: {}, use_long={:?}", 4564 self.get_display_name().unwrap_or_else(|| self.get_name()), 4565 use_long && self.long_help_exists(), 4566 ); 4567 4568 use_long = use_long && self.long_help_exists(); 4569 let usage = Usage::new(self); 4570 4571 let mut styled = StyledStr::new(); 4572 write_help(&mut styled, self, &usage, use_long); 4573 4574 styled 4575 } 4576 4577 pub(crate) fn write_version_err(&self, use_long: bool) -> StyledStr { 4578 let msg = self._render_version(use_long); 4579 let mut styled = StyledStr::new(); 4580 styled.none(msg); 4581 styled 4582 } 4583 4584 pub(crate) fn long_help_exists(&self) -> bool { 4585 debug!("Command::long_help_exists: {}", self.long_help_exists); 4586 self.long_help_exists 4587 } 4588 4589 fn long_help_exists_(&self) -> bool { 4590 debug!("Command::long_help_exists"); 4591 // In this case, both must be checked. This allows the retention of 4592 // original formatting, but also ensures that the actual -h or --help 4593 // specified by the user is sent through. If hide_short_help is not included, 4594 // then items specified with hidden_short_help will also be hidden. 4595 let should_long = |v: &Arg| { 4596 !v.is_hide_set() 4597 && (v.get_long_help().is_some() 4598 || v.is_hide_long_help_set() 4599 || v.is_hide_short_help_set() 4600 || (!v.is_hide_possible_values_set() 4601 && v.get_possible_values() 4602 .iter() 4603 .any(PossibleValue::should_show_help))) 4604 }; 4605 4606 // Subcommands aren't checked because we prefer short help for them, deferring to 4607 // `cmd subcmd --help` for more. 4608 self.get_long_about().is_some() 4609 || self.get_before_long_help().is_some() 4610 || self.get_after_long_help().is_some() 4611 || self.get_arguments().any(should_long) 4612 } 4613 4614 // Should we color the help? 4615 pub(crate) fn color_help(&self) -> ColorChoice { 4616 #[cfg(feature = "color")] 4617 if self.is_disable_colored_help_set() { 4618 return ColorChoice::Never; 4619 } 4620 4621 self.get_color() 4622 } 4623} 4624 4625impl Default for Command { 4626 fn default() -> Self { 4627 Self { 4628 name: Default::default(), 4629 long_flag: Default::default(), 4630 short_flag: Default::default(), 4631 display_name: Default::default(), 4632 bin_name: Default::default(), 4633 author: Default::default(), 4634 version: Default::default(), 4635 long_version: Default::default(), 4636 about: Default::default(), 4637 long_about: Default::default(), 4638 before_help: Default::default(), 4639 before_long_help: Default::default(), 4640 after_help: Default::default(), 4641 after_long_help: Default::default(), 4642 aliases: Default::default(), 4643 short_flag_aliases: Default::default(), 4644 long_flag_aliases: Default::default(), 4645 usage_str: Default::default(), 4646 usage_name: Default::default(), 4647 help_str: Default::default(), 4648 disp_ord: Default::default(), 4649 term_w: Default::default(), 4650 max_w: Default::default(), 4651 #[cfg(feature = "help")] 4652 template: Default::default(), 4653 settings: Default::default(), 4654 g_settings: Default::default(), 4655 args: Default::default(), 4656 subcommands: Default::default(), 4657 replacers: Default::default(), 4658 groups: Default::default(), 4659 current_help_heading: Default::default(), 4660 current_disp_ord: Some(0), 4661 subcommand_value_name: Default::default(), 4662 subcommand_heading: Default::default(), 4663 external_value_parser: Default::default(), 4664 long_help_exists: false, 4665 } 4666 } 4667} 4668 4669impl Index<&'_ Id> for Command { 4670 type Output = Arg; 4671 4672 fn index(&self, key: &Id) -> &Self::Output { 4673 self.find(key).expect(INTERNAL_ERROR_MSG) 4674 } 4675} 4676 4677impl From<&'_ Command> for Command { 4678 fn from(cmd: &'_ Command) -> Self { 4679 cmd.clone() 4680 } 4681} 4682 4683impl fmt::Display for Command { 4684 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 4685 write!(f, "{}", self.name) 4686 } 4687} 4688 4689fn two_elements_of<I, T>(mut iter: I) -> Option<(T, T)> 4690where 4691 I: Iterator<Item = T>, 4692{ 4693 let first = iter.next(); 4694 let second = iter.next(); 4695 4696 match (first, second) { 4697 (Some(first), Some(second)) => Some((first, second)), 4698 _ => None, 4699 } 4700} 4701 4702#[test] 4703fn check_auto_traits() { 4704 static_assertions::assert_impl_all!(Command: Send, Sync, Unpin); 4705} 4706