]>
git.proxmox.com Git - rustc.git/blob - vendor/structopt/src/lib.rs
1 // Copyright 2018 Guillaume Pinot (@TeXitoi) <texitoi@texitoi.eu>
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
11 //! This crate defines the `StructOpt` trait and its custom derive.
15 //! If you want to disable all the `clap` features (colors,
16 //! suggestions, ..) add `default-features = false` to the `structopt`
21 //! structopt = { version = "0.3", default-features = false }
24 //! Support for [`paw`](https://github.com/rust-cli/paw) (the
25 //! `Command line argument paw-rser abstraction for main`) is disabled
26 //! by default, but can be enabled in the `structopt` dependency
27 //! with the feature `paw`:
31 //! structopt = { version = "0.3", features = [ "paw" ] }
35 //! # Table of Contents
37 //! - [How to `derive(StructOpt)`](#how-to-derivestructopt)
38 //! - [Attributes](#attributes)
39 //! - [Raw methods](#raw-methods)
40 //! - [Magical methods](#magical-methods)
42 //! - [Type magic](#type-magic)
43 //! - [Specifying argument types](#specifying-argument-types)
44 //! - [Default values](#default-values)
45 //! - [Help messages](#help-messages)
46 //! - [Environment variable fallback](#environment-variable-fallback)
47 //! - [Skipping fields](#skipping-fields)
48 //! - [Subcommands](#subcommands)
49 //! - [Optional subcommands](#optional-subcommands)
50 //! - [External subcommands](#external-subcommands)
51 //! - [Flattening subcommands](#flattening-subcommands)
52 //! - [Flattening](#flattening)
53 //! - [Custom string parsers](#custom-string-parsers)
57 //! ## How to `derive(StructOpt)`
59 //! First, let's look at the example:
62 //! use std::path::PathBuf;
63 //! use structopt::StructOpt;
65 //! #[derive(Debug, StructOpt)]
66 //! #[structopt(name = "example", about = "An example of StructOpt usage.")]
68 //! /// Activate debug mode
69 //! // short and long flags (-d, --debug) will be deduced from the field's name
70 //! #[structopt(short, long)]
74 //! // we don't want to name it "speed", need to look smart
75 //! #[structopt(short = "v", long = "velocity", default_value = "42")]
79 //! #[structopt(parse(from_os_str))]
82 //! /// Output file, stdout if not present
83 //! #[structopt(parse(from_os_str))]
84 //! output: Option<PathBuf>,
86 //! /// Where to write the output: to `stdout` or `file`
87 //! #[structopt(short)]
90 //! /// File name: only required when `out-type` is set to `file`
91 //! #[structopt(name = "FILE", required_if("out-type", "file"))]
92 //! file_name: Option<String>,
96 //! let opt = Opt::from_args();
97 //! println!("{:?}", opt);
101 //! So `derive(StructOpt)` tells Rust to generate a command line parser,
102 //! and the various `structopt` attributes are simply
103 //! used for additional parameters.
105 //! First, define a struct, whatever its name. This structure
106 //! corresponds to a `clap::App`, its fields correspond to `clap::Arg`
107 //! (unless they're [subcommands](#subcommands)),
108 //! and you can adjust these apps and args by `#[structopt(...)]` [attributes](#attributes).
111 //! _________________
112 //! Keep in mind that `StructOpt` trait is more than just `from_args` method.
113 //! It has a number of additional features, including access to underlying
114 //! `clap::App` via `StructOpt::clap()`. See the
115 //! [trait's reference documentation](trait.StructOpt.html).
116 //! _________________
120 //! You can control the way `structopt` translates your struct into an actual
121 //! [`clap::App`] invocation via `#[structopt(...)]` attributes.
123 //! The attributes fall into two categories:
124 //! - `structopt`'s own [magical methods](#magical-methods).
126 //! They are used by `structopt` itself. They come mostly in
127 //! `attr = ["whatever"]` form, but some `attr(args...)` also exist.
129 //! - [`raw` attributes](#raw-methods).
131 //! They represent explicit `clap::Arg/App` method calls.
132 //! They are what used to be explicit `#[structopt(raw(...))]` attrs in pre-0.3 `structopt`
134 //! Every `structopt attribute` looks like comma-separated sequence of methods:
137 //! short, // method with no arguments - always magical
138 //! long = "--long-option", // method with one argument
139 //! required_if("out", "file"), // method with one and more args
140 //! parse(from_os_str = path::to::parser) // some magical methods have their own syntax
144 //! `#[structopt(...)]` attributes can be placed on top of `struct`, `enum`,
145 //! `struct` field or `enum` variant. Attributes on top of `struct` or `enum`
146 //! represent `clap::App` method calls, field or variant attributes correspond
147 //! to `clap::Arg` method calls.
149 //! In other words, the `Opt` struct from the example above
150 //! will be turned into this (*details omitted*):
153 //! # use structopt::clap::{Arg, App};
154 //! App::new("example")
155 //! .version("0.2.0")
156 //! .about("An example of StructOpt usage.")
157 //! .arg(Arg::with_name("debug")
158 //! .help("Activate debug mode")
161 //! .arg(Arg::with_name("speed")
162 //! .help("Set speed")
164 //! .long("velocity")
165 //! .default_value("42"))
172 //! They are the reason why `structopt` is so flexible. **Every and each method from
173 //! `clap::App/Arg` can be used this way!**
177 //! global = true, // name = arg form, neat for one-arg methods
178 //! required_if("out", "file") // name(arg1, arg2, ...) form.
182 //! The first form can only be used for methods which take only one argument.
183 //! The second form must be used with multi-arg methods, but can also be used with
184 //! single-arg methods. These forms are identical otherwise.
186 //! As long as `method_name` is not one of the magical methods -
187 //! it will be translated into a mere method call.
190 //! _________________
192 //! "Raw methods" are direct replacement for pre-0.3 structopt's
193 //! `#[structopt(raw(...))]` attributes, any time you would have used a `raw()` attribute
194 //! in 0.2 you should use raw method in 0.3.
196 //! Unfortunately, old raw attributes collide with `clap::Arg::raw` method. To explicitly
197 //! warn users of this change we allow `#[structopt(raw())]` only with `true` or `false`
198 //! literals (this method is supposed to be called only with `true` anyway).
199 //! __________________
201 //! ## Magical methods
203 //! They are the reason why `structopt` is so easy to use and convenient in most cases.
204 //! Many of them have defaults, some of them get used even if not mentioned.
206 //! Methods may be used on "top level" (on top of a `struct`, `enum` or `enum` variant)
207 //! and/or on "field-level" (on top of a `struct` field or *inside* of an enum variant).
208 //! Top level (non-magical) methods correspond to `App::method` calls, field-level methods
209 //! are `Arg::method` calls.
212 //! #[structopt(top_level)]
214 //! #[structopt(field_level)]
218 //! #[structopt(top_level)]
220 //! #[structopt(top_level)]
222 //! #[structopt(field_level)]
223 //! chocolate: String
226 //! #[structopt(top_level)]
231 //! - `name`: `[name = expr]`
232 //! - On top level: `App::new(expr)`.
234 //! The binary name displayed in help messages. Defaults to the crate name given by Cargo.
236 //! - On field-level: `Arg::with_name(expr)`.
238 //! The name for the argument the field stands for, this name appears in help messages.
239 //! Defaults to a name, deduced from a field, see also
240 //! [`rename_all`](#specifying-argument-types).
242 //! - `version`: `[version = "version"]`
244 //! Usable only on top level: `App::version("version" or env!(CARGO_PKG_VERSION))`.
246 //! The version displayed in help messages.
247 //! Defaults to the crate version given by Cargo. If `CARGO_PKG_VERSION` is not
248 //! set no `.version()` calls will be generated unless requested.
250 //! - `no_version`: `no_version`
252 //! Usable only on top level. Prevents default `App::version` call, i.e
253 //! when no `version = "version"` mentioned.
255 //! - `author`: `author [= "author"]`
257 //! Usable only on top level: `App::author("author" or env!(CARGO_PKG_AUTHORS))`.
259 //! Author/maintainer of the binary, this name appears in help messages.
260 //! Defaults to the crate author given by cargo, but only when `author` explicitly mentioned.
262 //! - `about`: `about [= "about"]`
264 //! Usable only on top level: `App::about("about" or env!(CARGO_PKG_DESCRIPTION))`.
266 //! Short description of the binary, appears in help messages.
267 //! Defaults to the crate description given by cargo,
268 //! but only when `about` explicitly mentioned.
270 //! - [`short`](#specifying-argument-types): `short [= "short-opt-name"]`
272 //! Usable only on field-level.
274 //! - [`long`](#specifying-argument-types): `long [= "long-opt-name"]`
276 //! Usable only on field-level.
278 //! - [`default_value`](#default-values): `default_value [= "default value"]`
280 //! Usable only on field-level.
282 //! - [`rename_all`](#specifying-argument-types):
283 //! [`rename_all = "kebab"/"snake"/"screaming-snake"/"camel"/"pascal"/"verbatim"/"lower"/"upper"]`
285 //! Usable both on top level and field level.
287 //! - [`parse`](#custom-string-parsers): `parse(type [= path::to::parser::fn])`
289 //! Usable only on field-level.
291 //! - [`skip`](#skipping-fields): `skip [= expr]`
293 //! Usable only on field-level.
295 //! - [`flatten`](#flattening): `flatten`
297 //! Usable on field-level or single-typed tuple variants.
299 //! - [`subcommand`](#subcommands): `subcommand`
301 //! Usable only on field-level.
303 //! - [`external_subcommand`](#external-subcommands)
305 //! Usable only on enum variants.
307 //! - [`env`](#environment-variable-fallback): `env [= str_literal]`
309 //! Usable only on field-level.
311 //! - [`rename_all_env`](##auto-deriving-environment-variables):
312 //! [`rename_all_env = "kebab"/"snake"/"screaming-snake"/"camel"/"pascal"/"verbatim"/"lower"/"upper"]`
314 //! Usable both on top level and field level.
316 //! - [`verbatim_doc_comment`](#doc-comment-preprocessing-and-structoptverbatim_doc_comment):
317 //! `verbatim_doc_comment`
319 //! Usable both on top level and field level.
323 //! One of major things that makes `structopt` so awesome is it's type magic.
324 //! Do you want optional positional argument? Use `Option<T>`! Or perhaps optional argument
325 //! that optionally takes value (`[--opt=[val]]`)? Use `Option<Option<T>>`!
327 //! Here is the table of types and `clap` methods they correspond to:
329 //! Type | Effect | Added method call to `clap::Arg`
330 //! -----------------------------|---------------------------------------------------|--------------------------------------
331 //! `bool` | `true` if the flag is present | `.takes_value(false).multiple(false)`
332 //! `Option<T: FromStr>` | optional positional argument or option | `.takes_value(true).multiple(false)`
333 //! `Option<Option<T: FromStr>>` | optional option with optional value | `.takes_value(true).multiple(false).min_values(0).max_values(1)`
334 //! `Vec<T: FromStr>` | list of options or the other positional arguments | `.takes_value(true).multiple(true)`
335 //! `Option<Vec<T: FromStr>` | optional list of options | `.takes_values(true).multiple(true).min_values(0)`
336 //! `T: FromStr` | required option or positional argument | `.takes_value(true).multiple(false).required(!has_default)`
338 //! The `FromStr` trait is used to convert the argument to the given
339 //! type, and the `Arg::validator` method is set to a method using
340 //! `to_string()` (`FromStr::Err` must implement `std::fmt::Display`).
341 //! If you would like to use a custom string parser other than `FromStr`, see
342 //! the [same titled section](#custom-string-parsers) below.
345 //! _________________
346 //! Pay attention that *only literal occurrence* of this types is special, for example
347 //! `Option<T>` is special while `::std::option::Option<T>` is not.
349 //! If you need to avoid special casing you can make a `type` alias and
350 //! use it in place of the said type.
351 //! _________________
354 //! _________________
355 //! `bool` cannot be used as positional argument unless you provide an explicit parser.
356 //! If you need a positional bool, for example to parse `true` or `false`, you must
357 //! annotate the field with explicit [`#[structopt(parse(...))]`](#custom-string-parsers).
358 //! _________________
360 //! Thus, the `speed` argument is generated as:
363 //! # fn parse_validator<T>(_: String) -> Result<(), String> { unimplemented!() }
364 //! clap::Arg::with_name("speed")
365 //! .takes_value(true)
368 //! .validator(parse_validator::<f64>)
370 //! .long("velocity")
371 //! .help("Set speed")
372 //! .default_value("42");
375 //! ## Specifying argument types
377 //! There are three types of arguments that can be supplied to each
380 //! - short (e.g. `-h`),
381 //! - long (e.g. `--help`)
382 //! - and positional.
384 //! Like clap, structopt defaults to creating positional arguments.
386 //! If you want to generate a long argument you can specify either
387 //! `long = $NAME`, or just `long` to get a long flag generated using
388 //! the field name. The generated casing style can be modified using
389 //! the `rename_all` attribute. See the `rename_all` example for more.
391 //! For short arguments, `short` will use the first letter of the
392 //! field name by default, but just like the long option it's also
393 //! possible to use a custom letter through `short = $LETTER`.
395 //! If an argument is renamed using `name = $NAME` any following call to
396 //! `short` or `long` will use the new name.
398 //! **Attention**: If these arguments are used without an explicit name
399 //! the resulting flag is going to be renamed using `kebab-case` if the
400 //! `rename_all` attribute was not specified previously. The same is true
401 //! for subcommands with implicit naming through the related data structure.
404 //! use structopt::StructOpt;
406 //! #[derive(StructOpt)]
407 //! #[structopt(rename_all = "kebab-case")]
409 //! /// This option can be specified with something like `--foo-option
410 //! /// value` or `--foo-option=value`
411 //! #[structopt(long)]
412 //! foo_option: String,
414 //! /// This option can be specified with something like `-b value` (but
415 //! /// not `--bar-option value`).
416 //! #[structopt(short)]
417 //! bar_option: String,
419 //! /// This option can be specified either `--baz value` or `-z value`.
420 //! #[structopt(short = "z", long = "baz")]
421 //! baz_option: String,
423 //! /// This option can be specified either by `--custom value` or
425 //! #[structopt(name = "custom", long, short)]
426 //! custom_option: String,
428 //! /// This option is positional, meaning it is the first unadorned string
429 //! /// you provide (multiple others could follow).
430 //! my_positional: String,
432 //! /// This option is skipped and will be filled with the default value
433 //! /// for its type (in this case 0).
434 //! #[structopt(skip)]
439 //! # Opt::from_iter(
440 //! # &["test", "--foo-option", "", "-b", "", "--baz", "", "--custom", "", "positional"]);
443 //! ## Default values
445 //! In clap, default values for options can be specified via [`Arg::default_value`].
447 //! Of course, you can use as a raw method:
449 //! # use structopt::StructOpt;
450 //! #[derive(StructOpt)]
452 //! #[structopt(default_value = "", long)]
457 //! This is quite mundane and error-prone to type the `"..."` default by yourself,
458 //! especially when the Rust ecosystem uses the [`Default`] trait for that.
459 //! It would be wonderful to have `structopt` to take the `Default_default` and fill it
460 //! for you. And yes, `structopt` can do that.
462 //! Unfortunately, `default_value` takes `&str` but `Default::default`
463 //! gives us some `Self` value. We need to map `Self` to `&str` somehow.
465 //! `structopt` solves this problem via [`ToString`] trait.
467 //! To be able to use auto-default the type must implement *both* `Default` and `ToString`:
470 //! # use structopt::StructOpt;
471 //! #[derive(StructOpt)]
473 //! // just leave the `= "..."` part and structopt will figure it for you
474 //! #[structopt(default_value, long)]
475 //! prefix: String // `String` implements both `Default` and `ToString`
479 //! [`Default`]: https://doc.rust-lang.org/std/default/trait.Default.html
480 //! [`ToString`]: https://doc.rust-lang.org/std/string/trait.ToString.html
481 //! [`Arg::default_value`]: https://docs.rs/clap/2.33.0/clap/struct.Arg.html#method.default_value
486 //! In clap, help messages for the whole binary can be specified
487 //! via [`App::about`] and [`App::long_about`] while help messages
488 //! for individual arguments can be specified via [`Arg::help`] and [`Arg::long_help`]".
490 //! `long_*` variants are used when user calls the program with
491 //! `--help` and "short" variants are used with `-h` flag. In `structopt`,
492 //! you can use them via [raw methods](#raw-methods), for example:
495 //! # use structopt::StructOpt;
497 //! #[derive(StructOpt)]
498 //! #[structopt(about = "I am a program and I work, just pass `-h`")]
500 //! #[structopt(short, help = "Pass `-h` and you'll see me!")]
505 //! For convenience, doc comments can be used instead of raw methods
506 //! (this example works exactly like the one above):
509 //! # use structopt::StructOpt;
511 //! #[derive(StructOpt)]
512 //! /// I am a program and I work, just pass `-h`
514 //! /// Pass `-h` and you'll see me!
519 //! Doc comments on [top-level](#magical-methods) will be turned into
520 //! `App::about/long_about` call (see below), doc comments on field-level are
521 //! `Arg::help/long_help` calls.
524 //! _________________
526 //! Raw methods have priority over doc comments!
528 //! **Top level doc comments always generate `App::about/long_about` calls!**
529 //! If you really want to use the `App::help/long_help` methods (you likely don't),
530 //! use a raw method to override the `App::about` call generated from the doc comment.
531 //! __________________
533 //! ### `long_help` and `--help`
535 //! A message passed to [`App::long_help`] or [`Arg::long_about`] will be displayed whenever
536 //! your program is called with `--help` instead of `-h`. Of course, you can
537 //! use them via raw methods as described [above](#help-messages).
539 //! The more convenient way is to use a so-called "long" doc comment:
542 //! # use structopt::StructOpt;
543 //! #[derive(StructOpt)]
544 //! /// Hi there, I'm Robo!
546 //! /// I like beeping, stumbling, eating your electricity,
547 //! /// and making records of you singing in a shower.
548 //! /// Pay up, or I'll upload it to youtube!
550 //! /// Call my brother SkyNet.
552 //! /// I am artificial superintelligence. I won't rest
553 //! /// until I'll have destroyed humanity. Enjoy your
554 //! /// pathetic existence, you mere mortals.
555 //! #[structopt(long)]
556 //! kill_all_humans: bool
560 //! A long doc comment consists of three parts:
562 //! * A blank line (whitespace only)
563 //! * Detailed description, all the rest
565 //! In other words, "long" doc comment consists of two or more paragraphs,
566 //! with the first being a summary and the rest being the detailed description.
568 //! **A long comment will result in two method calls**, `help(<summary>)` and
569 //! `long_help(<whole comment>)`, so clap will display the summary with `-h`
570 //! and the whole help message on `--help` (see below).
572 //! So, the example above will be turned into this (details omitted):
574 //! clap::App::new("<name>")
575 //! .about("Hi there, I'm Robo!")
576 //! .long_about("Hi there, I'm Robo!\n\n\
577 //! I like beeping, stumbling, eating your electricity,\
578 //! and making records of you singing in a shower.\
579 //! Pay up or I'll upload it to youtube!")
584 //! ### `-h` vs `--help` (A.K.A `help()` vs `long_help()`)
586 //! The `-h` flag is not the same as `--help`.
588 //! -h corresponds to Arg::help/App::about and requests short "summary" messages
589 //! while --help corresponds to Arg::long_help/App::long_about and requests more
590 //! detailed, descriptive messages.
592 //! It is entirely up to `clap` what happens if you used only one of
593 //! [`Arg::help`]/[`Arg::long_help`], see `clap`'s documentation for these methods.
595 //! As of clap v2.33, if only a short message ([`Arg::help`]) or only
596 //! a long ([`Arg::long_help`]) message is provided, clap will use it
597 //! for both -h and --help. The same logic applies to `about/long_about`.
599 //! ### Doc comment preprocessing and `#[structopt(verbatim_doc_comment)]`
601 //! `structopt` applies some preprocessing to doc comments to ease the most common uses:
603 //! * Strip leading and trailing whitespace from every line, if present.
605 //! * Strip leading and trailing blank lines, if present.
607 //! * Interpret each group of non-empty lines as a word-wrapped paragraph.
609 //! We replace newlines within paragraphs with spaces to allow the output
610 //! to be re-wrapped to the terminal width.
612 //! * Strip any excess blank lines so that there is exactly one per paragraph break.
614 //! * If the first paragraph ends in exactly one period,
615 //! remove the trailing period (i.e. strip trailing periods but not trailing ellipses).
617 //! Sometimes you don't want this preprocessing to apply, for example the comment contains
618 //! some ASCII art or markdown tables, you would need to preserve LFs along with
619 //! blank lines and the leading/trailing whitespace. You can ask `structopt` to preserve them
620 //! via `#[structopt(verbatim_doc_comment)]` attribute.
622 //! **This attribute must be applied to each field separately**, there's no global switch.
626 //! Keep in mind that `structopt` will *still* remove one leading space from each
627 //! line, even if this attribute is present, to allow for a space between
628 //! `///` and the content.
630 //! Also, `structopt` will *still* remove leading and trailing blank lines so
631 //! these formats are equivalent:
634 //! /** This is a doc comment
639 //! This is a doc comment
644 //! /// This is a doc comment
650 //! [`App::about`]: https://docs.rs/clap/2/clap/struct.App.html#method.about
651 //! [`App::long_about`]: https://docs.rs/clap/2/clap/struct.App.html#method.long_about
652 //! [`Arg::help`]: https://docs.rs/clap/2/clap/struct.Arg.html#method.help
653 //! [`Arg::long_help`]: https://docs.rs/clap/2/clap/struct.Arg.html#method.long_help
655 //! ## Environment variable fallback
657 //! It is possible to specify an environment variable fallback option for an arguments
658 //! so that its value is taken from the specified environment variable if not
659 //! given through the command-line:
662 //! # use structopt::StructOpt;
664 //! #[derive(StructOpt)]
666 //! #[structopt(short, long, env = "PARAMETER_VALUE")]
667 //! parameter_value: String
671 //! By default, values from the environment are shown in the help output (i.e. when invoking
675 //! $ cargo run -- --help
678 //! -p, --parameter-value <parameter-value> [env: PARAMETER_VALUE=env_value]
681 //! In some cases this may be undesirable, for example when being used for passing
682 //! credentials or secret tokens. In those cases you can use `hide_env_values` to avoid
683 //! having structopt emit the actual secret values:
685 //! # use structopt::StructOpt;
687 //! #[derive(StructOpt)]
689 //! #[structopt(long = "secret", env = "SECRET_VALUE", hide_env_values = true)]
690 //! secret_value: String
694 //! ### Auto-deriving environment variables
696 //! Environment variables tend to be called after the corresponding `struct`'s field,
697 //! as in example above. The field is `secret_value` and the env var is "SECRET_VALUE";
698 //! the name is the same, except casing is different.
700 //! It's pretty tedious and error-prone to type the same name twice,
701 //! so you can ask `structopt` to do that for you.
704 //! # use structopt::StructOpt;
706 //! #[derive(StructOpt)]
708 //! #[structopt(long = "secret", env)]
709 //! secret_value: String
713 //! It works just like `#[structopt(short/long)]`: if `env` is not set to some concrete
714 //! value the value will be derived from the field's name. This is controlled by
715 //! `#[structopt(rename_all_env)]`.
717 //! `rename_all_env` works exactly as `rename_all` (including overriding)
718 //! except default casing is `SCREAMING_SNAKE_CASE` instead of `kebab-case`.
720 //! ## Skipping fields
722 //! Sometimes you may want to add a field to your `Opt` struct that is not
723 //! a command line option and `clap` should know nothing about it. You can ask
724 //! `structopt` to skip the field entirely via `#[structopt(skip = value)]`
725 //! (`value` must implement `Into<FieldType>`)
726 //! or `#[structopt(skip)]` if you want assign the field with `Default::default()`
727 //! (obviously, the field's type must implement `Default`).
730 //! # use structopt::StructOpt;
731 //! #[derive(StructOpt)]
733 //! #[structopt(long, short)]
736 //! // these fields are to be assigned with Default::default()
738 //! #[structopt(skip)]
740 //! #[structopt(skip)]
743 //! // these fields get set explicitly
745 //! #[structopt(skip = vec![1, 2, 3])]
747 //! #[structopt(skip = "cake")] // &str implements Into<String>
754 //! Some applications, especially large ones, split their functionality
755 //! through the use of "subcommands". Each of these act somewhat like a separate
756 //! command, but is part of the larger group.
757 //! One example is `git`, which has subcommands such as `add`, `commit`,
758 //! and `clone`, to mention just a few.
760 //! `clap` has this functionality, and `structopt` supports it through enums:
763 //! # use structopt::StructOpt;
765 //! # use std::path::PathBuf;
766 //! #[derive(StructOpt)]
767 //! #[structopt(about = "the stupid content tracker")]
770 //! #[structopt(short)]
771 //! interactive: bool,
772 //! #[structopt(short)]
774 //! #[structopt(parse(from_os_str))]
775 //! files: Vec<PathBuf>
778 //! #[structopt(long)]
780 //! #[structopt(long)]
782 //! repository: Option<String>
785 //! #[structopt(short)]
786 //! message: Option<String>,
787 //! #[structopt(short)]
793 //! Using `derive(StructOpt)` on an enum instead of a struct will produce
794 //! a `clap::App` that only takes subcommands. So `git add`, `git fetch`,
795 //! and `git commit` would be commands allowed for the above example.
797 //! `structopt` also provides support for applications where certain flags
798 //! need to apply to all subcommands, as well as nested subcommands:
801 //! # use structopt::StructOpt;
802 //! #[derive(StructOpt)]
803 //! struct MakeCookie {
804 //! #[structopt(name = "supervisor", default_value = "Puck", long = "supervisor")]
805 //! supervising_faerie: String,
806 //! /// The faerie tree this cookie is being made in.
807 //! tree: Option<String>,
808 //! #[structopt(subcommand)] // Note that we mark a field as a subcommand
812 //! #[derive(StructOpt)]
814 //! /// Pound acorns into flour for cookie dough.
818 //! /// Add magical sparkles -- the secret ingredient!
820 //! #[structopt(short, parse(from_occurrences))]
822 //! #[structopt(short)]
828 //! // Subcommand can also be externalized by using a 1-uple enum variant
829 //! #[derive(StructOpt)]
831 //! #[structopt(short)]
833 //! #[structopt(subcommand)] // Note that we mark a field as a subcommand
834 //! finish_type: FinishType
837 //! // subsubcommand!
838 //! #[derive(StructOpt)]
839 //! enum FinishType {
841 //! applications: u32
850 //! Marking a field with `structopt(subcommand)` will add the subcommands of the
851 //! designated enum to the current `clap::App`. The designated enum *must* also
852 //! be derived `StructOpt`. So the above example would take the following
855 //! + `make-cookie pound 50`
856 //! + `make-cookie sparkle -mmm --color "green"`
857 //! + `make-cookie finish 130 glaze 3`
859 //! ### Optional subcommands
861 //! Subcommands may be optional:
864 //! # use structopt::StructOpt;
865 //! #[derive(StructOpt)]
868 //! #[structopt(subcommand)]
869 //! cmd: Option<Command>
872 //! #[derive(StructOpt)]
880 //! ### External subcommands
882 //! Sometimes you want to support not only the set of well-known subcommands
883 //! but you also want to allow other, user-driven subcommands. `clap` supports
884 //! this via [`AppSettings::AllowExternalSubcommands`].
886 //! `structopt` provides it's own dedicated syntax for that:
889 //! # use structopt::StructOpt;
890 //! #[derive(Debug, PartialEq, StructOpt)]
892 //! #[structopt(subcommand)]
893 //! sub: Subcommands,
896 //! #[derive(Debug, PartialEq, StructOpt)]
897 //! enum Subcommands {
898 //! // normal subcommand
901 //! // `external_subcommand` tells structopt to put
902 //! // all the extra arguments into this Vec
903 //! #[structopt(external_subcommand)]
904 //! Other(Vec<String>),
907 //! // normal subcommand
909 //! Opt::from_iter(&["test", "add"]),
911 //! sub: Subcommands::Add
916 //! Opt::from_iter(&["test", "git", "status"]),
918 //! sub: Subcommands::Other(vec!["git".into(), "status".into()])
922 //! // Please note that if you'd wanted to allow "no subcommands at all" case
923 //! // you should have used `sub: Option<Subcommands>` above
924 //! assert!(Opt::from_iter_safe(&["test"]).is_err());
927 //! In other words, you just add an extra tuple variant marked with
928 //! `#[structopt(subcommand)]`, and its type must be either
929 //! `Vec<String>` or `Vec<OsString>`. `structopt` will detect `String` in this context
930 //! and use appropriate `clap` API.
932 //! [`AppSettings::AllowExternalSubcommands`]: https://docs.rs/clap/2.32.0/clap/enum.AppSettings.html#variant.AllowExternalSubcommands
934 //! ### Flattening subcommands
936 //! It is also possible to combine multiple enums of subcommands into one.
937 //! All the subcommands will be on the same level.
940 //! # use structopt::StructOpt;
941 //! #[derive(StructOpt)]
948 //! #[derive(StructOpt)]
950 //! #[structopt(flatten)]
951 //! BaseCli(BaseCli),
965 //! It can sometimes be useful to group related arguments in a substruct,
966 //! while keeping the command-line interface flat. In these cases you can mark
967 //! a field as `flatten` and give it another type that derives `StructOpt`:
970 //! # use structopt::StructOpt;
971 //! #[derive(StructOpt)]
973 //! /// switch on verbosity
974 //! #[structopt(short)]
976 //! #[structopt(flatten)]
977 //! daemon_opts: DaemonOpts,
980 //! #[derive(StructOpt)]
981 //! struct DaemonOpts {
983 //! #[structopt(short)]
986 //! #[structopt(short)]
991 //! In this example, the derived `Cmdline` parser will support the options `-v`,
994 //! This feature also makes it possible to define a `StructOpt` struct in a
995 //! library, parse the corresponding arguments in the main argument parser, and
996 //! pass off this struct to a handler provided by that library.
998 //! ## Custom string parsers
1000 //! If the field type does not have a `FromStr` implementation, or you would
1001 //! like to provide a custom parsing scheme other than `FromStr`, you may
1002 //! provide a custom string parser using `parse(...)` like this:
1005 //! # use structopt::StructOpt;
1006 //! use std::num::ParseIntError;
1007 //! use std::path::PathBuf;
1009 //! fn parse_hex(src: &str) -> Result<u32, ParseIntError> {
1010 //! u32::from_str_radix(src, 16)
1013 //! #[derive(StructOpt)]
1014 //! struct HexReader {
1015 //! #[structopt(short, parse(try_from_str = parse_hex))]
1017 //! #[structopt(short, parse(from_os_str))]
1018 //! output: PathBuf,
1022 //! There are five kinds of custom parsers:
1024 //! | Kind | Signature | Default |
1025 //! |-------------------|---------------------------------------|---------------------------------|
1026 //! | `from_str` | `fn(&str) -> T` | `::std::convert::From::from` |
1027 //! | `try_from_str` | `fn(&str) -> Result<T, E>` | `::std::str::FromStr::from_str` |
1028 //! | `from_os_str` | `fn(&OsStr) -> T` | `::std::convert::From::from` |
1029 //! | `try_from_os_str` | `fn(&OsStr) -> Result<T, OsString>` | (no default function) |
1030 //! | `from_occurrences`| `fn(u64) -> T` | `value as T` |
1031 //! | `from_flag` | `fn(bool) -> T` | `::std::convert::From::from` |
1033 //! The `from_occurrences` parser is special. Using `parse(from_occurrences)`
1034 //! results in the _number of flags occurrences_ being stored in the relevant
1035 //! field or being passed to the supplied function. In other words, it converts
1036 //! something like `-vvv` to `3`. This is equivalent to
1037 //! `.takes_value(false).multiple(true)`. Note that the default parser can only
1038 //! be used with fields of integer types (`u8`, `usize`, `i64`, etc.).
1040 //! The `from_flag` parser is also special. Using `parse(from_flag)` or
1041 //! `parse(from_flag = some_func)` will result in the field being treated as a
1042 //! flag even if it does not have type `bool`.
1044 //! When supplying a custom string parser, `bool` will not be treated specially:
1046 //! Type | Effect | Added method call to `clap::Arg`
1047 //! ------------|-------------------|--------------------------------------
1048 //! `Option<T>` | optional argument | `.takes_value(true).multiple(false)`
1049 //! `Vec<T>` | list of arguments | `.takes_value(true).multiple(true)`
1050 //! `T` | required argument | `.takes_value(true).multiple(false).required(!has_default)`
1052 //! In the `try_from_*` variants, the function will run twice on valid input:
1053 //! once to validate, and once to parse. Hence, make sure the function is
1054 //! side-effect-free.
1056 // those mains are for a reason
1057 #![allow(clippy::needless_doctest_main)]
1060 pub use structopt_derive
::*;
1062 use std
::ffi
::OsString
;
1066 #[cfg(feature = "paw")]
1067 pub use paw_dep
as paw
;
1069 /// **This is NOT PUBLIC API**.
1071 pub use lazy_static
;
1073 /// A struct that is converted from command line arguments.
1074 pub trait StructOpt
{
1075 /// Returns the corresponding `clap::App`.
1076 fn clap
<'a
, 'b
>() -> clap
::App
<'a
, 'b
>;
1078 /// Creates the struct from `clap::ArgMatches`. It cannot fail
1079 /// with a parameter generated by `clap` by construction.
1080 fn from_clap(matches
: &clap
::ArgMatches
<'_
>) -> Self;
1082 /// Gets the struct from the command line arguments. Print the
1083 /// error message and quit the program in case of failure.
1084 fn from_args() -> Self
1088 Self::from_clap(&Self::clap().get_matches())
1091 /// Gets the struct from any iterator such as a `Vec` of your making.
1092 /// Print the error message and quit the program in case of failure.
1094 /// **NOTE**: The first argument will be parsed as the binary name unless
1095 /// [`AppSettings::NoBinaryName`] has been used.
1097 /// [`AppSettings::NoBinaryName`]: https://docs.rs/clap/2.33.0/clap/enum.AppSettings.html#variant.NoBinaryName
1098 fn from_iter
<I
>(iter
: I
) -> Self
1102 I
::Item
: Into
<OsString
> + Clone
,
1104 Self::from_clap(&Self::clap().get_matches_from(iter
))
1107 /// Gets the struct from any iterator such as a `Vec` of your making.
1109 /// Returns a `clap::Error` in case of failure. This does *not* exit in the
1110 /// case of `--help` or `--version`, to achieve the same behavior as
1111 /// `from_iter()` you must call `.exit()` on the error value.
1113 /// **NOTE**: The first argument will be parsed as the binary name unless
1114 /// [`AppSettings::NoBinaryName`] has been used.
1116 /// [`AppSettings::NoBinaryName`]: https://docs.rs/clap/2.33.0/clap/enum.AppSettings.html#variant.NoBinaryName
1117 fn from_iter_safe
<I
>(iter
: I
) -> Result
<Self, clap
::Error
>
1121 I
::Item
: Into
<OsString
> + Clone
,
1123 Ok(Self::from_clap(&Self::clap().get_matches_from_safe(iter
)?
))
1127 /// This trait is NOT API. **SUBJECT TO CHANGE WITHOUT NOTICE!**.
1129 pub trait StructOptInternal
: StructOpt
{
1130 fn augment_clap
<'a
, 'b
>(app
: clap
::App
<'a
, 'b
>) -> clap
::App
<'a
, 'b
> {
1134 fn is_subcommand() -> bool
{
1138 fn from_subcommand
<'a
, 'b
>(_sub
: (&'b
str, Option
<&'b clap
::ArgMatches
<'a
>>)) -> Option
<Self>
1140 Self: std
::marker
::Sized
,
1146 impl<T
: StructOpt
> StructOpt
for Box
<T
> {
1147 fn clap
<'a
, 'b
>() -> clap
::App
<'a
, 'b
> {
1148 <T
as StructOpt
>::clap()
1151 fn from_clap(matches
: &clap
::ArgMatches
<'_
>) -> Self {
1152 Box
::new(<T
as StructOpt
>::from_clap(matches
))
1156 impl<T
: StructOptInternal
> StructOptInternal
for Box
<T
> {
1158 fn is_subcommand() -> bool
{
1159 <T
as StructOptInternal
>::is_subcommand()
1163 fn from_subcommand
<'a
, 'b
>(sub
: (&'b
str, Option
<&'b clap
::ArgMatches
<'a
>>)) -> Option
<Self> {
1164 <T
as StructOptInternal
>::from_subcommand(sub
).map(Box
::new
)
1168 fn augment_clap
<'a
, 'b
>(app
: clap
::App
<'a
, 'b
>) -> clap
::App
<'a
, 'b
> {
1169 <T
as StructOptInternal
>::augment_clap(app
)