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