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