mirror of
https://github.com/clap-rs/clap
synced 2024-12-13 22:32:33 +00:00
Merge pull request #1243 from durka/flexible-validator
imp: make Arg::validator more flexible (v3)
This commit is contained in:
commit
9981bac22a
2 changed files with 22 additions and 8 deletions
|
@ -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
|
||||
}
|
||||
|
||||
|
|
15
tests/env.rs
15
tests/env.rs
|
@ -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");
|
||||
|
|
Loading…
Reference in a new issue