From c3033ca75f7218dd078b5bd0e84e2d7c7414c2dc Mon Sep 17 00:00:00 2001 From: Alex Burka Date: Fri, 27 Oct 2017 12:54:41 -0400 Subject: [PATCH 1/2] imp: make Arg::validator more flexible Makes the validator functions more flexible by changing the return type from Result<(), String> to Result where O is anything and E is anything convertible to a String. This allows, for example, using the same function for validating and parsing your argument. Breaking change (albeit tiny) due to function signature change. --- src/args/arg.rs | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/args/arg.rs b/src/args/arg.rs index 824c862b574..d827826fdbb 100644 --- a/src/args/arg.rs +++ b/src/args/arg.rs @@ -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(mut self, f: F) -> Self - where - F: Fn(String) -> Result<(), String> + 'static, + pub fn validator(mut self, f: F) -> Self + where F: Fn(String) -> Result + '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(mut self, f: F) -> Self - where - F: Fn(&OsStr) -> Result<(), OsString> + 'static, + pub fn validator_os(mut self, f: F) -> Self + where F: Fn(&OsStr) -> Result + 'static { - self.validator_os = Some(Rc::new(f)); + self.validator_os = Some(Rc::new(move |s| f(s).map(|_| ()))); self } From c5d79d854e50142e24881f098160a8290e017fd9 Mon Sep 17 00:00:00 2001 From: Alex Burka Date: Wed, 4 Apr 2018 20:45:22 -0400 Subject: [PATCH 2/2] test validator with custom return type --- tests/env.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/env.rs b/tests/env.rs index aded47bd8ca..431a0211734 100644 --- a/tests/env.rs +++ b/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::()) + ) + .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");