Merge pull request #1243 from durka/flexible-validator

imp: make Arg::validator more flexible (v3)
This commit is contained in:
Kevin K 2018-04-04 22:13:11 -04:00 committed by GitHub
commit 9981bac22a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 8 deletions

View file

@ -1830,11 +1830,11 @@ impl<'a, 'b> Arg<'a, 'b> {
/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
/// [`Err(String)`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err
/// [`Rc`]: https://doc.rust-lang.org/std/rc/struct.Rc.html
pub fn validator<F>(mut self, f: F) -> Self
where
F: Fn(String) -> Result<(), String> + 'static,
pub fn validator<F, O, E>(mut self, f: F) -> Self
where F: Fn(String) -> Result<O, E> + 'static,
E: ToString
{
self.validator = Some(Rc::new(f));
self.validator = Some(Rc::new(move |s| f(s).map(|_| ()).map_err(|e| e.to_string())));
self
}
@ -1868,11 +1868,10 @@ impl<'a, 'b> Arg<'a, 'b> {
/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
/// [`Err(String)`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err
/// [`Rc`]: https://doc.rust-lang.org/std/rc/struct.Rc.html
pub fn validator_os<F>(mut self, f: F) -> Self
where
F: Fn(&OsStr) -> Result<(), OsString> + 'static,
pub fn validator_os<F, O>(mut self, f: F) -> Self
where F: Fn(&OsStr) -> Result<O, OsString> + 'static
{
self.validator_os = Some(Rc::new(f));
self.validator_os = Some(Rc::new(move |s| f(s).map(|_| ())));
self
}

View file

@ -240,6 +240,21 @@ fn validator() {
assert_eq!(m.value_of("arg").unwrap(), "env");
}
#[test]
fn validator_output() {
env::set_var("CLP_TEST_ENV", "42");
let r = App::new("df")
.arg(
Arg::from_usage("[arg] 'some opt'")
.env("CLP_TEST_ENV")
.validator(|s| s.parse::<i32>())
)
.get_matches_from_safe(vec![""]);
assert_eq!(r.unwrap().value_of("arg").unwrap().parse(), Ok(42));
}
#[test]
fn validator_invalid() {
env::set_var("CLP_TEST_ENV", "env");