rust rustc 1.48.0std؝-6bf3f16f340782cacoreƞ-3375e4f89d420e7acompiler_builtins-f74b197469e67088rustc_std_workspace_core扪ڹ8-5e0675f526ef5c6ballocץޯČ-1ebf406bd4ea5769libcɄ-dfbef8c525de0186unwindܽ݇!-bd645b20c6c7b56dcfg_ifшC-b9e1e523c0c29a77 hashbrownǰ-c6632ca171f954ddrustc_std_workspace_allocW-b5bfd0198c7b740drustc_demangleة-3ac2d0878c297d42 addr2lineƄ-12740563628e601fgimlin-0ac82a1e1820dd21object»-af517d7f13e7c960 miniz_oxide֕㵤 -a2ba33c985785afeadler˯-3f6e9f8f4afbea6d panic_unwindի-13f3099d50c21bc6structopt_derive͞Q-dede3a01a8324980clap󟄸-a097ef7e83284276 ansi_term-1164fd4433ce14a8attyӌ-7ebf4c7664ea8481libcٕ{-39fcc1944b95b078bitflagsӳU-69acfc798c96d00cstrsim̤욘5-f824bb4277ee233dtextwrap⠮-6e40a0f62398dd02 unicode_widthஒK-ad20b503d31ef93fvec_map넪q-2ab22218ef725bf2 lazy_staticؗȊd-567e3c296460ef14 Ao'o|.;tL^D$QstdX^c{s9#Zi.hG{녯LҮq̛.T9:c\06^3>ASfU\vI !) StructOpth/n2Q@)clapbLB)3'ajq$'bgh#S0I(\ from_clapzSFJ1k from_argsM$6 ?LWzdjfrom_args_safejXiy"LFZW\ #rΉ@">ԅ from_iter*W@DֳI8#F'G7from_iter_safe']TŸ6giaIc!腚*6/^PXStructOptInternalIҙ8e augment_clapAÃt 'aM;N_;ug'b8г*1ҝ is_subcommandP y*톋from_subcommandYCH5a+Dt'ahp+O-@S1'bEX *e^E 5 tTo7^3ل+=clapu̽a'a} 5g-]2.'b n *ke%3 from_clapt"Qυ:ؓ+fd~!Tِ]]MjVA! is_subcommandt=qayH38ۮ!from_subcommandjjG|I$'a.63*#w&5P$'bXrs9| <! augment_clapydHC0Q''a+=Dt1G7X''bPep(㸩 ,L,tWz̐sY_OfIc PfYթռT^~zUGAVu^+|pU!U OsString5clap lazy_static  StructOptKѫideny missing_docs forbid unsafe_code @ This crate defines the `StructOpt` trait and its custom derive.C ## Features8 If you want to disable all the `clap` features (colors,;C suggestions, ..) add `default-features = false` to the `structopt`F dependency: ```toml  [dependencies]: structopt = { version = "0.3", default-features = false }= ```: Support for [`paw`](https://github.com/rust-cli/paw) (the=C `Command line argument paw-rser abstraction for main`) is disabledF= by default, but can be enabled in the `structopt` dependency@ with the feature `paw`: ```toml  [dependencies]6 structopt = { version = "0.3", features = [ "paw" ] }9 paw = "1.0" ``` # Table of Contents8 - [How to `derive(StructOpt)`](#how-to-derivestructopt); - [Attributes](#attributes) " - [Raw methods](#raw-methods) %* - [Magical methods](#magical-methods) - - Arguments  - [Type magic](#type-magic) #> - [Specifying argument types](#specifying-argument-types) A( - [Default values](#default-values) +& - [Help messages](#help-messages) )F - [Environment variable fallback](#environment-variable-fallback) I& - [Skipping fields](#skipping-fields) ) - [Subcommands](#subcommands) !4 - [Optional subcommands](#optional-subcommands) 74 - [External subcommands](#external-subcommands) 78 - [Flattening subcommands](#flattening-subcommands) ; - [Flattening](#flattening)2 - [Custom string parsers](#custom-string-parsers)5 - [Generics](#generics) ## How to `derive(StructOpt)`!" First, let's look at the example:% ``` use std::path::PathBuf; use structopt::StructOpt; #[derive(Debug, StructOpt)]I #[structopt(name = "example", about = "An example of StructOpt usage.")]L struct Opt { /// Activate debug modeP // short and long flags (-d, --debug) will be deduced from the field's nameS #[structopt(short, long)]! debug: bool, /// Set speed< // we don't want to name it "speed", need to look smart?G #[structopt(short = "v", long = "velocity", default_value = "42")]J speed: f64, /// Input file% #[structopt(parse(from_os_str))]( input: PathBuf,+ /// Output file, stdout if not present.% #[structopt(parse(from_os_str))]( output: Option, 9 /// Where to write the output: to `stdout` or `file`< #[structopt(short)] out_type: String,B /// File name: only required when `out-type` is set to `file`EA #[structopt(name = "FILE", required_if("out-type", "file"))]D file_name: Option," } fn main() { # /*  let opt = Opt::from_args();# # */ D # let opt = Opt::from_iter(&["binary", "-o", "stdout", "input"]);G println!("{:?}", opt); } ```E So `derive(StructOpt)` tells Rust to generate a command line parser,H2 and the various `structopt` attributes are simply5 used for additional parameters.#: First, define a struct, whatever its name. This structure=C corresponds to a `clap::App`, its fields correspond to `clap::Arg`F. (unless they're [subcommands](#subcommands)),1Y and you can adjust these apps and args by `#[structopt(...)]` [attributes](#attributes).\ **Note:**  _________________J Keep in mind that `StructOpt` trait is more than just `from_args` method.MG It has a number of additional features, including access to underlyingJ- `clap::App` via `StructOpt::clap()`. See the09 [trait's reference documentation](trait.StructOpt.html).< _________________ ## Attributes J You can control the way `structopt` translates your struct into an actual M= [`clap::App`] invocation via `#[structopt(...)]` attributes. @!) The attributes fall into two categories:!,9 - `structopt`'s own [magical methods](#magical-methods).!<"< They are used by `structopt` itself. They come mostly in"?D `attr = ["whatever"]` form, but some `attr(args...)` also exist."G#$ - [`raw` attributes](#raw-methods).#'#: They represent explicit `clap::Arg/App` method calls.#=\ They are what used to be explicit `#[structopt(raw(...))]` attrs in pre-0.3 `structopt`$_$L Every `structopt attribute` looks like comma-separated sequence of methods:$O ```%- # #[derive(structopt::StructOpt)] struct S {%0 #% #[structopt(%8 short, // method with no arguments - always magical&;8 long = "--long-option", // method with one argument&;A required_if("out", "file"), // method with one and more args'DX parse(from_os_str = path::to::parser) // some magical methods have their own syntax'[ )]( #(Y # s: () } mod path { pub(crate) mod to { pub(crate) fn parser(_: &std::ffi::OsStr) {} }}(\ ```))I `#[structopt(...)]` attributes can be placed on top of `struct`, `enum`,)LJ `struct` field or `enum` variant. Attributes on top of `struct` or `enum`)MK represent `clap::App` method calls, field or variant attributes correspond*N to `clap::Arg` method calls.+ +8 In other words, the `Opt` struct from the example above+;. will be turned into this (*details omitted*):+1, ```,# # use structopt::clap::{Arg, App};,& App::new("example"), .version("0.2.0"),- .about("An example of StructOpt usage."),0 .arg(Arg::with_name("debug")- ! .help("Activate debug mode")-$ .short("debug")- .long("debug")). .arg(Arg::with_name("speed").  .help("Set speed"). .short("v"). .long("velocity"). .default_value("42"))/ // and so on/ # ;/ ```// ## Raw methods//Q They are the reason why `structopt` is so flexible. **Every and each method from/T( `clap::App/Arg` can be used this way!**0+0 ```0- # #[derive(structopt::StructOpt)] struct S {00 #1 #[structopt(1@ global = true, // name = arg form, neat for one-arg methods1C> required_if("out", "file") // name(arg1, arg2, ...) form.2A )]2 #2 # s: String }2 ```22J The first form can only be used for methods which take only one argument.2MO The second form must be used with multi-arg methods, but can also be used with3R9 single-arg methods. These forms are identical otherwise.4<4= As long as `method_name` is not one of the magical methods -4@/ it will be translated into a mere method call.525 **Note:**5  _________________55= "Raw methods" are direct replacement for pre-0.3 structopt's5@V `#[structopt(raw(...))]` attributes, any time you would have used a `raw()` attribute6Y) in 0.2 you should use raw method in 0.3.7,7V Unfortunately, old raw attributes collide with `clap::Arg::raw` method. To explicitly7YU warn users of this change we allow `#[structopt(raw())]` only with `true` or `false`8XI literals (this method is supposed to be called only with `true` anyway).8L __________________99 ## Magical methods99T They are the reason why `structopt` is so easy to use and convenient in most cases.9WI Many of them have defaults, some of them get used even if not mentioned.:L;T Methods may be used on "top level" (on top of a `struct`, `enum` or `enum` variant);WU and/or on "field-level" (on top of a `struct` field or *inside* of an enum variant).;XW Top level (non-magical) methods correspond to `App::method` calls, field-level methods! field: u32> }>> #[structopt(top_level)]> enum Bar {> #[structopt(top_level)]> Pineapple {?" #[structopt(field_level)]?% chocolate: String? },? ? #[structopt(top_level)]? Orange,@ }@ ```@@ - `name`: `[name = expr]`@$ - On top level: `App::new(expr)`.@'@[ The binary name displayed in help messages. Defaults to the crate name given by Cargo.A^A, - On field-level: `Arg::with_name(expr)`.A/BX The name for the argument the field stands for, this name appears in help messages.B[7 Defaults to a name, deduced from a field, see alsoB:0 [`rename_all`](#specifying-argument-types).C3C% - `version`: `[version = "version"]`C(DT Usable only on top level: `App::version("version" or env!(CARGO_PKG_VERSION))`.DWD, The version displayed in help messages.D/P Defaults to the crate version given by Cargo. If `CARGO_PKG_VERSION` is notESB set no `.version()` calls will be generated unless requested.EEF - `no_version`: `no_version`F FH Usable only on top level. Prevents default `App::version` call, i.eFK- when no `version = "version"` mentioned.G0G" - `author`: `author [= "author"]`G%HR Usable only on top level: `App::author("author" or env!(CARGO_PKG_AUTHORS))`.HUHI Author/maintainer of the binary, this name appears in help messages.HL^ Defaults to the crate author given by cargo, but only when `author` explicitly mentioned.IaJ - `about`: `about [= "about"]`J"JT Usable only on top level: `App::about("about" or env!(CARGO_PKG_DESCRIPTION))`.JWK? Short description of the binary, appears in help messages.KB6 Defaults to the crate description given by cargo,K90 but only when `about` explicitly mentioned.L3LF - [`short`](#specifying-argument-types): `short [= "short-opt-name"]`LIM Usable only on field-level.M#MC - [`long`](#specifying-argument-types): `long [= "long-opt-name"]`MFN Usable only on field-level.N#NJ - [`default_value`](#default-values): `default_value [= "default value"]`NMO Usable only on field-level.O#O. - [`rename_all`](#specifying-argument-types):O1c [`rename_all = "kebab"/"snake"/"screaming-snake"/"camel"/"pascal"/"verbatim"/"lower"/"upper"]`OfP. Usable both on top level and field level.P1QL - [`parse`](#custom-string-parsers): `parse(type [= path::to::parser::fn])`QOQ Usable only on field-level.Q#R. - [`skip`](#skipping-fields): `skip [= expr]`R1R Usable only on field-level.R#R& - [`flatten`](#flattening): `flatten`R)S: Usable on field-level or single-typed tuple variants.S=S- - [`subcommand`](#subcommands): `subcommand`S0T Usable only on field-level.T#T1 - [`external_subcommand`](#external-subcommands)T4T" Usable only on enum variants.T%UA - [`env`](#environment-variable-fallback): `env [= str_literal]`UDU Usable only on field-level.U#V< - [`rename_all_env`](#auto-deriving-environment-variables):V?g [`rename_all_env = "kebab"/"snake"/"screaming-snake"/"camel"/"pascal"/"verbatim"/"lower"/"upper"]`VjW. Usable both on top level and field level.W1WZ - [`verbatim_doc_comment`](#doc-comment-preprocessing-and-structoptverbatim_doc_comment):W] `verbatim_doc_comment`XX. Usable both on top level and field level.X1Y ## Type magicYYJ One of major things that makes `structopt` so awesome is it's type magic.YMX Do you want optional positional argument? Use `Option`! Or perhaps optional argumentZ[H that optionally takes value (`[--opt=[val]]`)? Use `Option>`!ZK[B Here is the table of types and `clap` methods they correspond to:[E[t Type | Effect | Added method call to `clap::Arg`[wy -----------------------------|---------------------------------------------------|--------------------------------------\|y `bool` | `true` if the flag is present | `.takes_value(false).multiple(false)`]|x `Option` | optional positional argument or option | `.takes_value(true).multiple(false)`^{ `Option>` | optional option with optional value | `.takes_value(true).multiple(false).min_values(0).max_values(1)`_w `Vec` | list of options or the other positional arguments | `.takes_value(true).multiple(true)`az `Option` | optional list of options | `.takes_values(true).multiple(true).min_values(0)`a `T: FromStr` | required option or positional argument | `.takes_value(true).multiple(false).required(!has_default)`cdA The `FromStr` trait is used to convert the argument to the givendD? type, and the `Arg::validator` method is set to a method usingdBC `to_string()` (`FromStr::Err` must implement `std::fmt::Display`).eFJ If you would like to use a custom string parser other than `FromStr`, seeeM9 the [same titled section](#custom-string-parsers) below.f<f **Important:**f _________________gS Pay attention that *only literal occurrence* of this types is special, for examplegV@ `Option` is special while `::std::option::Option` is not.gChD If you need to avoid special casing you can make a `type` alias andhG" use it in place of the said type.i% _________________ii **Note:**i  _________________iT `bool` cannot be used as positional argument unless you provide an explicit parser.iWP If you need a positional bool, for example to parse `true` or `false`, you mustjSW annotate the field with explicit [`#[structopt(parse(...))]`](#custom-string-parsers).kZ _________________kl, Thus, the `speed` argument is generated as:l/l ```lN # fn parse_validator(_: String) -> Result<(), String> { unimplemented!() }lQ clap::Arg::with_name("speed")m! .takes_value(true)m .multiple(false)m .required(false)m' .validator(parse_validator::)n* .short("v")n .long("velocity")n .help("Set speed")n .default_value("42");o ```oo ## Specifying argument typeso o@ There are three types of arguments that can be supplied to eachoC (sub-)command:pp - short (e.g. `-h`),p - long (e.g. `--help`)p - and positional.pp@ Like clap, structopt defaults to creating positional arguments.pCq? If you want to generate a long argument you can specify eitherqBB `long = $NAME`, or just `long` to get a long flag generated usingrEB the field name. The generated casing style can be modified usingrEC the `rename_all` attribute. See the `rename_all` example for more.sFs> For short arguments, `short` will use the first letter of thesA? field name by default, but just like the long option it's alsotB; possible to use a custom letter through `short = $LETTER`.t>uE If an argument is renamed using `name = $NAME` any following call touH) `short` or `long` will use the new name.u,vD **Attention**: If these arguments are used without an explicit namevGD the resulting flag is going to be renamed using `kebab-case` if thevGF `rename_all` attribute was not specified previously. The same is truewII for subcommands with implicit naming through the related data structure.wLx ```x use structopt::StructOpt;xx #[derive(StructOpt)]x( #[structopt(rename_all = "kebab-case")]y+ struct Opt {yG /// This option can be specified with something like `--foo-optionyJ' /// value` or `--foo-option=value`z* #[structopt(long)]z foo_option: String,zzI /// This option can be specified with something like `-b value` (butzL# /// not `--bar-option value`).{& #[structopt(short)]{ bar_option: String,||I /// This option can be specified either `--baz value` or `-z value`.|L, #[structopt(short = "z", long = "baz")]|/ baz_option: String,}}C /// This option can be specified either by `--custom value` or}F /// `-c value`.~/ #[structopt(name = "custom", long, short)]~2 custom_option: String,~~L /// This option is positional, meaning it is the first unadorned string~O4 /// you provide (multiple others could follow).7 my_positional: String,I /// This option is skipped and will be filled with the default valueL' /// for its type (in this case 0).* #[structopt(skip)] skipped: u32, }сׁ # Opt::from_iter(ہZ # &["test", "--foo-option", "", "-b", "", "--baz", "", "--custom", "", "positional"]);] ```ςׂ ## Default valuesۂQ In clap, default values for options can be specified via [`Arg::default_value`].Tʃ( Of course, you can use as a raw method:΃+ ``` # use structopt::StructOpt; #[derive(StructOpt)] struct Opt {+ #[structopt(default_value = "", long)]̄. prefix: String, } ```O This is quite mundane and error-prone to type the `"..."` default by yourself,RH especially when the Rust ecosystem uses the [`Default`] trait for that.KT It would be wonderful to have `structopt` to take the `Default_default` and fill itĆW+ for you. And yes, `structopt` can do that..ˇC Unfortunately, `default_value` takes `&str` but `Default::default`χFE gives us some `Self` value. We need to map `Self` to `&str` somehow.H߈8 `structopt` solves this problem via [`ToString`] trait.;X To be able to use auto-default the type must implement *both* `Default` and `ToString`:[ ``` # use structopt::StructOpt; #[derive(StructOpt)] struct Opt {ĊJ // just leave the `= "..."` part and structopt will figure it for youՊM& #[structopt(default_value, long)])I prefix: String, // `String` implements both `Default` and `ToString`͋L } ```F [`Default`]: https://doc.rust-lang.org/std/default/trait.Default.htmlIG [`ToString`]: https://doc.rust-lang.org/std/string/trait.ToString.htmlJ^ [`Arg::default_value`]: https://docs.rs/clap/2.33.0/clap/struct.Arg.html#method.default_valuea ## Help messages= In clap, help messages for the whole binary can be specifiedĎ@? via [`App::about`] and [`App::long_about`] while help messagesBU for individual arguments can be specified via [`Arg::help`] and [`Arg::long_help`]".ȏX< `long_*` variants are used when user calls the program with?G `--help` and "short" variants are used with `-h` flag. In `structopt`,J? you can use them via [raw methods](#raw-methods), for example:B ``` # use structopt::StructOpt; #[derive(StructOpt)]B #[structopt(about = "I am a program and I work, just pass `-h`")]E struct Foo {? #[structopt(short, help = "Pass `-h` and you'll see me!")]B bar: String,֓ } ```A For convenience, doc comments can be used instead of raw methodsD1 (this example works exactly like the one above):”4 ``` # use structopt::StructOpt; #[derive(StructOpt)]. /// I am a program and I work, just pass `-h`1 struct Foo {% /// Pass `-h` and you'll see me!( bar: String, } ```ǖϖB Doc comments on [top-level](#magical-methods) will be turned intoӖEJ `App::about/long_about` call (see below), doc comments on field-level areM `Arg::help/long_help` calls.  **Important:** _________________- Raw methods have priority over doc comments!0J **Top level doc comments always generate `App::about/long_about` calls!**MP If you really want to use the `App::help/long_help` methods (you likely don't),SS use a raw method to override the `App::about` call generated from the doc comment.V __________________ ### `long_help` and `--help` Y A message passed to [`App::long_about`] or [`Arg::long_help`] will be displayed whenever\I your program is called with `--help` instead of `-h`. Of course, you canL? use them via raw methods as described [above](#help-messages).ќBB The more convenient way is to use a so-called "long" doc comment:Eޝ ``` # use structopt::StructOpt; #[derive(StructOpt)] /// Hi there, I'm Robo! ///8 /// I like beeping, stumbling, eating your electricity,Ǟ;3 /// and making records of you singing in a shower.6* /// Pay up, or I'll upload it to youtube!- struct Robo { /// Call my brother SkyNet.# /// 8 /// I am artificial superintelligence. I won't rest;7 /// until I'll have destroyed humanity. Enjoy your:. /// pathetic existence, you mere mortals.1 #[structopt(long)]ӡ kill_all_humans: bool, } ```, A long doc comment consists of three parts:/ * Short summaryϢ! * A blank line (whitespace only)$% * Detailed description, all the rest(G In other words, "long" doc comment consists of two or more paragraphs,JL with the first being a summary and the rest being the detailed description.OФJ **A long comment will result in two method calls**, `help()` andԤMI `long_help()`, so clap will display the summary with `-h`L4 and the whole help message on `--help` (see below).7B So, the example above will be turned into this (details omitted):E ``` clap::App::new("")" .about("Hi there, I'm Robo!")%* .long_about("Hi there, I'm Robo!\n\n\-F I like beeping, stumbling, eating your electricity,\IA and making records of you singing in a shower.\D8 Pay up or I'll upload it to youtube!"); // args... # ;ĩ ```̩ԩ7 ### `-h` vs `--help` (A.K.A `help()` vs `long_help()`)ة:+ The `-h` flag is not the same as `--help`..ƪO -h corresponds to `Arg::help/App::about` and requests short "summary" messagesʪRO while --help corresponds to `Arg::long_help/App::long_about` and requests moreR detailed, descriptive messages.#A It is entirely up to `clap` what happens if you used only one ofDP [`Arg::help`]/[`Arg::long_help`], see `clap`'s documentation for these methods.ݬSB As of clap v2.33, if only a short message ([`Arg::help`]) or onlyEB a long ([`Arg::long_help`]) message is provided, clap will use itEF for both -h and --help. The same logic applies to `about/long_about`.IG ### Doc comment preprocessing and `#[structopt(verbatim_doc_comment)]`JگU `structopt` applies some preprocessing to doc comments to ease the most common uses:ޯXE * Strip leading and trailing whitespace from every line, if present.H6 * Strip leading and trailing blank lines, if present.9±G * Interpret each group of non-empty lines as a word-wrapped paragraph.ƱJH We replace newlines within paragraphs with spaces to allow the outputK* to be re-wrapped to the terminal width.-Q * Strip any excess blank lines so that there is exactly one per paragraph break.T5 * If the first paragraph ends in exactly one period,8V remove the trailing period (i.e. strip trailing periods but not trailing ellipses).YW Sometimes you don't want this preprocessing to apply, for example the comment containsZM some ASCII art or markdown tables, you would need to preserve LFs along with޵PZ blank lines and the leading/trailing whitespace. You can ask `structopt` to preserve them]4 via `#[structopt(verbatim_doc_comment)]` attribute.7ŷW **This attribute must be applied to each field separately**, there's no global switch.ɷZ **Important:** ______________N Keep in mind that `structopt` will *still* remove one leading space from eachθQF line, even if this attribute is present, to allow for a space betweenI `///` and the content.J Also, `structopt` will *still* remove leading and trailing blank lines soM these formats are equivalent:׺! ``` /** This is a doc comment Hello! */  /** This is a doc commentۻ Hello!߻  */ /// This is a doc comment /// /// Hello! # # mod m {} ``` ______________ǼڼN [`App::about`]: https://docs.rs/clap/2/clap/struct.App.html#method.about޼QS [`App::long_about`]: https://docs.rs/clap/2/clap/struct.App.html#method.long_aboutVM [`Arg::help`]: https://docs.rs/clap/2/clap/struct.Arg.html#method.helpPR [`Arg::long_help`]: https://docs.rs/clap/2/clap/struct.Arg.html#method.long_helpؾU! ## Environment variable fallback$׿S It is possible to specify an environment variable fallback option for an argumentsۿVJ so that its value is taken from the specified environment variable if notM given through the command-line:# ``` # use structopt::StructOpt; #[derive(StructOpt)] struct Foo {7 #[structopt(short, long, env = "PARAMETER_VALUE")]: parameter_value: String,  } ```Y By default, values from the environment are shown in the help output (i.e. when invoking\ `--help`): ```shell  $ cargo run -- --help ... OPTIONS: O -p, --parameter-value [env: PARAMETER_VALUE=env_value]R ```O In some cases this may be undesirable, for example when being used for passingRT credentials or secret tokens. In those cases you can use `hide_env_values` to avoidW0 having structopt emit the actual secret values:3 ``` # use structopt::StructOpt; #[derive(StructOpt)] struct Foo {P #[structopt(long = "secret", env = "SECRET_VALUE", hide_env_values = true)]S secret_value: String, } ```( ### Auto-deriving environment variables+R Environment variables tend to be called after the corresponding `struct`'s field,UT as in example above. The field is `secret_value` and the env var is "SECRET_VALUE";W2 the name is the same, except casing is different.5A It's pretty tedious and error-prone to type the same name twice,D/ so you can ask `structopt` to do that for you.2 ``` # use structopt::StructOpt; #[derive(StructOpt)] struct Foo {' #[structopt(long = "secret", env)]* secret_value: String, } ```T It works just like `#[structopt(short/long)]`: if `env` is not set to some concreteWM value the value will be derived from the field's name. This is controlled byP `#[structopt(rename_all_env)]`.#F `rename_all_env` works exactly as `rename_all` (including overriding)II except default casing is `SCREAMING_SNAKE_CASE` instead of `kebab-case`.L ## Skipping fieldsG Sometimes you may want to add a field to your `Opt` struct that is notJK a command line option and `clap` should know nothing about it. You can askNH `structopt` to skip the field entirely via `#[structopt(skip = value)]`K+ (`value` must implement `Into`).O or `#[structopt(skip)]` if you want assign the field with `Default::default()`R8 (obviously, the field's type must implement `Default`).; ``` # use structopt::StructOpt; #[derive(StructOpt)] pub struct Opt { #[structopt(long, short)]! number: u32,? // these fields are to be assigned with Default::default()B #[structopt(skip)] k: String, #[structopt(skip)] v: Vec,' // these fields get set explicitly*' #[structopt(skip = vec![1, 2, 3])]* k2: Vec,@ #[structopt(skip = "cake")] // &str implements IntoC v2: String, } ``` ## SubcommandsD Some applications, especially large ones, split their functionalityGM through the use of "subcommands". Each of these act somewhat like a separateP* command, but is part of the larger group.-E One example is `git`, which has subcommands such as `add`, `commit`,H$ and `clone`, to mention just a few.'J `clap` has this functionality, and `structopt` supports it through enums:M ``` # use structopt::StructOpt; # use std::path::PathBuf; #[derive(StructOpt)]3 #[structopt(about = "the stupid content tracker")]6 enum Git { Add {  #[structopt(short)] interactive: bool, #[structopt(short)] patch: bool,) #[structopt(parse(from_os_str))], files: Vec,  },  Fetch { #[structopt(long)] dry_run: bool, #[structopt(long)] all: bool,$ repository: Option,' },  Commit { #[structopt(short)]! message: Option,$ #[structopt(short)] all: bool, },  } ```F Using `derive(StructOpt)` on an enum instead of a struct will produceIF a `clap::App` that only takes subcommands. So `git add`, `git fetch`,IB and `git commit` would be commands allowed for the above example.EG `structopt` also provides support for applications where certain flagsJA need to apply to all subcommands, as well as nested subcommands:D ``` # use structopt::StructOpt; #[derive(StructOpt)] struct MakeCookie {S #[structopt(name = "supervisor", default_value = "Puck", long = "supervisor")]V supervising_faerie: String,#6 /// The faerie tree this cookie is being made in.9 tree: Option,J #[structopt(subcommand)] // Note that we mark a field as a subcommandM cmd: Command, } #[derive(StructOpt)] enum Command {2 /// Pound acorns into flour for cookie dough.5 Pound { acorns: u32, }, 7 /// Add magical sparkles -- the secret ingredient!: Sparkle {5 #[structopt(short, parse(from_occurrences))]8 magicality: u64, #[structopt(short)] color: String, },  Finish(Finish), }F // Subcommand can also be externalized by using a 1-uple enum variantI #[derive(StructOpt)] struct Finish { #[structopt(short)] time: u32,J #[structopt(subcommand)] // Note that we mark a field as a subcommandM finish_type: FinishType,  } // subsubcommand! #[derive(StructOpt)] enum FinishType { Glaze { applications: u32, },  Powder { flavor: String, dips: u32, }  } ```M Marking a field with `structopt(subcommand)` will add the subcommands of thePL designated enum to the current `clap::App`. The designated enum *must* alsoOF be derived `StructOpt`. So the above example would take the followingI commands:  + `make-cookie pound 50`- + `make-cookie sparkle -mmm --color "green"`0# + `make-cookie finish 130 glaze 3`& ### Optional subcommands Subcommands may be optional:  ``` # use structopt::StructOpt; #[derive(StructOpt)] struct Foo { file: String, #[structopt(subcommand)]  cmd: Option, } #[derive(StructOpt)] enum Command { Bar,  Baz,  Quux,  } ``` ### External subcommandsI Sometimes you want to support not only the set of well-known subcommandsLK but you also want to allow other, user-driven subcommands. `clap` supportsN4 this via [`AppSettings::AllowExternalSubcommands`].79 `structopt` provides it's own dedicated syntax for that:< ``` # use structopt::StructOpt;' #[derive(Debug, PartialEq, StructOpt)]* struct Opt { #[structopt(subcommand)]  sub: Subcommands, }' #[derive(Debug, PartialEq, StructOpt)]* enum Subcommands { // normal subcommand Add, 4 // `external_subcommand` tells structopt to put7- // all the extra arguments into this Vec0& #[structopt(external_subcommand)]) Other(Vec), } // normal subcommand assert_eq!(& Opt::from_iter(&["test", "add"]),) Opt {  sub: Subcommands::Add! }  ); assert_eq!(0 Opt::from_iter(&["test", "git", "status"]),3 Opt { E sub: Subcommands::Other(vec!["git".into(), "status".into()])H }  );J // Please note that if you'd wanted to allow "no subcommands at all" caseM9 // you should have used `sub: Option` above<2 assert!(Opt::from_iter_safe(&["test"]).is_err());5 ```@ In other words, you just add an extra tuple variant marked withC8 `#[structopt(subcommand)]`, and its type must be either;S `Vec` or `Vec`. `structopt` will detect `String` in this contextV and use appropriate `clap` API.# [`AppSettings::AllowExternalSubcommands`]: https://docs.rs/clap/2.32.0/clap/enum.AppSettings.html#variant.AllowExternalSubcommands ### Flattening subcommandsG It is also possible to combine multiple enums of subcommands into one.J/ All the subcommands will be on the same level.ف2 ``` # use structopt::StructOpt; #[derive(StructOpt)] enum BaseCli {т Ghost10 { arg1: i32, }  } #[derive(StructOpt)] enum Opt { #[structopt(flatten)]Ƀ BaseCli(BaseCli), Dex {  arg2: i32, },  } ``` ```shellÄ  cli ghost10 42Є cli dex 42 ``` ## FlatteningF It can sometimes be useful to group related arguments in a substruct,IK while keeping the command-line interface flat. In these cases you can markޅNH a field as `flatten` and give it another type that derives `StructOpt`:K ``` # use structopt::StructOpt; #[derive(StructOpt)] struct Cmdline { /// switch on verbosityӇ #[structopt(short)] verbose: bool, #[structopt(flatten)] daemon_opts: DaemonOpts,Ĉ  } #[derive(StructOpt)] struct DaemonOpts { /// daemon user #[structopt(short)] user: String,ԉ /// daemon group #[structopt(short)] group: String, } ```ĊM In this example, the derived `Cmdline` parser will support the options `-v`,ȊP `-u` and `-g`.H This feature also makes it possible to define a `StructOpt` struct in aKL library, parse the corresponding arguments in the main argument parser, andO< pass off this struct to a handler provided by that library.̌? ## Custom string parsersI If the field type does not have a `FromStr` implementation, or you wouldLF like to provide a custom parsing scheme other than `FromStr`, you mayI= provide a custom string parser using `parse(...)` like this:Ȏ@ ``` # use structopt::StructOpt; use std::num::ParseIntError;  use std::path::PathBuf;֏8 fn parse_hex(src: &str) -> Result {;! u32::from_str_radix(src, 16)$ }אݐ #[derive(StructOpt)] struct HexReader {9 #[structopt(short, parse(try_from_str = parse_hex))]< number: u32,Α, #[structopt(short, parse(from_os_str))]/ output: PathBuf, } ```( There are five kinds of custom parsers:+` | Kind | Signature | Default |c` |-------------------|---------------------------------------|---------------------------------|ғc` | `from_str` | `fn(&str) -> T` | `::std::convert::From::from` |c` | `try_from_str` | `fn(&str) -> Result` | `::std::str::FromStr::from_str` |c` | `from_os_str` | `fn(&OsStr) -> T` | `::std::convert::From::from` |c` | `try_from_os_str` | `fn(&OsStr) -> Result` | (no default function) |c` | `from_occurrences`| `fn(u64) -> T` | `value as T` |Ɨc` | `from_flag` | `fn(bool) -> T` | `::std::convert::From::from` |cJ The `from_occurrences` parser is special. Using `parse(from_occurrences)`MJ results in the _number of flags occurrences_ being stored in the relevantML field or being passed to the supplied function. In other words, it convertsO4 something like `-vvv` to `3`. This is equivalent to7L `.takes_value(false).multiple(true)`. Note that the default parser can onlyOC be used with fields of integer types (`u8`, `usize`, `i64`, etc.).F͜D The `from_flag` parser is also special. Using `parse(from_flag)` orќGK `parse(from_flag = some_func)` will result in the field being treated as aN+ flag even if it does not have type `bool`..M When supplying a custom string parser, `bool` will not be treated specially:PC Type | Effect | Added method call to `clap::Arg`FH ------------|-------------------|--------------------------------------KG `Option` | optional argument | `.takes_value(true).multiple(false)`JF `Vec` | list of arguments | `.takes_value(true).multiple(true)`ΠI^ `T` | required argument | `.takes_value(true).multiple(false).required(!has_default)`aJ In the `try_from_*` variants, the function will run twice on valid input:MF once to validate, and once to parse. Hence, make sure the function is̢I side-effect-free. ## GenericsJ Generic structs and enums can be used. They require explicit trait boundsģMK on any generic types that will be used by the `StructOpt` derive macro. InNK some cases, associated types will require additional bounds. See the usageN+ of `FromStr` below for an example of this..ߥ ``` # use structopt::StructOpt; use std::{fmt, str::FromStr};!( // a struct with single custom argument+ #[derive(StructOpt)]ݦV struct GenericArgs where ::Err: fmt::Display + fmt::Debug {Y generic_arg_1: String,Ч generic_arg_2: String, custom_arg_1: T, } ``` or ```Ĩ # use structopt::StructOpt;̨= // a struct with multiple custom arguments in a substructure@ #[derive(StructOpt)]# struct GenericArgs {Ʃ& generic_arg_1: String, generic_arg_2: String, #[structopt(flatten)] custom_args: T,ɪ } ```allow clippy needless_doctest_main(!٭ ϭ8 A struct that is converted from command line arguments.; Self'3 Returns [`clap::App`] corresponding to the struct.6 Self 'a 'b 'a 'b'a 'b   matches 5H Builds the struct from [`clap::ArgMatches`]. It's guaranteed to succeedѮKQ if `matches` originates from an `App` generated by [`StructOpt::clap`] called onT( the same type, otherwise it must panic.+  vK Builds the struct from the command line arguments ([`std::env::args_os`]).N] Calls [`clap::Error::exit`] on failure, printing the error message and aborting the program.` ̲     v  ,,v, ,,, vK Builds the struct from the command line arguments ([`std::env::args_os`]).Ne Unlike [`StructOpt::from_args`], returns [`clap::Error`] on failure instead of aborting the program,h6 so calling [`.exit`][clap::Error::exit] is up to you.ٴ9 ,    , #b / (ֶֶݶb,b b#iter B Gets the struct from any iterator such as a `Vec` of your making.EA Print the error message and quit the program in case of failure.DF **NOTE**: The first argument will be parsed as the binary name unlessI3 [`clap::AppSettings::NoBinaryName`] has been used.̸6 II(ҹ (5 ʀ $$$$$$#    ƺƺƺƺ# ʀʺʺ$$55Ѻ˺ѺѺѺҺѺѺѺѺ5$5$5#5 5ƺѺiteriterھ žB Gets the struct from any iterator such as a `Vec` of your making.غEJ Returns a [`clap::Error`] in case of failure. This does *not* exit in theMA case of `--help` or `--version`, to achieve the same behavior asDg [`from_iter()`][StructOpt::from_iter] you must call [`.exit()`][clap::Error::exit] on the error value.żjF **NOTE**: The first argument will be parsed as the binary name unlessI3 [`clap::AppSettings::NoBinaryName`] has been used.6Ⱦ I׾ Àɿڿ ;;;;;**))(    ž  ( ʀ  )) )  ))Ok)**;  ;)  Err        )      ?Ok? ž))ھ?;?*?*?)?)?(? ???)iterھerr val)ž> This trait is NOT API. **SUBJECT TO CHANGE WITHOUT NOTICE!**.Adoc hiddenSelf  app X 'a'bXappX0 00_sub   'b 'b'a  _sub  UTT O 'a'b'a'b'a'b OOmatches s $$ $. [.s.$.matchess #$'T""Tdoc hidden #!!)' )TTsub doc hidden $ &'b &'b%'a!!..) .< , Ѥ ț<.<țsubapp doc hidden '('a)'b!!+& ++app# ͶͶͶͶ#ննննֶ##ͶͶmatches#  ׾ [̶a{(4<g#oJ6 ]ζc|*5=i%qL8 ^϶d}+6>j(tO;Pnpo`p Feնk2p/zVBF !/tvufv%24|~}s~-5M}2'P$3*<ön:;HOŶL ?L[3~9%zk~1H_})?e(<Rk'>Uv n!8Om/Uv,B[r.Ef} crate$crate$crate try_trait) try_traitlxV/home/seth/.cargo/registry/src/github.com-1ecc6299db9ec823/structopt-0.3.25/src/lib.rs 7Ěul;۾ BEB@A$D>GA :< &.$B,*J*"88< 6"& M T"@K)/)!=FE# $ HI6$>G2]NK1=NA-=@H(>`P1<1$5&E$@k2^2N\LFx}}|{ECGN=WDH&XT[0R"+!DDCFFGBC?I-HHJM,K+M'M0G3P8M+^U, /SLX/GI<\ N*MJKbACY@KC FCE5 2)FN!1NTW!]MCF <7.$ <;20%)KPNM8F&.JE<;/SS$ETFFJKYI:KL.U9Z[Q^8[RJN" RWQV%WN$ ;!]  SSX4 T,VX6E3 +XQ$JMKOL/S< "C++DHQ.I(N 7  -! (  %  JJFKE W$:N6 ;9  JN!  QPJ1'! ! MO8= +!+ 81**" 4I N=6D5  6JIN;% )>JRIoN;? )HB)K !b " *-!;7:!2cEK4򔒮Յ structoptx86_64-unknown-linux-gnu-c82ca7b62746f38fڱӮR `g rP$q$