2015-08-27 15:35:00 +00:00
|
|
|
use clap::{App, Arg};
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
// You can define a function (or a closure) to use as a validator to argument values. The
|
2021-07-28 15:34:44 +00:00
|
|
|
// function must accept a `&str` and return `Result<(), String>` where `Err(String)` is the
|
|
|
|
// message displayed to the user.
|
2015-08-27 15:35:00 +00:00
|
|
|
|
|
|
|
let matches = App::new("myapp")
|
2018-11-14 17:05:06 +00:00
|
|
|
// Application logic goes here...
|
|
|
|
.arg(
|
2020-05-14 20:50:56 +00:00
|
|
|
Arg::new("input")
|
2020-04-21 15:51:38 +00:00
|
|
|
.about("the input file to use")
|
2018-11-14 17:05:06 +00:00
|
|
|
.index(1)
|
|
|
|
.required(true)
|
|
|
|
// You can pass in a closure, or a function
|
|
|
|
.validator(is_png),
|
|
|
|
)
|
|
|
|
.get_matches();
|
2015-08-27 15:35:00 +00:00
|
|
|
|
2015-08-30 20:16:35 +00:00
|
|
|
// Here we can call .unwrap() because the argument is required.
|
|
|
|
println!("The .PNG file is: {}", matches.value_of("input").unwrap());
|
2015-08-27 15:35:00 +00:00
|
|
|
}
|
2016-01-27 22:22:34 +00:00
|
|
|
|
2020-04-30 17:52:45 +00:00
|
|
|
fn is_png(val: &str) -> Result<(), String> {
|
2016-01-27 22:22:34 +00:00
|
|
|
// val is the argument value passed in by the user
|
|
|
|
// val has type of String.
|
|
|
|
if val.ends_with(".png") {
|
|
|
|
Ok(())
|
|
|
|
} else {
|
|
|
|
// clap automatically adds "error: " to the beginning
|
|
|
|
// of the message.
|
|
|
|
Err(String::from("the file format must be png."))
|
|
|
|
}
|
|
|
|
// Of course, you can do more complicated validation as
|
|
|
|
// well, but for the simplicity, this example only checks
|
|
|
|
// if the value passed in ends with ".png" or not.
|
|
|
|
}
|