mirror of
https://github.com/clap-rs/clap
synced 2024-12-14 14:52:33 +00:00
7e899cd340
This reverts commits 24cb8b1..d0abb37 from clap-rs/clap#1840 This is part of #16. clap-rs/clap#1840 wasn't the right call but we don't have time to make the decision now, so instead of having one option and changing it in 4.0, this reverts back to clap2 behavior.
41 lines
1.3 KiB
Rust
41 lines
1.3 KiB
Rust
use clap::{App, Arg};
|
|
|
|
fn main() {
|
|
// You can define a function (or a closure) to use as a validator to argument values. The
|
|
// function must accept a `&str` and return `Result<(), String>` where `Err(String)` is the
|
|
// message displayed to the user.
|
|
|
|
let matches = App::new("myapp")
|
|
// Application logic goes here...
|
|
.arg(
|
|
Arg::new("input")
|
|
.help("the input file to use")
|
|
.index(1)
|
|
.required(true)
|
|
// You can pass in a closure, or a function
|
|
.validator(is_png),
|
|
)
|
|
.get_matches();
|
|
|
|
println!(
|
|
"The .PNG file is: {}",
|
|
matches
|
|
.value_of("input")
|
|
.expect("'input' is required and parsing will fail if its missing")
|
|
);
|
|
}
|
|
|
|
fn is_png(val: &str) -> Result<(), String> {
|
|
// 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.
|
|
}
|