clap/examples/04_using_matches.rs

62 lines
2.2 KiB
Rust
Raw Normal View History

2015-03-20 16:47:28 +00:00
use clap::{App, Arg};
fn main() {
2015-08-27 15:08:49 +00:00
// Once all App settings (including all arguments) have been set, you call get_matches() which
// parses the string provided by the user, and returns all the valid matches to the ones you
// specified.
//
// You can then query the matches struct to get information about how the user ran the program
// at startup.
//
// For this example, let's assume you created an App which accepts three arguments (plus two
// generated by clap), a flag to display debugging information triggered with "-d" or
// "--debug" as well as an option argument which specifies a custom configuration file to use
// triggered with "-c file" or "--config file" or "--config=file" and finally a positional
// argument which is the input file we want to work with, this will be the only required
// argument.
2015-03-20 16:47:28 +00:00
let matches = App::new("MyApp")
2018-01-25 04:05:05 +00:00
.about("Parses an input file to do awesome things")
.version("1.0")
.author("Kevin K. <kbknapp@gmail.com>")
.arg(
Arg::new("debug")
.help("turn on debugging information")
.short('d')
2018-01-25 04:05:05 +00:00
.long("debug"),
)
.arg(
Arg::new("config")
.help("sets the config file to use")
.short('c')
.long("config")
.takes_value(true),
2018-01-25 04:05:05 +00:00
)
.arg(
Arg::new("input")
.help("the input file to use")
2018-01-25 04:05:05 +00:00
.index(1)
.required(true),
)
.get_matches();
2015-03-20 16:47:28 +00:00
// We can find out whether or not debugging was turned on
if matches.is_present("debug") {
2015-08-27 15:08:49 +00:00
println!("Debugging is turned on");
2015-03-20 16:47:28 +00:00
}
2015-08-27 15:08:49 +00:00
// If we wanted to do some custom initialization based off some configuration file
// provided by the user, we could get the file (A string of the file)
2015-03-20 16:47:28 +00:00
if let Some(ref file) = matches.value_of("config") {
2015-08-27 15:08:49 +00:00
println!("Using config file: {}", file);
2015-03-20 16:47:28 +00:00
}
2018-01-25 04:05:05 +00:00
println!(
"Doing real work with file: {}",
matches
.value_of("input")
.expect("'input' is required and parsing will fail if its missing")
2018-01-25 04:05:05 +00:00
);
2015-08-27 15:08:49 +00:00
2015-03-20 16:47:28 +00:00
// Continued program logic goes here...
2015-08-27 15:08:49 +00:00
}