blob: c42fe1f098838eb2c5305c2b22b87d78878858f2 [file] [log] [blame]
Matthew Maurer32e76692020-06-02 11:15:15 -07001// Copyright 2018 Guillaume Pinot (@TeXitoi) <texitoi@texitoi.eu>
2//
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.
8
9#![deny(missing_docs)]
10
11//! This crate defines the `StructOpt` trait and its custom derive.
12//!
13//! ## Features
14//!
15//! If you want to disable all the `clap` features (colors,
16//! suggestions, ..) add `default-features = false` to the `structopt`
17//! dependency:
18//!
19//! ```toml
20//! [dependencies]
21//! structopt = { version = "0.3", default-features = false }
22//! ```
23//!
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`:
28//!
29//! ```toml
30//! [dependencies]
31//! structopt = { version = "0.3", features = [ "paw" ] }
32//! paw = "1.0"
33//! ```
34//!
35//! # Table of Contents
36//!
37//! - [How to `derive(StructOpt)`](#how-to-derivestructopt)
38//! - [Attributes](#attributes)
39//! - [Raw methods](#raw-methods)
40//! - [Magical methods](#magical-methods)
41//! - Arguments
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)
54//!
55//!
56//!
57//! ## How to `derive(StructOpt)`
58//!
59//! First, let's look at the example:
60//!
61//! ```should_panic
62//! use std::path::PathBuf;
63//! use structopt::StructOpt;
64//!
65//! #[derive(Debug, StructOpt)]
66//! #[structopt(name = "example", about = "An example of StructOpt usage.")]
67//! struct Opt {
68//! /// Activate debug mode
69//! // short and long flags (-d, --debug) will be deduced from the field's name
70//! #[structopt(short, long)]
71//! debug: bool,
72//!
73//! /// Set speed
74//! // we don't want to name it "speed", need to look smart
75//! #[structopt(short = "v", long = "velocity", default_value = "42")]
76//! speed: f64,
77//!
78//! /// Input file
79//! #[structopt(parse(from_os_str))]
80//! input: PathBuf,
81//!
82//! /// Output file, stdout if not present
83//! #[structopt(parse(from_os_str))]
84//! output: Option<PathBuf>,
85//!
86//! /// Where to write the output: to `stdout` or `file`
87//! #[structopt(short)]
88//! out_type: String,
89//!
90//! /// File name: only required when `out` is set to `file`
91//! #[structopt(name = "FILE", required_if("out_type", "file"))]
92//! file_name: String,
93//! }
94//!
95//! fn main() {
96//! let opt = Opt::from_args();
97//! println!("{:?}", opt);
98//! }
99//! ```
100//!
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.
104//!
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).
109//!
110//! **Note:**
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//! _________________
117//!
118//! ## Attributes
119//!
120//! You can control the way `structopt` translates your struct into an actual
121//! [`clap::App`] invocation via `#[structopt(...)]` attributes.
122//!
123//! The attributes fall into two categories:
124//! - `structopt`'s own [magical methods](#magical-methods).
125//!
126//! They are used by `structopt` itself. They come mostly in
127//! `attr = ["whatever"]` form, but some `attr(args...)` also exist.
128//!
129//! - [`raw` attributes](#raw-methods).
130//!
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`
133//!
134//! Every `structopt attribute` looks like comma-separated sequence of methods:
135//! ```rust,ignore
136//! #[structopt(
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
141//! )]
142//! ```
143//!
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.
148//!
149//! In other words, the `Opt` struct from the example above
150//! will be turned into this (*details omitted*):
151//!
152//! ```
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")
159//! .short("debug")
160//! .long("debug"))
161//! .arg(Arg::with_name("speed")
162//! .help("Set speed")
163//! .short("v")
164//! .long("velocity")
165//! .default_value("42"))
166//! // and so on
167//! # ;
168//! ```
169//!
170//! ## Raw methods
171//!
172//! They are the reason why `structopt` is so flexible. **Every and each method from
173//! `clap::App/Arg` can be used this way!**
174//!
175//! ```ignore
176//! #[structopt(
177//! global = true, // name = arg form, neat for one-arg methods
178//! required_if("out", "file") // name(arg1, arg2, ...) form.
179//! )]
180//! ```
181//!
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.
185//!
186//! As long as `method_name` is not one of the magical methods -
187//! it will be translated into a mere method call.
188//!
189//! **Note:**
190//! _________________
191//!
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.
195//!
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//! __________________
200//!
201//! ## Magical methods
202//!
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.
205//!
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.
210//!
211//! ```ignore
212//! #[structopt(top_level)]
213//! struct Foo {
214//! #[structopt(field_level)]
215//! field: u32
216//! }
217//!
218//! #[structopt(top_level)]
219//! enum Bar {
220//! #[structopt(top_level)]
221//! Pineapple {
222//! #[structopt(field_level)]
223//! chocolate: String
224//! },
225//!
226//! #[structopt(top_level)]
227//! Orange,
228//! }
229//! ```
230//!
231//! - `name`: `[name = expr]`
232//! - On top level: `App::new(expr)`.
233//!
234//! The binary name displayed in help messages. Defaults to the crate name given by Cargo.
235//!
236//! - On field-level: `Arg::with_name(expr)`.
237//!
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).
241//!
242//! - `version`: `[version = "version"]`
243//!
244//! Usable only on top level: `App::version("version" or env!(CARGO_PKG_VERSION))`.
245//!
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.
249//!
250//! - `no_version`: `no_version`
251//!
252//! Usable only on top level. Prevents default `App::version` call, i.e
253//! when no `version = "version"` mentioned.
254//!
255//! - `author`: `author [= "author"]`
256//!
257//! Usable only on top level: `App::author("author" or env!(CARGO_PKG_AUTHORS))`.
258//!
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.
261//!
262//! - `about`: `about [= "about"]`
263//!
264//! Usable only on top level: `App::about("about" or env!(CARGO_PKG_DESCRIPTION))`.
265//!
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.
269//!
270//! - [`short`](#specifying-argument-types): `short [= "short-opt-name"]`
271//!
272//! Usable only on field-level.
273//!
274//! - [`long`](#specifying-argument-types): `long [= "long-opt-name"]`
275//!
276//! Usable only on field-level.
277//!
278//! - [`default_value`](#default-values): `default_value [= "default value"]`
279//!
280//! Usable only on field-level.
281//!
282//! - [`rename_all`](#specifying-argument-types):
283//! [`rename_all = "kebab"/"snake"/"screaming-snake"/"camel"/"pascal"/"verbatim"]`
284//!
285//! Usable both on top level and field level.
286//!
287//! - [`parse`](#custom-string-parsers): `parse(type [= path::to::parser::fn])`
288//!
289//! Usable only on field-level.
290//!
291//! - [`skip`](#skipping-fields): `skip [= expr]`
292//!
293//! Usable only on field-level.
294//!
295//! - [`flatten`](#flattening): `flatten`
296//!
297//! Usable on field-level or single-typed tuple variants.
298//!
299//! - [`subcommand`](#subcommands): `subcommand`
300//!
301//! Usable only on field-level.
302//!
303//! - [`external_subcommand`](#external-subcommands)
304//!
305//! Usable only on enum variants.
306//!
307//! - [`env`](#environment-variable-fallback): `env [= str_literal]`
308//!
309//! Usable only on field-level.
310//!
311//! - [`rename_all_env`](##auto-deriving-environment-variables):
312//! [`rename_all_env = "kebab"/"snake"/"screaming-snake"/"camel"/"pascal"/"verbatim"]`
313//!
314//! Usable both on top level and field level.
315//!
316//! - [`verbatim_doc_comment`](#doc-comment-preprocessing-and-structoptverbatim_doc_comment):
317//! `verbatim_doc_comment`
318//!
319//! Usable both on top level and field level.
320//!
321//! ## Type magic
322//!
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>>`!
326//!
327//! Here is the table of types and `clap` methods they correspond to:
328//!
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)`
337//!
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.
343//!
344//! **Important:**
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.
348//!
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//! _________________
352//!
353//! **Note:**
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//! _________________
359//!
360//! Thus, the `speed` argument is generated as:
361//!
362//! ```
363//! # fn parse_validator<T>(_: String) -> Result<(), String> { unimplemented!() }
364//! clap::Arg::with_name("speed")
365//! .takes_value(true)
366//! .multiple(false)
367//! .required(false)
368//! .validator(parse_validator::<f64>)
369//! .short("v")
370//! .long("velocity")
371//! .help("Set speed")
372//! .default_value("42");
373//! ```
374//!
375//! ## Specifying argument types
376//!
377//! There are three types of arguments that can be supplied to each
378//! (sub-)command:
379//!
380//! - short (e.g. `-h`),
381//! - long (e.g. `--help`)
382//! - and positional.
383//!
384//! Like clap, structopt defaults to creating positional arguments.
385//!
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.
390//!
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`.
394//!
395//! If an argument is renamed using `name = $NAME` any following call to
396//! `short` or `long` will use the new name.
397//!
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.
402//!
403//! ```
404//! use structopt::StructOpt;
405//!
406//! #[derive(StructOpt)]
407//! #[structopt(rename_all = "kebab-case")]
408//! struct Opt {
409//! /// This option can be specified with something like `--foo-option
410//! /// value` or `--foo-option=value`
411//! #[structopt(long)]
412//! foo_option: String,
413//!
414//! /// This option can be specified with something like `-b value` (but
415//! /// not `--bar-option value`).
416//! #[structopt(short)]
417//! bar_option: String,
418//!
419//! /// This option can be specified either `--baz value` or `-z value`.
420//! #[structopt(short = "z", long = "baz")]
421//! baz_option: String,
422//!
423//! /// This option can be specified either by `--custom value` or
424//! /// `-c value`.
425//! #[structopt(name = "custom", long, short)]
426//! custom_option: String,
427//!
428//! /// This option is positional, meaning it is the first unadorned string
429//! /// you provide (multiple others could follow).
430//! my_positional: String,
431//!
432//! /// This option is skipped and will be filled with the default value
433//! /// for its type (in this case 0).
434//! #[structopt(skip)]
435//! skipped: u32,
436//!
437//! }
438//!
439//! # Opt::from_iter(
440//! # &["test", "--foo-option", "", "-b", "", "--baz", "", "--custom", "", "positional"]);
441//! ```
442//!
443//! ## Default values
444//!
445//! In clap, default values for options can be specified via [`Arg::default_value`].
446//!
447//! Of course, you can use as a raw method:
448//! ```
449//! # use structopt::StructOpt;
450//! #[derive(StructOpt)]
451//! struct Opt {
452//! #[structopt(default_value = "", long)]
453//! prefix: String
454//! }
455//! ```
456//!
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.
461//!
462//! Unfortunately, `default_value` takes `&str` but `Default::default`
463//! gives us some `Self` value. We need to map `Self` to `&str` somehow.
464//!
465//! `structopt` solves this problem via [`ToString`] trait.
466//!
467//! To be able to use auto-default the type must implement *both* `Default` and `ToString`:
468//!
469//! ```
470//! # use structopt::StructOpt;
471//! #[derive(StructOpt)]
472//! struct Opt {
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`
476//! }
477//! ```
478//!
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
482//!
483//!
484//! ## Help messages
485//!
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`]".
489//!
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:
493//!
494//! ```
495//! # use structopt::StructOpt;
496//!
497//! #[derive(StructOpt)]
498//! #[structopt(about = "I am a program and I work, just pass `-h`")]
499//! struct Foo {
500//! #[structopt(short, help = "Pass `-h` and you'll see me!")]
501//! bar: String
502//! }
503//! ```
504//!
505//! For convenience, doc comments can be used instead of raw methods
506//! (this example works exactly like the one above):
507//!
508//! ```
509//! # use structopt::StructOpt;
510//!
511//! #[derive(StructOpt)]
512//! /// I am a program and I work, just pass `-h`
513//! struct Foo {
514//! /// Pass `-h` and you'll see me!
515//! bar: String
516//! }
517//! ```
518//!
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.
522//!
523//! **Important:**
524//! _________________
525//!
526//! Raw methods have priority over doc comments!
527//!
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//! __________________
532//!
533//! ### `long_help` and `--help`
534//!
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).
538//!
539//! The more convenient way is to use a so-called "long" doc comment:
540//!
541//! ```
542//! # use structopt::StructOpt;
543//! #[derive(StructOpt)]
544//! /// Hi there, I'm Robo!
545//! ///
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!
549//! struct Robo {
550//! /// Call my brother SkyNet.
551//! ///
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
557//! }
558//! ```
559//!
560//! A long doc comment consists of three parts:
561//! * Short summary
562//! * A blank line (whitespace only)
563//! * Detailed description, all the rest
564//!
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.
567//!
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).
571//!
572//! So, the example above will be turned into this (details omitted):
573//! ```
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!")
580//! // args...
581//! # ;
582//! ```
583//!
584//! ### `-h` vs `--help` (A.K.A `help()` vs `long_help()`)
585//!
586//! The `-h` flag is not the same as `--help`.
587//!
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.
591//!
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.
594//!
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`.
598//!
599//! ### Doc comment preprocessing and `#[structopt(verbatim_doc_comment)]`
600//!
601//! `structopt` applies some preprocessing to doc comments to ease the most common uses:
602//!
603//! * Strip leading and trailing whitespace from every line, if present.
604//!
605//! * Strip leading and trailing blank lines, if present.
606//!
607//! * Interpret each group of non-empty lines as a word-wrapped paragraph.
608//!
609//! We replace newlines within paragraphs with spaces to allow the output
610//! to be re-wrapped to the terminal width.
611//!
612//! * Strip any excess blank lines so that there is exactly one per paragraph break.
613//!
614//! * If the first paragraph ends in exactly one period,
615//! remove the trailing period (i.e. strip trailing periods but not trailing ellipses).
616//!
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.
621//!
622//! **This attribute must be applied to each field separately**, there's no global switch.
623//!
624//! **Important:**
625//! ______________
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.
629//!
630//! Also, `structopt` will *still* remove leading and trailing blank lines so
631//! these formats are equivalent:
632//!
633//! ```ignore
634//! /** This is a doc comment
635//!
636//! Hello! */
637//!
638//! /**
639//! This is a doc comment
640//!
641//! Hello!
642//! */
643//!
644//! /// This is a doc comment
645//! ///
646//! /// Hello!
647//! ```
648//! ______________
649//!
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
654//!
655//! ## Environment variable fallback
656//!
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:
660//!
661//! ```
662//! # use structopt::StructOpt;
663//!
664//! #[derive(StructOpt)]
665//! struct Foo {
666//! #[structopt(short, long, env = "PARAMETER_VALUE")]
667//! parameter_value: String
668//! }
669//! ```
670//!
671//! By default, values from the environment are shown in the help output (i.e. when invoking
672//! `--help`):
673//!
674//! ```shell
675//! $ cargo run -- --help
676//! ...
677//! OPTIONS:
678//! -p, --parameter-value <parameter-value> [env: PARAMETER_VALUE=env_value]
679//! ```
680//!
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:
684//! ```
685//! # use structopt::StructOpt;
686//!
687//! #[derive(StructOpt)]
688//! struct Foo {
689//! #[structopt(long = "secret", env = "SECRET_VALUE", hide_env_values = true)]
690//! secret_value: String
691//! }
692//! ```
693//!
694//! ### Auto-deriving environment variables
695//!
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.
699//!
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.
702//!
703//! ```
704//! # use structopt::StructOpt;
705//!
706//! #[derive(StructOpt)]
707//! struct Foo {
708//! #[structopt(long = "secret", env)]
709//! secret_value: String
710//! }
711//! ```
712//!
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)]`.
716//!
717//! `rename_all_env` works exactly as `rename_all` (including overriding)
718//! except default casing is `SCREAMING_SNAKE_CASE` instead of `kebab-case`.
719//!
720//! ## Skipping fields
721//!
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`).
728//!
729//! ```
730//! # use structopt::StructOpt;
731//! #[derive(StructOpt)]
732//! pub struct Opt {
733//! #[structopt(long, short)]
734//! number: u32,
735//!
736//! // these fields are to be assigned with Default::default()
737//!
738//! #[structopt(skip)]
739//! k: String,
740//! #[structopt(skip)]
741//! v: Vec<u32>,
742//!
743//! // these fields get set explicitly
744//!
745//! #[structopt(skip = vec![1, 2, 3])]
746//! k2: Vec<u32>,
747//! #[structopt(skip = "cake")] // &str implements Into<String>
748//! v2: String,
749//! }
750//! ```
751//!
752//! ## Subcommands
753//!
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.
759//!
760//! `clap` has this functionality, and `structopt` supports it through enums:
761//!
762//! ```
763//! # use structopt::StructOpt;
764//!
765//! # use std::path::PathBuf;
766//! #[derive(StructOpt)]
767//! #[structopt(about = "the stupid content tracker")]
768//! enum Git {
769//! Add {
770//! #[structopt(short)]
771//! interactive: bool,
772//! #[structopt(short)]
773//! patch: bool,
774//! #[structopt(parse(from_os_str))]
775//! files: Vec<PathBuf>
776//! },
777//! Fetch {
778//! #[structopt(long)]
779//! dry_run: bool,
780//! #[structopt(long)]
781//! all: bool,
782//! repository: Option<String>
783//! },
784//! Commit {
785//! #[structopt(short)]
786//! message: Option<String>,
787//! #[structopt(short)]
788//! all: bool
789//! }
790//! }
791//! ```
792//!
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.
796//!
797//! `structopt` also provides support for applications where certain flags
798//! need to apply to all subcommands, as well as nested subcommands:
799//!
800//! ```
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
809//! cmd: Command
810//! }
811//!
812//! #[derive(StructOpt)]
813//! enum Command {
814//! /// Pound acorns into flour for cookie dough.
815//! Pound {
816//! acorns: u32
817//! },
818//! /// Add magical sparkles -- the secret ingredient!
819//! Sparkle {
820//! #[structopt(short, parse(from_occurrences))]
821//! magicality: u64,
822//! #[structopt(short)]
823//! color: String
824//! },
825//! Finish(Finish),
826//! }
827//!
828//! // Subcommand can also be externalized by using a 1-uple enum variant
829//! #[derive(StructOpt)]
830//! struct Finish {
831//! #[structopt(short)]
832//! time: u32,
833//! #[structopt(subcommand)] // Note that we mark a field as a subcommand
834//! finish_type: FinishType
835//! }
836//!
837//! // subsubcommand!
838//! #[derive(StructOpt)]
839//! enum FinishType {
840//! Glaze {
841//! applications: u32
842//! },
843//! Powder {
844//! flavor: String,
845//! dips: u32
846//! }
847//! }
848//! ```
849//!
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
853//! commands:
854//!
855//! + `make-cookie pound 50`
856//! + `make-cookie sparkle -mmm --color "green"`
857//! + `make-cookie finish 130 glaze 3`
858//!
859//! ### Optional subcommands
860//!
861//! Subcommands may be optional:
862//!
863//! ```
864//! # use structopt::StructOpt;
865//! #[derive(StructOpt)]
866//! struct Foo {
867//! file: String,
868//! #[structopt(subcommand)]
869//! cmd: Option<Command>
870//! }
871//!
872//! #[derive(StructOpt)]
873//! enum Command {
874//! Bar,
875//! Baz,
876//! Quux
877//! }
878//! ```
879//!
880//! ### External subcommands
881//!
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`].
885//!
886//! `structopt` provides it's own dedicated syntax for that:
887//!
888//! ```
889//! # use structopt::StructOpt;
890//! #[derive(Debug, PartialEq, StructOpt)]
891//! struct Opt {
892//! #[structopt(subcommand)]
893//! sub: Subcommands,
894//! }
895//!
896//! #[derive(Debug, PartialEq, StructOpt)]
897//! enum Subcommands {
898//! // normal subcommand
899//! Add,
900//!
901//! // `external_subcommand` tells structopt to put
902//! // all the extra arguments into this Vec
903//! #[structopt(external_subcommand)]
904//! Other(Vec<String>),
905//! }
906//!
907//! // normal subcommand
908//! assert_eq!(
909//! Opt::from_iter(&["test", "add"]),
910//! Opt {
911//! sub: Subcommands::Add
912//! }
913//! );
914//!
915//! assert_eq!(
916//! Opt::from_iter(&["test", "git", "status"]),
917//! Opt {
918//! sub: Subcommands::Other(vec!["git".into(), "status".into()])
919//! }
920//! );
921//!
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());
925//! ```
926//!
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.
931//!
932//! [`AppSettings::AllowExternalSubcommands`]: https://docs.rs/clap/2.32.0/clap/enum.AppSettings.html#variant.AllowExternalSubcommands
933//!
934//! ### Flattening subcommands
935//!
936//! It is also possible to combine multiple enums of subcommands into one.
937//! All the subcommands will be on the same level.
938//!
939//! ```
940//! # use structopt::StructOpt;
941//! #[derive(StructOpt)]
942//! enum BaseCli {
943//! Ghost10 {
944//! arg1: i32,
945//! }
946//! }
947//!
948//! #[derive(StructOpt)]
949//! enum Opt {
950//! #[structopt(flatten)]
951//! BaseCli(BaseCli),
952//! Dex {
953//! arg2: i32,
954//! }
955//! }
956//! ```
957//!
958//! ```shell
959//! cli ghost10 42
960//! cli dex 42
961//! ```
962//!
963//! ## Flattening
964//!
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`:
968//!
969//! ```
970//! # use structopt::StructOpt;
971//! #[derive(StructOpt)]
972//! struct Cmdline {
973//! /// switch on verbosity
974//! #[structopt(short)]
975//! verbose: bool,
976//! #[structopt(flatten)]
977//! daemon_opts: DaemonOpts,
978//! }
979//!
980//! #[derive(StructOpt)]
981//! struct DaemonOpts {
982//! /// daemon user
983//! #[structopt(short)]
984//! user: String,
985//! /// daemon group
986//! #[structopt(short)]
987//! group: String,
988//! }
989//! ```
990//!
991//! In this example, the derived `Cmdline` parser will support the options `-v`,
992//! `-u` and `-g`.
993//!
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.
997//!
998//! ## Custom string parsers
999//!
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:
1003//!
1004//! ```
1005//! # use structopt::StructOpt;
1006//! use std::num::ParseIntError;
1007//! use std::path::PathBuf;
1008//!
1009//! fn parse_hex(src: &str) -> Result<u32, ParseIntError> {
1010//! u32::from_str_radix(src, 16)
1011//! }
1012//!
1013//! #[derive(StructOpt)]
1014//! struct HexReader {
1015//! #[structopt(short, parse(try_from_str = parse_hex))]
1016//! number: u32,
1017//! #[structopt(short, parse(from_os_str))]
1018//! output: PathBuf,
1019//! }
1020//! ```
1021//!
1022//! There are five kinds of custom parsers:
1023//!
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` |
1032//!
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.).
1039//!
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`.
1043//!
1044//! When supplying a custom string parser, `bool` will not be treated specially:
1045//!
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)`
1051//!
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.
1055
1056// those mains are for a reason
1057#![allow(clippy::needless_doctest_main)]
1058
1059#[doc(hidden)]
1060pub use structopt_derive::*;
1061
1062use std::ffi::OsString;
1063
1064/// Re-exports
1065pub use clap;
1066
1067/// **This is NOT PUBLIC API**.
1068#[doc(hidden)]
1069pub use lazy_static;
1070
1071/// A struct that is converted from command line arguments.
1072pub trait StructOpt {
1073 /// Returns the corresponding `clap::App`.
1074 fn clap<'a, 'b>() -> clap::App<'a, 'b>;
1075
1076 /// Creates the struct from `clap::ArgMatches`. It cannot fail
1077 /// with a parameter generated by `clap` by construction.
1078 fn from_clap(matches: &clap::ArgMatches<'_>) -> Self;
1079
1080 /// Gets the struct from the command line arguments. Print the
1081 /// error message and quit the program in case of failure.
1082 fn from_args() -> Self
1083 where
1084 Self: Sized,
1085 {
1086 Self::from_clap(&Self::clap().get_matches())
1087 }
1088
1089 /// Gets the struct from any iterator such as a `Vec` of your making.
1090 /// Print the error message and quit the program in case of failure.
1091 ///
1092 /// **NOTE**: The first argument will be parsed as the binary name unless
1093 /// [`AppSettings::NoBinaryName`] has been used.
1094 ///
1095 /// [`AppSettings::NoBinaryName`]: https://docs.rs/clap/2.33.0/clap/enum.AppSettings.html#variant.NoBinaryName
1096 fn from_iter<I>(iter: I) -> Self
1097 where
1098 Self: Sized,
1099 I: IntoIterator,
1100 I::Item: Into<OsString> + Clone,
1101 {
1102 Self::from_clap(&Self::clap().get_matches_from(iter))
1103 }
1104
1105 /// Gets the struct from any iterator such as a `Vec` of your making.
1106 ///
1107 /// Returns a `clap::Error` in case of failure. This does *not* exit in the
1108 /// case of `--help` or `--version`, to achieve the same behavior as
1109 /// `from_iter()` you must call `.exit()` on the error value.
1110 ///
1111 /// **NOTE**: The first argument will be parsed as the binary name unless
1112 /// [`AppSettings::NoBinaryName`] has been used.
1113 ///
1114 /// [`AppSettings::NoBinaryName`]: https://docs.rs/clap/2.33.0/clap/enum.AppSettings.html#variant.NoBinaryName
1115 fn from_iter_safe<I>(iter: I) -> Result<Self, clap::Error>
1116 where
1117 Self: Sized,
1118 I: IntoIterator,
1119 I::Item: Into<OsString> + Clone,
1120 {
1121 Ok(Self::from_clap(&Self::clap().get_matches_from_safe(iter)?))
1122 }
1123}
1124
1125/// This trait is NOT API. **SUBJECT TO CHANGE WITHOUT NOTICE!**.
1126#[doc(hidden)]
1127pub trait StructOptInternal: StructOpt {
1128 fn augment_clap<'a, 'b>(app: clap::App<'a, 'b>) -> clap::App<'a, 'b> {
1129 app
1130 }
1131
1132 fn is_subcommand() -> bool {
1133 false
1134 }
1135
1136 fn from_subcommand<'a, 'b>(_sub: (&'b str, Option<&'b clap::ArgMatches<'a>>)) -> Option<Self>
1137 where
1138 Self: std::marker::Sized,
1139 {
1140 None
1141 }
1142}
1143
1144impl<T: StructOpt> StructOpt for Box<T> {
1145 fn clap<'a, 'b>() -> clap::App<'a, 'b> {
1146 <T as StructOpt>::clap()
1147 }
1148
1149 fn from_clap(matches: &clap::ArgMatches<'_>) -> Self {
1150 Box::new(<T as StructOpt>::from_clap(matches))
1151 }
1152}
1153
1154impl<T: StructOptInternal> StructOptInternal for Box<T> {
1155 #[doc(hidden)]
1156 fn is_subcommand() -> bool {
1157 <T as StructOptInternal>::is_subcommand()
1158 }
1159
1160 #[doc(hidden)]
1161 fn from_subcommand<'a, 'b>(sub: (&'b str, Option<&'b clap::ArgMatches<'a>>)) -> Option<Self> {
1162 <T as StructOptInternal>::from_subcommand(sub).map(Box::new)
1163 }
1164
1165 #[doc(hidden)]
1166 fn augment_clap<'a, 'b>(app: clap::App<'a, 'b>) -> clap::App<'a, 'b> {
1167 <T as StructOptInternal>::augment_clap(app)
1168 }
1169}