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