Crate structopt_derive [−] [src]
How to derive(StructOpt)
First, let's look at an example:
#[derive(StructOpt)] #[structopt(name = "example", about = "An example of StructOpt usage.")] struct Opt { #[structopt(short = "d", long = "debug", help = "Activate debug mode")] debug: bool, #[structopt(short = "s", long = "speed", help = "Set speed", default_value = "42")] speed: f64, #[structopt(help = "Input file")] input: String, #[structopt(help = "Output file, stdout if not present")] output: Option<String>, }
So derive(StructOpt)
tells Rust to generate a command line parser,
and the various structopt
attributes are simply
used for additional parameters.
First, define a struct, whatever its name. This structure will
correspond to a clap::App
. Every method of clap::App
in the
form of fn function_name(self, &str)
can be use through attributes
placed on the struct. In our example above, the about
attribute
will become an .about("An example of StructOpt usage.")
call on the
generated clap::App
. There are a few attributes that will default
if not specified:
name
: The binary name displayed in help messages. Defaults to the crate name given by Cargo.version
: Defaults to the crate version given by Cargo.author
: Defaults to the crate author name given by Cargo.about
: Defaults to the crate description given by Cargo.
Then, each field of the struct not marked as a subcommand corresponds
to a clap::Arg
. As with the struct attributes, every method of
clap::Arg
in the form of fn function_name(self, &str)
can be used
through specifying it as an attribute.
The name
attribute can be used to customize the
Arg::with_name()
call (defaults to the field name).
For functions that do not take a &str
as argument, the attribute can be
called function_name_raw
, e. g. aliases_raw = "&[\"alias\"]"
.
The type of the field gives the kind of argument:
Type | Effect | Added method call to clap::Arg |
---|---|---|
bool |
true if the flag is present |
.takes_value(false).multiple(false) |
u64 |
number of times the flag is used | .takes_value(false).multiple(true) |
Option<T: FromStr> |
optional positional argument or option | .takes_value(true).multiple(false) |
Vec<T: FromStr> |
list of options or the other positional arguments | .takes_value(true).multiple(true) |
T: FromStr |
required option or positional argument | .takes_value(true).multiple(false).required(!has_default) |
The FromStr
trait is used to convert the argument to the given
type, and the Arg::validator
method is set to a method using
to_string()
(FromStr::Err
must implement std::fmt::Display
).
If you would like to use a custom string parser other than FromStr
, see
the same titled section below.
Thus, the speed
argument is generated as:
clap::Arg::with_name("speed") .takes_value(true) .multiple(false) .required(false) .validator(parse_validator::<f64>) .short("s") .long("speed") .help("Set speed") .default_value("42")
Help messages
Help messages for the whole binary or individual arguments can be
specified using the about
attribute on the struct/field, as we've
already seen. For convenience, they can also be specified using
doc comments. For example:
#[derive(StructOpt)] #[structopt(name = "foo")] /// The help message that will be displayed when passing `--help`. struct Foo { ... #[structopt(short = "b")] /// The description for the arg that will be displayed when passing `--help`. bar: String ... }
Subcommands
Some applications, especially large ones, split their functionality
through the use of "subcommands". Each of these act somewhat like a separate
command, but is part of the larger group.
One example is git
, which has subcommands such as add
, commit
,
and clone
, to mention just a few.
clap
has this functionality, and structopt
supports it through enums:
#[derive(StructOpt)] #[structopt(name = "git", about = "the stupid content tracker")] enum Git { #[structopt(name = "add")] Add { #[structopt(short = "i")] interactive: bool, #[structopt(short = "p")] patch: bool, files: Vec<String> }, #[structopt(name = "fetch")] Fetch { #[structopt(long = "dry-run")] dry_run: bool, #[structopt(long = "all")] all: bool, repository: Option<String> }, #[structopt(name = "commit")] Commit { #[structopt(short = "m")] message: Option<String>, #[structopt(short = "a")] all: bool } }
Using derive(StructOpt)
on an enum instead of a struct will produce
a clap::App
that only takes subcommands. So git add
, git fetch
,
and git commit
would be commands allowed for the above example.
structopt
also provides support for applications where certain flags
need to apply to all subcommands, as well as nested subcommands:
#[derive(StructOpt)] #[structopt(name = "make-cookie")] struct MakeCookie { #[structopt(name = "supervisor", default_value = "Puck", required = false, long = "supervisor")] supervising_faerie: String, #[structopt(name = "tree")] /// The faerie tree this cookie is being made in. tree: Option<String>, #[structopt(subcommand)] // Note that we mark a field as a subcommand cmd: Command } #[derive(StructOpt)] enum Command { #[structopt(name = "pound")] /// Pound acorns into flour for cookie dough. Pound { acorns: u32 }, #[structopt(name = "sparkle")] /// Add magical sparkles -- the secret ingredient! Sparkle { #[structopt(short = "m")] magicality: u64, #[structopt(short = "c")] color: String }, #[structopt(name = "finish")] Finish { #[structopt(short = "t")] time: u32, #[structopt(subcommand)] // Note that we mark a field as a subcommand type: FinishType } } #[derive(StructOpt)] enum FinishType { #[structopt(name = "glaze")] Glaze { applications: u32 }, #[structopt(name = "powder")] Powder { flavor: String, dips: u32 } }
Marking a field with structopt(subcommand)
will add the subcommands of the
designated enum to the current clap::App
. The designated enum must also
be derived StructOpt
. So the above example would take the following
commands:
make-cookie pound 50
make-cookie sparkle -mmm --color "green"
make-cookie finish 130 glaze 3
Optional subcommands
A nested subcommand can be marked optional:
#[derive(StructOpt)] #[structopt(name = "foo")] struct Foo { file: String, #[structopt(subcommand)] cmd: Option<Command> } #[derive(StructOpt)] enum Command { Bar, Baz, Quux }
Custom string parsers
If the field type does not have a FromStr
implementation, or you would
like to provide a custom parsing scheme other than FromStr
, you may
provide a custom string parser using parse(...)
like this:
use std::num::ParseIntError; use std::path::PathBuf; fn parse_hex(src: &str) -> Result<u32, ParseIntError> { u32::from_str_radix(src, 16) } #[derive(StructOpt)] struct HexReader { #[structopt(short = "n", parse(try_from_str = "parse_hex"))] number: u32, #[structopt(short = "o", parse(from_os_str))] output: PathBuf, }
There are four kinds custom string parsers:
Kind | Signature | Default |
---|---|---|
from_str |
fn(&str) -> T |
::std::convert::From::from |
try_from_str |
fn(&str) -> Result<T, E> |
::std::str::FromStr::from_str |
from_os_str |
fn(&OsStr) -> T |
::std::convert::From::from |
try_from_os_str |
fn(&OsStr) -> Result<T, OsString> |
(no default function) |
When supplying a custom string parser, bool
and u64
will not be treated
specially:
Type | Effect | Added method call to clap::Arg |
---|---|---|
Option<T> |
optional argument | .takes_value(true).multiple(false) |
Vec<T> |
list of arguments | .takes_value(true).multiple(true) |
T |
required argument | .takes_value(true).multiple(false).required(!has_default) |
In the try_from_*
variants, the function will run twice on valid input:
once to validate, and once to parse. Hence, make sure the function is
side-effect-free.
Functions
structopt |
Generates the |