12 use std
::ffi
::{OsStr, OsString}
;
14 use std
::io
::{self, BufRead, BufWriter, Write}
;
18 use std
::result
::Result
as StdResult
;
21 #[cfg(feature = "yaml")]
26 use app
::parser
::Parser
;
27 use args
::{AnyArg, Arg, ArgGroup, ArgMatcher, ArgMatches, ArgSettings}
;
28 use errors
::Result
as ClapResult
;
29 pub use self::settings
::AppSettings
;
30 use completions
::Shell
;
31 use map
::{self, VecMap}
;
33 /// Used to create a representation of a command line program and all possible command line
34 /// arguments. Application settings are set using the "builder pattern" with the
35 /// [`App::get_matches`] family of methods being the terminal methods that starts the
36 /// runtime-parsing process. These methods then return information about the user supplied
37 /// arguments (or lack there of).
39 /// **NOTE:** There aren't any mandatory "options" that one must set. The "options" may
40 /// also appear in any order (so long as one of the [`App::get_matches`] methods is the last method
46 /// # use clap::{App, Arg};
47 /// let m = App::new("My Program")
48 /// .author("Me, me@mail.com")
50 /// .about("Explains in brief what the program does")
52 /// Arg::with_name("in_file").index(1)
54 /// .after_help("Longer explanation to appear after the options when \
55 /// displaying the help information from --help or -h")
58 /// // Your program logic starts here...
60 /// [`App::get_matches`]: ./struct.App.html#method.get_matches
61 #[allow(missing_debug_implementations)]
62 pub struct App
<'a
, 'b
>
66 pub p
: Parser
<'a
, 'b
>,
70 impl<'a
, 'b
> App
<'a
, 'b
> {
71 /// Creates a new instance of an application requiring a name. The name may be, but doesn't
72 /// have to be same as the binary. The name will be displayed to the user when they request to
73 /// print version or help and usage information.
78 /// # use clap::{App, Arg};
79 /// let prog = App::new("My Program")
82 pub fn new
<S
: Into
<String
>>(n
: S
) -> Self { App { p: Parser::with_name(n.into()) }
}
84 /// Get the name of the app
85 pub fn get_name(&self) -> &str { &self.p.meta.name }
87 /// Get the name of the binary
88 pub fn get_bin_name(&self) -> Option
<&str> { self.p.meta.bin_name.as_ref().map(|s| s.as_str()) }
90 /// Creates a new instance of an application requiring a name, but uses the [`crate_authors!`]
91 /// and [`crate_version!`] macros to fill in the [`App::author`] and [`App::version`] fields.
96 /// # use clap::{App, Arg};
97 /// let prog = App::with_defaults("My Program")
100 /// [`crate_authors!`]: ./macro.crate_authors!.html
101 /// [`crate_version!`]: ./macro.crate_version!.html
102 /// [`App::author`]: ./struct.App.html#method.author
103 /// [`App::version`]: ./struct.App.html#method.author
104 #[deprecated(since="2.14.1", note="Can never work; use explicit App::author() and App::version() calls instead")]
105 pub fn with_defaults
<S
: Into
<String
>>(n
: S
) -> Self {
106 let mut a
= App { p: Parser::with_name(n.into()) }
;
107 a
.p
.meta
.author
= Some("Kevin K. <kbknapp@gmail.com>");
108 a
.p
.meta
.version
= Some("2.19.2");
112 /// Creates a new instance of [`App`] from a .yml (YAML) file. A full example of supported YAML
113 /// objects can be found in [`examples/17_yaml.rs`] and [`examples/17_yaml.yml`]. One great use
114 /// for using YAML is when supporting multiple languages and dialects, as each language could
115 /// be a distinct YAML file and determined at compiletime via `cargo` "features" in your
118 /// In order to use this function you must compile `clap` with the `features = ["yaml"]` in
119 /// your settings for the `[dependencies.clap]` table of your `Cargo.toml`
121 /// **NOTE:** Due to how the YAML objects are built there is a convenience macro for loading
122 /// the YAML file at compile time (relative to the current file, like modules work). That YAML
123 /// object can then be passed to this function.
127 /// The YAML file must be properly formatted or this function will [`panic!`]. A good way to
128 /// ensure this doesn't happen is to run your program with the `--help` switch. If this passes
129 /// without error, you needn't worry because the YAML is properly formatted.
133 /// The following example shows how to load a properly formatted YAML file to build an instance
134 /// of an [`App`] struct.
138 /// # extern crate clap;
141 /// let yml = load_yaml!("app.yml");
142 /// let app = App::from_yaml(yml);
144 /// // continued logic goes here, such as `app.get_matches()` etc.
147 /// [`App`]: ./struct.App.html
148 /// [`examples/17_yaml.rs`]: https://github.com/kbknapp/clap-rs/blob/master/examples/17_yaml.rs
149 /// [`examples/17_yaml.yml`]: https://github.com/kbknapp/clap-rs/blob/master/examples/17_yaml.yml
150 /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html
151 #[cfg(feature = "yaml")]
152 pub fn from_yaml(yaml
: &'a Yaml
) -> App
<'a
, 'a
> { App::from(yaml) }
154 /// Sets a string of author(s) that will be displayed to the user when they
155 /// request the help information with `--help` or `-h`.
157 /// **Pro-tip:** Use `clap`s convenience macro [`crate_authors!`] to automatically set your
158 /// application's author(s) to the same thing as your crate at compile time. See the [`examples/`]
159 /// directory for more information
161 /// See the [`examples/`]
162 /// directory for more information
167 /// # use clap::{App, Arg};
168 /// App::new("myprog")
169 /// .author("Me, me@mymain.com")
172 /// [`crate_authors!`]: ./macro.crate_authors!.html
173 /// [`examples/`]: https://github.com/kbknapp/clap-rs/tree/master/examples
174 pub fn author
<S
: Into
<&'b
str>>(mut self, author
: S
) -> Self {
175 self.p
.meta
.author
= Some(author
.into());
179 /// Overrides the system-determined binary name. This should only be used when absolutely
180 /// necessary, such as when the binary name for your application is misleading, or perhaps
181 /// *not* how the user should invoke your program.
183 /// **Pro-tip:** When building things such as third party `cargo` subcommands, this setting
184 /// **should** be used!
186 /// **NOTE:** This command **should not** be used for [`SubCommand`]s.
191 /// # use clap::{App, Arg};
192 /// App::new("My Program")
193 /// .bin_name("my_binary")
196 /// [`SubCommand`]: ./struct.SubCommand.html
197 pub fn bin_name
<S
: Into
<String
>>(mut self, name
: S
) -> Self {
198 self.p
.meta
.bin_name
= Some(name
.into());
202 /// Sets a string describing what the program does. This will be displayed when displaying help
203 /// information with `-h`.
205 /// **NOTE:** If only `about` is provided, and not [`App::long_about`] but the user requests
206 /// `--help` clap will still display the contents of `about` appropriately
208 /// **NOTE:** Only [`App::about`] is used in completion script generation in order to be
214 /// # use clap::{App, Arg};
215 /// App::new("myprog")
216 /// .about("Does really amazing things to great people")
219 /// [`App::long_about`]: ./struct.App.html#method.long_about
220 pub fn about
<S
: Into
<&'b
str>>(mut self, about
: S
) -> Self {
221 self.p
.meta
.about
= Some(about
.into());
225 /// Sets a string describing what the program does. This will be displayed when displaying help
228 /// **NOTE:** If only `long_about` is provided, and not [`App::about`] but the user requests
229 /// `-h` clap will still display the contents of `long_about` appropriately
231 /// **NOTE:** Only [`App::about`] is used in completion script generation in order to be
237 /// # use clap::{App, Arg};
238 /// App::new("myprog")
240 /// "Does really amazing things to great people. Now let's talk a little
241 /// more in depth about how this subcommand really works. It may take about
242 /// a few lines of text, but that's ok!")
245 /// [`App::about`]: ./struct.App.html#method.about
246 pub fn long_about
<S
: Into
<&'b
str>>(mut self, about
: S
) -> Self {
247 self.p
.meta
.long_about
= Some(about
.into());
251 /// Sets the program's name. This will be displayed when displaying help information.
253 /// **Pro-top:** This function is particularly useful when configuring a program via
254 /// [`App::from_yaml`] in conjunction with the [`crate_name!`] macro to derive the program's
255 /// name from its `Cargo.toml`.
260 /// # extern crate clap;
263 /// let yml = load_yaml!("app.yml");
264 /// let app = App::from_yaml(yml)
265 /// .name(crate_name!());
267 /// // continued logic goes here, such as `app.get_matches()` etc.
271 /// [`App::from_yaml`]: ./struct.App.html#method.from_yaml
272 /// [`crate_name!`]: ./macro.crate_name.html
273 pub fn name
<S
: Into
<String
>>(mut self, name
: S
) -> Self {
274 self.p
.meta
.name
= name
.into();
278 /// Adds additional help information to be displayed in addition to auto-generated help. This
279 /// information is displayed **after** the auto-generated help information. This is often used
280 /// to describe how to use the arguments, or caveats to be noted.
286 /// App::new("myprog")
287 /// .after_help("Does really amazing things to great people...but be careful with -R")
290 pub fn after_help
<S
: Into
<&'b
str>>(mut self, help
: S
) -> Self {
291 self.p
.meta
.more_help
= Some(help
.into());
295 /// Adds additional help information to be displayed in addition to auto-generated help. This
296 /// information is displayed **before** the auto-generated help information. This is often used
297 /// for header information.
303 /// App::new("myprog")
304 /// .before_help("Some info I'd like to appear before the help info")
307 pub fn before_help
<S
: Into
<&'b
str>>(mut self, help
: S
) -> Self {
308 self.p
.meta
.pre_help
= Some(help
.into());
312 /// Sets a string of the version number to be displayed when displaying version or help
313 /// information with `-V`.
315 /// **NOTE:** If only `version` is provided, and not [`App::long_version`] but the user
316 /// requests `--version` clap will still display the contents of `version` appropriately
318 /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to automatically set your
319 /// application's version to the same thing as your crate at compile time. See the [`examples/`]
320 /// directory for more information
325 /// # use clap::{App, Arg};
326 /// App::new("myprog")
327 /// .version("v0.1.24")
330 /// [`crate_version!`]: ./macro.crate_version!.html
331 /// [`examples/`]: https://github.com/kbknapp/clap-rs/tree/master/examples
332 /// [`App::long_version`]: ./struct.App.html#method.long_version
333 pub fn version
<S
: Into
<&'b
str>>(mut self, ver
: S
) -> Self {
334 self.p
.meta
.version
= Some(ver
.into());
338 /// Sets a string of the version number to be displayed when displaying version or help
339 /// information with `--version`.
341 /// **NOTE:** If only `long_version` is provided, and not [`App::version`] but the user
342 /// requests `-V` clap will still display the contents of `long_version` appropriately
344 /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to automatically set your
345 /// application's version to the same thing as your crate at compile time. See the [`examples/`]
346 /// directory for more information
351 /// # use clap::{App, Arg};
352 /// App::new("myprog")
355 /// commit: abcdef89726d
361 /// [`crate_version!`]: ./macro.crate_version!.html
362 /// [`examples/`]: https://github.com/kbknapp/clap-rs/tree/master/examples
363 /// [`App::version`]: ./struct.App.html#method.version
364 pub fn long_version
<S
: Into
<&'b
str>>(mut self, ver
: S
) -> Self {
365 self.p
.meta
.long_version
= Some(ver
.into());
369 /// Sets a custom usage string to override the auto-generated usage string.
371 /// This will be displayed to the user when errors are found in argument parsing, or when you
372 /// call [`ArgMatches::usage`]
374 /// **CAUTION:** Using this setting disables `clap`s "context-aware" usage strings. After this
375 /// setting is set, this will be the only usage string displayed to the user!
377 /// **NOTE:** You do not need to specify the "USAGE: \n\t" portion, as that will
378 /// still be applied by `clap`, you only need to specify the portion starting
379 /// with the binary name.
381 /// **NOTE:** This will not replace the entire help message, *only* the portion
382 /// showing the usage.
387 /// # use clap::{App, Arg};
388 /// App::new("myprog")
389 /// .usage("myapp [-clDas] <some_file>")
392 /// [`ArgMatches::usage`]: ./struct.ArgMatches.html#method.usage
393 pub fn usage
<S
: Into
<&'b
str>>(mut self, usage
: S
) -> Self {
394 self.p
.meta
.usage_str
= Some(usage
.into());
398 /// Sets a custom help message and overrides the auto-generated one. This should only be used
399 /// when the auto-generated message does not suffice.
401 /// This will be displayed to the user when they use `--help` or `-h`
403 /// **NOTE:** This replaces the **entire** help message, so nothing will be auto-generated.
405 /// **NOTE:** This **only** replaces the help message for the current command, meaning if you
406 /// are using subcommands, those help messages will still be auto-generated unless you
407 /// specify a [`Arg::help`] for them as well.
412 /// # use clap::{App, Arg};
413 /// App::new("myapp")
414 /// .help("myapp v1.0\n\
415 /// Does awesome things\n\
416 /// (C) me@mail.com\n\n\
418 /// USAGE: myapp <opts> <comamnd>\n\n\
421 /// -h, --helpe Dispay this message\n\
422 /// -V, --version Display version info\n\
423 /// -s <stuff> Do something with stuff\n\
424 /// -v Be verbose\n\n\
427 /// help Prints this message\n\
428 /// work Do some work")
431 /// [`Arg::help`]: ./struct.Arg.html#method.help
432 pub fn help
<S
: Into
<&'b
str>>(mut self, help
: S
) -> Self {
433 self.p
.meta
.help_str
= Some(help
.into());
437 /// Sets the [`short`] for the auto-generated `help` argument.
439 /// By default `clap` automatically assigns `h`, but this can be overridden if you have a
440 /// different argument which you'd prefer to use the `-h` short with. This can be done by
441 /// defining your own argument with a lowercase `h` as the [`short`].
443 /// `clap` lazily generates these `help` arguments **after** you've defined any arguments of
446 /// **NOTE:** Any leading `-` characters will be stripped, and only the first
447 /// non `-` character will be used as the [`short`] version
452 /// # use clap::{App, Arg};
453 /// App::new("myprog")
454 /// .help_short("H") // Using an uppercase `H` instead of the default lowercase `h`
457 /// [`short`]: ./struct.Arg.html#method.short
458 pub fn help_short
<S
: AsRef
<str> + 'b
>(mut self, s
: S
) -> Self {
459 self.p
.help_short(s
.as_ref());
463 /// Sets the [`short`] for the auto-generated `version` argument.
465 /// By default `clap` automatically assigns `V`, but this can be overridden if you have a
466 /// different argument which you'd prefer to use the `-V` short with. This can be done by
467 /// defining your own argument with an uppercase `V` as the [`short`].
469 /// `clap` lazily generates these `version` arguments **after** you've defined any arguments of
472 /// **NOTE:** Any leading `-` characters will be stripped, and only the first
473 /// non `-` character will be used as the `short` version
478 /// # use clap::{App, Arg};
479 /// App::new("myprog")
480 /// .version_short("v") // Using a lowercase `v` instead of the default capital `V`
483 /// [`short`]: ./struct.Arg.html#method.short
484 pub fn version_short
<S
: AsRef
<str>>(mut self, s
: S
) -> Self {
485 self.p
.version_short(s
.as_ref());
489 /// Sets the help text for the auto-generated `help` argument.
491 /// By default `clap` sets this to `"Prints help information"`, but if you're using a
492 /// different convention for your help messages and would prefer a different phrasing you can
498 /// # use clap::{App, Arg};
499 /// App::new("myprog")
500 /// .help_message("Print help information") // Perhaps you want imperative help messages
504 pub fn help_message
<S
: Into
<&'a
str>>(mut self, s
: S
) -> Self {
505 self.p
.help_message
= Some(s
.into());
509 /// Sets the help text for the auto-generated `version` argument.
511 /// By default `clap` sets this to `"Prints version information"`, but if you're using a
512 /// different convention for your help messages and would prefer a different phrasing then you
517 /// # use clap::{App, Arg};
518 /// App::new("myprog")
519 /// .version_message("Print version information") // Perhaps you want imperative help messages
522 pub fn version_message
<S
: Into
<&'a
str>>(mut self, s
: S
) -> Self {
523 self.p
.version_message
= Some(s
.into());
527 /// Sets the help template to be used, overriding the default format.
529 /// Tags arg given inside curly brackets.
533 /// * `{bin}` - Binary name.
534 /// * `{version}` - Version number.
535 /// * `{author}` - Author information.
536 /// * `{about}` - General description (from [`App::about`])
537 /// * `{usage}` - Automatically generated or given usage string.
538 /// * `{all-args}` - Help for all arguments (options, flags, positionals arguments,
539 /// and subcommands) including titles.
540 /// * `{unified}` - Unified help for options and flags. Note, you must *also* set
541 /// [`AppSettings::UnifiedHelpMessage`] to fully merge both options and
542 /// flags, otherwise the ordering is "best effort"
543 /// * `{flags}` - Help for flags.
544 /// * `{options}` - Help for options.
545 /// * `{positionals}` - Help for positionals arguments.
546 /// * `{subcommands}` - Help for subcommands.
547 /// * `{after-help}` - Help from [`App::after_help`]
548 /// * `{before-help}` - Help from [`App::before_help`]
553 /// # use clap::{App, Arg};
554 /// App::new("myprog")
556 /// .template("{bin} ({version}) - {usage}")
559 /// **NOTE:**The template system is, on purpose, very simple. Therefore the tags have to writen
560 /// in the lowercase and without spacing.
561 /// [`App::about`]: ./struct.App.html#method.about
562 /// [`App::after_help`]: ./struct.App.html#method.after_help
563 /// [`App::before_help`]: ./struct.App.html#method.before_help
564 /// [`AppSettings::UnifiedHelpMessage`]: ./enum.AppSettings.html#variant.UnifiedHelpMessage
565 pub fn template
<S
: Into
<&'b
str>>(mut self, s
: S
) -> Self {
566 self.p
.meta
.template
= Some(s
.into());
570 /// Enables a single command, or [`SubCommand`], level settings.
572 /// See [`AppSettings`] for a full list of possibilities and examples.
577 /// # use clap::{App, Arg, AppSettings};
578 /// App::new("myprog")
579 /// .setting(AppSettings::SubcommandRequired)
580 /// .setting(AppSettings::WaitOnError)
583 /// [`SubCommand`]: ./struct.SubCommand.html
584 /// [`AppSettings`]: ./enum.AppSettings.html
585 pub fn setting(mut self, setting
: AppSettings
) -> Self {
590 /// Enables multiple command, or [`SubCommand`], level settings
592 /// See [`AppSettings`] for a full list of possibilities and examples.
597 /// # use clap::{App, Arg, AppSettings};
598 /// App::new("myprog")
599 /// .settings(&[AppSettings::SubcommandRequired,
600 /// AppSettings::WaitOnError])
603 /// [`SubCommand`]: ./struct.SubCommand.html
604 /// [`AppSettings`]: ./enum.AppSettings.html
605 pub fn settings(mut self, settings
: &[AppSettings
]) -> Self {
612 /// Enables a single setting that is propagated down through all child [`SubCommand`]s.
614 /// See [`AppSettings`] for a full list of possibilities and examples.
616 /// **NOTE**: The setting is *only* propagated *down* and not up through parent commands.
621 /// # use clap::{App, Arg, AppSettings};
622 /// App::new("myprog")
623 /// .global_setting(AppSettings::SubcommandRequired)
626 /// [`SubCommand`]: ./struct.SubCommand.html
627 /// [`AppSettings`]: ./enum.AppSettings.html
628 pub fn global_setting(mut self, setting
: AppSettings
) -> Self {
630 self.p
.g_settings
.set(setting
);
634 /// Enables multiple settings which are propagated *down* through all child [`SubCommand`]s.
636 /// See [`AppSettings`] for a full list of possibilities and examples.
638 /// **NOTE**: The setting is *only* propagated *down* and not up through parent commands.
643 /// # use clap::{App, Arg, AppSettings};
644 /// App::new("myprog")
645 /// .global_settings(&[AppSettings::SubcommandRequired,
646 /// AppSettings::ColoredHelp])
649 /// [`SubCommand`]: ./struct.SubCommand.html
650 /// [`AppSettings`]: ./enum.AppSettings.html
651 pub fn global_settings(mut self, settings
: &[AppSettings
]) -> Self {
654 self.p
.g_settings
.set(*s
)
659 /// Disables a single command, or [`SubCommand`], level setting.
661 /// See [`AppSettings`] for a full list of possibilities and examples.
666 /// # use clap::{App, AppSettings};
667 /// App::new("myprog")
668 /// .unset_setting(AppSettings::ColorAuto)
671 /// [`SubCommand`]: ./struct.SubCommand.html
672 /// [`AppSettings`]: ./enum.AppSettings.html
673 pub fn unset_setting(mut self, setting
: AppSettings
) -> Self {
674 self.p
.unset(setting
);
678 /// Disables multiple command, or [`SubCommand`], level settings.
680 /// See [`AppSettings`] for a full list of possibilities and examples.
685 /// # use clap::{App, AppSettings};
686 /// App::new("myprog")
687 /// .unset_settings(&[AppSettings::ColorAuto,
688 /// AppSettings::AllowInvalidUtf8])
691 /// [`SubCommand`]: ./struct.SubCommand.html
692 /// [`AppSettings`]: ./enum.AppSettings.html
693 pub fn unset_settings(mut self, settings
: &[AppSettings
]) -> Self {
700 /// Sets the terminal width at which to wrap help messages. Defaults to `120`. Using `0` will
701 /// ignore terminal widths and use source formatting.
703 /// `clap` automatically tries to determine the terminal width on Unix, Linux, OSX and Windows
704 /// if the `wrap_help` cargo "feature" has been used while compiling. If the terminal width
705 /// cannot be determined, `clap` defaults to `120`.
707 /// **NOTE:** This setting applies globally and *not* on a per-command basis.
709 /// **NOTE:** This setting must be set **before** any subcommands are added!
711 /// # Platform Specific
713 /// Only Unix, Linux, OSX and Windows support automatic determination of terminal width.
714 /// Even on those platforms, this setting is useful if for any reason the terminal width
715 /// cannot be determined.
721 /// App::new("myprog")
722 /// .set_term_width(80)
725 pub fn set_term_width(mut self, width
: usize) -> Self {
726 self.p
.meta
.term_w
= Some(width
);
730 /// Sets the max terminal width at which to wrap help messages. Using `0` will ignore terminal
731 /// widths and use source formatting.
733 /// `clap` automatically tries to determine the terminal width on Unix, Linux, OSX and Windows
734 /// if the `wrap_help` cargo "feature" has been used while compiling, but one might want to
735 /// limit the size (e.g. when the terminal is running fullscreen).
737 /// **NOTE:** This setting applies globally and *not* on a per-command basis.
739 /// **NOTE:** This setting must be set **before** any subcommands are added!
741 /// # Platform Specific
743 /// Only Unix, Linux, OSX and Windows support automatic determination of terminal width.
749 /// App::new("myprog")
750 /// .max_term_width(100)
753 pub fn max_term_width(mut self, w
: usize) -> Self {
754 self.p
.meta
.max_w
= Some(w
);
758 /// Adds an [argument] to the list of valid possibilities.
763 /// # use clap::{App, Arg};
764 /// App::new("myprog")
765 /// // Adding a single "flag" argument with a short and help text, using Arg::with_name()
767 /// Arg::with_name("debug")
769 /// .help("turns on debugging mode")
771 /// // Adding a single "option" argument with a short, a long, and help text using the less
772 /// // verbose Arg::from_usage()
774 /// Arg::from_usage("-c --config=[CONFIG] 'Optionally sets a config file to use'")
778 /// [argument]: ./struct.Arg.html
779 pub fn arg
<A
: Into
<Arg
<'a
, 'b
>>>(mut self, a
: A
) -> Self {
780 self.p
.add_arg(a
.into());
784 /// Adds multiple [arguments] to the list of valid possibilties
789 /// # use clap::{App, Arg};
790 /// App::new("myprog")
792 /// &[Arg::from_usage("[debug] -d 'turns on debugging info'"),
793 /// Arg::with_name("input").index(1).help("the input file to use")]
797 /// [arguments]: ./struct.Arg.html
798 pub fn args(mut self, args
: &[Arg
<'a
, 'b
>]) -> Self {
800 self.p
.add_arg_ref(arg
);
805 /// A convenience method for adding a single [argument] from a usage type string. The string
806 /// used follows the same rules and syntax as [`Arg::from_usage`]
808 /// **NOTE:** The downside to using this method is that you can not set any additional
809 /// properties of the [`Arg`] other than what [`Arg::from_usage`] supports.
814 /// # use clap::{App, Arg};
815 /// App::new("myprog")
816 /// .arg_from_usage("-c --config=<FILE> 'Sets a configuration file to use'")
819 /// [arguments]: ./struct.Arg.html
820 /// [`Arg`]: ./struct.Arg.html
821 /// [`Arg::from_usage`]: ./struct.Arg.html#method.from_usage
822 pub fn arg_from_usage(mut self, usage
: &'a
str) -> Self {
823 self.p
.add_arg(Arg
::from_usage(usage
));
827 /// Adds multiple [arguments] at once from a usage string, one per line. See
828 /// [`Arg::from_usage`] for details on the syntax and rules supported.
830 /// **NOTE:** Like [`App::arg_from_usage`] the downside is you only set properties for the
831 /// [`Arg`]s which [`Arg::from_usage`] supports.
836 /// # use clap::{App, Arg};
837 /// App::new("myprog")
838 /// .args_from_usage(
839 /// "-c --config=[FILE] 'Sets a configuration file to use'
840 /// [debug]... -d 'Sets the debugging level'
841 /// <FILE> 'The input file to use'"
845 /// [arguments]: ./struct.Arg.html
846 /// [`Arg::from_usage`]: ./struct.Arg.html#method.from_usage
847 /// [`App::arg_from_usage`]: ./struct.App.html#method.arg_from_usage
848 /// [`Arg`]: ./struct.Arg.html
849 pub fn args_from_usage(mut self, usage
: &'a
str) -> Self {
850 for line
in usage
.lines() {
855 self.p
.add_arg(Arg
::from_usage(l
));
860 /// Allows adding a [`SubCommand`] alias, which function as "hidden" subcommands that
861 /// automatically dispatch as if this subcommand was used. This is more efficient, and easier
862 /// than creating multiple hidden subcommands as one only needs to check for the existence of
863 /// this command, and not all variants.
868 /// # use clap::{App, Arg, SubCommand};
869 /// let m = App::new("myprog")
870 /// .subcommand(SubCommand::with_name("test")
871 /// .alias("do-stuff"))
872 /// .get_matches_from(vec!["myprog", "do-stuff"]);
873 /// assert_eq!(m.subcommand_name(), Some("test"));
875 /// [`SubCommand`]: ./struct.SubCommand.html
876 pub fn alias
<S
: Into
<&'b
str>>(mut self, name
: S
) -> Self {
877 if let Some(ref mut als
) = self.p
.meta
.aliases
{
878 als
.push((name
.into(), false));
880 self.p
.meta
.aliases
= Some(vec
![(name
.into(), false)]);
885 /// Allows adding [`SubCommand`] aliases, which function as "hidden" subcommands that
886 /// automatically dispatch as if this subcommand was used. This is more efficient, and easier
887 /// than creating multiple hidden subcommands as one only needs to check for the existence of
888 /// this command, and not all variants.
893 /// # use clap::{App, Arg, SubCommand};
894 /// let m = App::new("myprog")
895 /// .subcommand(SubCommand::with_name("test")
896 /// .aliases(&["do-stuff", "do-tests", "tests"]))
897 /// .arg(Arg::with_name("input")
898 /// .help("the file to add")
900 /// .required(false))
901 /// .get_matches_from(vec!["myprog", "do-tests"]);
902 /// assert_eq!(m.subcommand_name(), Some("test"));
904 /// [`SubCommand`]: ./struct.SubCommand.html
905 pub fn aliases(mut self, names
: &[&'b
str]) -> Self {
906 if let Some(ref mut als
) = self.p
.meta
.aliases
{
908 als
.push((n
, false));
911 self.p
.meta
.aliases
= Some(names
.iter().map(|n
| (*n
, false)).collect
::<Vec
<_
>>());
916 /// Allows adding a [`SubCommand`] alias that functions exactly like those defined with
917 /// [`App::alias`], except that they are visible inside the help message.
922 /// # use clap::{App, Arg, SubCommand};
923 /// let m = App::new("myprog")
924 /// .subcommand(SubCommand::with_name("test")
925 /// .visible_alias("do-stuff"))
926 /// .get_matches_from(vec!["myprog", "do-stuff"]);
927 /// assert_eq!(m.subcommand_name(), Some("test"));
929 /// [`SubCommand`]: ./struct.SubCommand.html
930 /// [`App::alias`]: ./struct.App.html#method.alias
931 pub fn visible_alias
<S
: Into
<&'b
str>>(mut self, name
: S
) -> Self {
932 if let Some(ref mut als
) = self.p
.meta
.aliases
{
933 als
.push((name
.into(), true));
935 self.p
.meta
.aliases
= Some(vec
![(name
.into(), true)]);
940 /// Allows adding multiple [`SubCommand`] aliases that functions exactly like those defined
941 /// with [`App::aliases`], except that they are visible inside the help message.
946 /// # use clap::{App, Arg, SubCommand};
947 /// let m = App::new("myprog")
948 /// .subcommand(SubCommand::with_name("test")
949 /// .visible_aliases(&["do-stuff", "tests"]))
950 /// .get_matches_from(vec!["myprog", "do-stuff"]);
951 /// assert_eq!(m.subcommand_name(), Some("test"));
953 /// [`SubCommand`]: ./struct.SubCommand.html
954 /// [`App::aliases`]: ./struct.App.html#method.aliases
955 pub fn visible_aliases(mut self, names
: &[&'b
str]) -> Self {
956 if let Some(ref mut als
) = self.p
.meta
.aliases
{
961 self.p
.meta
.aliases
= Some(names
.iter().map(|n
| (*n
, true)).collect
::<Vec
<_
>>());
966 /// Adds an [`ArgGroup`] to the application. [`ArgGroup`]s are a family of related arguments.
967 /// By placing them in a logical group, you can build easier requirement and exclusion rules.
968 /// For instance, you can make an entire [`ArgGroup`] required, meaning that one (and *only*
969 /// one) argument from that group must be present at runtime.
971 /// You can also do things such as name an [`ArgGroup`] as a conflict to another argument.
972 /// Meaning any of the arguments that belong to that group will cause a failure if present with
973 /// the conflicting argument.
975 /// Another added benfit of [`ArgGroup`]s is that you can extract a value from a group instead
976 /// of determining exactly which argument was used.
978 /// Finally, using [`ArgGroup`]s to ensure exclusion between arguments is another very common
983 /// The following example demonstrates using an [`ArgGroup`] to ensure that one, and only one,
984 /// of the arguments from the specified group is present at runtime.
987 /// # use clap::{App, ArgGroup};
989 /// .args_from_usage(
990 /// "--set-ver [ver] 'set the version manually'
991 /// --major 'auto increase major'
992 /// --minor 'auto increase minor'
993 /// --patch 'auto increase patch'")
994 /// .group(ArgGroup::with_name("vers")
995 /// .args(&["set-ver", "major", "minor","patch"])
999 /// [`ArgGroup`]: ./struct.ArgGroup.html
1000 pub fn group(mut self, group
: ArgGroup
<'a
>) -> Self {
1001 self.p
.add_group(group
);
1005 /// Adds multiple [`ArgGroup`]s to the [`App`] at once.
1010 /// # use clap::{App, ArgGroup};
1012 /// .args_from_usage(
1013 /// "--set-ver [ver] 'set the version manually'
1014 /// --major 'auto increase major'
1015 /// --minor 'auto increase minor'
1016 /// --patch 'auto increase patch'
1017 /// -c [FILE] 'a config file'
1018 /// -i [IFACE] 'an interface'")
1020 /// ArgGroup::with_name("vers")
1021 /// .args(&["set-ver", "major", "minor","patch"])
1022 /// .required(true),
1023 /// ArgGroup::with_name("input")
1024 /// .args(&["c", "i"])
1028 /// [`ArgGroup`]: ./struct.ArgGroup.html
1029 /// [`App`]: ./struct.App.html
1030 pub fn groups(mut self, groups
: &[ArgGroup
<'a
>]) -> Self {
1032 self = self.group(g
.into());
1037 /// Adds a [`SubCommand`] to the list of valid possibilities. Subcommands are effectively
1038 /// sub-[`App`]s, because they can contain their own arguments, subcommands, version, usage,
1039 /// etc. They also function just like [`App`]s, in that they get their own auto generated help,
1040 /// version, and usage.
1045 /// # use clap::{App, Arg, SubCommand};
1046 /// App::new("myprog")
1047 /// .subcommand(SubCommand::with_name("config")
1048 /// .about("Controls configuration features")
1049 /// .arg_from_usage("<config> 'Required configuration file to use'"))
1052 /// [`SubCommand`]: ./struct.SubCommand.html
1053 /// [`App`]: ./struct.App.html
1054 pub fn subcommand(mut self, subcmd
: App
<'a
, 'b
>) -> Self {
1055 self.p
.add_subcommand(subcmd
);
1059 /// Adds multiple subcommands to the list of valid possibilities by iterating over an
1060 /// [`IntoIterator`] of [`SubCommand`]s
1065 /// # use clap::{App, Arg, SubCommand};
1066 /// # App::new("myprog")
1067 /// .subcommands( vec![
1068 /// SubCommand::with_name("config").about("Controls configuration functionality")
1069 /// .arg(Arg::with_name("config_file").index(1)),
1070 /// SubCommand::with_name("debug").about("Controls debug functionality")])
1073 /// [`SubCommand`]: ./struct.SubCommand.html
1074 /// [`IntoIterator`]: https://doc.rust-lang.org/std/iter/trait.IntoIterator.html
1075 pub fn subcommands
<I
>(mut self, subcmds
: I
) -> Self
1076 where I
: IntoIterator
<Item
= App
<'a
, 'b
>>
1078 for subcmd
in subcmds
{
1079 self.p
.add_subcommand(subcmd
);
1084 /// Allows custom ordering of [`SubCommand`]s within the help message. Subcommands with a lower
1085 /// value will be displayed first in the help message. This is helpful when one would like to
1086 /// emphasise frequently used subcommands, or prioritize those towards the top of the list.
1087 /// Duplicate values **are** allowed. Subcommands with duplicate display orders will be
1088 /// displayed in alphabetical order.
1090 /// **NOTE:** The default is 999 for all subcommands.
1095 /// # use clap::{App, SubCommand};
1096 /// let m = App::new("cust-ord")
1097 /// .subcommand(SubCommand::with_name("alpha") // typically subcommands are grouped
1098 /// // alphabetically by name. Subcommands
1099 /// // without a display_order have a value of
1100 /// // 999 and are displayed alphabetically with
1101 /// // all other 999 subcommands
1102 /// .about("Some help and text"))
1103 /// .subcommand(SubCommand::with_name("beta")
1104 /// .display_order(1) // In order to force this subcommand to appear *first*
1105 /// // all we have to do is give it a value lower than 999.
1106 /// // Any other subcommands with a value of 1 will be displayed
1107 /// // alphabetically with this one...then 2 values, then 3, etc.
1108 /// .about("I should be first!"))
1109 /// .get_matches_from(vec![
1110 /// "cust-ord", "--help"
1114 /// The above example displays the following help message
1120 /// cust-ord [FLAGS] [OPTIONS]
1123 /// -h, --help Prints help information
1124 /// -V, --version Prints version information
1127 /// beta I should be first!
1128 /// alpha Some help and text
1130 /// [`SubCommand`]: ./struct.SubCommand.html
1131 pub fn display_order(mut self, ord
: usize) -> Self {
1132 self.p
.meta
.disp_ord
= ord
;
1136 /// Prints the full help message to [`io::stdout()`] using a [`BufWriter`] using the same
1137 /// method as if someone ran `-h` to request the help message
1139 /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
1140 /// depending on if the user ran [`-h` (short)] or [`--help` (long)]
1145 /// # use clap::App;
1146 /// let mut app = App::new("myprog");
1147 /// app.print_help();
1149 /// [`io::stdout()`]: https://doc.rust-lang.org/std/io/fn.stdout.html
1150 /// [`BufWriter`]: https://doc.rust-lang.org/std/io/struct.BufWriter.html
1151 /// [`-h` (short)]: ./struct.Arg.html#method.help
1152 /// [`--help` (long)]: ./struct.Arg.html#method.long_help
1153 pub fn print_help(&mut self) -> ClapResult
<()> {
1154 // If there are global arguments, or settings we need to propgate them down to subcommands
1155 // before parsing incase we run into a subcommand
1156 self.p
.propagate_globals();
1157 self.p
.propagate_settings();
1158 self.p
.derive_display_order();
1160 self.p
.create_help_and_version();
1161 let out
= io
::stdout();
1162 let mut buf_w
= BufWriter
::new(out
.lock());
1163 self.write_help(&mut buf_w
)
1166 /// Prints the full help message to [`io::stdout()`] using a [`BufWriter`] using the same
1167 /// method as if someone ran `--help` to request the help message
1169 /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
1170 /// depending on if the user ran [`-h` (short)] or [`--help` (long)]
1175 /// # use clap::App;
1176 /// let mut app = App::new("myprog");
1177 /// app.print_long_help();
1179 /// [`io::stdout()`]: https://doc.rust-lang.org/std/io/fn.stdout.html
1180 /// [`BufWriter`]: https://doc.rust-lang.org/std/io/struct.BufWriter.html
1181 /// [`-h` (short)]: ./struct.Arg.html#method.help
1182 /// [`--help` (long)]: ./struct.Arg.html#method.long_help
1183 pub fn print_long_help(&mut self) -> ClapResult
<()> {
1184 // If there are global arguments, or settings we need to propgate them down to subcommands
1185 // before parsing incase we run into a subcommand
1186 self.p
.propagate_globals();
1187 self.p
.propagate_settings();
1188 self.p
.derive_display_order();
1190 self.p
.create_help_and_version();
1191 let out
= io
::stdout();
1192 let mut buf_w
= BufWriter
::new(out
.lock());
1193 self.write_long_help(&mut buf_w
)
1196 /// Writes the full help message to the user to a [`io::Write`] object in the same method as if
1197 /// the user ran `-h`
1199 /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
1200 /// depending on if the user ran [`-h` (short)] or [`--help` (long)]
1202 /// **NOTE:** There is a known bug where this method does not write propagated global arguments
1203 /// or autogenerated arguments (i.e. the default help/version args). Prefer
1204 /// [`App::write_long_help`] instead if possibe!
1209 /// # use clap::App;
1211 /// let mut app = App::new("myprog");
1212 /// let mut out = io::stdout();
1213 /// app.write_help(&mut out).expect("failed to write to stdout");
1215 /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
1216 /// [`-h` (short)]: ./struct.Arg.html#method.help
1217 /// [`--help` (long)]: ./struct.Arg.html#method.long_help
1218 pub fn write_help
<W
: Write
>(&self, w
: &mut W
) -> ClapResult
<()> {
1219 // PENDING ISSUE: 808
1220 // https://github.com/kbknapp/clap-rs/issues/808
1221 // If there are global arguments, or settings we need to propgate them down to subcommands
1222 // before parsing incase we run into a subcommand
1223 // self.p.propagate_globals();
1224 // self.p.propagate_settings();
1225 // self.p.derive_display_order();
1226 // self.p.create_help_and_version();
1228 Help
::write_app_help(w
, self, false)
1231 /// Writes the full help message to the user to a [`io::Write`] object in the same method as if
1232 /// the user ran `--help`
1234 /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
1235 /// depending on if the user ran [`-h` (short)] or [`--help` (long)]
1240 /// # use clap::App;
1242 /// let mut app = App::new("myprog");
1243 /// let mut out = io::stdout();
1244 /// app.write_long_help(&mut out).expect("failed to write to stdout");
1246 /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
1247 /// [`-h` (short)]: ./struct.Arg.html#method.help
1248 /// [`--help` (long)]: ./struct.Arg.html#method.long_help
1249 pub fn write_long_help
<W
: Write
>(&mut self, w
: &mut W
) -> ClapResult
<()> {
1250 self.p
.propagate_globals();
1251 self.p
.propagate_settings();
1252 self.p
.derive_display_order();
1253 self.p
.create_help_and_version();
1255 Help
::write_app_help(w
, self, true)
1258 /// Writes the version message to the user to a [`io::Write`] object as if the user ran `-V`.
1260 /// **NOTE:** clap has the ability to distinguish between "short" and "long" version messages
1261 /// depending on if the user ran [`-V` (short)] or [`--version` (long)]
1266 /// # use clap::App;
1268 /// let mut app = App::new("myprog");
1269 /// let mut out = io::stdout();
1270 /// app.write_version(&mut out).expect("failed to write to stdout");
1272 /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
1273 /// [`-V` (short)]: ./struct.App.html#method.version
1274 /// [`--version` (long)]: ./struct.App.html#method.long_version
1275 pub fn write_version
<W
: Write
>(&self, w
: &mut W
) -> ClapResult
<()> {
1276 self.p
.write_version(w
, false).map_err(From
::from
)
1279 /// Writes the version message to the user to a [`io::Write`] object
1281 /// **NOTE:** clap has the ability to distinguish between "short" and "long" version messages
1282 /// depending on if the user ran [`-V` (short)] or [`--version` (long)]
1287 /// # use clap::App;
1289 /// let mut app = App::new("myprog");
1290 /// let mut out = io::stdout();
1291 /// app.write_long_version(&mut out).expect("failed to write to stdout");
1293 /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
1294 /// [`-V` (short)]: ./struct.App.html#method.version
1295 /// [`--version` (long)]: ./struct.App.html#method.long_version
1296 pub fn write_long_version
<W
: Write
>(&self, w
: &mut W
) -> ClapResult
<()> {
1297 self.p
.write_version(w
, true).map_err(From
::from
)
1300 /// Generate a completions file for a specified shell at compile time.
1302 /// **NOTE:** to generate the this file at compile time you must use a `build.rs` "Build Script"
1306 /// The following example generates a bash completion script via a `build.rs` script. In this
1307 /// simple example, we'll demo a very small application with only a single subcommand and two
1308 /// args. Real applications could be many multiple levels deep in subcommands, and have tens or
1309 /// potentially hundreds of arguments.
1311 /// First, it helps if we separate out our `App` definition into a separate file. Whether you
1312 /// do this as a function, or bare App definition is a matter of personal preference.
1317 /// use clap::{App, Arg, SubCommand};
1319 /// pub fn build_cli() -> App<'static, 'static> {
1320 /// App::new("compl")
1321 /// .about("Tests completions")
1322 /// .arg(Arg::with_name("file")
1323 /// .help("some input file"))
1324 /// .subcommand(SubCommand::with_name("test")
1325 /// .about("tests things")
1326 /// .arg(Arg::with_name("case")
1328 /// .takes_value(true)
1329 /// .help("the case to test")))
1333 /// In our regular code, we can simply call this `build_cli()` function, then call
1334 /// `get_matches()`, or any of the other normal methods directly after. For example:
1342 /// let m = cli::build_cli().get_matches();
1344 /// // normal logic continues...
1348 /// Next, we set up our `Cargo.toml` to use a `build.rs` build script.
1352 /// build = "build.rs"
1354 /// [build-dependencies]
1358 /// Next, we place a `build.rs` in our project root.
1361 /// extern crate clap;
1363 /// use clap::Shell;
1365 /// include!("src/cli.rs");
1368 /// let outdir = match env::var_os("OUT_DIR") {
1370 /// Some(outdir) => outdir,
1372 /// let mut app = build_cli();
1373 /// app.gen_completions("myapp", // We need to specify the bin name manually
1374 /// Shell::Bash, // Then say which shell to build completions for
1375 /// outdir); // Then say where write the completions to
1378 /// Now, once we combile there will be a `{bin_name}.bash-completion` file in the directory.
1379 /// Assuming we compiled with debug mode, it would be somewhere similar to
1380 /// `<project>/target/debug/build/myapp-<hash>/out/myapp.bash-completion`.
1382 /// Fish shell completions will use the file format `{bin_name}.fish`
1383 pub fn gen_completions
<T
: Into
<OsString
>, S
: Into
<String
>>(&mut self,
1387 self.p
.meta
.bin_name
= Some(bin_name
.into());
1388 self.p
.gen_completions(for_shell
, out_dir
.into());
1392 /// Generate a completions file for a specified shell at runtime. Until `cargo install` can
1393 /// install extra files like a completion script, this may be used e.g. in a command that
1394 /// outputs the contents of the completion script, to be redirected into a file by the user.
1398 /// Assuming a separate `cli.rs` like the [example above](./struct.App.html#method.gen_completions),
1399 /// we can let users generate a completion script using a command:
1408 /// let matches = cli::build_cli().get_matches();
1410 /// if matches.is_present("generate-bash-completions") {
1411 /// cli::build_cli().gen_completions_to("myapp", Shell::Bash, &mut io::stdout());
1414 /// // normal logic continues...
1422 /// $ myapp generate-bash-completions > /etc/bash_completion.d/myapp
1424 pub fn gen_completions_to
<W
: Write
, S
: Into
<String
>>(&mut self,
1428 self.p
.meta
.bin_name
= Some(bin_name
.into());
1429 self.p
.gen_completions_to(for_shell
, buf
);
1432 /// Starts the parsing process, upon a failed parse an error will be displayed to the user and
1433 /// the process will exit with the appropriate error code. By default this method gets all user
1434 /// provided arguments from [`env::args_os`] in order to allow for invalid UTF-8 code points,
1435 /// which are legal on many platforms.
1440 /// # use clap::{App, Arg};
1441 /// let matches = App::new("myprog")
1442 /// // Args and options go here...
1445 /// [`env::args_os`]: https://doc.rust-lang.org/std/env/fn.args_os.html
1446 pub fn get_matches(self) -> ArgMatches
<'a
> { self.get_matches_from(&mut env::args_os()) }
1448 /// Starts the parsing process. This method will return a [`clap::Result`] type instead of exiting
1449 /// the process on failed parse. By default this method gets matches from [`env::args_os`]
1451 /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
1452 /// used. It will return a [`clap::Error`], where the [`kind`] is a
1453 /// [`ErrorKind::HelpDisplayed`] or [`ErrorKind::VersionDisplayed`] respectively. You must call
1454 /// [`Error::exit`] or perform a [`std::process::exit`].
1459 /// # use clap::{App, Arg};
1460 /// let matches = App::new("myprog")
1461 /// // Args and options go here...
1462 /// .get_matches_safe()
1463 /// .unwrap_or_else( |e| e.exit() );
1465 /// [`env::args_os`]: https://doc.rust-lang.org/std/env/fn.args_os.html
1466 /// [`ErrorKind::HelpDisplayed`]: ./enum.ErrorKind.html#variant.HelpDisplayed
1467 /// [`ErrorKind::VersionDisplayed`]: ./enum.ErrorKind.html#variant.VersionDisplayed
1468 /// [`Error::exit`]: ./struct.Error.html#method.exit
1469 /// [`std::process::exit`]: https://doc.rust-lang.org/std/process/fn.exit.html
1470 /// [`clap::Result`]: ./type.Result.html
1471 /// [`clap::Error`]: ./struct.Error.html
1472 /// [`kind`]: ./struct.Error.html
1473 pub fn get_matches_safe(self) -> ClapResult
<ArgMatches
<'a
>> {
1474 // Start the parsing
1475 self.get_matches_from_safe(&mut env
::args_os())
1478 /// Starts the parsing process. Like [`App::get_matches`] this method does not return a [`clap::Result`]
1479 /// and will automatically exit with an error message. This method, however, lets you specify
1480 /// what iterator to use when performing matches, such as a [`Vec`] of your making.
1482 /// **NOTE:** The first argument will be parsed as the binary name unless
1483 /// [`AppSettings::NoBinaryName`] is used
1488 /// # use clap::{App, Arg};
1489 /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
1491 /// let matches = App::new("myprog")
1492 /// // Args and options go here...
1493 /// .get_matches_from(arg_vec);
1495 /// [`App::get_matches`]: ./struct.App.html#method.get_matches
1496 /// [`clap::Result`]: ./type.Result.html
1497 /// [`Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
1498 /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName
1499 pub fn get_matches_from
<I
, T
>(mut self, itr
: I
) -> ArgMatches
<'a
>
1500 where I
: IntoIterator
<Item
= T
>,
1501 T
: Into
<OsString
> + Clone
1503 self.get_matches_from_safe_borrow(itr
).unwrap_or_else(|e
| {
1504 // Otherwise, write to stderr and exit
1506 wlnerr
!("{}", e
.message
);
1507 if self.p
.is_set(AppSettings
::WaitOnError
) {
1508 wlnerr
!("\nPress [ENTER] / [RETURN] to continue...");
1509 let mut s
= String
::new();
1510 let i
= io
::stdin();
1511 i
.lock().read_line(&mut s
).unwrap();
1523 /// Starts the parsing process. A combination of [`App::get_matches_from`], and
1524 /// [`App::get_matches_safe`]
1526 /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
1527 /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::HelpDisplayed`]
1528 /// or [`ErrorKind::VersionDisplayed`] respectively. You must call [`Error::exit`] or
1529 /// perform a [`std::process::exit`] yourself.
1531 /// **NOTE:** The first argument will be parsed as the binary name unless
1532 /// [`AppSettings::NoBinaryName`] is used
1537 /// # use clap::{App, Arg};
1538 /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
1540 /// let matches = App::new("myprog")
1541 /// // Args and options go here...
1542 /// .get_matches_from_safe(arg_vec)
1543 /// .unwrap_or_else( |e| { panic!("An error occurs: {}", e) });
1545 /// [`App::get_matches_from`]: ./struct.App.html#method.get_matches_from
1546 /// [`App::get_matches_safe`]: ./struct.App.html#method.get_matches_safe
1547 /// [`ErrorKind::HelpDisplayed`]: ./enum.ErrorKind.html#variant.HelpDisplayed
1548 /// [`ErrorKind::VersionDisplayed`]: ./enum.ErrorKind.html#variant.VersionDisplayed
1549 /// [`Error::exit`]: ./struct.Error.html#method.exit
1550 /// [`std::process::exit`]: https://doc.rust-lang.org/std/process/fn.exit.html
1551 /// [`clap::Error`]: ./struct.Error.html
1552 /// [`Error::exit`]: ./struct.Error.html#method.exit
1553 /// [`kind`]: ./struct.Error.html
1554 /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName
1555 pub fn get_matches_from_safe
<I
, T
>(mut self, itr
: I
) -> ClapResult
<ArgMatches
<'a
>>
1556 where I
: IntoIterator
<Item
= T
>,
1557 T
: Into
<OsString
> + Clone
1559 self.get_matches_from_safe_borrow(itr
)
1562 /// Starts the parsing process without consuming the [`App`] struct `self`. This is normally not
1563 /// the desired functionality, instead prefer [`App::get_matches_from_safe`] which *does*
1566 /// **NOTE:** The first argument will be parsed as the binary name unless
1567 /// [`AppSettings::NoBinaryName`] is used
1572 /// # use clap::{App, Arg};
1573 /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
1575 /// let mut app = App::new("myprog");
1576 /// // Args and options go here...
1577 /// let matches = app.get_matches_from_safe_borrow(arg_vec)
1578 /// .unwrap_or_else( |e| { panic!("An error occurs: {}", e) });
1580 /// [`App`]: ./struct.App.html
1581 /// [`App::get_matches_from_safe`]: ./struct.App.html#method.get_matches_from_safe
1582 /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName
1583 pub fn get_matches_from_safe_borrow
<I
, T
>(&mut self, itr
: I
) -> ClapResult
<ArgMatches
<'a
>>
1584 where I
: IntoIterator
<Item
= T
>,
1585 T
: Into
<OsString
> + Clone
1587 // If there are global arguments, or settings we need to propgate them down to subcommands
1588 // before parsing incase we run into a subcommand
1589 if !self.p
.is_set(AppSettings
::Propagated
) {
1590 self.p
.propagate_globals();
1591 self.p
.propagate_settings();
1592 self.p
.derive_display_order();
1593 self.p
.set(AppSettings
::Propagated
);
1596 let mut matcher
= ArgMatcher
::new();
1598 let mut it
= itr
.into_iter();
1599 // Get the name of the program (argument 1 of env::args()) and determine the
1601 // that was used to execute the program. This is because a program called
1602 // ./target/release/my_prog -a
1603 // will have two arguments, './target/release/my_prog', '-a' but we don't want
1605 // the full path when displaying help messages and such
1606 if !self.p
.is_set(AppSettings
::NoBinaryName
) {
1607 if let Some(name
) = it
.next() {
1608 let bn_os
= name
.into();
1609 let p
= Path
::new(&*bn_os
);
1610 if let Some(f
) = p
.file_name() {
1611 if let Some(s
) = f
.to_os_string().to_str() {
1612 if self.p
.meta
.bin_name
.is_none() {
1613 self.p
.meta
.bin_name
= Some(s
.to_owned());
1620 // do the real parsing
1621 if let Err(e
) = self.p
.get_matches_with(&mut matcher
, &mut it
.peekable()) {
1625 let global_arg_vec
: Vec
<&str> = (&self).p
.global_args
.iter().map(|ga
| ga
.b
.name
).collect();
1626 matcher
.propagate_globals(&global_arg_vec
);
1632 #[cfg(feature = "yaml")]
1633 impl<'a
> From
<&'a Yaml
> for App
<'a
, 'a
> {
1634 fn from(mut yaml
: &'a Yaml
) -> Self {
1635 use args
::SubCommand
;
1636 // We WANT this to panic on error...so expect() is good.
1637 let mut is_sc
= None
;
1638 let mut a
= if let Some(name
) = yaml
["name"].as_str() {
1641 let yaml_hash
= yaml
.as_hash().unwrap();
1642 let sc_key
= yaml_hash
.keys().nth(0).unwrap();
1643 is_sc
= Some(yaml_hash
.get(sc_key
).unwrap());
1644 App
::new(sc_key
.as_str().unwrap())
1646 yaml
= if let Some(sc
) = is_sc { sc }
else { yaml }
;
1648 macro_rules
! yaml_str
{
1649 ($a
:ident
, $y
:ident
, $i
:ident
) => {
1650 if let Some(v
) = $y
[stringify
!($i
)].as_str() {
1652 } else if $y
[stringify
!($i
)] != Yaml
::BadValue
{
1653 panic
!("Failed to convert YAML value {:?} to a string", $y
[stringify
!($i
)]);
1658 yaml_str
!(a
, yaml
, version
);
1659 yaml_str
!(a
, yaml
, author
);
1660 yaml_str
!(a
, yaml
, bin_name
);
1661 yaml_str
!(a
, yaml
, about
);
1662 yaml_str
!(a
, yaml
, before_help
);
1663 yaml_str
!(a
, yaml
, after_help
);
1664 yaml_str
!(a
, yaml
, template
);
1665 yaml_str
!(a
, yaml
, usage
);
1666 yaml_str
!(a
, yaml
, help
);
1667 yaml_str
!(a
, yaml
, help_short
);
1668 yaml_str
!(a
, yaml
, version_short
);
1669 yaml_str
!(a
, yaml
, help_message
);
1670 yaml_str
!(a
, yaml
, version_message
);
1671 yaml_str
!(a
, yaml
, alias
);
1672 yaml_str
!(a
, yaml
, visible_alias
);
1674 if let Some(v
) = yaml
["display_order"].as_i64() {
1675 a
= a
.display_order(v
as usize);
1676 } else if yaml
["display_order"] != Yaml
::BadValue
{
1677 panic
!("Failed to convert YAML value {:?} to a u64",
1678 yaml
["display_order"]);
1680 if let Some(v
) = yaml
["setting"].as_str() {
1681 a
= a
.setting(v
.parse().expect("unknown AppSetting found in YAML file"));
1682 } else if yaml
["setting"] != Yaml
::BadValue
{
1683 panic
!("Failed to convert YAML value {:?} to an AppSetting",
1686 if let Some(v
) = yaml
["settings"].as_vec() {
1688 if let Some(s
) = ys
.as_str() {
1689 a
= a
.setting(s
.parse().expect("unknown AppSetting found in YAML file"));
1692 } else if let Some(v
) = yaml
["settings"].as_str() {
1693 a
= a
.setting(v
.parse().expect("unknown AppSetting found in YAML file"));
1694 } else if yaml
["settings"] != Yaml
::BadValue
{
1695 panic
!("Failed to convert YAML value {:?} to a string",
1698 if let Some(v
) = yaml
["global_setting"].as_str() {
1699 a
= a
.setting(v
.parse().expect("unknown AppSetting found in YAML file"));
1700 } else if yaml
["global_setting"] != Yaml
::BadValue
{
1701 panic
!("Failed to convert YAML value {:?} to an AppSetting",
1704 if let Some(v
) = yaml
["global_settings"].as_vec() {
1706 if let Some(s
) = ys
.as_str() {
1707 a
= a
.global_setting(s
.parse()
1708 .expect("unknown AppSetting found in YAML file"));
1711 } else if let Some(v
) = yaml
["global_settings"].as_str() {
1712 a
= a
.global_setting(v
.parse().expect("unknown AppSetting found in YAML file"));
1713 } else if yaml
["global_settings"] != Yaml
::BadValue
{
1714 panic
!("Failed to convert YAML value {:?} to a string",
1715 yaml
["global_settings"]);
1718 macro_rules
! vec_or_str
{
1719 ($a
:ident
, $y
:ident
, $as_vec
:ident
, $as_single
:ident
) => {{
1720 let maybe_vec
= $y
[stringify
!($as_vec
)].as_vec();
1721 if let Some(vec
) = maybe_vec
{
1723 if let Some(s
) = ys
.as_str() {
1724 $a
= $a
.$
as_single(s
);
1726 panic
!("Failed to convert YAML value {:?} to a string", ys
);
1730 if let Some(s
) = $y
[stringify
!($as_vec
)].as_str() {
1731 $a
= $a
.$
as_single(s
);
1732 } else if $y
[stringify
!($as_vec
)] != Yaml
::BadValue
{
1733 panic
!("Failed to convert YAML value {:?} to either a vec or string", $y
[stringify
!($as_vec
)]);
1741 a
= vec_or_str
!(a
, yaml
, aliases
, alias
);
1742 a
= vec_or_str
!(a
, yaml
, visible_aliases
, visible_alias
);
1744 if let Some(v
) = yaml
["args"].as_vec() {
1746 a
= a
.arg(Arg
::from_yaml(arg_yaml
.as_hash().unwrap()));
1749 if let Some(v
) = yaml
["subcommands"].as_vec() {
1751 a
= a
.subcommand(SubCommand
::from_yaml(sc_yaml
));
1754 if let Some(v
) = yaml
["groups"].as_vec() {
1756 a
= a
.group(ArgGroup
::from(ag_yaml
.as_hash().unwrap()));
1764 impl<'a
, 'b
> Clone
for App
<'a
, 'b
> {
1765 fn clone(&self) -> Self { App { p: self.p.clone() }
}
1768 impl<'n
, 'e
> AnyArg
<'n
, 'e
> for App
<'n
, 'e
> {
1769 fn name(&self) -> &'n
str {
1770 unreachable
!("App struct does not support AnyArg::name, this is a bug!")
1772 fn overrides(&self) -> Option
<&[&'e
str]> { None }
1773 fn requires(&self) -> Option
<&[(Option
<&'e
str>, &'n
str)]> { None }
1774 fn blacklist(&self) -> Option
<&[&'e
str]> { None }
1775 fn required_unless(&self) -> Option
<&[&'e
str]> { None }
1776 fn val_names(&self) -> Option
<&VecMap
<&'e
str>> { None }
1777 fn is_set(&self, _
: ArgSettings
) -> bool { false }
1778 fn val_terminator(&self) -> Option
<&'e
str> { None }
1779 fn set(&mut self, _
: ArgSettings
) {
1780 unreachable
!("App struct does not support AnyArg::set, this is a bug!")
1782 fn has_switch(&self) -> bool { false }
1783 fn max_vals(&self) -> Option
<u64> { None }
1784 fn num_vals(&self) -> Option
<u64> { None }
1785 fn possible_vals(&self) -> Option
<&[&'e
str]> { None }
1786 fn validator(&self) -> Option
<&Rc
<Fn(String
) -> StdResult
<(), String
>>> { None }
1787 fn validator_os(&self) -> Option
<&Rc
<Fn(&OsStr
) -> StdResult
<(), OsString
>>> { None }
1788 fn min_vals(&self) -> Option
<u64> { None }
1789 fn short(&self) -> Option
<char> { None }
1790 fn long(&self) -> Option
<&'e
str> { None }
1791 fn val_delim(&self) -> Option
<char> { None }
1792 fn takes_value(&self) -> bool { true }
1793 fn help(&self) -> Option
<&'e
str> { self.p.meta.about }
1794 fn long_help(&self) -> Option
<&'e
str> { self.p.meta.long_about }
1795 fn default_val(&self) -> Option
<&'e OsStr
> { None }
1796 fn default_vals_ifs(&self) -> Option
<map
::Values
<(&'n
str, Option
<&'e OsStr
>, &'e OsStr
)>> {
1799 fn env
<'s
>(&'s
self) -> Option
<(&'n OsStr
, Option
<&'s OsString
>)> { None }
1800 fn longest_filter(&self) -> bool { true }
1801 fn aliases(&self) -> Option
<Vec
<&'e
str>> {
1802 if let Some(ref aliases
) = self.p
.meta
.aliases
{
1803 let vis_aliases
: Vec
<_
> =
1804 aliases
.iter().filter_map(|&(n
, v
)| if v { Some(n) }
else { None }
).collect();
1805 if vis_aliases
.is_empty() {
1816 impl<'n
, 'e
> fmt
::Display
for App
<'n
, 'e
> {
1817 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result { write!(f, "{}
", self.p.meta.name) }