rust: Putting in place git-like subcommands the usage of structopt

The StructOpt crate lets in us to derive our human particular person capability from our Struct definitions.

We will be able to create a structop for our write subcommand that can take a brief and lengthy flag for our name argument

shipment upload structopt

structopt lets in us to derive argument parsing capability from our
structs. The title is a play on struct Choose {}. To do that we want to
derive(StructOpt) on our struct. On this case we’ve a subcommand,
so we will arrange one of the fields at the Choose struct to be a
structopt(subcommand). This subcommand price will probably be an enum,
indicating that best one subcommand can be utilized at a time.

structopt additionally provides us equipment to specify one of three argument varieties:

  • positional
  • brief
  • lengthy

Through default each and every argument is a positional argument, which means that that during
this example if we left it as-is, the CLI would serve as as

lawn write my-title

We wish to use a flag, so we will use structopt to generate brief and lengthy
flags for the name argument with structopt(brief, lengthy). That provides
the use the choice of -t and --title to specify a name.

structopt additionally comprises some kind processing, so all we want to do is
specify that name is an not obligatory string and the flags will grow to be
not obligatory. This is: a person can specify or now not specify a name.

struct Choose { #[structopt(subcommand)] cmd: Command,
enum Command { Write { #[structopt(short, long)] name: Possibility<String>, },

After putting in struct Choose, we will parse the args and use
the dbg!() macro to print them to the console so we will see
what they appear to be.

let choose = Choose::from_args();

To do this we additionally want to derive(Debug) along with
structopt on each the enum and the struct.

Given enter like

lawn write

We will be able to see the next output.

[src/] choose = Choose { cmd: Write { name: None, },

We will select to shipment construct after which ./goal/debug/lawn write
or we will use shipment run -- write. The -- guarantees that our arguments
get handed to the CLI we are development and now not shipment run. That is
particularly related when passing one thing like --help.