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