clap/examples/15_custom_validator.rs
Ed Page bfa02fd418 test: More thoroughly test examples
This ports our example testing over to [trycmd](https://docs.rs/) so
we can:
- More thoroughly test our examples
- Provide always-up-to-date example usage

The old way of testing automatically picked up examples.  This new way
requires we have a `.md` file that uses the example in some way.

Notes:
- Moved overall example description to the `.md` file
- I added cross-linking between related examples
- `14_groups` had a redundant paragraph (twice talked about "one and
  only one"
2021-11-23 13:13:41 -06:00

37 lines
1.1 KiB
Rust

use clap::{App, Arg};
fn main() {
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.
}