clap/examples/08_subcommands.rs

53 lines
2.3 KiB
Rust
Raw Normal View History

2018-11-14 17:05:06 +00:00
use clap::{App, Arg};
2015-03-20 19:06:44 +00:00
fn main() {
// Subcommands function exactly like sub-Apps, because that's exactly what they are. Each
// instance of a Subcommand can have its own version, author(s), Args, and even its own
2015-08-27 15:08:49 +00:00
// subcommands.
//
// # Help and Version
// Just like Apps, each subcommand will get its own "help" and "version" flags automatically
2015-08-27 15:08:49 +00:00
// generated. Also, like Apps, you can override "-V" or "-h" safely and still get "--help" and
// "--version" auto generated.
//
// NOTE: If you specify a subcommand for your App, clap will also autogenerate a "help"
// subcommand along with "-h" and "--help" (applies to sub-subcommands as well).
//
// Just like arg() and args(), subcommands can be specified one at a time via subcommand() or
// multiple ones at once with a Vec<App> provided to subcommands().
2015-03-20 19:06:44 +00:00
let matches = App::new("MyApp")
2018-11-14 17:05:06 +00:00
// Normal App and Arg configuration goes here...
// In the following example assume we wanted an application which
// supported an "add" subcommand, this "add" subcommand also took
// one positional argument of a file to add:
.subcommand(
App::new("add") // The name we call argument with
.about("Adds files to myapp") // The message displayed in "myapp -h"
// or "myapp help"
.version("0.1") // Subcommands can have independent version
.author("Kevin K.") // And authors
.arg(
Arg::new("input") // And their own arguments
.about("the file to add")
2018-11-14 17:05:06 +00:00
.index(1)
.required(true),
),
)
.get_matches();
2015-03-20 19:06:44 +00:00
// You can get the independent subcommand matches (which function exactly like App matches)
if let Some(matches) = matches.subcommand_matches("add") {
2015-08-27 15:08:49 +00:00
// Safe to use unwrap() because of the required() option
println!("Adding file: {}", matches.value_of("input").unwrap());
2015-03-20 19:06:44 +00:00
}
// You can also match on a subcommand's name
match matches.subcommand_name() {
2015-08-27 15:08:49 +00:00
Some("add") => println!("'myapp add' was used"),
2018-01-25 04:05:05 +00:00
None => println!("No subcommand was used"),
_ => println!("Some other subcommand was used"),
2015-03-20 19:06:44 +00:00
}
2015-08-27 15:08:49 +00:00
2015-03-20 19:06:44 +00:00
// Continued program logic goes here...
}