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 #[doc(hidden)] 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 {
84 p
: Parser
::with_name(n
.into()),
88 /// Get the name of the app
89 pub fn get_name(&self) -> &str { &self.p.meta.name }
91 /// Get the name of the binary
92 pub fn get_bin_name(&self) -> Option
<&str> { self.p.meta.bin_name.as_ref().map(|s| s.as_str()) }
94 /// Creates a new instance of an application requiring a name, but uses the [`crate_authors!`]
95 /// and [`crate_version!`] macros to fill in the [`App::author`] and [`App::version`] fields.
100 /// # use clap::{App, Arg};
101 /// let prog = App::with_defaults("My Program")
104 /// [`crate_authors!`]: ./macro.crate_authors!.html
105 /// [`crate_version!`]: ./macro.crate_version!.html
106 /// [`App::author`]: ./struct.App.html#method.author
107 /// [`App::version`]: ./struct.App.html#method.author
108 #[deprecated(since="2.14.1", note="Can never work; use explicit App::author() and App::version() calls instead")]
109 pub fn with_defaults
<S
: Into
<String
>>(n
: S
) -> Self {
111 p
: Parser
::with_name(n
.into()),
113 a
.p
.meta
.author
= Some("Kevin K. <kbknapp@gmail.com>");
114 a
.p
.meta
.version
= Some("2.19.2");
118 /// Creates a new instance of [`App`] from a .yml (YAML) file. A full example of supported YAML
119 /// objects can be found in [`examples/17_yaml.rs`] and [`examples/17_yaml.yml`]. One great use
120 /// for using YAML is when supporting multiple languages and dialects, as each language could
121 /// be a distinct YAML file and determined at compiletime via `cargo` "features" in your
124 /// In order to use this function you must compile `clap` with the `features = ["yaml"]` in
125 /// your settings for the `[dependencies.clap]` table of your `Cargo.toml`
127 /// **NOTE:** Due to how the YAML objects are built there is a convenience macro for loading
128 /// the YAML file at compile time (relative to the current file, like modules work). That YAML
129 /// object can then be passed to this function.
133 /// The YAML file must be properly formatted or this function will [`panic!`]. A good way to
134 /// ensure this doesn't happen is to run your program with the `--help` switch. If this passes
135 /// without error, you needn't worry because the YAML is properly formatted.
139 /// The following example shows how to load a properly formatted YAML file to build an instance
140 /// of an [`App`] struct.
144 /// # extern crate clap;
147 /// let yml = load_yaml!("app.yml");
148 /// let app = App::from_yaml(yml);
150 /// // continued logic goes here, such as `app.get_matches()` etc.
153 /// [`App`]: ./struct.App.html
154 /// [`examples/17_yaml.rs`]: https://github.com/kbknapp/clap-rs/blob/master/examples/17_yaml.rs
155 /// [`examples/17_yaml.yml`]: https://github.com/kbknapp/clap-rs/blob/master/examples/17_yaml.yml
156 /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html
157 #[cfg(feature = "yaml")]
158 pub fn from_yaml(yaml
: &'a Yaml
) -> App
<'a
, 'a
> { App::from(yaml) }
160 /// Sets a string of author(s) that will be displayed to the user when they
161 /// request the help information with `--help` or `-h`.
163 /// **Pro-tip:** Use `clap`s convenience macro [`crate_authors!`] to automatically set your
164 /// application's author(s) to the same thing as your crate at compile time. See the [`examples/`]
165 /// directory for more information
167 /// See the [`examples/`]
168 /// directory for more information
173 /// # use clap::{App, Arg};
174 /// App::new("myprog")
175 /// .author("Me, me@mymain.com")
178 /// [`crate_authors!`]: ./macro.crate_authors!.html
179 /// [`examples/`]: https://github.com/kbknapp/clap-rs/tree/master/examples
180 pub fn author
<S
: Into
<&'b
str>>(mut self, author
: S
) -> Self {
181 self.p
.meta
.author
= Some(author
.into());
185 /// Overrides the system-determined binary name. This should only be used when absolutely
186 /// necessary, such as when the binary name for your application is misleading, or perhaps
187 /// *not* how the user should invoke your program.
189 /// **Pro-tip:** When building things such as third party `cargo` subcommands, this setting
190 /// **should** be used!
192 /// **NOTE:** This command **should not** be used for [`SubCommand`]s.
197 /// # use clap::{App, Arg};
198 /// App::new("My Program")
199 /// .bin_name("my_binary")
202 /// [`SubCommand`]: ./struct.SubCommand.html
203 pub fn bin_name
<S
: Into
<String
>>(mut self, name
: S
) -> Self {
204 self.p
.meta
.bin_name
= Some(name
.into());
208 /// Sets a string describing what the program does. This will be displayed when displaying help
209 /// information with `-h`.
211 /// **NOTE:** If only `about` is provided, and not [`App::long_about`] but the user requests
212 /// `--help` clap will still display the contents of `about` appropriately
214 /// **NOTE:** Only [`App::about`] is used in completion script generation in order to be
220 /// # use clap::{App, Arg};
221 /// App::new("myprog")
222 /// .about("Does really amazing things to great people")
225 /// [`App::long_about`]: ./struct.App.html#method.long_about
226 pub fn about
<S
: Into
<&'b
str>>(mut self, about
: S
) -> Self {
227 self.p
.meta
.about
= Some(about
.into());
231 /// Sets a string describing what the program does. This will be displayed when displaying help
234 /// **NOTE:** If only `long_about` is provided, and not [`App::about`] but the user requests
235 /// `-h` clap will still display the contents of `long_about` appropriately
237 /// **NOTE:** Only [`App::about`] is used in completion script generation in order to be
243 /// # use clap::{App, Arg};
244 /// App::new("myprog")
246 /// "Does really amazing things to great people. Now let's talk a little
247 /// more in depth about how this subcommand really works. It may take about
248 /// a few lines of text, but that's ok!")
251 /// [`App::about`]: ./struct.App.html#method.about
252 pub fn long_about
<S
: Into
<&'b
str>>(mut self, about
: S
) -> Self {
253 self.p
.meta
.long_about
= Some(about
.into());
257 /// Sets the program's name. This will be displayed when displaying help information.
259 /// **Pro-top:** This function is particularly useful when configuring a program via
260 /// [`App::from_yaml`] in conjunction with the [`crate_name!`] macro to derive the program's
261 /// name from its `Cargo.toml`.
266 /// # extern crate clap;
269 /// let yml = load_yaml!("app.yml");
270 /// let app = App::from_yaml(yml)
271 /// .name(crate_name!());
273 /// // continued logic goes here, such as `app.get_matches()` etc.
277 /// [`App::from_yaml`]: ./struct.App.html#method.from_yaml
278 /// [`crate_name!`]: ./macro.crate_name.html
279 pub fn name
<S
: Into
<String
>>(mut self, name
: S
) -> Self {
280 self.p
.meta
.name
= name
.into();
284 /// Adds additional help information to be displayed in addition to auto-generated help. This
285 /// information is displayed **after** the auto-generated help information. This is often used
286 /// to describe how to use the arguments, or caveats to be noted.
292 /// App::new("myprog")
293 /// .after_help("Does really amazing things to great people...but be careful with -R")
296 pub fn after_help
<S
: Into
<&'b
str>>(mut self, help
: S
) -> Self {
297 self.p
.meta
.more_help
= Some(help
.into());
301 /// Adds additional help information to be displayed in addition to auto-generated help. This
302 /// information is displayed **before** the auto-generated help information. This is often used
303 /// for header information.
309 /// App::new("myprog")
310 /// .before_help("Some info I'd like to appear before the help info")
313 pub fn before_help
<S
: Into
<&'b
str>>(mut self, help
: S
) -> Self {
314 self.p
.meta
.pre_help
= Some(help
.into());
318 /// Sets a string of the version number to be displayed when displaying version or help
319 /// information with `-V`.
321 /// **NOTE:** If only `version` is provided, and not [`App::long_version`] but the user
322 /// requests `--version` clap will still display the contents of `version` appropriately
324 /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to automatically set your
325 /// application's version to the same thing as your crate at compile time. See the [`examples/`]
326 /// directory for more information
331 /// # use clap::{App, Arg};
332 /// App::new("myprog")
333 /// .version("v0.1.24")
336 /// [`crate_version!`]: ./macro.crate_version!.html
337 /// [`examples/`]: https://github.com/kbknapp/clap-rs/tree/master/examples
338 /// [`App::long_version`]: ./struct.App.html#method.long_version
339 pub fn version
<S
: Into
<&'b
str>>(mut self, ver
: S
) -> Self {
340 self.p
.meta
.version
= Some(ver
.into());
344 /// Sets a string of the version number to be displayed when displaying version or help
345 /// information with `--version`.
347 /// **NOTE:** If only `long_version` is provided, and not [`App::version`] but the user
348 /// requests `-V` clap will still display the contents of `long_version` appropriately
350 /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to automatically set your
351 /// application's version to the same thing as your crate at compile time. See the [`examples/`]
352 /// directory for more information
357 /// # use clap::{App, Arg};
358 /// App::new("myprog")
361 /// commit: abcdef89726d
367 /// [`crate_version!`]: ./macro.crate_version!.html
368 /// [`examples/`]: https://github.com/kbknapp/clap-rs/tree/master/examples
369 /// [`App::version`]: ./struct.App.html#method.version
370 pub fn long_version
<S
: Into
<&'b
str>>(mut self, ver
: S
) -> Self {
371 self.p
.meta
.long_version
= Some(ver
.into());
375 /// Sets a custom usage string to override the auto-generated usage string.
377 /// This will be displayed to the user when errors are found in argument parsing, or when you
378 /// call [`ArgMatches::usage`]
380 /// **CAUTION:** Using this setting disables `clap`s "context-aware" usage strings. After this
381 /// setting is set, this will be the only usage string displayed to the user!
383 /// **NOTE:** You do not need to specify the "USAGE: \n\t" portion, as that will
384 /// still be applied by `clap`, you only need to specify the portion starting
385 /// with the binary name.
387 /// **NOTE:** This will not replace the entire help message, *only* the portion
388 /// showing the usage.
393 /// # use clap::{App, Arg};
394 /// App::new("myprog")
395 /// .usage("myapp [-clDas] <some_file>")
398 /// [`ArgMatches::usage`]: ./struct.ArgMatches.html#method.usage
399 pub fn usage
<S
: Into
<&'b
str>>(mut self, usage
: S
) -> Self {
400 self.p
.meta
.usage_str
= Some(usage
.into());
404 /// Sets a custom help message and overrides the auto-generated one. This should only be used
405 /// when the auto-generated message does not suffice.
407 /// This will be displayed to the user when they use `--help` or `-h`
409 /// **NOTE:** This replaces the **entire** help message, so nothing will be auto-generated.
411 /// **NOTE:** This **only** replaces the help message for the current command, meaning if you
412 /// are using subcommands, those help messages will still be auto-generated unless you
413 /// specify a [`Arg::help`] for them as well.
418 /// # use clap::{App, Arg};
419 /// App::new("myapp")
420 /// .help("myapp v1.0\n\
421 /// Does awesome things\n\
422 /// (C) me@mail.com\n\n\
424 /// USAGE: myapp <opts> <comamnd>\n\n\
427 /// -h, --helpe Dispay this message\n\
428 /// -V, --version Display version info\n\
429 /// -s <stuff> Do something with stuff\n\
430 /// -v Be verbose\n\n\
433 /// help Prints this message\n\
434 /// work Do some work")
437 /// [`Arg::help`]: ./struct.Arg.html#method.help
438 pub fn help
<S
: Into
<&'b
str>>(mut self, help
: S
) -> Self {
439 self.p
.meta
.help_str
= Some(help
.into());
443 /// Sets the [`short`] for the auto-generated `help` argument.
445 /// By default `clap` automatically assigns `h`, but this can be overridden if you have a
446 /// different argument which you'd prefer to use the `-h` short with. This can be done by
447 /// defining your own argument with a lowercase `h` as the [`short`].
449 /// `clap` lazily generates these `help` arguments **after** you've defined any arguments of
452 /// **NOTE:** Any leading `-` characters will be stripped, and only the first
453 /// non `-` character will be used as the [`short`] version
458 /// # use clap::{App, Arg};
459 /// App::new("myprog")
460 /// .help_short("H") // Using an uppercase `H` instead of the default lowercase `h`
463 /// [`short`]: ./struct.Arg.html#method.short
464 pub fn help_short
<S
: AsRef
<str> + 'b
>(mut self, s
: S
) -> Self {
465 self.p
.help_short(s
.as_ref());
469 /// Sets the [`short`] for the auto-generated `version` argument.
471 /// By default `clap` automatically assigns `V`, but this can be overridden if you have a
472 /// different argument which you'd prefer to use the `-V` short with. This can be done by
473 /// defining your own argument with an uppercase `V` as the [`short`].
475 /// `clap` lazily generates these `version` arguments **after** you've defined any arguments of
478 /// **NOTE:** Any leading `-` characters will be stripped, and only the first
479 /// non `-` character will be used as the `short` version
484 /// # use clap::{App, Arg};
485 /// App::new("myprog")
486 /// .version_short("v") // Using a lowercase `v` instead of the default capital `V`
489 /// [`short`]: ./struct.Arg.html#method.short
490 pub fn version_short
<S
: AsRef
<str>>(mut self, s
: S
) -> Self {
491 self.p
.version_short(s
.as_ref());
495 /// Sets the help text for the auto-generated `help` argument.
497 /// By default `clap` sets this to `"Prints help information"`, but if you're using a
498 /// different convention for your help messages and would prefer a different phrasing you can
504 /// # use clap::{App, Arg};
505 /// App::new("myprog")
506 /// .help_message("Print help information") // Perhaps you want imperative help messages
510 pub fn help_message
<S
: Into
<&'a
str>>(mut self, s
: S
) -> Self {
511 self.p
.help_message
= Some(s
.into());
515 /// Sets the help text for the auto-generated `version` argument.
517 /// By default `clap` sets this to `"Prints version information"`, but if you're using a
518 /// different convention for your help messages and would prefer a different phrasing then you
523 /// # use clap::{App, Arg};
524 /// App::new("myprog")
525 /// .version_message("Print version information") // Perhaps you want imperative help messages
528 pub fn version_message
<S
: Into
<&'a
str>>(mut self, s
: S
) -> Self {
529 self.p
.version_message
= Some(s
.into());
533 /// Sets the help template to be used, overriding the default format.
535 /// Tags arg given inside curly brackets.
539 /// * `{bin}` - Binary name.
540 /// * `{version}` - Version number.
541 /// * `{author}` - Author information.
542 /// * `{about}` - General description (from [`App::about`])
543 /// * `{usage}` - Automatically generated or given usage string.
544 /// * `{all-args}` - Help for all arguments (options, flags, positionals arguments,
545 /// and subcommands) including titles.
546 /// * `{unified}` - Unified help for options and flags. Note, you must *also* set
547 /// [`AppSettings::UnifiedHelpMessage`] to fully merge both options and
548 /// flags, otherwise the ordering is "best effort"
549 /// * `{flags}` - Help for flags.
550 /// * `{options}` - Help for options.
551 /// * `{positionals}` - Help for positionals arguments.
552 /// * `{subcommands}` - Help for subcommands.
553 /// * `{after-help}` - Help from [`App::after_help`]
554 /// * `{before-help}` - Help from [`App::before_help`]
559 /// # use clap::{App, Arg};
560 /// App::new("myprog")
562 /// .template("{bin} ({version}) - {usage}")
565 /// **NOTE:**The template system is, on purpose, very simple. Therefore the tags have to writen
566 /// in the lowercase and without spacing.
567 /// [`App::about`]: ./struct.App.html#method.about
568 /// [`App::after_help`]: ./struct.App.html#method.after_help
569 /// [`App::before_help`]: ./struct.App.html#method.before_help
570 /// [`AppSettings::UnifiedHelpMessage`]: ./enum.AppSettings.html#variant.UnifiedHelpMessage
571 pub fn template
<S
: Into
<&'b
str>>(mut self, s
: S
) -> Self {
572 self.p
.meta
.template
= Some(s
.into());
576 /// Enables a single command, or [`SubCommand`], level settings.
578 /// See [`AppSettings`] for a full list of possibilities and examples.
583 /// # use clap::{App, Arg, AppSettings};
584 /// App::new("myprog")
585 /// .setting(AppSettings::SubcommandRequired)
586 /// .setting(AppSettings::WaitOnError)
589 /// [`SubCommand`]: ./struct.SubCommand.html
590 /// [`AppSettings`]: ./enum.AppSettings.html
591 pub fn setting(mut self, setting
: AppSettings
) -> Self {
596 /// Enables multiple command, or [`SubCommand`], level settings
598 /// See [`AppSettings`] for a full list of possibilities and examples.
603 /// # use clap::{App, Arg, AppSettings};
604 /// App::new("myprog")
605 /// .settings(&[AppSettings::SubcommandRequired,
606 /// AppSettings::WaitOnError])
609 /// [`SubCommand`]: ./struct.SubCommand.html
610 /// [`AppSettings`]: ./enum.AppSettings.html
611 pub fn settings(mut self, settings
: &[AppSettings
]) -> Self {
618 /// Enables a single setting that is propagated down through all child [`SubCommand`]s.
620 /// See [`AppSettings`] for a full list of possibilities and examples.
622 /// **NOTE**: The setting is *only* propagated *down* and not up through parent commands.
627 /// # use clap::{App, Arg, AppSettings};
628 /// App::new("myprog")
629 /// .global_setting(AppSettings::SubcommandRequired)
632 /// [`SubCommand`]: ./struct.SubCommand.html
633 /// [`AppSettings`]: ./enum.AppSettings.html
634 pub fn global_setting(mut self, setting
: AppSettings
) -> Self {
636 self.p
.g_settings
.set(setting
);
640 /// Enables multiple settings which are propagated *down* through all child [`SubCommand`]s.
642 /// See [`AppSettings`] for a full list of possibilities and examples.
644 /// **NOTE**: The setting is *only* propagated *down* and not up through parent commands.
649 /// # use clap::{App, Arg, AppSettings};
650 /// App::new("myprog")
651 /// .global_settings(&[AppSettings::SubcommandRequired,
652 /// AppSettings::ColoredHelp])
655 /// [`SubCommand`]: ./struct.SubCommand.html
656 /// [`AppSettings`]: ./enum.AppSettings.html
657 pub fn global_settings(mut self, settings
: &[AppSettings
]) -> Self {
660 self.p
.g_settings
.set(*s
)
665 /// Disables a single command, or [`SubCommand`], level setting.
667 /// See [`AppSettings`] for a full list of possibilities and examples.
672 /// # use clap::{App, AppSettings};
673 /// App::new("myprog")
674 /// .unset_setting(AppSettings::ColorAuto)
677 /// [`SubCommand`]: ./struct.SubCommand.html
678 /// [`AppSettings`]: ./enum.AppSettings.html
679 pub fn unset_setting(mut self, setting
: AppSettings
) -> Self {
680 self.p
.unset(setting
);
684 /// Disables multiple command, or [`SubCommand`], level settings.
686 /// See [`AppSettings`] for a full list of possibilities and examples.
691 /// # use clap::{App, AppSettings};
692 /// App::new("myprog")
693 /// .unset_settings(&[AppSettings::ColorAuto,
694 /// AppSettings::AllowInvalidUtf8])
697 /// [`SubCommand`]: ./struct.SubCommand.html
698 /// [`AppSettings`]: ./enum.AppSettings.html
699 pub fn unset_settings(mut self, settings
: &[AppSettings
]) -> Self {
706 /// Sets the terminal width at which to wrap help messages. Defaults to `120`. Using `0` will
707 /// ignore terminal widths and use source formatting.
709 /// `clap` automatically tries to determine the terminal width on Unix, Linux, OSX and Windows
710 /// if the `wrap_help` cargo "feature" has been used while compiling. If the terminal width
711 /// cannot be determined, `clap` defaults to `120`.
713 /// **NOTE:** This setting applies globally and *not* on a per-command basis.
715 /// **NOTE:** This setting must be set **before** any subcommands are added!
717 /// # Platform Specific
719 /// Only Unix, Linux, OSX and Windows support automatic determination of terminal width.
720 /// Even on those platforms, this setting is useful if for any reason the terminal width
721 /// cannot be determined.
727 /// App::new("myprog")
728 /// .set_term_width(80)
731 pub fn set_term_width(mut self, width
: usize) -> Self {
732 self.p
.meta
.term_w
= Some(width
);
736 /// Sets the max terminal width at which to wrap help messages. Using `0` will ignore terminal
737 /// widths and use source formatting.
739 /// `clap` automatically tries to determine the terminal width on Unix, Linux, OSX and Windows
740 /// if the `wrap_help` cargo "feature" has been used while compiling, but one might want to
741 /// limit the size (e.g. when the terminal is running fullscreen).
743 /// **NOTE:** This setting applies globally and *not* on a per-command basis.
745 /// **NOTE:** This setting must be set **before** any subcommands are added!
747 /// # Platform Specific
749 /// Only Unix, Linux, OSX and Windows support automatic determination of terminal width.
755 /// App::new("myprog")
756 /// .max_term_width(100)
759 pub fn max_term_width(mut self, w
: usize) -> Self {
760 self.p
.meta
.max_w
= Some(w
);
764 /// Adds an [argument] to the list of valid possibilities.
769 /// # use clap::{App, Arg};
770 /// App::new("myprog")
771 /// // Adding a single "flag" argument with a short and help text, using Arg::with_name()
773 /// Arg::with_name("debug")
775 /// .help("turns on debugging mode")
777 /// // Adding a single "option" argument with a short, a long, and help text using the less
778 /// // verbose Arg::from_usage()
780 /// Arg::from_usage("-c --config=[CONFIG] 'Optionally sets a config file to use'")
784 /// [argument]: ./struct.Arg.html
785 pub fn arg
<A
: Into
<Arg
<'a
, 'b
>>>(mut self, a
: A
) -> Self {
786 self.p
.add_arg(a
.into());
790 /// Adds multiple [arguments] to the list of valid possibilties
795 /// # use clap::{App, Arg};
796 /// App::new("myprog")
798 /// &[Arg::from_usage("[debug] -d 'turns on debugging info'"),
799 /// Arg::with_name("input").index(1).help("the input file to use")]
803 /// [arguments]: ./struct.Arg.html
804 pub fn args(mut self, args
: &[Arg
<'a
, 'b
>]) -> Self {
806 self.p
.add_arg_ref(arg
);
811 /// A convenience method for adding a single [argument] from a usage type string. The string
812 /// used follows the same rules and syntax as [`Arg::from_usage`]
814 /// **NOTE:** The downside to using this method is that you can not set any additional
815 /// properties of the [`Arg`] other than what [`Arg::from_usage`] supports.
820 /// # use clap::{App, Arg};
821 /// App::new("myprog")
822 /// .arg_from_usage("-c --config=<FILE> 'Sets a configuration file to use'")
825 /// [arguments]: ./struct.Arg.html
826 /// [`Arg`]: ./struct.Arg.html
827 /// [`Arg::from_usage`]: ./struct.Arg.html#method.from_usage
828 pub fn arg_from_usage(mut self, usage
: &'a
str) -> Self {
829 self.p
.add_arg(Arg
::from_usage(usage
));
833 /// Adds multiple [arguments] at once from a usage string, one per line. See
834 /// [`Arg::from_usage`] for details on the syntax and rules supported.
836 /// **NOTE:** Like [`App::arg_from_usage`] the downside is you only set properties for the
837 /// [`Arg`]s which [`Arg::from_usage`] supports.
842 /// # use clap::{App, Arg};
843 /// App::new("myprog")
844 /// .args_from_usage(
845 /// "-c --config=[FILE] 'Sets a configuration file to use'
846 /// [debug]... -d 'Sets the debugging level'
847 /// <FILE> 'The input file to use'"
851 /// [arguments]: ./struct.Arg.html
852 /// [`Arg::from_usage`]: ./struct.Arg.html#method.from_usage
853 /// [`App::arg_from_usage`]: ./struct.App.html#method.arg_from_usage
854 /// [`Arg`]: ./struct.Arg.html
855 pub fn args_from_usage(mut self, usage
: &'a
str) -> Self {
856 for line
in usage
.lines() {
861 self.p
.add_arg(Arg
::from_usage(l
));
866 /// Allows adding a [`SubCommand`] alias, which function as "hidden" subcommands that
867 /// automatically dispatch as if this subcommand was used. This is more efficient, and easier
868 /// than creating multiple hidden subcommands as one only needs to check for the existence of
869 /// this command, and not all variants.
874 /// # use clap::{App, Arg, SubCommand};
875 /// let m = App::new("myprog")
876 /// .subcommand(SubCommand::with_name("test")
877 /// .alias("do-stuff"))
878 /// .get_matches_from(vec!["myprog", "do-stuff"]);
879 /// assert_eq!(m.subcommand_name(), Some("test"));
881 /// [`SubCommand`]: ./struct.SubCommand.html
882 pub fn alias
<S
: Into
<&'b
str>>(mut self, name
: S
) -> Self {
883 if let Some(ref mut als
) = self.p
.meta
.aliases
{
884 als
.push((name
.into(), false));
886 self.p
.meta
.aliases
= Some(vec
![(name
.into(), false)]);
891 /// Allows adding [`SubCommand`] aliases, which function as "hidden" subcommands that
892 /// automatically dispatch as if this subcommand was used. This is more efficient, and easier
893 /// than creating multiple hidden subcommands as one only needs to check for the existence of
894 /// this command, and not all variants.
899 /// # use clap::{App, Arg, SubCommand};
900 /// let m = App::new("myprog")
901 /// .subcommand(SubCommand::with_name("test")
902 /// .aliases(&["do-stuff", "do-tests", "tests"]))
903 /// .arg(Arg::with_name("input")
904 /// .help("the file to add")
906 /// .required(false))
907 /// .get_matches_from(vec!["myprog", "do-tests"]);
908 /// assert_eq!(m.subcommand_name(), Some("test"));
910 /// [`SubCommand`]: ./struct.SubCommand.html
911 pub fn aliases(mut self, names
: &[&'b
str]) -> Self {
912 if let Some(ref mut als
) = self.p
.meta
.aliases
{
914 als
.push((n
, false));
917 self.p
.meta
.aliases
= Some(names
.iter().map(|n
| (*n
, false)).collect
::<Vec
<_
>>());
922 /// Allows adding a [`SubCommand`] alias that functions exactly like those defined with
923 /// [`App::alias`], except that they are visible inside the help message.
928 /// # use clap::{App, Arg, SubCommand};
929 /// let m = App::new("myprog")
930 /// .subcommand(SubCommand::with_name("test")
931 /// .visible_alias("do-stuff"))
932 /// .get_matches_from(vec!["myprog", "do-stuff"]);
933 /// assert_eq!(m.subcommand_name(), Some("test"));
935 /// [`SubCommand`]: ./struct.SubCommand.html
936 /// [`App::alias`]: ./struct.App.html#method.alias
937 pub fn visible_alias
<S
: Into
<&'b
str>>(mut self, name
: S
) -> Self {
938 if let Some(ref mut als
) = self.p
.meta
.aliases
{
939 als
.push((name
.into(), true));
941 self.p
.meta
.aliases
= Some(vec
![(name
.into(), true)]);
946 /// Allows adding multiple [`SubCommand`] aliases that functions exactly like those defined
947 /// with [`App::aliases`], except that they are visible inside the help message.
952 /// # use clap::{App, Arg, SubCommand};
953 /// let m = App::new("myprog")
954 /// .subcommand(SubCommand::with_name("test")
955 /// .visible_aliases(&["do-stuff", "tests"]))
956 /// .get_matches_from(vec!["myprog", "do-stuff"]);
957 /// assert_eq!(m.subcommand_name(), Some("test"));
959 /// [`SubCommand`]: ./struct.SubCommand.html
960 /// [`App::aliases`]: ./struct.App.html#method.aliases
961 pub fn visible_aliases(mut self, names
: &[&'b
str]) -> Self {
962 if let Some(ref mut als
) = self.p
.meta
.aliases
{
967 self.p
.meta
.aliases
= Some(names
.iter().map(|n
| (*n
, true)).collect
::<Vec
<_
>>());
972 /// Adds an [`ArgGroup`] to the application. [`ArgGroup`]s are a family of related arguments.
973 /// By placing them in a logical group, you can build easier requirement and exclusion rules.
974 /// For instance, you can make an entire [`ArgGroup`] required, meaning that one (and *only*
975 /// one) argument from that group must be present at runtime.
977 /// You can also do things such as name an [`ArgGroup`] as a conflict to another argument.
978 /// Meaning any of the arguments that belong to that group will cause a failure if present with
979 /// the conflicting argument.
981 /// Another added benfit of [`ArgGroup`]s is that you can extract a value from a group instead
982 /// of determining exactly which argument was used.
984 /// Finally, using [`ArgGroup`]s to ensure exclusion between arguments is another very common
989 /// The following example demonstrates using an [`ArgGroup`] to ensure that one, and only one,
990 /// of the arguments from the specified group is present at runtime.
993 /// # use clap::{App, ArgGroup};
995 /// .args_from_usage(
996 /// "--set-ver [ver] 'set the version manually'
997 /// --major 'auto increase major'
998 /// --minor 'auto increase minor'
999 /// --patch 'auto increase patch'")
1000 /// .group(ArgGroup::with_name("vers")
1001 /// .args(&["set-ver", "major", "minor","patch"])
1002 /// .required(true))
1005 /// [`ArgGroup`]: ./struct.ArgGroup.html
1006 pub fn group(mut self, group
: ArgGroup
<'a
>) -> Self {
1007 self.p
.add_group(group
);
1011 /// Adds multiple [`ArgGroup`]s to the [`App`] at once.
1016 /// # use clap::{App, ArgGroup};
1018 /// .args_from_usage(
1019 /// "--set-ver [ver] 'set the version manually'
1020 /// --major 'auto increase major'
1021 /// --minor 'auto increase minor'
1022 /// --patch 'auto increase patch'
1023 /// -c [FILE] 'a config file'
1024 /// -i [IFACE] 'an interface'")
1026 /// ArgGroup::with_name("vers")
1027 /// .args(&["set-ver", "major", "minor","patch"])
1028 /// .required(true),
1029 /// ArgGroup::with_name("input")
1030 /// .args(&["c", "i"])
1034 /// [`ArgGroup`]: ./struct.ArgGroup.html
1035 /// [`App`]: ./struct.App.html
1036 pub fn groups(mut self, groups
: &[ArgGroup
<'a
>]) -> Self {
1038 self = self.group(g
.into());
1043 /// Adds a [`SubCommand`] to the list of valid possibilities. Subcommands are effectively
1044 /// sub-[`App`]s, because they can contain their own arguments, subcommands, version, usage,
1045 /// etc. They also function just like [`App`]s, in that they get their own auto generated help,
1046 /// version, and usage.
1051 /// # use clap::{App, Arg, SubCommand};
1052 /// App::new("myprog")
1053 /// .subcommand(SubCommand::with_name("config")
1054 /// .about("Controls configuration features")
1055 /// .arg_from_usage("<config> 'Required configuration file to use'"))
1058 /// [`SubCommand`]: ./struct.SubCommand.html
1059 /// [`App`]: ./struct.App.html
1060 pub fn subcommand(mut self, subcmd
: App
<'a
, 'b
>) -> Self {
1061 self.p
.add_subcommand(subcmd
);
1065 /// Adds multiple subcommands to the list of valid possibilities by iterating over an
1066 /// [`IntoIterator`] of [`SubCommand`]s
1071 /// # use clap::{App, Arg, SubCommand};
1072 /// # App::new("myprog")
1073 /// .subcommands( vec![
1074 /// SubCommand::with_name("config").about("Controls configuration functionality")
1075 /// .arg(Arg::with_name("config_file").index(1)),
1076 /// SubCommand::with_name("debug").about("Controls debug functionality")])
1079 /// [`SubCommand`]: ./struct.SubCommand.html
1080 /// [`IntoIterator`]: https://doc.rust-lang.org/std/iter/trait.IntoIterator.html
1081 pub fn subcommands
<I
>(mut self, subcmds
: I
) -> Self
1083 I
: IntoIterator
<Item
= App
<'a
, 'b
>>,
1085 for subcmd
in subcmds
{
1086 self.p
.add_subcommand(subcmd
);
1091 /// Allows custom ordering of [`SubCommand`]s within the help message. Subcommands with a lower
1092 /// value will be displayed first in the help message. This is helpful when one would like to
1093 /// emphasise frequently used subcommands, or prioritize those towards the top of the list.
1094 /// Duplicate values **are** allowed. Subcommands with duplicate display orders will be
1095 /// displayed in alphabetical order.
1097 /// **NOTE:** The default is 999 for all subcommands.
1102 /// # use clap::{App, SubCommand};
1103 /// let m = App::new("cust-ord")
1104 /// .subcommand(SubCommand::with_name("alpha") // typically subcommands are grouped
1105 /// // alphabetically by name. Subcommands
1106 /// // without a display_order have a value of
1107 /// // 999 and are displayed alphabetically with
1108 /// // all other 999 subcommands
1109 /// .about("Some help and text"))
1110 /// .subcommand(SubCommand::with_name("beta")
1111 /// .display_order(1) // In order to force this subcommand to appear *first*
1112 /// // all we have to do is give it a value lower than 999.
1113 /// // Any other subcommands with a value of 1 will be displayed
1114 /// // alphabetically with this one...then 2 values, then 3, etc.
1115 /// .about("I should be first!"))
1116 /// .get_matches_from(vec![
1117 /// "cust-ord", "--help"
1121 /// The above example displays the following help message
1127 /// cust-ord [FLAGS] [OPTIONS]
1130 /// -h, --help Prints help information
1131 /// -V, --version Prints version information
1134 /// beta I should be first!
1135 /// alpha Some help and text
1137 /// [`SubCommand`]: ./struct.SubCommand.html
1138 pub fn display_order(mut self, ord
: usize) -> Self {
1139 self.p
.meta
.disp_ord
= ord
;
1143 /// Prints the full help message to [`io::stdout()`] using a [`BufWriter`] using the same
1144 /// method as if someone ran `-h` to request the help message
1146 /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
1147 /// depending on if the user ran [`-h` (short)] or [`--help` (long)]
1152 /// # use clap::App;
1153 /// let mut app = App::new("myprog");
1154 /// app.print_help();
1156 /// [`io::stdout()`]: https://doc.rust-lang.org/std/io/fn.stdout.html
1157 /// [`BufWriter`]: https://doc.rust-lang.org/std/io/struct.BufWriter.html
1158 /// [`-h` (short)]: ./struct.Arg.html#method.help
1159 /// [`--help` (long)]: ./struct.Arg.html#method.long_help
1160 pub fn print_help(&mut self) -> ClapResult
<()> {
1161 // If there are global arguments, or settings we need to propgate them down to subcommands
1162 // before parsing incase we run into a subcommand
1163 self.p
.propagate_globals();
1164 self.p
.propagate_settings();
1165 self.p
.derive_display_order();
1167 self.p
.create_help_and_version();
1168 let out
= io
::stdout();
1169 let mut buf_w
= BufWriter
::new(out
.lock());
1170 self.write_help(&mut buf_w
)
1173 /// Prints the full help message to [`io::stdout()`] using a [`BufWriter`] using the same
1174 /// method as if someone ran `--help` to request the help message
1176 /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
1177 /// depending on if the user ran [`-h` (short)] or [`--help` (long)]
1182 /// # use clap::App;
1183 /// let mut app = App::new("myprog");
1184 /// app.print_long_help();
1186 /// [`io::stdout()`]: https://doc.rust-lang.org/std/io/fn.stdout.html
1187 /// [`BufWriter`]: https://doc.rust-lang.org/std/io/struct.BufWriter.html
1188 /// [`-h` (short)]: ./struct.Arg.html#method.help
1189 /// [`--help` (long)]: ./struct.Arg.html#method.long_help
1190 pub fn print_long_help(&mut self) -> ClapResult
<()> {
1191 // If there are global arguments, or settings we need to propgate them down to subcommands
1192 // before parsing incase we run into a subcommand
1193 self.p
.propagate_globals();
1194 self.p
.propagate_settings();
1195 self.p
.derive_display_order();
1197 self.p
.create_help_and_version();
1198 let out
= io
::stdout();
1199 let mut buf_w
= BufWriter
::new(out
.lock());
1200 self.write_long_help(&mut buf_w
)
1203 /// Writes the full help message to the user to a [`io::Write`] object in the same method as if
1204 /// the user ran `-h`
1206 /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
1207 /// depending on if the user ran [`-h` (short)] or [`--help` (long)]
1209 /// **NOTE:** There is a known bug where this method does not write propagated global arguments
1210 /// or autogenerated arguments (i.e. the default help/version args). Prefer
1211 /// [`App::write_long_help`] instead if possibe!
1216 /// # use clap::App;
1218 /// let mut app = App::new("myprog");
1219 /// let mut out = io::stdout();
1220 /// app.write_help(&mut out).expect("failed to write to stdout");
1222 /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
1223 /// [`-h` (short)]: ./struct.Arg.html#method.help
1224 /// [`--help` (long)]: ./struct.Arg.html#method.long_help
1225 pub fn write_help
<W
: Write
>(&self, w
: &mut W
) -> ClapResult
<()> {
1226 // PENDING ISSUE: 808
1227 // https://github.com/kbknapp/clap-rs/issues/808
1228 // If there are global arguments, or settings we need to propgate them down to subcommands
1229 // before parsing incase we run into a subcommand
1230 // self.p.propagate_globals();
1231 // self.p.propagate_settings();
1232 // self.p.derive_display_order();
1233 // self.p.create_help_and_version();
1235 Help
::write_app_help(w
, self, false)
1238 /// Writes the full help message to the user to a [`io::Write`] object in the same method as if
1239 /// the user ran `--help`
1241 /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
1242 /// depending on if the user ran [`-h` (short)] or [`--help` (long)]
1247 /// # use clap::App;
1249 /// let mut app = App::new("myprog");
1250 /// let mut out = io::stdout();
1251 /// app.write_long_help(&mut out).expect("failed to write to stdout");
1253 /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
1254 /// [`-h` (short)]: ./struct.Arg.html#method.help
1255 /// [`--help` (long)]: ./struct.Arg.html#method.long_help
1256 pub fn write_long_help
<W
: Write
>(&mut self, w
: &mut W
) -> ClapResult
<()> {
1257 self.p
.propagate_globals();
1258 self.p
.propagate_settings();
1259 self.p
.derive_display_order();
1260 self.p
.create_help_and_version();
1262 Help
::write_app_help(w
, self, true)
1265 /// Writes the version message to the user to a [`io::Write`] object as if the user ran `-V`.
1267 /// **NOTE:** clap has the ability to distinguish between "short" and "long" version messages
1268 /// depending on if the user ran [`-V` (short)] or [`--version` (long)]
1273 /// # use clap::App;
1275 /// let mut app = App::new("myprog");
1276 /// let mut out = io::stdout();
1277 /// app.write_version(&mut out).expect("failed to write to stdout");
1279 /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
1280 /// [`-V` (short)]: ./struct.App.html#method.version
1281 /// [`--version` (long)]: ./struct.App.html#method.long_version
1282 pub fn write_version
<W
: Write
>(&self, w
: &mut W
) -> ClapResult
<()> {
1283 self.p
.write_version(w
, false).map_err(From
::from
)
1286 /// Writes the version message to the user to a [`io::Write`] object
1288 /// **NOTE:** clap has the ability to distinguish between "short" and "long" version messages
1289 /// depending on if the user ran [`-V` (short)] or [`--version` (long)]
1294 /// # use clap::App;
1296 /// let mut app = App::new("myprog");
1297 /// let mut out = io::stdout();
1298 /// app.write_long_version(&mut out).expect("failed to write to stdout");
1300 /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
1301 /// [`-V` (short)]: ./struct.App.html#method.version
1302 /// [`--version` (long)]: ./struct.App.html#method.long_version
1303 pub fn write_long_version
<W
: Write
>(&self, w
: &mut W
) -> ClapResult
<()> {
1304 self.p
.write_version(w
, true).map_err(From
::from
)
1307 /// Generate a completions file for a specified shell at compile time.
1309 /// **NOTE:** to generate the this file at compile time you must use a `build.rs` "Build Script"
1313 /// The following example generates a bash completion script via a `build.rs` script. In this
1314 /// simple example, we'll demo a very small application with only a single subcommand and two
1315 /// args. Real applications could be many multiple levels deep in subcommands, and have tens or
1316 /// potentially hundreds of arguments.
1318 /// First, it helps if we separate out our `App` definition into a separate file. Whether you
1319 /// do this as a function, or bare App definition is a matter of personal preference.
1324 /// use clap::{App, Arg, SubCommand};
1326 /// pub fn build_cli() -> App<'static, 'static> {
1327 /// App::new("compl")
1328 /// .about("Tests completions")
1329 /// .arg(Arg::with_name("file")
1330 /// .help("some input file"))
1331 /// .subcommand(SubCommand::with_name("test")
1332 /// .about("tests things")
1333 /// .arg(Arg::with_name("case")
1335 /// .takes_value(true)
1336 /// .help("the case to test")))
1340 /// In our regular code, we can simply call this `build_cli()` function, then call
1341 /// `get_matches()`, or any of the other normal methods directly after. For example:
1349 /// let m = cli::build_cli().get_matches();
1351 /// // normal logic continues...
1355 /// Next, we set up our `Cargo.toml` to use a `build.rs` build script.
1359 /// build = "build.rs"
1361 /// [build-dependencies]
1365 /// Next, we place a `build.rs` in our project root.
1368 /// extern crate clap;
1370 /// use clap::Shell;
1372 /// include!("src/cli.rs");
1375 /// let outdir = match env::var_os("OUT_DIR") {
1377 /// Some(outdir) => outdir,
1379 /// let mut app = build_cli();
1380 /// app.gen_completions("myapp", // We need to specify the bin name manually
1381 /// Shell::Bash, // Then say which shell to build completions for
1382 /// outdir); // Then say where write the completions to
1385 /// Now, once we compile there will be a `{bin_name}.bash` file in the directory.
1386 /// Assuming we compiled with debug mode, it would be somewhere similar to
1387 /// `<project>/target/debug/build/myapp-<hash>/out/myapp.bash`.
1389 /// Fish shell completions will use the file format `{bin_name}.fish`
1390 pub fn gen_completions
<T
: Into
<OsString
>, S
: Into
<String
>>(
1396 self.p
.meta
.bin_name
= Some(bin_name
.into());
1397 self.p
.gen_completions(for_shell
, out_dir
.into());
1401 /// Generate a completions file for a specified shell at runtime. Until `cargo install` can
1402 /// install extra files like a completion script, this may be used e.g. in a command that
1403 /// outputs the contents of the completion script, to be redirected into a file by the user.
1407 /// Assuming a separate `cli.rs` like the [example above](./struct.App.html#method.gen_completions),
1408 /// we can let users generate a completion script using a command:
1417 /// let matches = cli::build_cli().get_matches();
1419 /// if matches.is_present("generate-bash-completions") {
1420 /// cli::build_cli().gen_completions_to("myapp", Shell::Bash, &mut io::stdout());
1423 /// // normal logic continues...
1431 /// $ myapp generate-bash-completions > /usr/share/bash-completion/completions/myapp.bash
1433 pub fn gen_completions_to
<W
: Write
, S
: Into
<String
>>(
1439 self.p
.meta
.bin_name
= Some(bin_name
.into());
1440 self.p
.gen_completions_to(for_shell
, buf
);
1443 /// Starts the parsing process, upon a failed parse an error will be displayed to the user and
1444 /// the process will exit with the appropriate error code. By default this method gets all user
1445 /// provided arguments from [`env::args_os`] in order to allow for invalid UTF-8 code points,
1446 /// which are legal on many platforms.
1451 /// # use clap::{App, Arg};
1452 /// let matches = App::new("myprog")
1453 /// // Args and options go here...
1456 /// [`env::args_os`]: https://doc.rust-lang.org/std/env/fn.args_os.html
1457 pub fn get_matches(self) -> ArgMatches
<'a
> { self.get_matches_from(&mut env::args_os()) }
1459 /// Starts the parsing process. This method will return a [`clap::Result`] type instead of exiting
1460 /// the process on failed parse. By default this method gets matches from [`env::args_os`]
1462 /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
1463 /// used. It will return a [`clap::Error`], where the [`kind`] is a
1464 /// [`ErrorKind::HelpDisplayed`] or [`ErrorKind::VersionDisplayed`] respectively. You must call
1465 /// [`Error::exit`] or perform a [`std::process::exit`].
1470 /// # use clap::{App, Arg};
1471 /// let matches = App::new("myprog")
1472 /// // Args and options go here...
1473 /// .get_matches_safe()
1474 /// .unwrap_or_else( |e| e.exit() );
1476 /// [`env::args_os`]: https://doc.rust-lang.org/std/env/fn.args_os.html
1477 /// [`ErrorKind::HelpDisplayed`]: ./enum.ErrorKind.html#variant.HelpDisplayed
1478 /// [`ErrorKind::VersionDisplayed`]: ./enum.ErrorKind.html#variant.VersionDisplayed
1479 /// [`Error::exit`]: ./struct.Error.html#method.exit
1480 /// [`std::process::exit`]: https://doc.rust-lang.org/std/process/fn.exit.html
1481 /// [`clap::Result`]: ./type.Result.html
1482 /// [`clap::Error`]: ./struct.Error.html
1483 /// [`kind`]: ./struct.Error.html
1484 pub fn get_matches_safe(self) -> ClapResult
<ArgMatches
<'a
>> {
1485 // Start the parsing
1486 self.get_matches_from_safe(&mut env
::args_os())
1489 /// Starts the parsing process. Like [`App::get_matches`] this method does not return a [`clap::Result`]
1490 /// and will automatically exit with an error message. This method, however, lets you specify
1491 /// what iterator to use when performing matches, such as a [`Vec`] of your making.
1493 /// **NOTE:** The first argument will be parsed as the binary name unless
1494 /// [`AppSettings::NoBinaryName`] is used
1499 /// # use clap::{App, Arg};
1500 /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
1502 /// let matches = App::new("myprog")
1503 /// // Args and options go here...
1504 /// .get_matches_from(arg_vec);
1506 /// [`App::get_matches`]: ./struct.App.html#method.get_matches
1507 /// [`clap::Result`]: ./type.Result.html
1508 /// [`Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
1509 /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName
1510 pub fn get_matches_from
<I
, T
>(mut self, itr
: I
) -> ArgMatches
<'a
>
1512 I
: IntoIterator
<Item
= T
>,
1513 T
: Into
<OsString
> + Clone
,
1515 self.get_matches_from_safe_borrow(itr
).unwrap_or_else(|e
| {
1516 // Otherwise, write to stderr and exit
1518 wlnerr
!("{}", e
.message
);
1519 if self.p
.is_set(AppSettings
::WaitOnError
) {
1520 wlnerr
!("\nPress [ENTER] / [RETURN] to continue...");
1521 let mut s
= String
::new();
1522 let i
= io
::stdin();
1523 i
.lock().read_line(&mut s
).unwrap();
1535 /// Starts the parsing process. A combination of [`App::get_matches_from`], and
1536 /// [`App::get_matches_safe`]
1538 /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
1539 /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::HelpDisplayed`]
1540 /// or [`ErrorKind::VersionDisplayed`] respectively. You must call [`Error::exit`] or
1541 /// perform a [`std::process::exit`] yourself.
1543 /// **NOTE:** The first argument will be parsed as the binary name unless
1544 /// [`AppSettings::NoBinaryName`] is used
1549 /// # use clap::{App, Arg};
1550 /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
1552 /// let matches = App::new("myprog")
1553 /// // Args and options go here...
1554 /// .get_matches_from_safe(arg_vec)
1555 /// .unwrap_or_else( |e| { panic!("An error occurs: {}", e) });
1557 /// [`App::get_matches_from`]: ./struct.App.html#method.get_matches_from
1558 /// [`App::get_matches_safe`]: ./struct.App.html#method.get_matches_safe
1559 /// [`ErrorKind::HelpDisplayed`]: ./enum.ErrorKind.html#variant.HelpDisplayed
1560 /// [`ErrorKind::VersionDisplayed`]: ./enum.ErrorKind.html#variant.VersionDisplayed
1561 /// [`Error::exit`]: ./struct.Error.html#method.exit
1562 /// [`std::process::exit`]: https://doc.rust-lang.org/std/process/fn.exit.html
1563 /// [`clap::Error`]: ./struct.Error.html
1564 /// [`Error::exit`]: ./struct.Error.html#method.exit
1565 /// [`kind`]: ./struct.Error.html
1566 /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName
1567 pub fn get_matches_from_safe
<I
, T
>(mut self, itr
: I
) -> ClapResult
<ArgMatches
<'a
>>
1569 I
: IntoIterator
<Item
= T
>,
1570 T
: Into
<OsString
> + Clone
,
1572 self.get_matches_from_safe_borrow(itr
)
1575 /// Starts the parsing process without consuming the [`App`] struct `self`. This is normally not
1576 /// the desired functionality, instead prefer [`App::get_matches_from_safe`] which *does*
1579 /// **NOTE:** The first argument will be parsed as the binary name unless
1580 /// [`AppSettings::NoBinaryName`] is used
1585 /// # use clap::{App, Arg};
1586 /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
1588 /// let mut app = App::new("myprog");
1589 /// // Args and options go here...
1590 /// let matches = app.get_matches_from_safe_borrow(arg_vec)
1591 /// .unwrap_or_else( |e| { panic!("An error occurs: {}", e) });
1593 /// [`App`]: ./struct.App.html
1594 /// [`App::get_matches_from_safe`]: ./struct.App.html#method.get_matches_from_safe
1595 /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName
1596 pub fn get_matches_from_safe_borrow
<I
, T
>(&mut self, itr
: I
) -> ClapResult
<ArgMatches
<'a
>>
1598 I
: IntoIterator
<Item
= T
>,
1599 T
: Into
<OsString
> + Clone
,
1601 // If there are global arguments, or settings we need to propgate them down to subcommands
1602 // before parsing incase we run into a subcommand
1603 if !self.p
.is_set(AppSettings
::Propagated
) {
1604 self.p
.propagate_globals();
1605 self.p
.propagate_settings();
1606 self.p
.derive_display_order();
1607 self.p
.set(AppSettings
::Propagated
);
1610 let mut matcher
= ArgMatcher
::new();
1612 let mut it
= itr
.into_iter();
1613 // Get the name of the program (argument 1 of env::args()) and determine the
1615 // that was used to execute the program. This is because a program called
1616 // ./target/release/my_prog -a
1617 // will have two arguments, './target/release/my_prog', '-a' but we don't want
1619 // the full path when displaying help messages and such
1620 if !self.p
.is_set(AppSettings
::NoBinaryName
) {
1621 if let Some(name
) = it
.next() {
1622 let bn_os
= name
.into();
1623 let p
= Path
::new(&*bn_os
);
1624 if let Some(f
) = p
.file_name() {
1625 if let Some(s
) = f
.to_os_string().to_str() {
1626 if self.p
.meta
.bin_name
.is_none() {
1627 self.p
.meta
.bin_name
= Some(s
.to_owned());
1634 // do the real parsing
1635 if let Err(e
) = self.p
.get_matches_with(&mut matcher
, &mut it
.peekable()) {
1639 let global_arg_vec
: Vec
<&str> = (&self).p
.global_args
.iter().map(|ga
| ga
.b
.name
).collect();
1640 matcher
.propagate_globals(&global_arg_vec
);
1646 #[cfg(feature = "yaml")]
1647 impl<'a
> From
<&'a Yaml
> for App
<'a
, 'a
> {
1648 fn from(mut yaml
: &'a Yaml
) -> Self {
1649 use args
::SubCommand
;
1650 // We WANT this to panic on error...so expect() is good.
1651 let mut is_sc
= None
;
1652 let mut a
= if let Some(name
) = yaml
["name"].as_str() {
1655 let yaml_hash
= yaml
.as_hash().unwrap();
1656 let sc_key
= yaml_hash
.keys().nth(0).unwrap();
1657 is_sc
= Some(yaml_hash
.get(sc_key
).unwrap());
1658 App
::new(sc_key
.as_str().unwrap())
1660 yaml
= if let Some(sc
) = is_sc { sc }
else { yaml }
;
1662 macro_rules
! yaml_str
{
1663 ($a
:ident
, $y
:ident
, $i
:ident
) => {
1664 if let Some(v
) = $y
[stringify
!($i
)].as_str() {
1666 } else if $y
[stringify
!($i
)] != Yaml
::BadValue
{
1667 panic
!("Failed to convert YAML value {:?} to a string", $y
[stringify
!($i
)]);
1672 yaml_str
!(a
, yaml
, version
);
1673 yaml_str
!(a
, yaml
, author
);
1674 yaml_str
!(a
, yaml
, bin_name
);
1675 yaml_str
!(a
, yaml
, about
);
1676 yaml_str
!(a
, yaml
, before_help
);
1677 yaml_str
!(a
, yaml
, after_help
);
1678 yaml_str
!(a
, yaml
, template
);
1679 yaml_str
!(a
, yaml
, usage
);
1680 yaml_str
!(a
, yaml
, help
);
1681 yaml_str
!(a
, yaml
, help_short
);
1682 yaml_str
!(a
, yaml
, version_short
);
1683 yaml_str
!(a
, yaml
, help_message
);
1684 yaml_str
!(a
, yaml
, version_message
);
1685 yaml_str
!(a
, yaml
, alias
);
1686 yaml_str
!(a
, yaml
, visible_alias
);
1688 if let Some(v
) = yaml
["display_order"].as_i64() {
1689 a
= a
.display_order(v
as usize);
1690 } else if yaml
["display_order"] != Yaml
::BadValue
{
1692 "Failed to convert YAML value {:?} to a u64",
1693 yaml
["display_order"]
1696 if let Some(v
) = yaml
["setting"].as_str() {
1697 a
= a
.setting(v
.parse().expect("unknown AppSetting found in YAML file"));
1698 } else if yaml
["setting"] != Yaml
::BadValue
{
1700 "Failed to convert YAML value {:?} to an AppSetting",
1704 if let Some(v
) = yaml
["settings"].as_vec() {
1706 if let Some(s
) = ys
.as_str() {
1707 a
= a
.setting(s
.parse().expect("unknown AppSetting found in YAML file"));
1710 } else if let Some(v
) = yaml
["settings"].as_str() {
1711 a
= a
.setting(v
.parse().expect("unknown AppSetting found in YAML file"));
1712 } else if yaml
["settings"] != Yaml
::BadValue
{
1714 "Failed to convert YAML value {:?} to a string",
1718 if let Some(v
) = yaml
["global_setting"].as_str() {
1719 a
= a
.setting(v
.parse().expect("unknown AppSetting found in YAML file"));
1720 } else if yaml
["global_setting"] != Yaml
::BadValue
{
1722 "Failed to convert YAML value {:?} to an AppSetting",
1726 if let Some(v
) = yaml
["global_settings"].as_vec() {
1728 if let Some(s
) = ys
.as_str() {
1729 a
= a
.global_setting(s
.parse().expect("unknown AppSetting found in YAML file"));
1732 } else if let Some(v
) = yaml
["global_settings"].as_str() {
1733 a
= a
.global_setting(v
.parse().expect("unknown AppSetting found in YAML file"));
1734 } else if yaml
["global_settings"] != Yaml
::BadValue
{
1736 "Failed to convert YAML value {:?} to a string",
1737 yaml
["global_settings"]
1741 macro_rules
! vec_or_str
{
1742 ($a
:ident
, $y
:ident
, $as_vec
:ident
, $as_single
:ident
) => {{
1743 let maybe_vec
= $y
[stringify
!($as_vec
)].as_vec();
1744 if let Some(vec
) = maybe_vec
{
1746 if let Some(s
) = ys
.as_str() {
1747 $a
= $a
.$
as_single(s
);
1749 panic
!("Failed to convert YAML value {:?} to a string", ys
);
1753 if let Some(s
) = $y
[stringify
!($as_vec
)].as_str() {
1754 $a
= $a
.$
as_single(s
);
1755 } else if $y
[stringify
!($as_vec
)] != Yaml
::BadValue
{
1756 panic
!("Failed to convert YAML value {:?} to either a vec or string", $y
[stringify
!($as_vec
)]);
1764 a
= vec_or_str
!(a
, yaml
, aliases
, alias
);
1765 a
= vec_or_str
!(a
, yaml
, visible_aliases
, visible_alias
);
1767 if let Some(v
) = yaml
["args"].as_vec() {
1769 a
= a
.arg(Arg
::from_yaml(arg_yaml
.as_hash().unwrap()));
1772 if let Some(v
) = yaml
["subcommands"].as_vec() {
1774 a
= a
.subcommand(SubCommand
::from_yaml(sc_yaml
));
1777 if let Some(v
) = yaml
["groups"].as_vec() {
1779 a
= a
.group(ArgGroup
::from(ag_yaml
.as_hash().unwrap()));
1787 impl<'a
, 'b
> Clone
for App
<'a
, 'b
> {
1788 fn clone(&self) -> Self { App { p: self.p.clone() }
}
1791 impl<'n
, 'e
> AnyArg
<'n
, 'e
> for App
<'n
, 'e
> {
1792 fn name(&self) -> &'n
str {
1793 unreachable
!("App struct does not support AnyArg::name, this is a bug!")
1795 fn overrides(&self) -> Option
<&[&'e
str]> { None }
1796 fn requires(&self) -> Option
<&[(Option
<&'e
str>, &'n
str)]> { None }
1797 fn blacklist(&self) -> Option
<&[&'e
str]> { None }
1798 fn required_unless(&self) -> Option
<&[&'e
str]> { None }
1799 fn val_names(&self) -> Option
<&VecMap
<&'e
str>> { None }
1800 fn is_set(&self, _
: ArgSettings
) -> bool { false }
1801 fn val_terminator(&self) -> Option
<&'e
str> { None }
1802 fn set(&mut self, _
: ArgSettings
) {
1803 unreachable
!("App struct does not support AnyArg::set, this is a bug!")
1805 fn has_switch(&self) -> bool { false }
1806 fn max_vals(&self) -> Option
<u64> { None }
1807 fn num_vals(&self) -> Option
<u64> { None }
1808 fn possible_vals(&self) -> Option
<&[&'e
str]> { None }
1809 fn validator(&self) -> Option
<&Rc
<Fn(String
) -> StdResult
<(), String
>>> { None }
1810 fn validator_os(&self) -> Option
<&Rc
<Fn(&OsStr
) -> StdResult
<(), OsString
>>> { None }
1811 fn min_vals(&self) -> Option
<u64> { None }
1812 fn short(&self) -> Option
<char> { None }
1813 fn long(&self) -> Option
<&'e
str> { None }
1814 fn val_delim(&self) -> Option
<char> { None }
1815 fn takes_value(&self) -> bool { true }
1816 fn help(&self) -> Option
<&'e
str> { self.p.meta.about }
1817 fn long_help(&self) -> Option
<&'e
str> { self.p.meta.long_about }
1818 fn default_val(&self) -> Option
<&'e OsStr
> { None }
1819 fn default_vals_ifs(&self) -> Option
<map
::Values
<(&'n
str, Option
<&'e OsStr
>, &'e OsStr
)>> {
1822 fn env
<'s
>(&'s
self) -> Option
<(&'n OsStr
, Option
<&'s OsString
>)> { None }
1823 fn longest_filter(&self) -> bool { true }
1824 fn aliases(&self) -> Option
<Vec
<&'e
str>> {
1825 if let Some(ref aliases
) = self.p
.meta
.aliases
{
1826 let vis_aliases
: Vec
<_
> = aliases
1828 .filter_map(|&(n
, v
)| if v { Some(n) }
else { None }
)
1830 if vis_aliases
.is_empty() {
1841 impl<'n
, 'e
> fmt
::Display
for App
<'n
, 'e
> {
1842 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result { write!(f, "{}
", self.p.meta.name) }