clap_builder/builder/
command.rs

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