Crate structopt_derive [] [src]

How to derive(StructOpt)

First, let's look at an example:

Be careful when using this code, it's not being tested!
#[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).

The type of the field gives the kind of argument:

Type Effect Added method call to clap::Arg
bool true if present .takes_value(false).multiple(false)
u64 number of params .takes_value(false).multiple(true)
Option<T: FromStr> optional argument .takes_value(true).multiple(false)
Vec<T: FromStr> list of arguments .takes_value(true).multiple(true)
T: FromStr required 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 FromStr::Error::description().

Thus, the speed argument is generated as:

Be careful when using this code, it's not being tested!
clap::Arg::with_name("speed")
    .takes_value(true)
    .multiple(false)
    .required(false)
    .validator(parse_validator::<f64>)
    .short("s")
    .long("debug")
    .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:

Be careful when using this code, it's not being tested!
#[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:

Be careful when using this code, it's not being tested!
#[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:

Be careful when using this code, it's not being tested!
#[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:

Be careful when using this code, it's not being tested!
#[derive(StructOpt)]
#[structopt(name = "foo")]
struct Foo {
    file: String,
    #[structopt(subcommand)]
    cmd: Option<Command>
}

#[derive(StructOpt)]
enum Command {
    Bar,
    Baz,
    Quux
}

Functions

structopt

Generates the StructOpt impl.