1 #[cfg(debug_assertions)]
2 mod debug_asserts;
3 mod settings;
4 #[cfg(test)]
5 mod tests;
6 
7 pub use self::settings::AppSettings;
8 
9 // Std
10 use std::{
11     collections::HashMap,
12     env,
13     ffi::OsString,
14     fmt,
15     io::{self, BufRead, Write},
16     ops::Index,
17     path::Path,
18 };
19 
20 // Third Party
21 #[cfg(feature = "yaml")]
22 use yaml_rust::Yaml;
23 
24 // Internal
25 use crate::{
26     build::{app::settings::AppFlags, Arg, ArgGroup, ArgSettings},
27     mkeymap::MKeyMap,
28     output::{fmt::Colorizer, Help, HelpWriter, Usage},
29     parse::{ArgMatcher, ArgMatches, Input, Parser},
30     util::{safe_exit, termcolor::ColorChoice, ArgStr, Id, Key},
31     Result as ClapResult, INTERNAL_ERROR_MSG,
32 };
33 
34 // @TODO FIXME (@CreepySkeleton): some of these variants (None) are never constructed
35 #[derive(Clone, Debug, PartialEq, Eq)]
36 pub(crate) enum Propagation {
37     To(Id),
38     Full,
39     #[cfg_attr(not(test), allow(unused))]
40     NextLevel,
41     #[allow(unused)]
42     None,
43 }
44 
45 /// Represents a command line interface which is made up of all possible
46 /// command line arguments and subcommands. Interface arguments and settings are
47 /// configured using the "builder pattern." Once all configuration is complete,
48 /// the [`App::get_matches`] family of methods starts the runtime-parsing
49 /// process. These methods then return information about the user supplied
50 /// arguments (or lack thereof).
51 ///
52 /// **NOTE:** There aren't any mandatory "options" that one must set. The "options" may
53 /// also appear in any order (so long as one of the [`App::get_matches`] methods is the last method
54 /// called).
55 ///
56 /// # Examples
57 ///
58 /// ```no_run
59 /// # use clap::{App, Arg};
60 /// let m = App::new("My Program")
61 ///     .author("Me, me@mail.com")
62 ///     .version("1.0.2")
63 ///     .about("Explains in brief what the program does")
64 ///     .arg(
65 ///         Arg::new("in_file").index(1)
66 ///     )
67 ///     .after_help("Longer explanation to appear after the options when \
68 ///                  displaying the help information from --help or -h")
69 ///     .get_matches();
70 ///
71 /// // Your program logic starts here...
72 /// ```
73 /// [`App::get_matches`]: ./struct.App.html#method.get_matches
74 #[derive(Default, Debug, Clone)]
75 pub struct App<'help> {
76     pub(crate) id: Id,
77     pub(crate) name: String,
78     pub(crate) long_flag: Option<&'help str>,
79     pub(crate) short_flag: Option<char>,
80     pub(crate) bin_name: Option<String>,
81     pub(crate) author: Option<&'help str>,
82     pub(crate) version: Option<&'help str>,
83     pub(crate) long_version: Option<&'help str>,
84     pub(crate) about: Option<&'help str>,
85     pub(crate) long_about: Option<&'help str>,
86     pub(crate) before_help: Option<&'help str>,
87     pub(crate) before_long_help: Option<&'help str>,
88     pub(crate) after_help: Option<&'help str>,
89     pub(crate) after_long_help: Option<&'help str>,
90     pub(crate) aliases: Vec<(&'help str, bool)>, // (name, visible)
91     pub(crate) short_flag_aliases: Vec<(char, bool)>, // (name, visible)
92     pub(crate) long_flag_aliases: Vec<(&'help str, bool)>, // (name, visible)
93     pub(crate) usage_str: Option<&'help str>,
94     pub(crate) usage: Option<String>,
95     pub(crate) help_str: Option<&'help str>,
96     pub(crate) disp_ord: usize,
97     pub(crate) term_w: Option<usize>,
98     pub(crate) max_w: Option<usize>,
99     pub(crate) template: Option<&'help str>,
100     pub(crate) settings: AppFlags,
101     pub(crate) g_settings: AppFlags,
102     pub(crate) args: MKeyMap<'help>,
103     pub(crate) subcommands: Vec<App<'help>>,
104     pub(crate) replacers: HashMap<&'help str, &'help [&'help str]>,
105     pub(crate) groups: Vec<ArgGroup<'help>>,
106     pub(crate) current_help_heading: Option<&'help str>,
107     pub(crate) subcommand_placeholder: Option<&'help str>,
108     pub(crate) subcommand_header: Option<&'help str>,
109 }
110 
111 impl<'help> App<'help> {
112     /// Get the name of the app.
113     #[inline]
get_name(&self) -> &str114     pub fn get_name(&self) -> &str {
115         &self.name
116     }
117 
118     /// Get the short flag of the subcommand.
119     #[inline]
get_short_flag(&self) -> Option<char>120     pub fn get_short_flag(&self) -> Option<char> {
121         self.short_flag
122     }
123 
124     /// Get the long flag of the subcommand.
125     #[inline]
get_long_flag(&self) -> Option<&str>126     pub fn get_long_flag(&self) -> Option<&str> {
127         self.long_flag
128     }
129 
130     /// Get the name of the binary.
131     #[inline]
get_bin_name(&self) -> Option<&str>132     pub fn get_bin_name(&self) -> Option<&str> {
133         self.bin_name.as_deref()
134     }
135 
136     /// Set binary name. Uses `&mut self` instead of `self`.
set_bin_name<S: Into<String>>(&mut self, name: S)137     pub fn set_bin_name<S: Into<String>>(&mut self, name: S) {
138         self.bin_name = Some(name.into());
139     }
140 
141     /// Get the help message specified via [`App::about`].
142     ///
143     /// [`App::about`]: ./struct.App.html#method.about
144     #[inline]
get_about(&self) -> Option<&str>145     pub fn get_about(&self) -> Option<&str> {
146         self.about.as_deref()
147     }
148 
149     /// Iterate through the *visible* aliases for this subcommand.
150     #[inline]
get_visible_aliases(&self) -> impl Iterator<Item = &str>151     pub fn get_visible_aliases(&self) -> impl Iterator<Item = &str> {
152         self.aliases.iter().filter(|(_, vis)| *vis).map(|a| a.0)
153     }
154 
155     /// Iterate through the *visible* short aliases for this subcommand.
156     #[inline]
get_visible_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_157     pub fn get_visible_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ {
158         self.short_flag_aliases
159             .iter()
160             .filter(|(_, vis)| *vis)
161             .map(|a| a.0)
162     }
163 
164     /// Iterate through the *visible* short aliases for this subcommand.
165     #[inline]
get_visible_long_flag_aliases(&self) -> impl Iterator<Item = &'help str> + '_166     pub fn get_visible_long_flag_aliases(&self) -> impl Iterator<Item = &'help str> + '_ {
167         self.long_flag_aliases
168             .iter()
169             .filter(|(_, vis)| *vis)
170             .map(|a| a.0)
171     }
172 
173     /// Iterate through the set of *all* the aliases for this subcommand, both visible and hidden.
174     #[inline]
get_all_aliases(&self) -> impl Iterator<Item = &str>175     pub fn get_all_aliases(&self) -> impl Iterator<Item = &str> {
176         self.aliases.iter().map(|a| a.0)
177     }
178 
179     /// Iterate through the set of *all* the short aliases for this subcommand, both visible and hidden.
180     #[inline]
get_all_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_181     pub fn get_all_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ {
182         self.short_flag_aliases.iter().map(|a| a.0)
183     }
184 
185     /// Iterate through the set of *all* the long aliases for this subcommand, both visible and hidden.
186     #[inline]
get_all_long_flag_aliases(&self) -> impl Iterator<Item = &'help str> + '_187     pub fn get_all_long_flag_aliases(&self) -> impl Iterator<Item = &'help str> + '_ {
188         self.long_flag_aliases.iter().map(|a| a.0)
189     }
190 
191     /// Iterate through the set of subcommands, getting a reference to each.
192     #[inline]
get_subcommands(&self) -> impl Iterator<Item = &App<'help>>193     pub fn get_subcommands(&self) -> impl Iterator<Item = &App<'help>> {
194         self.subcommands.iter()
195     }
196 
197     /// Iterate through the set of subcommands, getting a mutable reference to each.
198     #[inline]
get_subcommands_mut(&mut self) -> impl Iterator<Item = &mut App<'help>>199     pub fn get_subcommands_mut(&mut self) -> impl Iterator<Item = &mut App<'help>> {
200         self.subcommands.iter_mut()
201     }
202 
203     /// Iterate through the set of arguments.
204     #[inline]
get_arguments(&self) -> impl Iterator<Item = &Arg<'help>>205     pub fn get_arguments(&self) -> impl Iterator<Item = &Arg<'help>> {
206         self.args.args.iter()
207     }
208 
209     /// Get the list of *positional* arguments.
210     #[inline]
get_positionals(&self) -> impl Iterator<Item = &Arg<'help>>211     pub fn get_positionals(&self) -> impl Iterator<Item = &Arg<'help>> {
212         self.get_arguments().filter(|a| a.is_positional())
213     }
214 
215     /// Iterate through the *flags* that don't have custom heading.
get_flags_with_no_heading(&self) -> impl Iterator<Item = &Arg<'help>>216     pub fn get_flags_with_no_heading(&self) -> impl Iterator<Item = &Arg<'help>> {
217         self.get_arguments()
218             .filter(|a| !a.is_set(ArgSettings::TakesValue) && a.get_index().is_none())
219             .filter(|a| a.get_help_heading().is_none())
220     }
221 
222     /// Iterate through the *options* that don't have custom heading.
get_opts_with_no_heading(&self) -> impl Iterator<Item = &Arg<'help>>223     pub fn get_opts_with_no_heading(&self) -> impl Iterator<Item = &Arg<'help>> {
224         self.get_arguments()
225             .filter(|a| a.is_set(ArgSettings::TakesValue) && a.get_index().is_none())
226             .filter(|a| a.get_help_heading().is_none())
227     }
228 
229     /// Get a list of all arguments the given argument conflicts with.
230     ///
231     /// ### Panics
232     ///
233     /// If the given arg contains a conflict with an argument that is unknown to
234     /// this `App`.
get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg<'help>>235     pub fn get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg<'help>> // FIXME: This could probably have been an iterator
236     {
237         arg.blacklist
238             .iter()
239             .map(|id| {
240                 self.args.args.iter().find(|arg| arg.id == *id).expect(
241                     "App::get_arg_conflicts_with: \
242                     The passed arg conflicts with an arg unknown to the app",
243                 )
244             })
245             .collect()
246     }
247 
248     /// Returns `true` if the given [`AppSettings`] variant is currently set in
249     /// this `App` (checks both [local] and [global settings]).
250     ///
251     /// [`AppSettings`]: ./enum.AppSettings.html
252     /// [local]: ./struct.App.html#method.setting
253     /// [global settings]: ./struct.App.html#method.global_setting
254     #[inline]
is_set(&self, s: AppSettings) -> bool255     pub fn is_set(&self, s: AppSettings) -> bool {
256         self.settings.is_set(s) || self.g_settings.is_set(s)
257     }
258 
259     /// Returns `true` if this `App` has subcommands.
260     #[inline]
has_subcommands(&self) -> bool261     pub fn has_subcommands(&self) -> bool {
262         !self.subcommands.is_empty()
263     }
264 
265     /// Find subcommand such that its name or one of aliases equals `name`.
266     ///
267     /// This does not recurse through subcommands of subcommands.
268     #[inline]
find_subcommand<T>(&self, name: &T) -> Option<&App<'help>> where T: PartialEq<str> + ?Sized,269     pub fn find_subcommand<T>(&self, name: &T) -> Option<&App<'help>>
270     where
271         T: PartialEq<str> + ?Sized,
272     {
273         self.get_subcommands().find(|s| s.aliases_to(name))
274     }
275 }
276 
277 impl<'help> App<'help> {
278     /// Creates a new instance of an `App` requiring a `name`.
279     ///
280     /// It is common, but not required, to use binary name as the `name`. This
281     /// name will only be displayed to the user when they request to print
282     /// version or help and usage information.
283     ///
284     /// An `App` represents a command line interface (CLI) which is made up of
285     /// all possible command line arguments and subcommands. "Subcommands" are
286     /// sub-CLIs with their own arguments, settings, and even subcommands
287     /// forming a sort of hierarchy.
288     ///
289     /// # Examples
290     ///
291     /// ```no_run
292     /// # use clap::App;
293     /// App::new("My Program")
294     /// # ;
295     /// ```
new<S: Into<String>>(name: S) -> Self296     pub fn new<S: Into<String>>(name: S) -> Self {
297         let name = name.into();
298         App {
299             id: Id::from(&*name),
300             name,
301             disp_ord: 999,
302             ..Default::default()
303         }
304     }
305 
306     /// Sets a string of author(s) that will be displayed to the user when they
307     /// request the help message.
308     ///
309     /// **Pro-tip:** Use `clap`s convenience macro [`crate_authors!`] to
310     /// automatically set your application's author(s) to the same thing as your
311     /// crate at compile time.
312     ///
313     /// See the [`examples/`] directory for more information.
314     ///
315     /// # Examples
316     ///
317     /// ```no_run
318     /// # use clap::App;
319     /// App::new("myprog")
320     ///      .author("Me, me@mymain.com")
321     /// # ;
322     /// ```
323     /// [`crate_authors!`]: ./macro.crate_authors!.html
324     /// [`examples/`]: https://github.com/clap-rs/clap/tree/master/examples
author<S: Into<&'help str>>(mut self, author: S) -> Self325     pub fn author<S: Into<&'help str>>(mut self, author: S) -> Self {
326         self.author = Some(author.into());
327         self
328     }
329 
330     /// Overrides the runtime-determined name of the binary. This should only be
331     /// used when absolutely necessary, such as when the binary name for your
332     /// application is misleading, or perhaps *not* how the user should invoke
333     /// your program.
334     ///
335     /// Normally, the binary name is used in help and error messages. `clap`
336     /// automatically determines the binary name at runtime, however by manually
337     /// setting the binary name, one can effectively override what will be
338     /// displayed in the help or error messages.
339     ///
340     /// **Pro-tip:** When building things such as third party `cargo`
341     /// subcommands, this setting **should** be used!
342     ///
343     /// **NOTE:** This *does not* change or set the name of the binary file on
344     /// disk. It only changes what clap thinks the name is for the purposes of
345     /// error or help messages.
346     ///
347     /// # Examples
348     ///
349     /// ```no_run
350     /// # use clap::App;
351     /// App::new("My Program")
352     ///      .bin_name("my_binary")
353     /// # ;
354     /// ```
bin_name<S: Into<String>>(mut self, name: S) -> Self355     pub fn bin_name<S: Into<String>>(mut self, name: S) -> Self {
356         self.bin_name = Some(name.into());
357         self
358     }
359 
360     /// Sets a string describing what the program does. This will be displayed
361     /// when the user requests the short format help message (`-h`).
362     ///
363     /// `clap` can display two different help messages, a [long format] and a
364     /// [short format] depending on whether the user used `-h` (short) or
365     /// `--help` (long). This method sets the message during the short format
366     /// (`-h`) message. However, if no long format message is configured, this
367     /// message will be displayed for *both* the long format, or short format
368     /// help message.
369     ///
370     /// **NOTE:** Only [`App::about`] (short format) is used in completion
371     /// script generation in order to be concise.
372     ///
373     /// # Examples
374     ///
375     /// ```no_run
376     /// # use clap::App;
377     /// App::new("myprog")
378     ///     .about("Does really amazing things for great people")
379     /// # ;
380     /// ```
381     /// [long format]: ./struct.App.html#method.long_about
382     /// [short format]: ./struct.App.html#method.about
383     /// [`App::about`]: ./struct.App.html#method.about
about<S: Into<&'help str>>(mut self, about: S) -> Self384     pub fn about<S: Into<&'help str>>(mut self, about: S) -> Self {
385         self.about = Some(about.into());
386         self
387     }
388 
389     /// Sets a long format string describing what the program does. This will be
390     /// displayed when the user requests the long format help message (`--help`).
391     ///
392     /// ## Advanced
393     ///
394     /// `clap` can display two different help messages, a [long format] and a
395     /// [short format] depending on whether the user used `-h` (short) or
396     /// `--help` (long). This method sets the message during the long format
397     /// (`--help`) message. However, if no short format message is configured,
398     /// this message will be displayed for *both* the long format, or short
399     /// format help message.
400     ///
401     /// **NOTE:** Only [`App::about`] (short format) is used in completion
402     /// script generation in order to be concise.
403     ///
404     /// # Examples
405     ///
406     /// ```no_run
407     /// # use clap::App;
408     /// App::new("myprog")
409     ///     .long_about(
410     /// "Does really amazing things to great people. Now let's talk a little
411     ///  more in depth about how this subcommand really works. It may take about
412     ///  a few lines of text, but that's ok!")
413     /// # ;
414     /// ```
415     /// [long format]: ./struct.App.html#method.long_about
416     /// [short format]: ./struct.App.html#method.about
417     /// [`App::about`]: ./struct.App.html#method.about
long_about<S: Into<&'help str>>(mut self, about: S) -> Self418     pub fn long_about<S: Into<&'help str>>(mut self, about: S) -> Self {
419         self.long_about = Some(about.into());
420         self
421     }
422 
423     /// (Re)Sets the program's name. This will be displayed when displaying help
424     /// or version messages.
425     ///
426     /// **Pro-tip:** This function is particularly useful when configuring a
427     /// program via `App::from(yaml)` in conjunction with the [`crate_name!`]
428     /// macro to derive the program's name from its `Cargo.toml`.
429     ///
430     /// # Examples
431     ///
432     /// ```ignore
433     /// # use clap::{App, load_yaml};
434     /// let yaml = load_yaml!("app.yaml");
435     /// let app = App::from(yaml)
436     ///     .name(crate_name!());
437     ///
438     /// // continued logic goes here, such as `app.get_matches()` etc.
439     /// ```
440     ///
441     /// [`crate_name!`]: ./macro.crate_name.html
name<S: Into<String>>(mut self, name: S) -> Self442     pub fn name<S: Into<String>>(mut self, name: S) -> Self {
443         self.name = name.into();
444         self
445     }
446 
447     /// Adds additional help information to be displayed at the end of the
448     /// auto-generated help. This is often used to describe how to use the
449     /// arguments, caveats to be noted, or license and contact information.
450     ///
451     /// **NOTE:** If only `after_long_help` is provided, and not [`App::after_help`] but the user requests
452     /// `-h` clap will still display the contents of `after_help` appropriately.
453     ///
454     /// # Examples
455     ///
456     /// ```no_run
457     /// # use clap::App;
458     /// App::new("myprog")
459     ///     .after_help("Does really amazing things for great people... but be careful with -R!")
460     /// # ;
461     /// ```
462     ///
463     /// [`App::after_help`]: ./struct.App.html#method.after_help
after_help<S: Into<&'help str>>(mut self, help: S) -> Self464     pub fn after_help<S: Into<&'help str>>(mut self, help: S) -> Self {
465         self.after_help = Some(help.into());
466         self
467     }
468 
469     /// Adds additional help information to be displayed in addition to auto-generated help. This
470     /// information is displayed **after** the auto-generated help information and is meant to be
471     /// more verbose than `after_help`. This is often used to describe how to use the arguments, or
472     /// caveats to be noted in man pages.
473     ///
474     /// **NOTE:** If only `after_help` is provided, and not [`App::after_long_help`] but the user
475     /// requests `--help`, clap will still display the contents of `after_help` appropriately.
476     ///
477     /// # Examples
478     ///
479     /// ```no_run
480     /// # use clap::App;
481     /// App::new("myprog")
482     ///     .after_long_help("Does really amazing things to great people... but be careful with -R, \
483     ///                      like, for real, be careful with this!")
484     /// # ;
485     /// ```
486     /// [`App::after_long_help`]: ./struct.App.html#method.after_long_help
after_long_help<S: Into<&'help str>>(mut self, help: S) -> Self487     pub fn after_long_help<S: Into<&'help str>>(mut self, help: S) -> Self {
488         self.after_long_help = Some(help.into());
489         self
490     }
491 
492     /// Adds additional help information to be displayed prior to the
493     /// auto-generated help. This is often used for header, copyright, or
494     /// license information.
495     ///
496     /// **NOTE:** If only `before_long_help` is provided, and not [`App::before_help`] but the user
497     /// requests `-h` clap will still display the contents of `before_long_help` appropriately.
498     ///
499     /// # Examples
500     ///
501     /// ```no_run
502     /// # use clap::App;
503     /// App::new("myprog")
504     ///     .before_help("Some info I'd like to appear before the help info")
505     /// # ;
506     /// ```
507     /// [`App::before_help`]: ./struct.App.html#method.before_help
before_help<S: Into<&'help str>>(mut self, help: S) -> Self508     pub fn before_help<S: Into<&'help str>>(mut self, help: S) -> Self {
509         self.before_help = Some(help.into());
510         self
511     }
512 
513     /// Adds additional help information to be displayed prior to the
514     /// auto-generated help. This is often used for header, copyright, or
515     /// license information.
516     ///
517     /// **NOTE:** If only `before_help` is provided, and not [`App::before_long_help`] but the user
518     /// requests `--help`, clap will still display the contents of `before_help` appropriately.
519     ///
520     /// # Examples
521     ///
522     /// ```no_run
523     /// # use clap::App;
524     /// App::new("myprog")
525     ///     .before_long_help("Some verbose and long info I'd like to appear before the help info")
526     /// # ;
527     /// ```
528     /// [`App::before_long_help`]: ./struct.App.html#method.before_long_help
before_long_help<S: Into<&'help str>>(mut self, help: S) -> Self529     pub fn before_long_help<S: Into<&'help str>>(mut self, help: S) -> Self {
530         self.before_long_help = Some(help.into());
531         self
532     }
533 
534     /// Allows the subcommand to be used as if it were an [`Arg::short`].
535     ///
536     /// Sets the short version of the subcommand flag without the preceding `-`.
537     ///
538     /// # Examples
539     ///
540     /// ```
541     /// # use clap::{App, Arg};
542     /// let matches = App::new("pacman")
543     ///     .subcommand(
544     ///         App::new("sync").short_flag('S').arg(
545     ///             Arg::new("search")
546     ///                 .short('s')
547     ///                 .long("search")
548     ///                 .about("search remote repositories for matching strings"),
549     ///         ),
550     ///     )
551     ///     .get_matches_from(vec!["pacman", "-Ss"]);
552     ///
553     /// assert_eq!(matches.subcommand_name().unwrap(), "sync");
554     /// let sync_matches = matches.subcommand_matches("sync").unwrap();
555     /// assert!(sync_matches.is_present("search"));
556     /// ```
557     /// [`Arg::short`]: ./struct.Arg.html#method.short
short_flag(mut self, short: char) -> Self558     pub fn short_flag(mut self, short: char) -> Self {
559         self.short_flag = Some(short);
560         self
561     }
562 
563     /// Allows the subcommand to be used as if it were an [`Arg::long`].
564     ///
565     /// Sets the long version of the subcommand flag without the preceding `--`.
566     ///
567     /// **NOTE:** Any leading `-` characters will be stripped.
568     ///
569     /// # Examples
570     ///
571     /// To set `long_flag` use a word containing valid UTF-8 codepoints. If you supply a double leading
572     /// `--` such as `--sync` they will be stripped. Hyphens in the middle of the word; however,
573     /// will *not* be stripped (i.e. `sync-file` is allowed).
574     ///
575     /// ```
576     /// # use clap::{App, Arg};
577     /// let matches = App::new("pacman")
578     ///     .subcommand(
579     ///         App::new("sync").long_flag("sync").arg(
580     ///             Arg::new("search")
581     ///                 .short('s')
582     ///                 .long("search")
583     ///                 .about("search remote repositories for matching strings"),
584     ///         ),
585     ///     )
586     ///     .get_matches_from(vec!["pacman", "--sync", "--search"]);
587     ///
588     /// assert_eq!(matches.subcommand_name().unwrap(), "sync");
589     /// let sync_matches = matches.subcommand_matches("sync").unwrap();
590     /// assert!(sync_matches.is_present("search"));
591     /// ```
592     ///
593     /// [`Arg::long`]: ./struct.Arg.html#method.long
long_flag(mut self, long: &'help str) -> Self594     pub fn long_flag(mut self, long: &'help str) -> Self {
595         self.long_flag = Some(long.trim_start_matches(|c| c == '-'));
596         self
597     }
598 
599     /// Sets a string of the version number to be displayed when displaying the
600     /// short format version message (`-V`) or the help message.
601     ///
602     /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to
603     /// automatically set your application's version to the same thing as your
604     /// crate at compile time. See the [`examples/`] directory for more
605     /// information.
606     ///
607     /// `clap` can display two different version messages, a [long format] and a
608     /// [short format] depending on whether the user used `-V` (short) or
609     /// `--version` (long). This method sets the message during the short format
610     /// (`-V`). However, if no long format message is configured, this
611     /// message will be displayed for *both* the long format, or short format
612     /// version message.
613     ///
614     /// # Examples
615     ///
616     /// ```no_run
617     /// # use clap::App;
618     /// App::new("myprog")
619     ///     .version("v0.1.24")
620     /// # ;
621     /// ```
622     /// [`crate_version!`]: ./macro.crate_version!.html
623     /// [`examples/`]: https://github.com/clap-rs/clap/tree/master/examples
624     /// [`App::long_version`]: ./struct.App.html#method.long_version
version<S: Into<&'help str>>(mut self, ver: S) -> Self625     pub fn version<S: Into<&'help str>>(mut self, ver: S) -> Self {
626         self.version = Some(ver.into());
627         self
628     }
629 
630     /// Sets a string of the version number to be displayed when the user
631     /// requests the long format version message (`--version`) or the help
632     /// message.
633     ///
634     /// This is often used to display things such as commit ID, or compile time
635     /// configured options.
636     ///
637     /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to
638     /// automatically set your application's version to the same thing as your
639     /// crate at compile time. See the [`examples/`] directory for more
640     /// information.
641     ///
642     /// `clap` can display two different version messages, a [long format] and a
643     /// [short format] depending on whether the user used `-V` (short) or
644     /// `--version` (long). This method sets the message during the long format
645     /// (`--version`). However, if no short format message is configured, this
646     /// message will be displayed for *both* the long format, or short format
647     /// version message.
648     ///
649     /// # Examples
650     ///
651     /// ```no_run
652     /// # use clap::App;
653     /// App::new("myprog")
654     ///     .long_version(
655     /// "v0.1.24
656     ///  commit: abcdef89726d
657     ///  revision: 123
658     ///  release: 2
659     ///  binary: myprog")
660     /// # ;
661     /// ```
662     /// [`crate_version!`]: ./macro.crate_version!.html
663     /// [`examples/`]: https://github.com/kbknapp/clap-rs/tree/master/examples
664     /// [`App::version`]: ./struct.App.html#method.version
long_version<S: Into<&'help str>>(mut self, ver: S) -> Self665     pub fn long_version<S: Into<&'help str>>(mut self, ver: S) -> Self {
666         self.long_version = Some(ver.into());
667         self
668     }
669 
670     /// Overrides the `clap` generated usage string.
671     ///
672     /// This will be displayed to the user when errors are found in argument parsing.
673     ///
674     /// **CAUTION:** Using this setting disables `clap`s "context-aware" usage
675     /// strings. After this setting is set, this will be *the only* usage string
676     /// displayed to the user!
677     ///
678     /// **NOTE:** This will not replace the entire help message, *only* the portion
679     /// showing the usage.
680     ///
681     /// # Examples
682     ///
683     /// ```no_run
684     /// # use clap::{App, Arg};
685     /// App::new("myprog")
686     ///     .override_usage("myapp [-clDas] <some_file>")
687     /// # ;
688     /// ```
689     /// [`ArgMatches::usage`]: ./struct.ArgMatches.html#method.usage
override_usage<S: Into<&'help str>>(mut self, usage: S) -> Self690     pub fn override_usage<S: Into<&'help str>>(mut self, usage: S) -> Self {
691         self.usage_str = Some(usage.into());
692         self
693     }
694 
695     /// Overrides the `clap` generated help message. This should only be used
696     /// when the auto-generated message does not suffice.
697     ///
698     /// This will be displayed to the user when they use `--help` or `-h`.
699     ///
700     /// **NOTE:** This replaces the **entire** help message, so nothing will be
701     /// auto-generated.
702     ///
703     /// **NOTE:** This **only** replaces the help message for the current
704     /// command, meaning if you are using subcommands, those help messages will
705     /// still be auto-generated unless you specify a [`Arg::override_help`] for
706     /// them as well.
707     ///
708     /// # Examples
709     ///
710     /// ```no_run
711     /// # use clap::{App, Arg};
712     /// App::new("myapp")
713     ///     .override_help("myapp v1.0\n\
714     ///            Does awesome things\n\
715     ///            (C) me@mail.com\n\n\
716     ///
717     ///            USAGE: myapp <opts> <comamnd>\n\n\
718     ///
719     ///            Options:\n\
720     ///            -h, --help       Display this message\n\
721     ///            -V, --version    Display version info\n\
722     ///            -s <stuff>       Do something with stuff\n\
723     ///            -v               Be verbose\n\n\
724     ///
725     ///            Commmands:\n\
726     ///            help             Prints this message\n\
727     ///            work             Do some work")
728     /// # ;
729     /// ```
730     /// [`Arg::override_help`]: ./struct.Arg.html#method.override_help
override_help<S: Into<&'help str>>(mut self, help: S) -> Self731     pub fn override_help<S: Into<&'help str>>(mut self, help: S) -> Self {
732         self.help_str = Some(help.into());
733         self
734     }
735 
736     /// Sets the help template to be used, overriding the default format.
737     ///
738     /// **NOTE:** The template system is by design very simple. Therefore, the
739     /// tags have to be written in the lowercase and without spacing.
740     ///
741     /// Tags are given inside curly brackets.
742     ///
743     /// Valid tags are:
744     ///
745     ///   * `{bin}`                 - Binary name.
746     ///   * `{version}`             - Version number.
747     ///   * `{author}`              - Author information.
748     ///   * `{author-with-newline}` - Author followed by `\n`.
749     ///   * `{about}`               - General description (from [`App::about`] or
750     ///                               [`App::long_about`]).
751     ///   * `{about-with-newline}`  - About followed by `\n`.
752     ///   * `{usage-heading}`       - Automatically generated usage heading.
753     ///   * `{usage}`               - Automatically generated or given usage string.
754     ///   * `{all-args}`            - Help for all arguments (options, flags, positional
755     ///                               arguments, and subcommands) including titles.
756     ///   * `{unified}`             - Unified help for options and flags. Note, you must *also*
757     ///                               set [`AppSettings::UnifiedHelpMessage`] to fully merge both
758     ///                               options and flags, otherwise the ordering is "best effort".
759     ///   * `{flags}`               - Help for flags.
760     ///   * `{options}`             - Help for options.
761     ///   * `{positionals}`         - Help for positional arguments.
762     ///   * `{subcommands}`         - Help for subcommands.
763     ///   * `{after-help}`          - Help from [`App::after_help`] or [`App::after_long_help`].
764     ///   * `{before-help}`         - Help from [`App::before_help`] or [`App::before_long_help`].
765     ///
766     /// # Examples
767     ///
768     /// ```no_run
769     /// # use clap::App;
770     /// App::new("myprog")
771     ///     .version("1.0")
772     ///     .help_template("{bin} ({version}) - {usage}")
773     /// # ;
774     /// ```
775     /// [`App::about`]: ./struct.App.html#method.about
776     /// [`App::long_about`]: ./struct.App.html#method.long_about
777     /// [`App::after_help`]: ./struct.App.html#method.after_help
778     /// [`App::after_long_help`]: ./struct.App.html#method.after_long_help
779     /// [`App::before_help`]: ./struct.App.html#method.before_help
780     /// [`App::before_long_help`]: ./struct.App.html#method.before_long_help
781     /// [`AppSettings::UnifiedHelpMessage`]: ./enum.AppSettings.html#variant.UnifiedHelpMessage
help_template<S: Into<&'help str>>(mut self, s: S) -> Self782     pub fn help_template<S: Into<&'help str>>(mut self, s: S) -> Self {
783         self.template = Some(s.into());
784         self
785     }
786 
787     /// Enables a single settings for the current (this `App` instance) command or subcommand.
788     ///
789     /// See [`AppSettings`] for a full list of possibilities and examples.
790     ///
791     /// # Examples
792     ///
793     /// ```no_run
794     /// # use clap::{App, AppSettings};
795     /// App::new("myprog")
796     ///     .setting(AppSettings::SubcommandRequired)
797     ///     .setting(AppSettings::WaitOnError)
798     /// # ;
799     /// ```
800     /// [`AppSettings`]: ./enum.AppSettings.html
801     #[inline]
setting(mut self, setting: AppSettings) -> Self802     pub fn setting(mut self, setting: AppSettings) -> Self {
803         self.settings.set(setting);
804         self
805     }
806 
807     /// Disables a single setting for the current (this `App` instance) command or subcommand.
808     ///
809     /// See [`AppSettings`] for a full list of possibilities and examples.
810     ///
811     /// # Examples
812     ///
813     /// ```no_run
814     /// # use clap::{App, AppSettings};
815     /// App::new("myprog")
816     ///     .unset_setting(AppSettings::ColorAuto)
817     /// # ;
818     /// ```
819     /// [`AppSettings`]: ./enum.AppSettings.html
820     /// [global]: ./struct.App.html#method.global_setting
821     #[inline]
unset_setting(mut self, setting: AppSettings) -> Self822     pub fn unset_setting(mut self, setting: AppSettings) -> Self {
823         self.settings.unset(setting);
824         self.g_settings.unset(setting);
825         self
826     }
827 
828     /// Enables a single setting that is propagated **down** through all child
829     /// subcommands.
830     ///
831     /// See [`AppSettings`] for a full list of possibilities and examples.
832     ///
833     /// **NOTE**: The setting is *only* propagated *down* and not up through parent commands.
834     ///
835     /// # Examples
836     ///
837     /// ```no_run
838     /// # use clap::{App, AppSettings};
839     /// App::new("myprog")
840     ///     .global_setting(AppSettings::SubcommandRequired)
841     /// # ;
842     /// ```
843     /// [`AppSettings`]: ./enum.AppSettings.html
844     #[inline]
global_setting(mut self, setting: AppSettings) -> Self845     pub fn global_setting(mut self, setting: AppSettings) -> Self {
846         self.settings.set(setting);
847         self.g_settings.set(setting);
848         self
849     }
850 
851     /// Disables a global setting, and stops propagating down to child
852     /// subcommands.
853     ///
854     /// See [`AppSettings`] for a full list of possibilities and examples.
855     ///
856     /// **NOTE:** The setting being unset will be unset from both local and
857     /// [global] settings.
858     ///
859     /// # Examples
860     ///
861     /// ```no_run
862     /// # use clap::{App, AppSettings};
863     /// App::new("myprog")
864     ///     .unset_global_setting(AppSettings::ColorAuto)
865     /// # ;
866     /// ```
867     /// [`AppSettings`]: ./enum.AppSettings.html
868     /// [global]: ./struct.App.html#method.global_setting
869     #[inline]
unset_global_setting(mut self, setting: AppSettings) -> Self870     pub fn unset_global_setting(mut self, setting: AppSettings) -> Self {
871         self.settings.unset(setting);
872         self.g_settings.unset(setting);
873         self
874     }
875 
876     /// Sets the terminal width at which to wrap help messages. Defaults to
877     /// `120`. Using `0` will ignore terminal widths and use source formatting.
878     ///
879     /// `clap` automatically tries to determine the terminal width on Unix,
880     /// Linux, OSX and Windows if the `wrap_help` cargo "feature" has been enabled
881     /// at compile time. If the terminal width cannot be determined, `clap`
882     /// fall back to `100`.
883     ///
884     /// **NOTE:** This setting applies globally and *not* on a per-command basis.
885     ///
886     /// **NOTE:** This setting must be set **before** any subcommands are added!
887     ///
888     /// # Platform Specific
889     ///
890     /// Only Unix, Linux, OSX and Windows support automatic determination of
891     /// terminal width. Even on those platforms, this setting is useful if for
892     /// any reason the terminal width cannot be determined.
893     ///
894     /// # Examples
895     ///
896     /// ```no_run
897     /// # use clap::App;
898     /// App::new("myprog")
899     ///     .term_width(80)
900     /// # ;
901     /// ```
902     #[inline]
term_width(mut self, width: usize) -> Self903     pub fn term_width(mut self, width: usize) -> Self {
904         self.term_w = Some(width);
905         self
906     }
907 
908     /// Sets the maximum terminal width at which to wrap help messages. Using `0`
909     /// will ignore terminal widths and use source formatting.
910     ///
911     /// `clap` automatically tries to determine the terminal width on Unix,
912     /// Linux, OSX and Windows if the `wrap_help` cargo "feature" has been
913     /// enabled at compile time, but one might want to limit the size to some
914     /// maximum (e.g. when the terminal is running fullscreen).
915     ///
916     /// **NOTE:** This setting applies globally and *not* on a per-command basis.
917     ///
918     /// **NOTE:** This setting must be set **before** any subcommands are added!
919     ///
920     /// # Platform Specific
921     ///
922     /// Only Unix, Linux, OSX and Windows support automatic determination of terminal width.
923     ///
924     /// # Examples
925     ///
926     /// ```no_run
927     /// # use clap::App;
928     /// App::new("myprog")
929     ///     .max_term_width(100)
930     /// # ;
931     /// ```
932     #[inline]
max_term_width(mut self, w: usize) -> Self933     pub fn max_term_width(mut self, w: usize) -> Self {
934         self.max_w = Some(w);
935         self
936     }
937 
938     /// Adds an [argument] to the list of valid possibilities.
939     ///
940     /// # Examples
941     ///
942     /// ```no_run
943     /// # use clap::{App, Arg};
944     /// App::new("myprog")
945     ///     // Adding a single "flag" argument with a short and help text, using Arg::new()
946     ///     .arg(
947     ///         Arg::new("debug")
948     ///            .short('d')
949     ///            .about("turns on debugging mode")
950     ///     )
951     ///     // Adding a single "option" argument with a short, a long, and help text using the less
952     ///     // verbose Arg::from()
953     ///     .arg(
954     ///         Arg::from("-c --config=[CONFIG] 'Optionally sets a config file to use'")
955     ///     )
956     /// # ;
957     /// ```
958     /// [argument]: ./struct.Arg.html
arg<A: Into<Arg<'help>>>(mut self, a: A) -> Self959     pub fn arg<A: Into<Arg<'help>>>(mut self, a: A) -> Self {
960         let mut arg = a.into();
961         if let Some(help_heading) = self.current_help_heading {
962             arg = arg.help_heading(Some(help_heading));
963         }
964         self.args.push(arg);
965         self
966     }
967 
968     /// Set a custom section heading for future args. Every call to [`App::arg`]
969     /// (and its related methods) will use this header (instead of the default
970     /// header for the specified argument type) until a subsequent call to
971     /// [`App::help_heading`] or [`App::stop_custom_headings`].
972     ///
973     /// This is useful if the default `FLAGS`, `OPTIONS`, or `ARGS` headings are
974     /// not specific enough for one's use case.
975     ///
976     /// [`App::arg`]: ./struct.App.html#method.arg
977     /// [`App::help_heading`]: ./struct.App.html#method.help_heading
978     /// [`App::stop_custom_headings`]: ./struct.App.html#method.stop_custom_headings
979     #[inline]
help_heading(mut self, heading: &'help str) -> Self980     pub fn help_heading(mut self, heading: &'help str) -> Self {
981         self.current_help_heading = Some(heading);
982         self
983     }
984 
985     /// Stop using [custom argument headings] and return to default headings.
986     ///
987     /// [custom argument headings]: ./struct.App.html#method.help_heading
988     #[inline]
stop_custom_headings(mut self) -> Self989     pub fn stop_custom_headings(mut self) -> Self {
990         self.current_help_heading = None;
991         self
992     }
993 
994     /// Adds multiple [arguments] to the list of valid possibilities.
995     ///
996     /// # Examples
997     ///
998     /// ```no_run
999     /// # use clap::{App, Arg};
1000     /// App::new("myprog")
1001     ///     .args(&[
1002     ///         Arg::from("[debug] -d 'turns on debugging info'"),
1003     ///         Arg::new("input").index(1).about("the input file to use")
1004     ///     ])
1005     /// # ;
1006     /// ```
1007     /// [arguments]: ./struct.Arg.html
args<I, T>(mut self, args: I) -> Self where I: IntoIterator<Item = T>, T: Into<Arg<'help>>,1008     pub fn args<I, T>(mut self, args: I) -> Self
1009     where
1010         I: IntoIterator<Item = T>,
1011         T: Into<Arg<'help>>,
1012     {
1013         // @TODO @perf @p4 @v3-beta: maybe extend_from_slice would be possible and perform better?
1014         // But that may also not let us do `&["-a 'some'", "-b 'other']` because of not Into<Arg>
1015         for arg in args.into_iter() {
1016             self.args.push(arg.into());
1017         }
1018         self
1019     }
1020 
1021     /// If this `App` instance is a subcommand, this method adds an alias, which
1022     /// allows this subcommand to be accessed via *either* the original name, or
1023     /// this given alias. This is more efficient and easier than creating
1024     /// multiple hidden subcommands as one only needs to check for the existence
1025     /// of this command, and not all aliased variants.
1026     ///
1027     /// **NOTE:** Aliases defined with this method are *hidden* from the help
1028     /// message. If you're looking for aliases that will be displayed in the help
1029     /// message, see [`App::visible_alias`].
1030     ///
1031     /// **NOTE:** When using aliases and checking for the existence of a
1032     /// particular subcommand within an [`ArgMatches`] struct, one only needs to
1033     /// search for the original name and not all aliases.
1034     ///
1035     /// # Examples
1036     ///
1037     /// ```rust
1038     /// # use clap::{App, Arg, };
1039     /// let m = App::new("myprog")
1040     ///     .subcommand(App::new("test")
1041     ///         .alias("do-stuff"))
1042     ///     .get_matches_from(vec!["myprog", "do-stuff"]);
1043     /// assert_eq!(m.subcommand_name(), Some("test"));
1044     /// ```
1045     /// [`ArgMatches`]: ./struct.ArgMatches.html
1046     /// [`App::visible_alias`]: ./struct.App.html#method.visible_alias
alias<S: Into<&'help str>>(mut self, name: S) -> Self1047     pub fn alias<S: Into<&'help str>>(mut self, name: S) -> Self {
1048         self.aliases.push((name.into(), false));
1049         self
1050     }
1051 
1052     /// Allows adding an alias, which function as "hidden" short flag subcommands that
1053     /// automatically dispatch as if this subcommand was used. This is more efficient, and easier
1054     /// than creating multiple hidden subcommands as one only needs to check for the existence of
1055     /// this command, and not all variants.
1056     ///
1057     /// # Examples
1058     ///
1059     /// ```no_run
1060     /// # use clap::{App, Arg, };
1061     /// let m = App::new("myprog")
1062     ///             .subcommand(App::new("test").short_flag('t')
1063     ///                 .short_flag_alias('d'))
1064     ///             .get_matches_from(vec!["myprog", "-d"]);
1065     /// assert_eq!(m.subcommand_name(), Some("test"));
1066     /// ```
short_flag_alias(mut self, name: char) -> Self1067     pub fn short_flag_alias(mut self, name: char) -> Self {
1068         if name == '-' {
1069             panic!("short alias name cannot be `-`");
1070         }
1071         self.short_flag_aliases.push((name, false));
1072         self
1073     }
1074 
1075     /// Allows adding an alias, which function as "hidden" long flag subcommands that
1076     /// automatically dispatch as if this subcommand was used. This is more efficient, and easier
1077     /// than creating multiple hidden subcommands as one only needs to check for the existence of
1078     /// this command, and not all variants.
1079     ///
1080     /// # Examples
1081     ///
1082     /// ```no_run
1083     /// # use clap::{App, Arg, };
1084     /// let m = App::new("myprog")
1085     ///             .subcommand(App::new("test").long_flag("test")
1086     ///                 .long_flag_alias("testing"))
1087     ///             .get_matches_from(vec!["myprog", "--testing"]);
1088     /// assert_eq!(m.subcommand_name(), Some("test"));
1089     /// ```
long_flag_alias(mut self, name: &'help str) -> Self1090     pub fn long_flag_alias(mut self, name: &'help str) -> Self {
1091         self.long_flag_aliases.push((name, false));
1092         self
1093     }
1094 
1095     /// If this `App` instance is a subcommand, this method adds a multiple
1096     /// aliases, which allows this subcommand to be accessed via *either* the
1097     /// original name or any of the given aliases. This is more efficient, and
1098     /// easier than creating multiple hidden subcommands as one only needs to
1099     /// check for the existence of this command and not all aliased variants.
1100     ///
1101     /// **NOTE:** Aliases defined with this method are *hidden* from the help
1102     /// message. If looking for aliases that will be displayed in the help
1103     /// message, see [`App::visible_aliases`].
1104     ///
1105     /// **NOTE:** When using aliases and checking for the existence of a
1106     /// particular subcommand within an [`ArgMatches`] struct, one only needs to
1107     /// search for the original name and not all aliases.
1108     ///
1109     /// # Examples
1110     ///
1111     /// ```rust
1112     /// # use clap::{App, Arg};
1113     /// let m = App::new("myprog")
1114     ///     .subcommand(App::new("test")
1115     ///         .aliases(&["do-stuff", "do-tests", "tests"]))
1116     ///         .arg(Arg::new("input")
1117     ///             .about("the file to add")
1118     ///             .index(1)
1119     ///             .required(false))
1120     ///     .get_matches_from(vec!["myprog", "do-tests"]);
1121     /// assert_eq!(m.subcommand_name(), Some("test"));
1122     /// ```
1123     /// [`ArgMatches`]: ./struct.ArgMatches.html
1124     /// [`App::visible_aliases`]: ./struct.App.html#method.visible_aliases
aliases(mut self, names: &[&'help str]) -> Self1125     pub fn aliases(mut self, names: &[&'help str]) -> Self {
1126         self.aliases.extend(names.iter().map(|n| (*n, false)));
1127         self
1128     }
1129 
1130     /// Allows adding aliases, which function as "hidden" short flag subcommands that
1131     /// automatically dispatch as if this subcommand was used. This is more efficient, and easier
1132     /// than creating multiple hidden subcommands as one only needs to check for the existence of
1133     /// this command, and not all variants.
1134     ///
1135     /// # Examples
1136     ///
1137     /// ```rust
1138     /// # use clap::{App, Arg, };
1139     /// let m = App::new("myprog")
1140     ///     .subcommand(App::new("test").short_flag('t')
1141     ///         .short_flag_aliases(&['a', 'b', 'c']))
1142     ///         .arg(Arg::new("input")
1143     ///             .about("the file to add")
1144     ///             .index(1)
1145     ///             .required(false))
1146     ///     .get_matches_from(vec!["myprog", "-a"]);
1147     /// assert_eq!(m.subcommand_name(), Some("test"));
1148     /// ```
short_flag_aliases(mut self, names: &[char]) -> Self1149     pub fn short_flag_aliases(mut self, names: &[char]) -> Self {
1150         for s in names {
1151             if s == &'-' {
1152                 panic!("short alias name cannot be `-`");
1153             }
1154             self.short_flag_aliases.push((*s, false));
1155         }
1156         self
1157     }
1158 
1159     /// Allows adding aliases, which function as "hidden" long flag subcommands that
1160     /// automatically dispatch as if this subcommand was used. This is more efficient, and easier
1161     /// than creating multiple hidden subcommands as one only needs to check for the existence of
1162     /// this command, and not all variants.
1163     ///
1164     /// # Examples
1165     ///
1166     /// ```rust
1167     /// # use clap::{App, Arg, };
1168     /// let m = App::new("myprog")
1169     ///             .subcommand(App::new("test").long_flag("test")
1170     ///                 .long_flag_aliases(&["testing", "testall", "test_all"]))
1171     ///                 .arg(Arg::new("input")
1172     ///                             .about("the file to add")
1173     ///                             .index(1)
1174     ///                             .required(false))
1175     ///             .get_matches_from(vec!["myprog", "--testing"]);
1176     /// assert_eq!(m.subcommand_name(), Some("test"));
1177     /// ```
long_flag_aliases(mut self, names: &[&'help str]) -> Self1178     pub fn long_flag_aliases(mut self, names: &[&'help str]) -> Self {
1179         for s in names {
1180             self.long_flag_aliases.push((s, false));
1181         }
1182         self
1183     }
1184 
1185     /// If this `App` instance is a subcommand, this method adds a visible
1186     /// alias, which allows this subcommand to be accessed via *either* the
1187     /// original name or the given alias. This is more efficient and easier
1188     /// than creating hidden subcommands as one only needs to check for
1189     /// the existence of this command and not all aliased variants.
1190     ///
1191     /// **NOTE:** The alias defined with this method is *visible* from the help
1192     /// message and displayed as if it were just another regular subcommand. If
1193     /// looking for an alias that will not be displayed in the help message, see
1194     /// [`App::alias`].
1195     ///
1196     /// **NOTE:** When using aliases and checking for the existence of a
1197     /// particular subcommand within an [`ArgMatches`] struct, one only needs to
1198     /// search for the original name and not all aliases.
1199     ///
1200     /// # Examples
1201     ///
1202     /// ```no_run
1203     /// # use clap::{App, Arg};
1204     /// let m = App::new("myprog")
1205     ///     .subcommand(App::new("test")
1206     ///         .visible_alias("do-stuff"))
1207     ///     .get_matches_from(vec!["myprog", "do-stuff"]);
1208     /// assert_eq!(m.subcommand_name(), Some("test"));
1209     /// ```
1210     /// [`ArgMatches`]: ./struct.ArgMatches.html
1211     /// [`App::alias`]: ./struct.App.html#method.alias
visible_alias<S: Into<&'help str>>(mut self, name: S) -> Self1212     pub fn visible_alias<S: Into<&'help str>>(mut self, name: S) -> Self {
1213         self.aliases.push((name.into(), true));
1214         self
1215     }
1216 
1217     /// Allows adding an alias that functions exactly like those defined with
1218     /// [`App::short_flag_alias`], except that they are visible inside the help message.
1219     ///
1220     /// # Examples
1221     ///
1222     /// ```no_run
1223     /// # use clap::{App, Arg, };
1224     /// let m = App::new("myprog")
1225     ///             .subcommand(App::new("test").short_flag('t')
1226     ///                 .visible_short_flag_alias('d'))
1227     ///             .get_matches_from(vec!["myprog", "-d"]);
1228     /// assert_eq!(m.subcommand_name(), Some("test"));
1229     /// ```
1230     /// [`App::short_flag_alias`]: ./struct.App.html#method.short_flag_alias
visible_short_flag_alias(mut self, name: char) -> Self1231     pub fn visible_short_flag_alias(mut self, name: char) -> Self {
1232         if name == '-' {
1233             panic!("short alias name cannot be `-`");
1234         }
1235         self.short_flag_aliases.push((name, true));
1236         self
1237     }
1238 
1239     /// Allows adding an alias that functions exactly like those defined with
1240     /// [`App::long_flag_alias`], except that they are visible inside the help message.
1241     ///
1242     /// # Examples
1243     ///
1244     /// ```no_run
1245     /// # use clap::{App, Arg, };
1246     /// let m = App::new("myprog")
1247     ///             .subcommand(App::new("test").long_flag("test")
1248     ///                 .visible_long_flag_alias("testing"))
1249     ///             .get_matches_from(vec!["myprog", "--testing"]);
1250     /// assert_eq!(m.subcommand_name(), Some("test"));
1251     /// ```
1252     /// [`App::long_flag_alias`]: ./struct.App.html#method.long_flag_alias
visible_long_flag_alias(mut self, name: &'help str) -> Self1253     pub fn visible_long_flag_alias(mut self, name: &'help str) -> Self {
1254         self.long_flag_aliases.push((name, true));
1255         self
1256     }
1257 
1258     /// If this `App` instance is a subcommand, this method adds multiple visible
1259     /// aliases, which allows this subcommand to be accessed via *either* the
1260     /// original name or any of the given aliases. This is more efficient and easier
1261     /// than creating multiple hidden subcommands as one only needs to check for
1262     /// the existence of this command and not all aliased variants.
1263     ///
1264     /// **NOTE:** The alias defined with this method is *visible* from the help
1265     /// message and displayed as if it were just another regular subcommand. If
1266     /// looking for an alias that will not be displayed in the help message, see
1267     /// [`App::alias`].
1268     ///
1269     /// **NOTE:** When using aliases, and checking for the existence of a
1270     /// particular subcommand within an [`ArgMatches`] struct, one only needs to
1271     /// search for the original name and not all aliases.
1272     ///
1273     /// # Examples
1274     ///
1275     /// ```no_run
1276     /// # use clap::{App, Arg, };
1277     /// let m = App::new("myprog")
1278     ///     .subcommand(App::new("test")
1279     ///         .visible_aliases(&["do-stuff", "tests"]))
1280     ///     .get_matches_from(vec!["myprog", "do-stuff"]);
1281     /// assert_eq!(m.subcommand_name(), Some("test"));
1282     /// ```
1283     /// [`ArgMatches`]: ./struct.ArgMatches.html
1284     /// [`App::alias`]: ./struct.App.html#method.alias
visible_aliases(mut self, names: &[&'help str]) -> Self1285     pub fn visible_aliases(mut self, names: &[&'help str]) -> Self {
1286         self.aliases.extend(names.iter().map(|n| (*n, true)));
1287         self
1288     }
1289 
1290     /// Allows adding multiple short flag aliases that functions exactly like those defined
1291     /// with [`App::short_flag_aliases`], except that they are visible inside the help message.
1292     ///
1293     /// # Examples
1294     ///
1295     /// ```no_run
1296     /// # use clap::{App, Arg, };
1297     /// let m = App::new("myprog")
1298     ///             .subcommand(App::new("test").short_flag('b')
1299     ///                 .visible_short_flag_aliases(&['t']))
1300     ///             .get_matches_from(vec!["myprog", "-t"]);
1301     /// assert_eq!(m.subcommand_name(), Some("test"));
1302     /// ```
1303     /// [`App::short_flag_aliases`]: ./struct.App.html#method.short_flag_aliases
visible_short_flag_aliases(mut self, names: &[char]) -> Self1304     pub fn visible_short_flag_aliases(mut self, names: &[char]) -> Self {
1305         for s in names {
1306             if s == &'-' {
1307                 panic!("short alias name cannot be `-`");
1308             }
1309             self.short_flag_aliases.push((*s, true));
1310         }
1311         self
1312     }
1313 
1314     /// Allows adding multiple long flag aliases that functions exactly like those defined
1315     /// with [`App::long_flag_aliases`], except that they are visible inside the help message.
1316     ///
1317     /// # Examples
1318     ///
1319     /// ```no_run
1320     /// # use clap::{App, Arg, };
1321     /// let m = App::new("myprog")
1322     ///             .subcommand(App::new("test").long_flag("test")
1323     ///                 .visible_long_flag_aliases(&["testing", "testall", "test_all"]))
1324     ///             .get_matches_from(vec!["myprog", "--testing"]);
1325     /// assert_eq!(m.subcommand_name(), Some("test"));
1326     /// ```
1327     /// [`App::long_flag_aliases`]: ./struct.App.html#method.long_flag_aliases
visible_long_flag_aliases(mut self, names: &[&'help str]) -> Self1328     pub fn visible_long_flag_aliases(mut self, names: &[&'help str]) -> Self {
1329         for s in names {
1330             self.long_flag_aliases.push((s, true));
1331         }
1332         self
1333     }
1334 
1335     /// Replaces an argument or subcommand used on the CLI at runtime with other arguments or subcommands.
1336     ///
1337     /// When this method is used, `name` is removed from the CLI, and `target`
1338     /// is inserted in it's place. Parsing continues as if the user typed
1339     /// `target` instead of `name`.
1340     ///
1341     /// This can be used to create "shortcuts" for subcommands, or if a
1342     /// particular argument has the semantic meaning of several other specific
1343     /// arguments and values.
1344     ///
1345     /// Some examples may help to clear this up.
1346     ///
1347     /// # Examples
1348     ///
1349     /// We'll start with the "subcommand short" example. In this example, let's
1350     /// assume we have a program with a subcommand `module` which can be invoked
1351     /// via `app module`. Now let's also assume `module` also has a subcommand
1352     /// called `install` which can be invoked `app module install`. If for some
1353     /// reason users needed to be able to reach `app module install` via the
1354     /// short-hand `app install`, we'd have several options.
1355     ///
1356     /// We *could* create another sibling subcommand to `module` called
1357     /// `install`, but then we would need to manage another subcommand and manually
1358     /// dispatch to `app module install` handling code. This is error prone and
1359     /// tedious.
1360     ///
1361     /// We could instead use [`App::replace`] so that, when the user types `app
1362     /// install`, `clap` will replace `install` with `module install` which will
1363     /// end up getting parsed as if the user typed the entire incantation.
1364     ///
1365     /// ```rust
1366     /// # use clap::App;
1367     /// let m = App::new("app")
1368     ///     .subcommand(App::new("module")
1369     ///         .subcommand(App::new("install")))
1370     ///     .replace("install", &["module", "install"])
1371     ///     .get_matches_from(vec!["app", "install"]);
1372     ///
1373     /// assert!(m.subcommand_matches("module").is_some());
1374     /// assert!(m.subcommand_matches("module").unwrap().subcommand_matches("install").is_some());
1375     /// ```
1376     ///
1377     /// Now let's show an argument example!
1378     ///
1379     /// Let's assume we have an application with two flags `--save-context` and
1380     /// `--save-runtime`. But often users end up needing to do *both* at the
1381     /// same time. We can add a third flag `--save-all` which semantically means
1382     /// the same thing as `app --save-context --save-runtime`. To implement that,
1383     /// we have several options.
1384     ///
1385     /// We could create this third argument and manually check if that argument
1386     /// and in our own consumer code handle the fact that both `--save-context`
1387     /// and `--save-runtime` *should* have been used. But again this is error
1388     /// prone and tedious. If we had code relying on checking `--save-context`
1389     /// and we forgot to update that code to *also* check `--save-all` it'd mean
1390     /// an error!
1391     ///
1392     /// Luckily we can use [`App::replace`] so that when the user types
1393     /// `--save-all`, `clap` will replace that argument with `--save-context
1394     /// --save-runtime`, and parsing will continue like normal. Now all our code
1395     /// that was originally checking for things like `--save-context` doesn't
1396     /// need to change!
1397     ///
1398     /// ```rust
1399     /// # use clap::{App, Arg};
1400     /// let m = App::new("app")
1401     ///     .arg(Arg::new("save-context")
1402     ///         .long("save-context"))
1403     ///     .arg(Arg::new("save-runtime")
1404     ///         .long("save-runtime"))
1405     ///     .replace("--save-all", &["--save-context", "--save-runtime"])
1406     ///     .get_matches_from(vec!["app", "--save-all"]);
1407     ///
1408     /// assert!(m.is_present("save-context"));
1409     /// assert!(m.is_present("save-runtime"));
1410     /// ```
1411     ///
1412     /// This can also be used with options, for example if our application with
1413     /// `--save-*` above also had a `--format=TYPE` option. Let's say it
1414     /// accepted `txt` or `json` values. However, when `--save-all` is used,
1415     /// only `--format=json` is allowed, or valid. We could change the example
1416     /// above to enforce this:
1417     ///
1418     /// ```rust
1419     /// # use clap::{App, Arg};
1420     /// let m = App::new("app")
1421     ///     .arg(Arg::new("save-context")
1422     ///         .long("save-context"))
1423     ///     .arg(Arg::new("save-runtime")
1424     ///         .long("save-runtime"))
1425     ///     .arg(Arg::new("format")
1426     ///         .long("format")
1427     ///         .takes_value(true)
1428     ///         .possible_values(&["txt", "json"]))
1429     ///     .replace("--save-all", &["--save-context", "--save-runtime", "--format=json"])
1430     ///     .get_matches_from(vec!["app", "--save-all"]);
1431     ///
1432     /// assert!(m.is_present("save-context"));
1433     /// assert!(m.is_present("save-runtime"));
1434     /// assert_eq!(m.value_of("format"), Some("json"));
1435     /// ```
1436     ///
1437     /// [`App::replace`]: ./struct.App.html#method.replace
1438     #[inline]
replace(mut self, name: &'help str, target: &'help [&'help str]) -> Self1439     pub fn replace(mut self, name: &'help str, target: &'help [&'help str]) -> Self {
1440         self.replacers.insert(name, target);
1441         self
1442     }
1443 
1444     /// Adds an [`ArgGroup`] to the application. [`ArgGroup`]s are a family of related arguments.
1445     /// By placing them in a logical group, you can build easier requirement and exclusion rules.
1446     /// For instance, you can make an entire [`ArgGroup`] required, meaning that one (and *only*
1447     /// one) argument from that group must be present at runtime.
1448     ///
1449     /// You can also do things such as name an [`ArgGroup`] as a conflict to another argument.
1450     /// Meaning any of the arguments that belong to that group will cause a failure if present with
1451     /// the conflicting argument.
1452     ///
1453     /// Another added benefit of [`ArgGroup`]s is that you can extract a value from a group instead
1454     /// of determining exactly which argument was used.
1455     ///
1456     /// Finally, using [`ArgGroup`]s to ensure exclusion between arguments is another very common
1457     /// use.
1458     ///
1459     /// # Examples
1460     ///
1461     /// The following example demonstrates using an [`ArgGroup`] to ensure that one, and only one,
1462     /// of the arguments from the specified group is present at runtime.
1463     ///
1464     /// ```no_run
1465     /// # use clap::{App, ArgGroup};
1466     /// App::new("app")
1467     ///     .arg("--set-ver [ver] 'set the version manually'")
1468     ///     .arg("--major 'auto increase major'")
1469     ///     .arg("--minor 'auto increase minor'")
1470     ///     .arg("--patch 'auto increase patch'")
1471     ///     .group(ArgGroup::new("vers")
1472     ///          .args(&["set-ver", "major", "minor","patch"])
1473     ///          .required(true))
1474     /// # ;
1475     /// ```
1476     /// [`ArgGroup`]: ./struct.ArgGroup.html
1477     #[inline]
group(mut self, group: ArgGroup<'help>) -> Self1478     pub fn group(mut self, group: ArgGroup<'help>) -> Self {
1479         self.groups.push(group);
1480         self
1481     }
1482 
1483     /// Adds multiple [`ArgGroup`]s to the [`App`] at once.
1484     ///
1485     /// # Examples
1486     ///
1487     /// ```no_run
1488     /// # use clap::{App, ArgGroup};
1489     /// App::new("app")
1490     ///     .arg("--set-ver [ver] 'set the version manually'")
1491     ///     .arg("--major         'auto increase major'")
1492     ///     .arg("--minor         'auto increase minor'")
1493     ///     .arg("--patch         'auto increase patch'")
1494     ///     .arg("-c [FILE]       'a config file'")
1495     ///     .arg("-i [IFACE]      'an interface'")
1496     ///     .groups(&[
1497     ///         ArgGroup::new("vers")
1498     ///             .args(&["set-ver", "major", "minor","patch"])
1499     ///             .required(true),
1500     ///         ArgGroup::new("input")
1501     ///             .args(&["c", "i"])
1502     ///     ])
1503     /// # ;
1504     /// ```
1505     /// [`ArgGroup`]: ./struct.ArgGroup.html
1506     /// [`App`]: ./struct.App.html
groups(mut self, groups: &[ArgGroup<'help>]) -> Self1507     pub fn groups(mut self, groups: &[ArgGroup<'help>]) -> Self {
1508         for g in groups {
1509             self = self.group(g.into());
1510         }
1511         self
1512     }
1513 
1514     /// Adds a subcommand to the list of valid possibilities. Subcommands are effectively
1515     /// sub-[`App`]s, because they can contain their own arguments, subcommands, version, usage,
1516     /// etc. They also function just like [`App`]s, in that they get their own auto generated help,
1517     /// version, and usage.
1518     ///
1519     /// # Examples
1520     ///
1521     /// ```no_run
1522     /// # use clap::{App, Arg, };
1523     /// App::new("myprog")
1524     ///     .subcommand(App::new("config")
1525     ///         .about("Controls configuration features")
1526     ///         .arg("<config> 'Required configuration file to use'"))
1527     /// # ;
1528     /// ```
1529     /// [`App`]: ./struct.App.html
1530     #[inline]
subcommand(mut self, subcmd: App<'help>) -> Self1531     pub fn subcommand(mut self, subcmd: App<'help>) -> Self {
1532         self.subcommands.push(subcmd);
1533         self
1534     }
1535 
1536     /// Adds multiple subcommands to the list of valid possibilities by iterating over an
1537     /// [`IntoIterator`] of [`App`]s.
1538     ///
1539     /// # Examples
1540     ///
1541     /// ```rust
1542     /// # use clap::{App, Arg, };
1543     /// # App::new("myprog")
1544     /// .subcommands( vec![
1545     ///        App::new("config").about("Controls configuration functionality")
1546     ///                                 .arg(Arg::new("config_file").index(1)),
1547     ///        App::new("debug").about("Controls debug functionality")])
1548     /// # ;
1549     /// ```
1550     /// [`App`]: ./struct.App.html
1551     /// [`IntoIterator`]: https://doc.rust-lang.org/std/iter/trait.IntoIterator.html
subcommands<I>(mut self, subcmds: I) -> Self where I: IntoIterator<Item = App<'help>>,1552     pub fn subcommands<I>(mut self, subcmds: I) -> Self
1553     where
1554         I: IntoIterator<Item = App<'help>>,
1555     {
1556         for subcmd in subcmds {
1557             self.subcommands.push(subcmd);
1558         }
1559         self
1560     }
1561 
1562     /// Allows custom ordering of subcommands within the help message. Subcommands with a lower
1563     /// value will be displayed first in the help message. This is helpful when one would like to
1564     /// emphasize frequently used subcommands, or prioritize those towards the top of the list.
1565     /// Duplicate values **are** allowed. Subcommands with duplicate display orders will be
1566     /// displayed in alphabetical order.
1567     ///
1568     /// **NOTE:** The default is 999 for all subcommands.
1569     ///
1570     /// # Examples
1571     ///
1572     /// ```rust
1573     /// # use clap::{App, };
1574     /// let m = App::new("cust-ord")
1575     ///     .subcommand(App::new("alpha") // typically subcommands are grouped
1576     ///                                                // alphabetically by name. Subcommands
1577     ///                                                // without a display_order have a value of
1578     ///                                                // 999 and are displayed alphabetically with
1579     ///                                                // all other 999 subcommands
1580     ///         .about("Some help and text"))
1581     ///     .subcommand(App::new("beta")
1582     ///         .display_order(1)   // In order to force this subcommand to appear *first*
1583     ///                             // all we have to do is give it a value lower than 999.
1584     ///                             // Any other subcommands with a value of 1 will be displayed
1585     ///                             // alphabetically with this one...then 2 values, then 3, etc.
1586     ///         .about("I should be first!"))
1587     ///     .get_matches_from(vec![
1588     ///         "cust-ord", "--help"
1589     ///     ]);
1590     /// ```
1591     ///
1592     /// The above example displays the following help message
1593     ///
1594     /// ```text
1595     /// cust-ord
1596     ///
1597     /// USAGE:
1598     ///     cust-ord [FLAGS] [OPTIONS]
1599     ///
1600     /// FLAGS:
1601     ///     -h, --help       Prints help information
1602     ///     -V, --version    Prints version information
1603     ///
1604     /// SUBCOMMANDS:
1605     ///     beta    I should be first!
1606     ///     alpha   Some help and text
1607     /// ```
1608     #[inline]
display_order(mut self, ord: usize) -> Self1609     pub fn display_order(mut self, ord: usize) -> Self {
1610         self.disp_ord = ord;
1611         self
1612     }
1613 
1614     /// Allows one to mutate an [`Arg`] after it's been added to an [`App`].
1615     ///
1616     /// # Examples
1617     ///
1618     /// ```rust
1619     /// # use clap::{App, Arg};
1620     ///
1621     /// let mut app = App::new("foo")
1622     ///     .arg(Arg::new("bar")
1623     ///         .short('b'))
1624     ///     .mut_arg("bar", |a| a.short('B'));
1625     ///
1626     /// let res = app.try_get_matches_from_mut(vec!["foo", "-b"]);
1627     ///
1628     /// // Since we changed `bar`'s short to "B" this should err as there
1629     /// // is no `-b` anymore, only `-B`
1630     ///
1631     /// assert!(res.is_err());
1632     ///
1633     /// let res = app.try_get_matches_from_mut(vec!["foo", "-B"]);
1634     /// assert!(res.is_ok());
1635     /// ```
1636     /// [`Arg`]: ./struct.Arg.html
1637     /// [`App`]: ./struct.App.html
mut_arg<T, F>(mut self, arg_id: T, f: F) -> Self where F: FnOnce(Arg<'help>) -> Arg<'help>, T: Key + Into<&'help str>,1638     pub fn mut_arg<T, F>(mut self, arg_id: T, f: F) -> Self
1639     where
1640         F: FnOnce(Arg<'help>) -> Arg<'help>,
1641         T: Key + Into<&'help str>,
1642     {
1643         let arg_id: &str = arg_id.into();
1644         let id = Id::from(arg_id);
1645         let a = self.args.remove_by_name(&id).unwrap_or_else(|| Arg {
1646             id,
1647             name: arg_id,
1648             ..Arg::default()
1649         });
1650         self.args.push(f(a));
1651 
1652         self
1653     }
1654 
1655     /// Prints the full help message to [`io::stdout()`] using a [`BufWriter`] using the same
1656     /// method as if someone ran `-h` to request the help message.
1657     ///
1658     /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
1659     /// depending on if the user ran [`-h` (short)] or [`--help` (long)].
1660     ///
1661     /// # Examples
1662     ///
1663     /// ```rust
1664     /// # use clap::App;
1665     /// let mut app = App::new("myprog");
1666     /// app.print_help();
1667     /// ```
1668     /// [`io::stdout()`]: https://doc.rust-lang.org/std/io/fn.stdout.html
1669     /// [`-h` (short)]: ./struct.Arg.html#method.about
1670     /// [`--help` (long)]: ./struct.Arg.html#method.long_about
print_help(&mut self) -> io::Result<()>1671     pub fn print_help(&mut self) -> io::Result<()> {
1672         self._build();
1673 
1674         let p = Parser::new(self);
1675         let mut c = Colorizer::new(false, p.color_help());
1676         Help::new(HelpWriter::Buffer(&mut c), &p, false).write_help()?;
1677         c.print()
1678     }
1679 
1680     /// Prints the full help message to [`io::stdout()`] using a [`BufWriter`] using the same
1681     /// method as if someone ran `--help` to request the help message.
1682     ///
1683     /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
1684     /// depending on if the user ran [`-h` (short)] or [`--help` (long)].
1685     ///
1686     /// # Examples
1687     ///
1688     /// ```rust
1689     /// # use clap::App;
1690     /// let mut app = App::new("myprog");
1691     /// app.print_long_help();
1692     /// ```
1693     /// [`io::stdout()`]: https://doc.rust-lang.org/std/io/fn.stdout.html
1694     /// [`BufWriter`]: https://doc.rust-lang.org/std/io/struct.BufWriter.html
1695     /// [`-h` (short)]: ./struct.Arg.html#method.about
1696     /// [`--help` (long)]: ./struct.Arg.html#method.long_about
print_long_help(&mut self) -> io::Result<()>1697     pub fn print_long_help(&mut self) -> io::Result<()> {
1698         self._build();
1699 
1700         let p = Parser::new(self);
1701         let mut c = Colorizer::new(false, p.color_help());
1702         Help::new(HelpWriter::Buffer(&mut c), &p, true).write_help()?;
1703         c.print()
1704     }
1705 
1706     /// Writes the full help message to the user to a [`io::Write`] object in the same method as if
1707     /// the user ran `-h`.
1708     ///
1709     /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
1710     /// depending on if the user ran [`-h` (short)] or [`--help` (long)].
1711     ///
1712     /// # Examples
1713     ///
1714     /// ```rust
1715     /// # use clap::App;
1716     /// use std::io;
1717     /// let mut app = App::new("myprog");
1718     /// let mut out = io::stdout();
1719     /// app.write_help(&mut out).expect("failed to write to stdout");
1720     /// ```
1721     /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
1722     /// [`-h` (short)]: ./struct.Arg.html#method.about
1723     /// [`--help` (long)]: ./struct.Arg.html#method.long_about
write_help<W: Write>(&mut self, w: &mut W) -> io::Result<()>1724     pub fn write_help<W: Write>(&mut self, w: &mut W) -> io::Result<()> {
1725         self._build();
1726 
1727         let p = Parser::new(self);
1728         Help::new(HelpWriter::Normal(w), &p, false).write_help()?;
1729         w.flush()
1730     }
1731 
1732     /// Writes the full help message to the user to a [`io::Write`] object in the same method as if
1733     /// the user ran `--help`.
1734     ///
1735     /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
1736     /// depending on if the user ran [`-h` (short)] or [`--help` (long)].
1737     ///
1738     /// # Examples
1739     ///
1740     /// ```rust
1741     /// # use clap::App;
1742     /// use std::io;
1743     /// let mut app = App::new("myprog");
1744     /// let mut out = io::stdout();
1745     /// app.write_long_help(&mut out).expect("failed to write to stdout");
1746     /// ```
1747     /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
1748     /// [`-h` (short)]: ./struct.Arg.html#method.about
1749     /// [`--help` (long)]: ./struct.Arg.html#method.long_about
write_long_help<W: Write>(&mut self, w: &mut W) -> io::Result<()>1750     pub fn write_long_help<W: Write>(&mut self, w: &mut W) -> io::Result<()> {
1751         self._build();
1752 
1753         let p = Parser::new(self);
1754         Help::new(HelpWriter::Normal(w), &p, true).write_help()?;
1755         w.flush()
1756     }
1757 
1758     /// Returns the version message rendered as if the user ran `-V`.
1759     ///
1760     /// **NOTE:** clap has the ability to distinguish between "short" and "long" version messages
1761     /// depending on if the user ran [`-V` (short)] or [`--version` (long)].
1762     ///
1763     /// ### Coloring
1764     ///
1765     /// This function does not try to color the message nor it inserts any [ANSI escape codes].
1766     ///
1767     /// ### Examples
1768     ///
1769     /// ```rust
1770     /// # use clap::App;
1771     /// use std::io;
1772     /// let app = App::new("myprog");
1773     /// println!("{}", app.render_version());
1774     /// ```
1775     /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
1776     /// [`-V` (short)]: ./struct.App.html#method.version
1777     /// [`--version` (long)]: ./struct.App.html#method.long_version
1778     /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code
render_version(&self) -> String1779     pub fn render_version(&self) -> String {
1780         self._render_version(false)
1781     }
1782 
1783     /// Returns the version message rendered as if the user ran `--version`.
1784     ///
1785     /// **NOTE:** clap has the ability to distinguish between "short" and "long" version messages
1786     /// depending on if the user ran [`-V` (short)] or [`--version` (long)].
1787     ///
1788     /// ### Coloring
1789     ///
1790     /// This function does not try to color the message nor it inserts any [ANSI escape codes].
1791     ///
1792     /// ### Examples
1793     ///
1794     /// ```rust
1795     /// # use clap::App;
1796     /// use std::io;
1797     /// let app = App::new("myprog");
1798     /// println!("{}", app.render_long_version());
1799     /// ```
1800     /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
1801     /// [`-V` (short)]: ./struct.App.html#method.version
1802     /// [`--version` (long)]: ./struct.App.html#method.long_version
1803     /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code
render_long_version(&self) -> String1804     pub fn render_long_version(&self) -> String {
1805         self._render_version(true)
1806     }
1807 
1808     /// @TODO-v3-alpha @docs @p2: write docs
generate_usage(&mut self) -> String1809     pub fn generate_usage(&mut self) -> String {
1810         // If there are global arguments, or settings we need to propagate them down to subcommands
1811         // before parsing incase we run into a subcommand
1812         if !self.settings.is_set(AppSettings::Built) {
1813             self._build();
1814         }
1815 
1816         let mut parser = Parser::new(self);
1817         parser._build();
1818         Usage::new(&parser).create_usage_with_title(&[])
1819     }
1820 
1821     /// Starts the parsing process, upon a failed parse an error will be displayed to the user and
1822     /// the process will exit with the appropriate error code. By default this method gets all user
1823     /// provided arguments from [`env::args_os`] in order to allow for invalid UTF-8 code points,
1824     /// which are legal on many platforms.
1825     ///
1826     /// # Examples
1827     ///
1828     /// ```no_run
1829     /// # use clap::{App, Arg};
1830     /// let matches = App::new("myprog")
1831     ///     // Args and options go here...
1832     ///     .get_matches();
1833     /// ```
1834     /// [`env::args_os`]: https://doc.rust-lang.org/std/env/fn.args_os.html
1835     #[inline]
get_matches(self) -> ArgMatches1836     pub fn get_matches(self) -> ArgMatches {
1837         self.get_matches_from(&mut env::args_os())
1838     }
1839 
1840     /// Starts the parsing process, just like [`App::get_matches`] but doesn't consume the `App`.
1841     ///
1842     /// # Examples
1843     ///
1844     /// ```no_run
1845     /// # use clap::{App, Arg};
1846     /// let mut app = App::new("myprog")
1847     ///     // Args and options go here...
1848     ///     ;
1849     /// let matches = app.get_matches_mut();
1850     /// ```
1851     /// [`env::args_os`]: https://doc.rust-lang.org/std/env/fn.args_os.html
1852     /// [`App::get_matches`]: ./struct.App.html#method.get_matches
get_matches_mut(&mut self) -> ArgMatches1853     pub fn get_matches_mut(&mut self) -> ArgMatches {
1854         self.try_get_matches_from_mut(&mut env::args_os())
1855             .unwrap_or_else(|e| {
1856                 // Otherwise, write to stderr and exit
1857                 if e.use_stderr() {
1858                     e.message.print().expect("Error writing Error to stderr");
1859 
1860                     if self.settings.is_set(AppSettings::WaitOnError) {
1861                         wlnerr!("\nPress [ENTER] / [RETURN] to continue...");
1862                         let mut s = String::new();
1863                         let i = io::stdin();
1864                         i.lock().read_line(&mut s).unwrap();
1865                     }
1866 
1867                     drop(e);
1868                     safe_exit(2);
1869                 }
1870 
1871                 e.exit()
1872             })
1873     }
1874 
1875     /// Starts the parsing process. This method will return a [`clap::Result`] type instead of exiting
1876     /// the process on failed parse. By default this method gets matches from [`env::args_os`].
1877     ///
1878     /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
1879     /// used. It will return a [`clap::Error`], where the [`kind`] is a
1880     /// [`ErrorKind::DisplayHelp`] or [`ErrorKind::DisplayVersion`] respectively. You must call
1881     /// [`Error::exit`] or perform a [`std::process::exit`].
1882     ///
1883     /// # Examples
1884     ///
1885     /// ```no_run
1886     /// # use clap::{App, Arg};
1887     /// let matches = App::new("myprog")
1888     ///     // Args and options go here...
1889     ///     .try_get_matches()
1890     ///     .unwrap_or_else(|e| e.exit());
1891     /// ```
1892     /// [`env::args_os`]: https://doc.rust-lang.org/std/env/fn.args_os.html
1893     /// [`ErrorKind::DisplayHelp`]: ./enum.ErrorKind.html#variant.DisplayHelp
1894     /// [`ErrorKind::DisplayVersion`]: ./enum.ErrorKind.html#variant.DisplayVersion
1895     /// [`Error::exit`]: ./struct.Error.html#method.exit
1896     /// [`std::process::exit`]: https://doc.rust-lang.org/std/process/fn.exit.html
1897     /// [`clap::Result`]: ./type.Result.html
1898     /// [`clap::Error`]: ./struct.Error.html
1899     /// [`kind`]: ./struct.Error.html
1900     #[inline]
try_get_matches(self) -> ClapResult<ArgMatches>1901     pub fn try_get_matches(self) -> ClapResult<ArgMatches> {
1902         // Start the parsing
1903         self.try_get_matches_from(&mut env::args_os())
1904     }
1905 
1906     /// Starts the parsing process. Like [`App::get_matches`] this method does not return a [`clap::Result`]
1907     /// and will automatically exit with an error message. This method, however, lets you specify
1908     /// what iterator to use when performing matches, such as a [`Vec`] of your making.
1909     ///
1910     /// **NOTE:** The first argument will be parsed as the binary name unless
1911     /// [`AppSettings::NoBinaryName`] is used.
1912     ///
1913     /// # Examples
1914     ///
1915     /// ```no_run
1916     /// # use clap::{App, Arg};
1917     /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
1918     ///
1919     /// let matches = App::new("myprog")
1920     ///     // Args and options go here...
1921     ///     .get_matches_from(arg_vec);
1922     /// ```
1923     /// [`App::get_matches`]: ./struct.App.html#method.get_matches
1924     /// [`clap::Result`]: ./type.Result.html
1925     /// [`Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
1926     /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName
get_matches_from<I, T>(mut self, itr: I) -> ArgMatches where I: IntoIterator<Item = T>, T: Into<OsString> + Clone,1927     pub fn get_matches_from<I, T>(mut self, itr: I) -> ArgMatches
1928     where
1929         I: IntoIterator<Item = T>,
1930         T: Into<OsString> + Clone,
1931     {
1932         self.try_get_matches_from_mut(itr).unwrap_or_else(|e| {
1933             // Otherwise, write to stderr and exit
1934             if e.use_stderr() {
1935                 e.message.print().expect("Error writing Error to stderr");
1936 
1937                 if self.settings.is_set(AppSettings::WaitOnError) {
1938                     wlnerr!("\nPress [ENTER] / [RETURN] to continue...");
1939                     let mut s = String::new();
1940                     let i = io::stdin();
1941                     i.lock().read_line(&mut s).unwrap();
1942                 }
1943 
1944                 drop(self);
1945                 drop(e);
1946                 safe_exit(2);
1947             }
1948 
1949             drop(self);
1950             e.exit()
1951         })
1952     }
1953 
1954     /// Starts the parsing process. A combination of [`App::get_matches_from`], and
1955     /// [`App::try_get_matches`].
1956     ///
1957     /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
1958     /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`]
1959     /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or
1960     /// perform a [`std::process::exit`] yourself.
1961     ///
1962     /// **NOTE:** The first argument will be parsed as the binary name unless
1963     /// [`AppSettings::NoBinaryName`] is used.
1964     ///
1965     /// # Examples
1966     ///
1967     /// ```no_run
1968     /// # use clap::{App, Arg};
1969     /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
1970     ///
1971     /// let matches = App::new("myprog")
1972     ///     // Args and options go here...
1973     ///     .try_get_matches_from(arg_vec)
1974     ///     .unwrap_or_else(|e| e.exit());
1975     /// ```
1976     /// [`App::get_matches_from`]: ./struct.App.html#method.get_matches_from
1977     /// [`App::try_get_matches`]: ./struct.App.html#method.try_get_matches
1978     /// [`ErrorKind::DisplayHelp`]: ./enum.ErrorKind.html#variant.DisplayHelp
1979     /// [`ErrorKind::DisplayVersion`]: ./enum.ErrorKind.html#variant.DisplayVersion
1980     /// [`Error::exit`]: ./struct.Error.html#method.exit
1981     /// [`std::process::exit`]: https://doc.rust-lang.org/std/process/fn.exit.html
1982     /// [`clap::Error`]: ./struct.Error.html
1983     /// [`Error::exit`]: ./struct.Error.html#method.exit
1984     /// [`kind`]: ./struct.Error.html
1985     /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName
try_get_matches_from<I, T>(mut self, itr: I) -> ClapResult<ArgMatches> where I: IntoIterator<Item = T>, T: Into<OsString> + Clone,1986     pub fn try_get_matches_from<I, T>(mut self, itr: I) -> ClapResult<ArgMatches>
1987     where
1988         I: IntoIterator<Item = T>,
1989         T: Into<OsString> + Clone,
1990     {
1991         self.try_get_matches_from_mut(itr)
1992     }
1993 
1994     /// Starts the parsing process without consuming the [`App`] struct `self`. This is normally not
1995     /// the desired functionality, instead prefer [`App::try_get_matches_from`] which *does*
1996     /// consume `self`.
1997     ///
1998     /// **NOTE:** The first argument will be parsed as the binary name unless
1999     /// [`AppSettings::NoBinaryName`] is used.
2000     ///
2001     /// # Examples
2002     ///
2003     /// ```no_run
2004     /// # use clap::{App, Arg};
2005     /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
2006     ///
2007     /// let mut app = App::new("myprog");
2008     ///     // Args and options go here...
2009     /// let matches = app.try_get_matches_from_mut(arg_vec)
2010     ///     .unwrap_or_else(|e| e.exit());
2011     /// ```
2012     /// [`App`]: ./struct.App.html
2013     /// [`App::try_get_matches_from`]: ./struct.App.html#method.try_get_matches_from
2014     /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName
try_get_matches_from_mut<I, T>(&mut self, itr: I) -> ClapResult<ArgMatches> where I: IntoIterator<Item = T>, T: Into<OsString> + Clone,2015     pub fn try_get_matches_from_mut<I, T>(&mut self, itr: I) -> ClapResult<ArgMatches>
2016     where
2017         I: IntoIterator<Item = T>,
2018         T: Into<OsString> + Clone,
2019     {
2020         let mut it = Input::from(itr.into_iter());
2021         // Get the name of the program (argument 1 of env::args()) and determine the
2022         // actual file
2023         // that was used to execute the program. This is because a program called
2024         // ./target/release/my_prog -a
2025         // will have two arguments, './target/release/my_prog', '-a' but we don't want
2026         // to display
2027         // the full path when displaying help messages and such
2028         if !self.settings.is_set(AppSettings::NoBinaryName) {
2029             if let Some((name, _)) = it.next(None) {
2030                 let p = Path::new(name);
2031 
2032                 if let Some(f) = p.file_name() {
2033                     if let Some(s) = f.to_os_string().to_str() {
2034                         if self.bin_name.is_none() {
2035                             self.bin_name = Some(s.to_owned());
2036                         }
2037                     }
2038                 }
2039             }
2040         }
2041 
2042         self._do_parse(&mut it)
2043     }
2044 
2045     /// Sets the placeholder text used for subcommands when printing usage and help.
2046     /// By default, this is "SUBCOMMAND" with a header of "SUBCOMMANDS".
2047     ///
2048     /// # Examples
2049     ///
2050     /// ```no_run
2051     /// # use clap::{App, Arg};
2052     /// App::new("myprog")
2053     ///     .subcommand(App::new("sub1"))
2054     ///     .print_help()
2055     /// # ;
2056     /// ```
2057     ///
2058     /// will produce
2059     ///
2060     /// ```text
2061     /// myprog
2062     ///
2063     /// USAGE:
2064     ///     myprog [SUBCOMMAND]
2065     ///
2066     /// FLAGS:
2067     ///     -h, --help       Prints help information
2068     ///     -V, --version    Prints version information
2069     ///
2070     /// SUBCOMMANDS:
2071     ///     help    Prints this message or the help of the given subcommand(s)
2072     ///     sub1
2073     /// ```
2074     ///
2075     /// but usage of `subcommand_placeholder`
2076     ///
2077     /// ```no_run
2078     /// # use clap::{App, Arg};
2079     /// App::new("myprog")
2080     ///     .subcommand(App::new("sub1"))
2081     ///     .subcommand_placeholder("THING", "THINGS")
2082     ///     .print_help()
2083     /// # ;
2084     /// ```
2085     ///
2086     /// will produce
2087     ///
2088     /// ```text
2089     /// myprog
2090     ///
2091     /// USAGE:
2092     ///     myprog [THING]
2093     ///
2094     /// FLAGS:
2095     ///     -h, --help       Prints help information
2096     ///     -V, --version    Prints version information
2097     ///
2098     /// THINGS:
2099     ///     help    Prints this message or the help of the given subcommand(s)
2100     ///     sub1
2101     /// ```
subcommand_placeholder<S, T>(mut self, placeholder: S, header: T) -> Self where S: Into<&'help str>, T: Into<&'help str>,2102     pub fn subcommand_placeholder<S, T>(mut self, placeholder: S, header: T) -> Self
2103     where
2104         S: Into<&'help str>,
2105         T: Into<&'help str>,
2106     {
2107         self.subcommand_placeholder = Some(placeholder.into());
2108         self.subcommand_header = Some(header.into());
2109         self
2110     }
2111 }
2112 
2113 // Internally used only
2114 impl<'help> App<'help> {
_do_parse(&mut self, it: &mut Input) -> ClapResult<ArgMatches>2115     fn _do_parse(&mut self, it: &mut Input) -> ClapResult<ArgMatches> {
2116         debug!("App::_do_parse");
2117         let mut matcher = ArgMatcher::default();
2118 
2119         // If there are global arguments, or settings we need to propagate them down to subcommands
2120         // before parsing in case we run into a subcommand
2121         if !self.settings.is_set(AppSettings::Built) {
2122             self._build();
2123         }
2124 
2125         // do the real parsing
2126         let mut parser = Parser::new(self);
2127         parser.get_matches_with(&mut matcher, it)?;
2128 
2129         let global_arg_vec: Vec<Id> = self
2130             .args
2131             .args
2132             .iter()
2133             .filter(|a| a.global)
2134             .map(|ga| ga.id.clone())
2135             .collect();
2136 
2137         matcher.propagate_globals(&global_arg_vec);
2138 
2139         Ok(matcher.into_inner())
2140     }
2141 
2142     // used in clap_generate (https://github.com/clap-rs/clap_generate)
2143     #[doc(hidden)]
_build(&mut self)2144     pub fn _build(&mut self) {
2145         debug!("App::_build");
2146 
2147         // Make sure all the globally set flags apply to us as well
2148         self.settings = self.settings | self.g_settings;
2149 
2150         self._propagate(Propagation::Full);
2151 
2152         self._derive_display_order();
2153         self._create_help_and_version();
2154 
2155         let mut pos_counter = 1;
2156         for a in self.args.args.iter_mut() {
2157             // Fill in the groups
2158             for g in &a.groups {
2159                 if let Some(ag) = self.groups.iter_mut().find(|grp| grp.id == *g) {
2160                     ag.args.push(a.id.clone());
2161                 } else {
2162                     let mut ag = ArgGroup::with_id(g.clone());
2163                     ag.args.push(a.id.clone());
2164                     self.groups.push(ag);
2165                 }
2166             }
2167 
2168             // Figure out implied settings
2169             if a.is_set(ArgSettings::Last) {
2170                 // if an arg has `Last` set, we need to imply DontCollapseArgsInUsage so that args
2171                 // in the usage string don't get confused or left out.
2172                 self.settings.set(AppSettings::DontCollapseArgsInUsage);
2173                 self.settings.set(AppSettings::ContainsLast);
2174             }
2175             a._build();
2176             if a.short.is_none() && a.long.is_none() && a.index.is_none() {
2177                 a.index = Some(pos_counter);
2178                 pos_counter += 1;
2179             }
2180         }
2181 
2182         self.args._build();
2183         self.settings.set(AppSettings::Built);
2184 
2185         #[cfg(debug_assertions)]
2186         self::debug_asserts::assert_app(self);
2187     }
2188 
_panic_on_missing_help(&self, help_required_globally: bool)2189     fn _panic_on_missing_help(&self, help_required_globally: bool) {
2190         if self.is_set(AppSettings::HelpRequired) || help_required_globally {
2191             let args_missing_help: Vec<String> = self
2192                 .args
2193                 .args
2194                 .iter()
2195                 .filter(|arg| arg.about.is_none() && arg.long_about.is_none())
2196                 .map(|arg| String::from(arg.name))
2197                 .collect();
2198 
2199             if !args_missing_help.is_empty() {
2200                 panic!(format!(
2201                     "AppSettings::HelpRequired is enabled for the App {}, but at least one of its arguments does not have either `help` or `long_help` set. List of such arguments: {}",
2202                     self.name,
2203                     args_missing_help.join(", ")
2204                 ));
2205             }
2206         }
2207 
2208         for sub_app in &self.subcommands {
2209             sub_app._panic_on_missing_help(help_required_globally);
2210         }
2211     }
2212 
2213     #[cfg(debug_assertions)]
two_args_of<F>(&self, condition: F) -> Option<(&Arg<'help>, &Arg<'help>)> where F: Fn(&Arg) -> bool,2214     fn two_args_of<F>(&self, condition: F) -> Option<(&Arg<'help>, &Arg<'help>)>
2215     where
2216         F: Fn(&Arg) -> bool,
2217     {
2218         two_elements_of(self.args.args.iter().filter(|a: &&Arg| condition(a)))
2219     }
2220 
2221     // just in case
2222     #[allow(unused)]
two_groups_of<F>(&self, condition: F) -> Option<(&ArgGroup, &ArgGroup)> where F: Fn(&ArgGroup) -> bool,2223     fn two_groups_of<F>(&self, condition: F) -> Option<(&ArgGroup, &ArgGroup)>
2224     where
2225         F: Fn(&ArgGroup) -> bool,
2226     {
2227         two_elements_of(self.groups.iter().filter(|a| condition(a)))
2228     }
2229 
_propagate(&mut self, prop: Propagation)2230     pub(crate) fn _propagate(&mut self, prop: Propagation) {
2231         macro_rules! propagate_subcmd {
2232             ($_self:expr, $sc:expr) => {{
2233                 // We have to create a new scope in order to tell rustc the borrow of `sc` is
2234                 // done and to recursively call this method
2235                 {
2236                     let vsc = $_self.settings.is_set(AppSettings::VersionlessSubcommands);
2237                     let gv = $_self.settings.is_set(AppSettings::GlobalVersion);
2238 
2239                     if vsc {
2240                         $sc.set(AppSettings::DisableVersion);
2241                     }
2242                     if gv && $sc.version.is_none() && $_self.version.is_some() {
2243                         $sc.set(AppSettings::GlobalVersion);
2244                         $sc.version = Some($_self.version.unwrap());
2245                     }
2246                     $sc.settings = $sc.settings | $_self.g_settings;
2247                     $sc.g_settings = $sc.g_settings | $_self.g_settings;
2248                     $sc.term_w = $_self.term_w;
2249                     $sc.max_w = $_self.max_w;
2250                 }
2251                 {
2252                     // FIXME: This doesn't belong here at all.
2253                     for a in $_self.args.args.iter().filter(|a| a.global) {
2254                         if $sc.find(&a.id).is_none() {
2255                             $sc.args.push(a.clone());
2256                         }
2257                     }
2258                 }
2259             }};
2260         }
2261 
2262         debug!("App::_propagate:{}", self.name);
2263 
2264         match prop {
2265             Propagation::NextLevel | Propagation::Full => {
2266                 for sc in &mut self.subcommands {
2267                     propagate_subcmd!(self, sc);
2268                     if prop == Propagation::Full {
2269                         sc._propagate(prop.clone());
2270                     }
2271                 }
2272             }
2273             Propagation::To(id) => {
2274                 let mut sc = self
2275                     .subcommands
2276                     .iter_mut()
2277                     .find(|sc| sc.id == id)
2278                     .expect(INTERNAL_ERROR_MSG);
2279                 propagate_subcmd!(self, sc);
2280             }
2281             Propagation::None => (),
2282         }
2283     }
2284 
_create_help_and_version(&mut self)2285     pub(crate) fn _create_help_and_version(&mut self) {
2286         debug!("App::_create_help_and_version");
2287 
2288         if !(self
2289             .args
2290             .args
2291             .iter()
2292             .any(|x| x.long == Some("help") || x.id == Id::help_hash())
2293             || self.is_set(AppSettings::DisableHelpFlags)
2294             || self
2295                 .subcommands
2296                 .iter()
2297                 .any(|sc| sc.short_flag == Some('h') || sc.long_flag == Some("help")))
2298         {
2299             debug!("App::_create_help_and_version: Building --help");
2300             let mut help = Arg::new("help")
2301                 .long("help")
2302                 .about("Prints help information");
2303             if !self.args.args.iter().any(|x| x.short == Some('h')) {
2304                 help = help.short('h');
2305             }
2306 
2307             self.args.push(help);
2308         }
2309         if !(self
2310             .args
2311             .args
2312             .iter()
2313             .any(|x| x.long == Some("version") || x.id == Id::version_hash())
2314             || self.is_set(AppSettings::DisableVersion)
2315             || self
2316                 .subcommands
2317                 .iter()
2318                 .any(|sc| sc.short_flag == Some('V') || sc.long_flag == Some("version")))
2319         {
2320             debug!("App::_create_help_and_version: Building --version");
2321             let mut version = Arg::new("version")
2322                 .long("version")
2323                 .about("Prints version information");
2324             if !self.args.args.iter().any(|x| x.short == Some('V')) {
2325                 version = version.short('V');
2326             }
2327 
2328             self.args.push(version);
2329         }
2330         if self.has_subcommands()
2331             && !self.is_set(AppSettings::DisableHelpSubcommand)
2332             && !self.subcommands.iter().any(|s| s.id == Id::help_hash())
2333         {
2334             debug!("App::_create_help_and_version: Building help");
2335             self.subcommands.push(
2336                 App::new("help")
2337                     .about("Prints this message or the help of the given subcommand(s)"),
2338             );
2339         }
2340     }
2341 
_derive_display_order(&mut self)2342     pub(crate) fn _derive_display_order(&mut self) {
2343         debug!("App::_derive_display_order:{}", self.name);
2344 
2345         if self.settings.is_set(AppSettings::DeriveDisplayOrder) {
2346             for (i, a) in self
2347                 .args
2348                 .args
2349                 .iter_mut()
2350                 .filter(|a| a.has_switch())
2351                 .filter(|a| a.disp_ord == 999)
2352                 .enumerate()
2353             {
2354                 a.disp_ord = i;
2355             }
2356             for (i, mut sc) in &mut self
2357                 .subcommands
2358                 .iter_mut()
2359                 .enumerate()
2360                 .filter(|&(_, ref sc)| sc.disp_ord == 999)
2361             {
2362                 sc.disp_ord = i;
2363             }
2364         }
2365         for sc in &mut self.subcommands {
2366             sc._derive_display_order();
2367         }
2368     }
2369 
2370     // used in clap_generate (https://github.com/clap-rs/clap_generate)
2371     #[doc(hidden)]
_build_bin_names(&mut self)2372     pub fn _build_bin_names(&mut self) {
2373         debug!("App::_build_bin_names");
2374 
2375         for mut sc in &mut self.subcommands {
2376             debug!("App::_build_bin_names:iter: bin_name set...");
2377 
2378             if sc.bin_name.is_none() {
2379                 debug!("No");
2380                 let bin_name = format!(
2381                     "{}{}{}",
2382                     self.bin_name.as_ref().unwrap_or(&self.name.clone()),
2383                     if self.bin_name.is_some() { " " } else { "" },
2384                     &*sc.name
2385                 );
2386                 debug!(
2387                     "App::_build_bin_names:iter: Setting bin_name of {} to {}",
2388                     self.name, bin_name
2389                 );
2390                 sc.bin_name = Some(bin_name);
2391             } else {
2392                 debug!("yes ({:?})", sc.bin_name);
2393             }
2394             debug!(
2395                 "App::_build_bin_names:iter: Calling build_bin_names from...{}",
2396                 sc.name
2397             );
2398             sc._build_bin_names();
2399         }
2400     }
2401 
_render_version(&self, use_long: bool) -> String2402     pub(crate) fn _render_version(&self, use_long: bool) -> String {
2403         debug!("App::_render_version");
2404 
2405         let ver = if use_long {
2406             self.long_version
2407                 .unwrap_or_else(|| self.version.unwrap_or(""))
2408         } else {
2409             self.version
2410                 .unwrap_or_else(|| self.long_version.unwrap_or(""))
2411         };
2412         if let Some(bn) = self.bin_name.as_ref() {
2413             if bn.contains(' ') {
2414                 // In case we're dealing with subcommands i.e. git mv is translated to git-mv
2415                 format!("{} {}\n", bn.replace(" ", "-"), ver)
2416             } else {
2417                 format!("{} {}\n", &self.name[..], ver)
2418             }
2419         } else {
2420             format!("{} {}\n", &self.name[..], ver)
2421         }
2422     }
2423 
format_group(&self, g: &Id) -> String2424     pub(crate) fn format_group(&self, g: &Id) -> String {
2425         let g_string = self
2426             .unroll_args_in_group(g)
2427             .iter()
2428             .filter_map(|x| self.find(x))
2429             .map(|x| {
2430                 if x.index.is_some() {
2431                     x.name.to_owned()
2432                 } else {
2433                     x.to_string()
2434                 }
2435             })
2436             .collect::<Vec<_>>()
2437             .join("|");
2438         format!("<{}>", &*g_string)
2439     }
2440 }
2441 
2442 // Internal Query Methods
2443 impl<'help> App<'help> {
find(&self, arg_id: &Id) -> Option<&Arg<'help>>2444     pub(crate) fn find(&self, arg_id: &Id) -> Option<&Arg<'help>> {
2445         self.args.args.iter().find(|a| a.id == *arg_id)
2446     }
2447 
2448     #[inline]
2449     // Should we color the output?
color(&self) -> ColorChoice2450     pub(crate) fn color(&self) -> ColorChoice {
2451         debug!("App::color: Color setting...");
2452 
2453         if self.is_set(AppSettings::ColorNever) {
2454             debug!("Never");
2455             ColorChoice::Never
2456         } else if self.is_set(AppSettings::ColorAlways) {
2457             debug!("Always");
2458             ColorChoice::Always
2459         } else {
2460             debug!("Auto");
2461             ColorChoice::Auto
2462         }
2463     }
2464 
2465     #[inline]
contains_short(&self, s: char) -> bool2466     pub(crate) fn contains_short(&self, s: char) -> bool {
2467         if !self.is_set(AppSettings::Built) {
2468             panic!("If App::_build hasn't been called, manually search through Arg shorts");
2469         }
2470 
2471         self.args.contains(s)
2472     }
2473 
2474     #[inline]
set(&mut self, s: AppSettings)2475     pub(crate) fn set(&mut self, s: AppSettings) {
2476         self.settings.set(s)
2477     }
2478 
2479     #[inline]
unset(&mut self, s: AppSettings)2480     pub(crate) fn unset(&mut self, s: AppSettings) {
2481         self.settings.unset(s)
2482     }
2483 
2484     #[inline]
has_args(&self) -> bool2485     pub(crate) fn has_args(&self) -> bool {
2486         !self.args.is_empty()
2487     }
2488 
2489     #[inline]
has_opts(&self) -> bool2490     pub(crate) fn has_opts(&self) -> bool {
2491         self.get_opts_with_no_heading().count() > 0
2492     }
2493 
2494     #[inline]
has_flags(&self) -> bool2495     pub(crate) fn has_flags(&self) -> bool {
2496         self.get_flags_with_no_heading().count() > 0
2497     }
2498 
has_visible_subcommands(&self) -> bool2499     pub(crate) fn has_visible_subcommands(&self) -> bool {
2500         self.subcommands
2501             .iter()
2502             .any(|sc| sc.name != "help" && !sc.is_set(AppSettings::Hidden))
2503     }
2504 
2505     /// Check if this subcommand can be referred to as `name`. In other words,
2506     /// check if `name` is the name of this subcommand or is one of its aliases.
2507     #[inline]
aliases_to<T>(&self, name: &T) -> bool where T: PartialEq<str> + ?Sized,2508     pub(crate) fn aliases_to<T>(&self, name: &T) -> bool
2509     where
2510         T: PartialEq<str> + ?Sized,
2511     {
2512         *name == *self.get_name() || self.get_all_aliases().any(|alias| *name == *alias)
2513     }
2514 
2515     /// Check if this subcommand can be referred to as `name`. In other words,
2516     /// check if `name` is the name of this short flag subcommand or is one of its short flag aliases.
2517     #[inline]
short_flag_aliases_to(&self, flag: char) -> bool2518     pub(crate) fn short_flag_aliases_to(&self, flag: char) -> bool {
2519         Some(flag) == self.short_flag
2520             || self.get_all_short_flag_aliases().any(|alias| flag == alias)
2521     }
2522 
2523     /// Check if this subcommand can be referred to as `name`. In other words,
2524     /// check if `name` is the name of this long flag subcommand or is one of its long flag aliases.
2525     #[inline]
long_flag_aliases_to<T>(&self, flag: &T) -> bool where T: PartialEq<str> + ?Sized,2526     pub(crate) fn long_flag_aliases_to<T>(&self, flag: &T) -> bool
2527     where
2528         T: PartialEq<str> + ?Sized,
2529     {
2530         match self.long_flag {
2531             Some(long_flag) => {
2532                 flag == long_flag || self.get_all_long_flag_aliases().any(|alias| flag == alias)
2533             }
2534             None => self.get_all_long_flag_aliases().any(|alias| flag == alias),
2535         }
2536     }
2537 
2538     #[cfg(debug_assertions)]
id_exists(&self, id: &Id) -> bool2539     pub(crate) fn id_exists(&self, id: &Id) -> bool {
2540         self.args.args.iter().any(|x| x.id == *id) || self.groups.iter().any(|x| x.id == *id)
2541     }
2542 
2543     /// Iterate through the groups this arg is member of.
groups_for_arg<'a>(&'a self, arg: &Id) -> impl Iterator<Item = Id> + 'a2544     pub(crate) fn groups_for_arg<'a>(&'a self, arg: &Id) -> impl Iterator<Item = Id> + 'a {
2545         debug!("App::groups_for_arg: id={:?}", arg);
2546         let arg = arg.clone();
2547         self.groups
2548             .iter()
2549             .filter(move |grp| grp.args.iter().any(|a| a == &arg))
2550             .map(|grp| grp.id.clone())
2551     }
2552 
2553     /// Iterate through all the names of all subcommands (not recursively), including aliases.
2554     /// Used for suggestions.
all_subcommand_names<'a>(&'a self) -> impl Iterator<Item = &'a str> where 'help: 'a,2555     pub(crate) fn all_subcommand_names<'a>(&'a self) -> impl Iterator<Item = &'a str>
2556     where
2557         'help: 'a,
2558     {
2559         let a: Vec<_> = self
2560             .get_subcommands()
2561             .flat_map(|sc| {
2562                 let name = sc.get_name();
2563                 let aliases = sc.get_all_aliases();
2564                 std::iter::once(name).chain(aliases)
2565             })
2566             .collect();
2567 
2568         // Strictly speaking, we don't need this trip through the Vec.
2569         // We should have been able to return FlatMap iter above directly.
2570         //
2571         // Unfortunately, that would trigger
2572         // https://github.com/rust-lang/rust/issues/34511#issuecomment-373423999
2573         //
2574         // I think this "collect to vec" solution is better then the linked one
2575         // because it's simpler and it doesn't really matter performance-wise.
2576         a.into_iter()
2577     }
2578 
unroll_args_in_group(&self, group: &Id) -> Vec<Id>2579     pub(crate) fn unroll_args_in_group(&self, group: &Id) -> Vec<Id> {
2580         debug!("App::unroll_args_in_group: group={:?}", group);
2581         let mut g_vec = vec![group];
2582         let mut args = vec![];
2583 
2584         while let Some(g) = g_vec.pop() {
2585             for n in self
2586                 .groups
2587                 .iter()
2588                 .find(|grp| grp.id == *g)
2589                 .expect(INTERNAL_ERROR_MSG)
2590                 .args
2591                 .iter()
2592             {
2593                 debug!("App::unroll_args_in_group:iter: entity={:?}", n);
2594                 if !args.contains(n) {
2595                     if self.find(n).is_some() {
2596                         debug!("App::unroll_args_in_group:iter: this is an arg");
2597                         args.push(n.clone())
2598                     } else {
2599                         debug!("App::unroll_args_in_group:iter: this is a group");
2600                         g_vec.push(n);
2601                     }
2602                 }
2603             }
2604         }
2605 
2606         args
2607     }
2608 
unroll_requirements_for_arg(&self, arg: &Id, matcher: &ArgMatcher) -> Vec<Id>2609     pub(crate) fn unroll_requirements_for_arg(&self, arg: &Id, matcher: &ArgMatcher) -> Vec<Id> {
2610         let requires_if_or_not = |(val, req_arg): &(Option<&str>, Id)| -> Option<Id> {
2611             if let Some(v) = val {
2612                 if matcher
2613                     .get(arg)
2614                     .map(|ma| ma.contains_val(v))
2615                     .unwrap_or(false)
2616                 {
2617                     Some(req_arg.clone())
2618                 } else {
2619                     None
2620                 }
2621             } else {
2622                 Some(req_arg.clone())
2623             }
2624         };
2625 
2626         let mut processed = vec![];
2627         let mut r_vec = vec![arg];
2628         let mut args = vec![];
2629 
2630         while let Some(a) = r_vec.pop() {
2631             if processed.contains(&a) {
2632                 continue;
2633             }
2634 
2635             processed.push(a);
2636 
2637             if let Some(arg) = self.find(a) {
2638                 for r in arg.requires.iter().filter_map(requires_if_or_not) {
2639                     if let Some(req) = self.find(&r) {
2640                         if !req.requires.is_empty() {
2641                             r_vec.push(&req.id)
2642                         }
2643                     }
2644                     args.push(r);
2645                 }
2646             }
2647         }
2648 
2649         args
2650     }
2651 
2652     /// Find a flag subcommand name by short flag or an alias
find_short_subcmd(&self, c: char) -> Option<&str>2653     pub(crate) fn find_short_subcmd(&self, c: char) -> Option<&str> {
2654         self.get_subcommands()
2655             .find(|sc| sc.short_flag_aliases_to(c))
2656             .map(|sc| sc.get_name())
2657     }
2658 
2659     /// Find a flag subcommand name by long flag or an alias
find_long_subcmd(&self, long: &ArgStr) -> Option<&str>2660     pub(crate) fn find_long_subcmd(&self, long: &ArgStr) -> Option<&str> {
2661         self.get_subcommands()
2662             .find(|sc| sc.long_flag_aliases_to(long))
2663             .map(|sc| sc.get_name())
2664     }
2665 }
2666 
2667 impl<'help> Index<&'_ Id> for App<'help> {
2668     type Output = Arg<'help>;
2669 
index(&self, key: &Id) -> &Self::Output2670     fn index(&self, key: &Id) -> &Self::Output {
2671         self.find(key).expect(INTERNAL_ERROR_MSG)
2672     }
2673 }
2674 
2675 #[cfg(feature = "yaml")]
2676 impl<'help> From<&'help Yaml> for App<'help> {
2677     #[allow(clippy::cognitive_complexity)]
from(mut yaml: &'help Yaml) -> Self2678     fn from(mut yaml: &'help Yaml) -> Self {
2679         // We WANT this to panic on error...so expect() is good.
2680         let mut is_sc = None;
2681         let mut a = if let Some(name) = yaml["name"].as_str() {
2682             App::new(name)
2683         } else {
2684             let yaml_hash = yaml.as_hash().unwrap();
2685             let sc_key = yaml_hash.keys().next().unwrap();
2686             is_sc = Some(yaml_hash.get(sc_key).unwrap());
2687             App::new(sc_key.as_str().unwrap())
2688         };
2689         yaml = if let Some(sc) = is_sc { sc } else { yaml };
2690 
2691         macro_rules! yaml_str {
2692             ($a:ident, $y:ident, $i:ident) => {
2693                 if let Some(v) = $y[stringify!($i)].as_str() {
2694                     $a = $a.$i(v);
2695                 } else if $y[stringify!($i)] != Yaml::BadValue {
2696                     panic!(
2697                         "Failed to convert YAML value {:?} to a string",
2698                         $y[stringify!($i)]
2699                     );
2700                 }
2701             };
2702         }
2703 
2704         yaml_str!(a, yaml, version);
2705         yaml_str!(a, yaml, long_version);
2706         yaml_str!(a, yaml, author);
2707         yaml_str!(a, yaml, bin_name);
2708         yaml_str!(a, yaml, about);
2709         yaml_str!(a, yaml, before_help);
2710         yaml_str!(a, yaml, before_long_help);
2711         yaml_str!(a, yaml, after_help);
2712         yaml_str!(a, yaml, after_long_help);
2713         yaml_str!(a, yaml, alias);
2714         yaml_str!(a, yaml, visible_alias);
2715 
2716         if let Some(v) = yaml["display_order"].as_i64() {
2717             a = a.display_order(v as usize);
2718         } else if yaml["display_order"] != Yaml::BadValue {
2719             panic!(
2720                 "Failed to convert YAML value {:?} to a u64",
2721                 yaml["display_order"]
2722             );
2723         }
2724         if let Some(v) = yaml["setting"].as_str() {
2725             a = a.setting(v.parse().expect("unknown AppSetting found in YAML file"));
2726         } else if yaml["setting"] != Yaml::BadValue {
2727             panic!(
2728                 "Failed to convert YAML value {:?} to an AppSetting",
2729                 yaml["setting"]
2730             );
2731         }
2732         if let Some(v) = yaml["settings"].as_vec() {
2733             for ys in v {
2734                 if let Some(s) = ys.as_str() {
2735                     a = a.setting(s.parse().expect("unknown AppSetting found in YAML file"));
2736                 }
2737             }
2738         } else if let Some(v) = yaml["settings"].as_str() {
2739             a = a.setting(v.parse().expect("unknown AppSetting found in YAML file"));
2740         } else if yaml["settings"] != Yaml::BadValue {
2741             panic!(
2742                 "Failed to convert YAML value {:?} to a string",
2743                 yaml["settings"]
2744             );
2745         }
2746         if let Some(v) = yaml["global_setting"].as_str() {
2747             a = a.setting(v.parse().expect("unknown AppSetting found in YAML file"));
2748         } else if yaml["global_setting"] != Yaml::BadValue {
2749             panic!(
2750                 "Failed to convert YAML value {:?} to an AppSetting",
2751                 yaml["setting"]
2752             );
2753         }
2754         if let Some(v) = yaml["global_settings"].as_vec() {
2755             for ys in v {
2756                 if let Some(s) = ys.as_str() {
2757                     a = a.global_setting(s.parse().expect("unknown AppSetting found in YAML file"));
2758                 }
2759             }
2760         } else if let Some(v) = yaml["global_settings"].as_str() {
2761             a = a.global_setting(v.parse().expect("unknown AppSetting found in YAML file"));
2762         } else if yaml["global_settings"] != Yaml::BadValue {
2763             panic!(
2764                 "Failed to convert YAML value {:?} to a string",
2765                 yaml["global_settings"]
2766             );
2767         }
2768 
2769         macro_rules! vec_or_str {
2770             ($a:ident, $y:ident, $as_vec:ident, $as_single:ident) => {{
2771                 let maybe_vec = $y[stringify!($as_vec)].as_vec();
2772                 if let Some(vec) = maybe_vec {
2773                     for ys in vec {
2774                         if let Some(s) = ys.as_str() {
2775                             $a = $a.$as_single(s);
2776                         } else {
2777                             panic!("Failed to convert YAML value {:?} to a string", ys);
2778                         }
2779                     }
2780                 } else {
2781                     if let Some(s) = $y[stringify!($as_vec)].as_str() {
2782                         $a = $a.$as_single(s);
2783                     } else if $y[stringify!($as_vec)] != Yaml::BadValue {
2784                         panic!(
2785                             "Failed to convert YAML value {:?} to either a vec or string",
2786                             $y[stringify!($as_vec)]
2787                         );
2788                     }
2789                 }
2790                 $a
2791             }};
2792         }
2793 
2794         a = vec_or_str!(a, yaml, aliases, alias);
2795         a = vec_or_str!(a, yaml, visible_aliases, visible_alias);
2796 
2797         if let Some(v) = yaml["args"].as_vec() {
2798             for arg_yaml in v {
2799                 a = a.arg(Arg::from(arg_yaml));
2800             }
2801         }
2802         if let Some(v) = yaml["subcommands"].as_vec() {
2803             for sc_yaml in v {
2804                 a = a.subcommand(App::from(sc_yaml));
2805             }
2806         }
2807         if let Some(v) = yaml["groups"].as_vec() {
2808             for ag_yaml in v {
2809                 a = a.group(ArgGroup::from(ag_yaml));
2810             }
2811         }
2812 
2813         a
2814     }
2815 }
2816 
2817 impl fmt::Display for App<'_> {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result2818     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2819         write!(f, "{}", self.name)
2820     }
2821 }
2822 
two_elements_of<I, T>(mut iter: I) -> Option<(T, T)> where I: Iterator<Item = T>,2823 fn two_elements_of<I, T>(mut iter: I) -> Option<(T, T)>
2824 where
2825     I: Iterator<Item = T>,
2826 {
2827     let first = iter.next();
2828     let second = iter.next();
2829 
2830     match (first, second) {
2831         (Some(first), Some(second)) => Some((first, second)),
2832         _ => None,
2833     }
2834 }
2835