]> git.proxmox.com Git - rustc.git/blob - src/vendor/clap/src/app/mod.rs
New upstream version 1.24.1+dfsg1
[rustc.git] / src / vendor / clap / src / app / mod.rs
1 mod settings;
2 #[macro_use]
3 mod macros;
4 pub mod parser;
5 mod meta;
6 mod help;
7 mod validator;
8 mod usage;
9
10 // Std
11 use std::env;
12 use std::ffi::{OsStr, OsString};
13 use std::fmt;
14 use std::io::{self, BufRead, BufWriter, Write};
15 use std::path::Path;
16 use std::process;
17 use std::rc::Rc;
18 use std::result::Result as StdResult;
19
20 // Third Party
21 #[cfg(feature = "yaml")]
22 use yaml_rust::Yaml;
23
24 // Internal
25 use app::help::Help;
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};
32
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).
38 ///
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
41 /// called).
42 ///
43 /// # Examples
44 ///
45 /// ```no_run
46 /// # use clap::{App, Arg};
47 /// let m = App::new("My Program")
48 /// .author("Me, me@mail.com")
49 /// .version("1.0.2")
50 /// .about("Explains in brief what the program does")
51 /// .arg(
52 /// Arg::with_name("in_file").index(1)
53 /// )
54 /// .after_help("Longer explanation to appear after the options when \
55 /// displaying the help information from --help or -h")
56 /// .get_matches();
57 ///
58 /// // Your program logic starts here...
59 /// ```
60 /// [`App::get_matches`]: ./struct.App.html#method.get_matches
61 #[allow(missing_debug_implementations)]
62 pub struct App<'a, 'b>
63 where
64 'a: 'b,
65 {
66 #[doc(hidden)] pub p: Parser<'a, 'b>,
67 }
68
69
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.
74 ///
75 /// # Examples
76 ///
77 /// ```no_run
78 /// # use clap::{App, Arg};
79 /// let prog = App::new("My Program")
80 /// # ;
81 /// ```
82 pub fn new<S: Into<String>>(n: S) -> Self {
83 App {
84 p: Parser::with_name(n.into()),
85 }
86 }
87
88 /// Get the name of the app
89 pub fn get_name(&self) -> &str { &self.p.meta.name }
90
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()) }
93
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.
96 ///
97 /// # Examples
98 ///
99 /// ```no_run
100 /// # use clap::{App, Arg};
101 /// let prog = App::with_defaults("My Program")
102 /// # ;
103 /// ```
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 {
110 let mut a = App {
111 p: Parser::with_name(n.into()),
112 };
113 a.p.meta.author = Some("Kevin K. <kbknapp@gmail.com>");
114 a.p.meta.version = Some("2.19.2");
115 a
116 }
117
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
122 /// `Cargo.toml`
123 ///
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`
126 ///
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.
130 ///
131 /// # Panics
132 ///
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.
136 ///
137 /// # Examples
138 ///
139 /// The following example shows how to load a properly formatted YAML file to build an instance
140 /// of an [`App`] struct.
141 ///
142 /// ```ignore
143 /// # #[macro_use]
144 /// # extern crate clap;
145 /// # use clap::App;
146 /// # fn main() {
147 /// let yml = load_yaml!("app.yml");
148 /// let app = App::from_yaml(yml);
149 ///
150 /// // continued logic goes here, such as `app.get_matches()` etc.
151 /// # }
152 /// ```
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) }
159
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`.
162 ///
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
166 ///
167 /// See the [`examples/`]
168 /// directory for more information
169 ///
170 /// # Examples
171 ///
172 /// ```no_run
173 /// # use clap::{App, Arg};
174 /// App::new("myprog")
175 /// .author("Me, me@mymain.com")
176 /// # ;
177 /// ```
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());
182 self
183 }
184
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.
188 ///
189 /// **Pro-tip:** When building things such as third party `cargo` subcommands, this setting
190 /// **should** be used!
191 ///
192 /// **NOTE:** This command **should not** be used for [`SubCommand`]s.
193 ///
194 /// # Examples
195 ///
196 /// ```no_run
197 /// # use clap::{App, Arg};
198 /// App::new("My Program")
199 /// .bin_name("my_binary")
200 /// # ;
201 /// ```
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());
205 self
206 }
207
208 /// Sets a string describing what the program does. This will be displayed when displaying help
209 /// information with `-h`.
210 ///
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
213 ///
214 /// **NOTE:** Only [`App::about`] is used in completion script generation in order to be
215 /// concise
216 ///
217 /// # Examples
218 ///
219 /// ```no_run
220 /// # use clap::{App, Arg};
221 /// App::new("myprog")
222 /// .about("Does really amazing things to great people")
223 /// # ;
224 /// ```
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());
228 self
229 }
230
231 /// Sets a string describing what the program does. This will be displayed when displaying help
232 /// information.
233 ///
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
236 ///
237 /// **NOTE:** Only [`App::about`] is used in completion script generation in order to be
238 /// concise
239 ///
240 /// # Examples
241 ///
242 /// ```no_run
243 /// # use clap::{App, Arg};
244 /// App::new("myprog")
245 /// .long_about(
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!")
249 /// # ;
250 /// ```
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());
254 self
255 }
256
257 /// Sets the program's name. This will be displayed when displaying help information.
258 ///
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`.
262 ///
263 /// # Examples
264 /// ```ignore
265 /// # #[macro_use]
266 /// # extern crate clap;
267 /// # use clap::App;
268 /// # fn main() {
269 /// let yml = load_yaml!("app.yml");
270 /// let app = App::from_yaml(yml)
271 /// .name(crate_name!());
272 ///
273 /// // continued logic goes here, such as `app.get_matches()` etc.
274 /// # }
275 /// ```
276 ///
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();
281 self
282 }
283
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.
287 ///
288 /// # Examples
289 ///
290 /// ```no_run
291 /// # use clap::App;
292 /// App::new("myprog")
293 /// .after_help("Does really amazing things to great people...but be careful with -R")
294 /// # ;
295 /// ```
296 pub fn after_help<S: Into<&'b str>>(mut self, help: S) -> Self {
297 self.p.meta.more_help = Some(help.into());
298 self
299 }
300
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.
304 ///
305 /// # Examples
306 ///
307 /// ```no_run
308 /// # use clap::App;
309 /// App::new("myprog")
310 /// .before_help("Some info I'd like to appear before the help info")
311 /// # ;
312 /// ```
313 pub fn before_help<S: Into<&'b str>>(mut self, help: S) -> Self {
314 self.p.meta.pre_help = Some(help.into());
315 self
316 }
317
318 /// Sets a string of the version number to be displayed when displaying version or help
319 /// information with `-V`.
320 ///
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
323 ///
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
327 ///
328 /// # Examples
329 ///
330 /// ```no_run
331 /// # use clap::{App, Arg};
332 /// App::new("myprog")
333 /// .version("v0.1.24")
334 /// # ;
335 /// ```
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());
341 self
342 }
343
344 /// Sets a string of the version number to be displayed when displaying version or help
345 /// information with `--version`.
346 ///
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
349 ///
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
353 ///
354 /// # Examples
355 ///
356 /// ```no_run
357 /// # use clap::{App, Arg};
358 /// App::new("myprog")
359 /// .long_version(
360 /// "v0.1.24
361 /// commit: abcdef89726d
362 /// revision: 123
363 /// release: 2
364 /// binary: myprog")
365 /// # ;
366 /// ```
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());
372 self
373 }
374
375 /// Sets a custom usage string to override the auto-generated usage string.
376 ///
377 /// This will be displayed to the user when errors are found in argument parsing, or when you
378 /// call [`ArgMatches::usage`]
379 ///
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!
382 ///
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.
386 ///
387 /// **NOTE:** This will not replace the entire help message, *only* the portion
388 /// showing the usage.
389 ///
390 /// # Examples
391 ///
392 /// ```no_run
393 /// # use clap::{App, Arg};
394 /// App::new("myprog")
395 /// .usage("myapp [-clDas] <some_file>")
396 /// # ;
397 /// ```
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());
401 self
402 }
403
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.
406 ///
407 /// This will be displayed to the user when they use `--help` or `-h`
408 ///
409 /// **NOTE:** This replaces the **entire** help message, so nothing will be auto-generated.
410 ///
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.
414 ///
415 /// # Examples
416 ///
417 /// ```no_run
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\
423 ///
424 /// USAGE: myapp <opts> <comamnd>\n\n\
425 ///
426 /// Options:\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\
431 ///
432 /// Commmands:\n\
433 /// help Prints this message\n\
434 /// work Do some work")
435 /// # ;
436 /// ```
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());
440 self
441 }
442
443 /// Sets the [`short`] for the auto-generated `help` argument.
444 ///
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`].
448 ///
449 /// `clap` lazily generates these `help` arguments **after** you've defined any arguments of
450 /// your own.
451 ///
452 /// **NOTE:** Any leading `-` characters will be stripped, and only the first
453 /// non `-` character will be used as the [`short`] version
454 ///
455 /// # Examples
456 ///
457 /// ```no_run
458 /// # use clap::{App, Arg};
459 /// App::new("myprog")
460 /// .help_short("H") // Using an uppercase `H` instead of the default lowercase `h`
461 /// # ;
462 /// ```
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());
466 self
467 }
468
469 /// Sets the [`short`] for the auto-generated `version` argument.
470 ///
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`].
474 ///
475 /// `clap` lazily generates these `version` arguments **after** you've defined any arguments of
476 /// your own.
477 ///
478 /// **NOTE:** Any leading `-` characters will be stripped, and only the first
479 /// non `-` character will be used as the `short` version
480 ///
481 /// # Examples
482 ///
483 /// ```no_run
484 /// # use clap::{App, Arg};
485 /// App::new("myprog")
486 /// .version_short("v") // Using a lowercase `v` instead of the default capital `V`
487 /// # ;
488 /// ```
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());
492 self
493 }
494
495 /// Sets the help text for the auto-generated `help` argument.
496 ///
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
499 /// override it.
500 ///
501 /// # Examples
502 ///
503 /// ```no_run
504 /// # use clap::{App, Arg};
505 /// App::new("myprog")
506 /// .help_message("Print help information") // Perhaps you want imperative help messages
507 ///
508 /// # ;
509 /// ```
510 pub fn help_message<S: Into<&'a str>>(mut self, s: S) -> Self {
511 self.p.help_message = Some(s.into());
512 self
513 }
514
515 /// Sets the help text for the auto-generated `version` argument.
516 ///
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
519 /// can change it.
520 ///
521 /// # Examples
522 /// ```no_run
523 /// # use clap::{App, Arg};
524 /// App::new("myprog")
525 /// .version_message("Print version information") // Perhaps you want imperative help messages
526 /// # ;
527 /// ```
528 pub fn version_message<S: Into<&'a str>>(mut self, s: S) -> Self {
529 self.p.version_message = Some(s.into());
530 self
531 }
532
533 /// Sets the help template to be used, overriding the default format.
534 ///
535 /// Tags arg given inside curly brackets.
536 ///
537 /// Valid tags are:
538 ///
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`]
555 ///
556 /// # Examples
557 ///
558 /// ```no_run
559 /// # use clap::{App, Arg};
560 /// App::new("myprog")
561 /// .version("1.0")
562 /// .template("{bin} ({version}) - {usage}")
563 /// # ;
564 /// ```
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());
573 self
574 }
575
576 /// Enables a single command, or [`SubCommand`], level settings.
577 ///
578 /// See [`AppSettings`] for a full list of possibilities and examples.
579 ///
580 /// # Examples
581 ///
582 /// ```no_run
583 /// # use clap::{App, Arg, AppSettings};
584 /// App::new("myprog")
585 /// .setting(AppSettings::SubcommandRequired)
586 /// .setting(AppSettings::WaitOnError)
587 /// # ;
588 /// ```
589 /// [`SubCommand`]: ./struct.SubCommand.html
590 /// [`AppSettings`]: ./enum.AppSettings.html
591 pub fn setting(mut self, setting: AppSettings) -> Self {
592 self.p.set(setting);
593 self
594 }
595
596 /// Enables multiple command, or [`SubCommand`], level settings
597 ///
598 /// See [`AppSettings`] for a full list of possibilities and examples.
599 ///
600 /// # Examples
601 ///
602 /// ```no_run
603 /// # use clap::{App, Arg, AppSettings};
604 /// App::new("myprog")
605 /// .settings(&[AppSettings::SubcommandRequired,
606 /// AppSettings::WaitOnError])
607 /// # ;
608 /// ```
609 /// [`SubCommand`]: ./struct.SubCommand.html
610 /// [`AppSettings`]: ./enum.AppSettings.html
611 pub fn settings(mut self, settings: &[AppSettings]) -> Self {
612 for s in settings {
613 self.p.set(*s);
614 }
615 self
616 }
617
618 /// Enables a single setting that is propagated down through all child [`SubCommand`]s.
619 ///
620 /// See [`AppSettings`] for a full list of possibilities and examples.
621 ///
622 /// **NOTE**: The setting is *only* propagated *down* and not up through parent commands.
623 ///
624 /// # Examples
625 ///
626 /// ```no_run
627 /// # use clap::{App, Arg, AppSettings};
628 /// App::new("myprog")
629 /// .global_setting(AppSettings::SubcommandRequired)
630 /// # ;
631 /// ```
632 /// [`SubCommand`]: ./struct.SubCommand.html
633 /// [`AppSettings`]: ./enum.AppSettings.html
634 pub fn global_setting(mut self, setting: AppSettings) -> Self {
635 self.p.set(setting);
636 self.p.g_settings.set(setting);
637 self
638 }
639
640 /// Enables multiple settings which are propagated *down* through all child [`SubCommand`]s.
641 ///
642 /// See [`AppSettings`] for a full list of possibilities and examples.
643 ///
644 /// **NOTE**: The setting is *only* propagated *down* and not up through parent commands.
645 ///
646 /// # Examples
647 ///
648 /// ```no_run
649 /// # use clap::{App, Arg, AppSettings};
650 /// App::new("myprog")
651 /// .global_settings(&[AppSettings::SubcommandRequired,
652 /// AppSettings::ColoredHelp])
653 /// # ;
654 /// ```
655 /// [`SubCommand`]: ./struct.SubCommand.html
656 /// [`AppSettings`]: ./enum.AppSettings.html
657 pub fn global_settings(mut self, settings: &[AppSettings]) -> Self {
658 for s in settings {
659 self.p.set(*s);
660 self.p.g_settings.set(*s)
661 }
662 self
663 }
664
665 /// Disables a single command, or [`SubCommand`], level setting.
666 ///
667 /// See [`AppSettings`] for a full list of possibilities and examples.
668 ///
669 /// # Examples
670 ///
671 /// ```no_run
672 /// # use clap::{App, AppSettings};
673 /// App::new("myprog")
674 /// .unset_setting(AppSettings::ColorAuto)
675 /// # ;
676 /// ```
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);
681 self
682 }
683
684 /// Disables multiple command, or [`SubCommand`], level settings.
685 ///
686 /// See [`AppSettings`] for a full list of possibilities and examples.
687 ///
688 /// # Examples
689 ///
690 /// ```no_run
691 /// # use clap::{App, AppSettings};
692 /// App::new("myprog")
693 /// .unset_settings(&[AppSettings::ColorAuto,
694 /// AppSettings::AllowInvalidUtf8])
695 /// # ;
696 /// ```
697 /// [`SubCommand`]: ./struct.SubCommand.html
698 /// [`AppSettings`]: ./enum.AppSettings.html
699 pub fn unset_settings(mut self, settings: &[AppSettings]) -> Self {
700 for s in settings {
701 self.p.unset(*s);
702 }
703 self
704 }
705
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.
708 ///
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`.
712 ///
713 /// **NOTE:** This setting applies globally and *not* on a per-command basis.
714 ///
715 /// **NOTE:** This setting must be set **before** any subcommands are added!
716 ///
717 /// # Platform Specific
718 ///
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.
722 ///
723 /// # Examples
724 ///
725 /// ```no_run
726 /// # use clap::App;
727 /// App::new("myprog")
728 /// .set_term_width(80)
729 /// # ;
730 /// ```
731 pub fn set_term_width(mut self, width: usize) -> Self {
732 self.p.meta.term_w = Some(width);
733 self
734 }
735
736 /// Sets the max terminal width at which to wrap help messages. Using `0` will ignore terminal
737 /// widths and use source formatting.
738 ///
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).
742 ///
743 /// **NOTE:** This setting applies globally and *not* on a per-command basis.
744 ///
745 /// **NOTE:** This setting must be set **before** any subcommands are added!
746 ///
747 /// # Platform Specific
748 ///
749 /// Only Unix, Linux, OSX and Windows support automatic determination of terminal width.
750 ///
751 /// # Examples
752 ///
753 /// ```no_run
754 /// # use clap::App;
755 /// App::new("myprog")
756 /// .max_term_width(100)
757 /// # ;
758 /// ```
759 pub fn max_term_width(mut self, w: usize) -> Self {
760 self.p.meta.max_w = Some(w);
761 self
762 }
763
764 /// Adds an [argument] to the list of valid possibilities.
765 ///
766 /// # Examples
767 ///
768 /// ```no_run
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()
772 /// .arg(
773 /// Arg::with_name("debug")
774 /// .short("d")
775 /// .help("turns on debugging mode")
776 /// )
777 /// // Adding a single "option" argument with a short, a long, and help text using the less
778 /// // verbose Arg::from_usage()
779 /// .arg(
780 /// Arg::from_usage("-c --config=[CONFIG] 'Optionally sets a config file to use'")
781 /// )
782 /// # ;
783 /// ```
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());
787 self
788 }
789
790 /// Adds multiple [arguments] to the list of valid possibilties
791 ///
792 /// # Examples
793 ///
794 /// ```no_run
795 /// # use clap::{App, Arg};
796 /// App::new("myprog")
797 /// .args(
798 /// &[Arg::from_usage("[debug] -d 'turns on debugging info'"),
799 /// Arg::with_name("input").index(1).help("the input file to use")]
800 /// )
801 /// # ;
802 /// ```
803 /// [arguments]: ./struct.Arg.html
804 pub fn args(mut self, args: &[Arg<'a, 'b>]) -> Self {
805 for arg in args {
806 self.p.add_arg_ref(arg);
807 }
808 self
809 }
810
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`]
813 ///
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.
816 ///
817 /// # Examples
818 ///
819 /// ```no_run
820 /// # use clap::{App, Arg};
821 /// App::new("myprog")
822 /// .arg_from_usage("-c --config=<FILE> 'Sets a configuration file to use'")
823 /// # ;
824 /// ```
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));
830 self
831 }
832
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.
835 ///
836 /// **NOTE:** Like [`App::arg_from_usage`] the downside is you only set properties for the
837 /// [`Arg`]s which [`Arg::from_usage`] supports.
838 ///
839 /// # Examples
840 ///
841 /// ```no_run
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'"
848 /// )
849 /// # ;
850 /// ```
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() {
857 let l = line.trim();
858 if l.is_empty() {
859 continue;
860 }
861 self.p.add_arg(Arg::from_usage(l));
862 }
863 self
864 }
865
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.
870 ///
871 /// # Examples
872 ///
873 /// ```no_run
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"));
880 /// ```
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));
885 } else {
886 self.p.meta.aliases = Some(vec![(name.into(), false)]);
887 }
888 self
889 }
890
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.
895 ///
896 /// # Examples
897 ///
898 /// ```rust
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")
905 /// .index(1)
906 /// .required(false))
907 /// .get_matches_from(vec!["myprog", "do-tests"]);
908 /// assert_eq!(m.subcommand_name(), Some("test"));
909 /// ```
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 {
913 for n in names {
914 als.push((n, false));
915 }
916 } else {
917 self.p.meta.aliases = Some(names.iter().map(|n| (*n, false)).collect::<Vec<_>>());
918 }
919 self
920 }
921
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.
924 ///
925 /// # Examples
926 ///
927 /// ```no_run
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"));
934 /// ```
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));
940 } else {
941 self.p.meta.aliases = Some(vec![(name.into(), true)]);
942 }
943 self
944 }
945
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.
948 ///
949 /// # Examples
950 ///
951 /// ```no_run
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"));
958 /// ```
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 {
963 for n in names {
964 als.push((n, true));
965 }
966 } else {
967 self.p.meta.aliases = Some(names.iter().map(|n| (*n, true)).collect::<Vec<_>>());
968 }
969 self
970 }
971
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.
976 ///
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.
980 ///
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.
983 ///
984 /// Finally, using [`ArgGroup`]s to ensure exclusion between arguments is another very common
985 /// use
986 ///
987 /// # Examples
988 ///
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.
991 ///
992 /// ```no_run
993 /// # use clap::{App, ArgGroup};
994 /// App::new("app")
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))
1003 /// # ;
1004 /// ```
1005 /// [`ArgGroup`]: ./struct.ArgGroup.html
1006 pub fn group(mut self, group: ArgGroup<'a>) -> Self {
1007 self.p.add_group(group);
1008 self
1009 }
1010
1011 /// Adds multiple [`ArgGroup`]s to the [`App`] at once.
1012 ///
1013 /// # Examples
1014 ///
1015 /// ```no_run
1016 /// # use clap::{App, ArgGroup};
1017 /// App::new("app")
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'")
1025 /// .groups(&[
1026 /// ArgGroup::with_name("vers")
1027 /// .args(&["set-ver", "major", "minor","patch"])
1028 /// .required(true),
1029 /// ArgGroup::with_name("input")
1030 /// .args(&["c", "i"])
1031 /// ])
1032 /// # ;
1033 /// ```
1034 /// [`ArgGroup`]: ./struct.ArgGroup.html
1035 /// [`App`]: ./struct.App.html
1036 pub fn groups(mut self, groups: &[ArgGroup<'a>]) -> Self {
1037 for g in groups {
1038 self = self.group(g.into());
1039 }
1040 self
1041 }
1042
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.
1047 ///
1048 /// # Examples
1049 ///
1050 /// ```no_run
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'"))
1056 /// # ;
1057 /// ```
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);
1062 self
1063 }
1064
1065 /// Adds multiple subcommands to the list of valid possibilities by iterating over an
1066 /// [`IntoIterator`] of [`SubCommand`]s
1067 ///
1068 /// # Examples
1069 ///
1070 /// ```rust
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")])
1077 /// # ;
1078 /// ```
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
1082 where
1083 I: IntoIterator<Item = App<'a, 'b>>,
1084 {
1085 for subcmd in subcmds {
1086 self.p.add_subcommand(subcmd);
1087 }
1088 self
1089 }
1090
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.
1096 ///
1097 /// **NOTE:** The default is 999 for all subcommands.
1098 ///
1099 /// # Examples
1100 ///
1101 /// ```rust
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"
1118 /// ]);
1119 /// ```
1120 ///
1121 /// The above example displays the following help message
1122 ///
1123 /// ```text
1124 /// cust-ord
1125 ///
1126 /// USAGE:
1127 /// cust-ord [FLAGS] [OPTIONS]
1128 ///
1129 /// FLAGS:
1130 /// -h, --help Prints help information
1131 /// -V, --version Prints version information
1132 ///
1133 /// SUBCOMMANDS:
1134 /// beta I should be first!
1135 /// alpha Some help and text
1136 /// ```
1137 /// [`SubCommand`]: ./struct.SubCommand.html
1138 pub fn display_order(mut self, ord: usize) -> Self {
1139 self.p.meta.disp_ord = ord;
1140 self
1141 }
1142
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
1145 ///
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)]
1148 ///
1149 /// # Examples
1150 ///
1151 /// ```rust
1152 /// # use clap::App;
1153 /// let mut app = App::new("myprog");
1154 /// app.print_help();
1155 /// ```
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();
1166
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)
1171 }
1172
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
1175 ///
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)]
1178 ///
1179 /// # Examples
1180 ///
1181 /// ```rust
1182 /// # use clap::App;
1183 /// let mut app = App::new("myprog");
1184 /// app.print_long_help();
1185 /// ```
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();
1196
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)
1201 }
1202
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`
1205 ///
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)]
1208 ///
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!
1212 ///
1213 /// # Examples
1214 ///
1215 /// ```rust
1216 /// # use clap::App;
1217 /// use std::io;
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");
1221 /// ```
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();
1234
1235 Help::write_app_help(w, self, false)
1236 }
1237
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`
1240 ///
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)]
1243 ///
1244 /// # Examples
1245 ///
1246 /// ```rust
1247 /// # use clap::App;
1248 /// use std::io;
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");
1252 /// ```
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();
1261
1262 Help::write_app_help(w, self, true)
1263 }
1264
1265 /// Writes the version message to the user to a [`io::Write`] object as if the user ran `-V`.
1266 ///
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)]
1269 ///
1270 /// # Examples
1271 ///
1272 /// ```rust
1273 /// # use clap::App;
1274 /// use std::io;
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");
1278 /// ```
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)
1284 }
1285
1286 /// Writes the version message to the user to a [`io::Write`] object
1287 ///
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)]
1290 ///
1291 /// # Examples
1292 ///
1293 /// ```rust
1294 /// # use clap::App;
1295 /// use std::io;
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");
1299 /// ```
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)
1305 }
1306
1307 /// Generate a completions file for a specified shell at compile time.
1308 ///
1309 /// **NOTE:** to generate the this file at compile time you must use a `build.rs` "Build Script"
1310 ///
1311 /// # Examples
1312 ///
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.
1317 ///
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.
1320 ///
1321 /// ```
1322 /// // src/cli.rs
1323 ///
1324 /// use clap::{App, Arg, SubCommand};
1325 ///
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")
1334 /// .long("case")
1335 /// .takes_value(true)
1336 /// .help("the case to test")))
1337 /// }
1338 /// ```
1339 ///
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:
1342 ///
1343 /// ```ignore
1344 /// // src/main.rs
1345 ///
1346 /// mod cli;
1347 ///
1348 /// fn main() {
1349 /// let m = cli::build_cli().get_matches();
1350 ///
1351 /// // normal logic continues...
1352 /// }
1353 /// ```
1354 ///
1355 /// Next, we set up our `Cargo.toml` to use a `build.rs` build script.
1356 ///
1357 /// ```toml
1358 /// # Cargo.toml
1359 /// build = "build.rs"
1360 ///
1361 /// [build-dependencies]
1362 /// clap = "2.23"
1363 /// ```
1364 ///
1365 /// Next, we place a `build.rs` in our project root.
1366 ///
1367 /// ```ignore
1368 /// extern crate clap;
1369 ///
1370 /// use clap::Shell;
1371 ///
1372 /// include!("src/cli.rs");
1373 ///
1374 /// fn main() {
1375 /// let outdir = match env::var_os("OUT_DIR") {
1376 /// None => return,
1377 /// Some(outdir) => outdir,
1378 /// };
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
1383 /// }
1384 /// ```
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`.
1388 ///
1389 /// Fish shell completions will use the file format `{bin_name}.fish`
1390 pub fn gen_completions<T: Into<OsString>, S: Into<String>>(
1391 &mut self,
1392 bin_name: S,
1393 for_shell: Shell,
1394 out_dir: T,
1395 ) {
1396 self.p.meta.bin_name = Some(bin_name.into());
1397 self.p.gen_completions(for_shell, out_dir.into());
1398 }
1399
1400
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.
1404 ///
1405 /// # Examples
1406 ///
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:
1409 ///
1410 /// ```ignore
1411 /// // src/main.rs
1412 ///
1413 /// mod cli;
1414 /// use std::io;
1415 ///
1416 /// fn main() {
1417 /// let matches = cli::build_cli().get_matches();
1418 ///
1419 /// if matches.is_present("generate-bash-completions") {
1420 /// cli::build_cli().gen_completions_to("myapp", Shell::Bash, &mut io::stdout());
1421 /// }
1422 ///
1423 /// // normal logic continues...
1424 /// }
1425 ///
1426 /// ```
1427 ///
1428 /// Usage:
1429 ///
1430 /// ```shell
1431 /// $ myapp generate-bash-completions > /usr/share/bash-completion/completions/myapp.bash
1432 /// ```
1433 pub fn gen_completions_to<W: Write, S: Into<String>>(
1434 &mut self,
1435 bin_name: S,
1436 for_shell: Shell,
1437 buf: &mut W,
1438 ) {
1439 self.p.meta.bin_name = Some(bin_name.into());
1440 self.p.gen_completions_to(for_shell, buf);
1441 }
1442
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.
1447 ///
1448 /// # Examples
1449 ///
1450 /// ```no_run
1451 /// # use clap::{App, Arg};
1452 /// let matches = App::new("myprog")
1453 /// // Args and options go here...
1454 /// .get_matches();
1455 /// ```
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()) }
1458
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`]
1461 ///
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`].
1466 ///
1467 /// # Examples
1468 ///
1469 /// ```no_run
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() );
1475 /// ```
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())
1487 }
1488
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.
1492 ///
1493 /// **NOTE:** The first argument will be parsed as the binary name unless
1494 /// [`AppSettings::NoBinaryName`] is used
1495 ///
1496 /// # Examples
1497 ///
1498 /// ```no_run
1499 /// # use clap::{App, Arg};
1500 /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
1501 ///
1502 /// let matches = App::new("myprog")
1503 /// // Args and options go here...
1504 /// .get_matches_from(arg_vec);
1505 /// ```
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>
1511 where
1512 I: IntoIterator<Item = T>,
1513 T: Into<OsString> + Clone,
1514 {
1515 self.get_matches_from_safe_borrow(itr).unwrap_or_else(|e| {
1516 // Otherwise, write to stderr and exit
1517 if e.use_stderr() {
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();
1524 }
1525 drop(self);
1526 drop(e);
1527 process::exit(1);
1528 }
1529
1530 drop(self);
1531 e.exit()
1532 })
1533 }
1534
1535 /// Starts the parsing process. A combination of [`App::get_matches_from`], and
1536 /// [`App::get_matches_safe`]
1537 ///
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.
1542 ///
1543 /// **NOTE:** The first argument will be parsed as the binary name unless
1544 /// [`AppSettings::NoBinaryName`] is used
1545 ///
1546 /// # Examples
1547 ///
1548 /// ```no_run
1549 /// # use clap::{App, Arg};
1550 /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
1551 ///
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) });
1556 /// ```
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>>
1568 where
1569 I: IntoIterator<Item = T>,
1570 T: Into<OsString> + Clone,
1571 {
1572 self.get_matches_from_safe_borrow(itr)
1573 }
1574
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*
1577 /// consume `self`.
1578 ///
1579 /// **NOTE:** The first argument will be parsed as the binary name unless
1580 /// [`AppSettings::NoBinaryName`] is used
1581 ///
1582 /// # Examples
1583 ///
1584 /// ```no_run
1585 /// # use clap::{App, Arg};
1586 /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
1587 ///
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) });
1592 /// ```
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>>
1597 where
1598 I: IntoIterator<Item = T>,
1599 T: Into<OsString> + Clone,
1600 {
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);
1608 }
1609
1610 let mut matcher = ArgMatcher::new();
1611
1612 let mut it = itr.into_iter();
1613 // Get the name of the program (argument 1 of env::args()) and determine the
1614 // actual file
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
1618 // to display
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());
1628 }
1629 }
1630 }
1631 }
1632 }
1633
1634 // do the real parsing
1635 if let Err(e) = self.p.get_matches_with(&mut matcher, &mut it.peekable()) {
1636 return Err(e);
1637 }
1638
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);
1641
1642 Ok(matcher.into())
1643 }
1644 }
1645
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() {
1653 App::new(name)
1654 } else {
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())
1659 };
1660 yaml = if let Some(sc) = is_sc { sc } else { yaml };
1661
1662 macro_rules! yaml_str {
1663 ($a:ident, $y:ident, $i:ident) => {
1664 if let Some(v) = $y[stringify!($i)].as_str() {
1665 $a = $a.$i(v);
1666 } else if $y[stringify!($i)] != Yaml::BadValue {
1667 panic!("Failed to convert YAML value {:?} to a string", $y[stringify!($i)]);
1668 }
1669 };
1670 }
1671
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);
1687
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 {
1691 panic!(
1692 "Failed to convert YAML value {:?} to a u64",
1693 yaml["display_order"]
1694 );
1695 }
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 {
1699 panic!(
1700 "Failed to convert YAML value {:?} to an AppSetting",
1701 yaml["setting"]
1702 );
1703 }
1704 if let Some(v) = yaml["settings"].as_vec() {
1705 for ys in v {
1706 if let Some(s) = ys.as_str() {
1707 a = a.setting(s.parse().expect("unknown AppSetting found in YAML file"));
1708 }
1709 }
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 {
1713 panic!(
1714 "Failed to convert YAML value {:?} to a string",
1715 yaml["settings"]
1716 );
1717 }
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 {
1721 panic!(
1722 "Failed to convert YAML value {:?} to an AppSetting",
1723 yaml["setting"]
1724 );
1725 }
1726 if let Some(v) = yaml["global_settings"].as_vec() {
1727 for ys in v {
1728 if let Some(s) = ys.as_str() {
1729 a = a.global_setting(s.parse().expect("unknown AppSetting found in YAML file"));
1730 }
1731 }
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 {
1735 panic!(
1736 "Failed to convert YAML value {:?} to a string",
1737 yaml["global_settings"]
1738 );
1739 }
1740
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 {
1745 for ys in vec {
1746 if let Some(s) = ys.as_str() {
1747 $a = $a.$as_single(s);
1748 } else {
1749 panic!("Failed to convert YAML value {:?} to a string", ys);
1750 }
1751 }
1752 } else {
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)]);
1757 }
1758 }
1759 $a
1760 }
1761 };
1762 }
1763
1764 a = vec_or_str!(a, yaml, aliases, alias);
1765 a = vec_or_str!(a, yaml, visible_aliases, visible_alias);
1766
1767 if let Some(v) = yaml["args"].as_vec() {
1768 for arg_yaml in v {
1769 a = a.arg(Arg::from_yaml(arg_yaml.as_hash().unwrap()));
1770 }
1771 }
1772 if let Some(v) = yaml["subcommands"].as_vec() {
1773 for sc_yaml in v {
1774 a = a.subcommand(SubCommand::from_yaml(sc_yaml));
1775 }
1776 }
1777 if let Some(v) = yaml["groups"].as_vec() {
1778 for ag_yaml in v {
1779 a = a.group(ArgGroup::from(ag_yaml.as_hash().unwrap()));
1780 }
1781 }
1782
1783 a
1784 }
1785 }
1786
1787 impl<'a, 'b> Clone for App<'a, 'b> {
1788 fn clone(&self) -> Self { App { p: self.p.clone() } }
1789 }
1790
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!")
1794 }
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!")
1804 }
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)>> {
1820 None
1821 }
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
1827 .iter()
1828 .filter_map(|&(n, v)| if v { Some(n) } else { None })
1829 .collect();
1830 if vis_aliases.is_empty() {
1831 None
1832 } else {
1833 Some(vis_aliases)
1834 }
1835 } else {
1836 None
1837 }
1838 }
1839 }
1840
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) }
1843 }