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