Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add validator_all, validator_all_os #3029

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/build/arg/mod.rs
Expand Up @@ -45,6 +45,9 @@ pub use self::regex::RegexRef;

type Validator<'a> = dyn FnMut(&str) -> Result<(), Box<dyn Error + Send + Sync>> + Send + 'a;
type ValidatorOs<'a> = dyn FnMut(&OsStr) -> Result<(), Box<dyn Error + Send + Sync>> + Send + 'a;
type ValidatorAll<'a> = dyn FnMut(&[&str]) -> Result<(), Box<dyn Error + Send + Sync>> + Send + 'a;
type ValidatorAllOs<'a> =
dyn FnMut(&[&OsStr]) -> Result<(), Box<dyn Error + Send + Sync>> + Send + 'a;

#[derive(Debug, Clone, Eq, PartialEq)]
pub(crate) enum ArgProvider {
Expand Down Expand Up @@ -110,6 +113,8 @@ pub struct Arg<'help> {
pub(crate) min_vals: Option<usize>,
pub(crate) validator: Option<Arc<Mutex<Validator<'help>>>>,
pub(crate) validator_os: Option<Arc<Mutex<ValidatorOs<'help>>>>,
pub(crate) validator_all: Option<Arc<Mutex<ValidatorAll<'help>>>>,
pub(crate) validator_all_os: Option<Arc<Mutex<ValidatorAllOs<'help>>>>,
pub(crate) val_delim: Option<char>,
pub(crate) default_vals: Vec<&'help OsStr>,
pub(crate) default_vals_ifs: Vec<(Id, Option<&'help OsStr>, Option<&'help OsStr>)>,
Expand Down Expand Up @@ -2347,6 +2352,30 @@ impl<'help> Arg<'help> {
self
}

/// Works identically to `validator` but is passed all the values sent.
pub fn validator_all<F, O, E>(mut self, mut f: F) -> Self
where
F: FnMut(&[&str]) -> Result<O, E> + Send + 'help,
E: Into<Box<dyn Error + Send + Sync + 'static>>,
{
self.validator_all = Some(Arc::new(Mutex::new(move |s: &[&str]| {
f(s).map(|_| ()).map_err(|e| e.into())
})));
self
}

/// Works identically to `validator_all` but is passed all the values sent as `OsString`'s.
pub fn validator_all_os<F, O, E>(mut self, mut f: F) -> Self
where
F: FnMut(&[&OsStr]) -> Result<O, E> + Send + 'help,
E: Into<Box<dyn Error + Send + Sync + 'static>>,
{
self.validator_all_os = Some(Arc::new(Mutex::new(move |s: &[&OsStr]| {
f(s).map(|_| ()).map_err(|e| e.into())
})));
self
}

/// Validates the argument via the given regular expression.
///
/// As regular expressions are not very user friendly, the additional `err_message` should
Expand Down
9 changes: 8 additions & 1 deletion src/parse/errors.rs
Expand Up @@ -919,13 +919,15 @@ impl Error {
arg: String,
val: String,
err: Box<dyn error::Error + Send + Sync>,
multiple: bool,
) -> Self {
let mut err = Self::value_validation_with_color(
arg,
val,
err,
app.get_color(),
app.settings.is_set(AppSettings::WaitOnError),
multiple,
);
match &mut err.message {
Message::Raw(_) => {
Expand All @@ -941,7 +943,7 @@ impl Error {
val: String,
err: Box<dyn error::Error + Send + Sync>,
) -> Self {
Self::value_validation_with_color(arg, val, err, ColorChoice::Never, false)
Self::value_validation_with_color(arg, val, err, ColorChoice::Never, false, false)
}

fn value_validation_with_color(
Expand All @@ -950,11 +952,16 @@ impl Error {
err: Box<dyn error::Error + Send + Sync>,
color: ColorChoice,
wait_on_exit: bool,
multiple: bool,
) -> Self {
let mut c = Colorizer::new(true, color);

start_error(&mut c, "Invalid value");

if multiple {
c.none("s");
}

c.none(" for '");
c.warning(arg.clone());
c.none("'");
Expand Down
41 changes: 41 additions & 0 deletions src/parse/validator.rs
@@ -1,3 +1,5 @@
use std::borrow::Borrow;

// Internal
use crate::{
build::{arg::PossibleValue, AppSettings as AS, Arg, ArgSettings},
Expand Down Expand Up @@ -86,6 +88,43 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
ma: &MatchedArg,
matcher: &ArgMatcher,
) -> ClapResult<()> {
if let Some(ref vtor) = arg.validator_all {
debug!("Validator::validate_arg_values: checking validator_all...");
let mut vtor = vtor.lock().unwrap();
let vals = ma
.vals_flatten()
.map(|s| s.to_string_lossy())
.collect::<Vec<_>>();
if let Err(e) = vtor(&vals.iter().map(|s| s.borrow()).collect::<Vec<_>>()) {
debug!("error");
return Err(Error::value_validation(
self.p.app,
arg.to_string(),
String::new(),
e,
true,
));
} else {
debug!("good");
}
}
if let Some(ref vtor) = arg.validator_all_os {
debug!("Validator::validate_arg_values: checking validator_all_os...");
let mut vtor = vtor.lock().unwrap();
let vals = ma.vals_flatten().map(|s| s.as_os_str()).collect::<Vec<_>>();
if let Err(e) = vtor(vals.as_slice()) {
debug!("error");
return Err(Error::value_validation(
self.p.app,
arg.to_string(),
String::new(),
e,
true,
));
} else {
debug!("good");
}
}
debug!("Validator::validate_arg_values: arg={:?}", arg.name);
for val in ma.vals_flatten() {
if !arg.is_set(ArgSettings::AllowInvalidUtf8) && val.to_str().is_none() {
Expand Down Expand Up @@ -152,6 +191,7 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
arg.to_string(),
val.to_string_lossy().into_owned(),
e,
false,
));
} else {
debug!("good");
Expand All @@ -167,6 +207,7 @@ impl<'help, 'app, 'parser> Validator<'help, 'app, 'parser> {
arg.to_string(),
val.to_string_lossy().into(),
e,
false,
));
} else {
debug!("good");
Expand Down
73 changes: 73 additions & 0 deletions tests/validators.rs
Expand Up @@ -64,3 +64,76 @@ fn stateful_validator() {

assert!(state);
}

#[test]
fn validator_all() {
App::new("test")
.arg(
Arg::new("test")
.short('d')
.takes_value(true)
.multiple_values(true)
.validator_all(|vals| {
if vals.len() % 3 == 0 {
Ok(())
} else {
Err("not % 3!")
}
}),
)
.try_get_matches_from(&["app", "-d", "f", "f", "f"])
.unwrap();
}

#[test]
fn validator_all_and_validator() {
let app = App::new("test").arg(
Arg::new("test")
.short('d')
.takes_value(true)
.multiple_values(true)
.validator_all(|vals| {
if vals.len() % 3 == 0 {
Ok(())
} else {
Err("not % 3!")
}
})
.validator(|val| val.parse::<u32>().map_err(|e| e.to_string())),
);

app.clone()
.try_get_matches_from(&["app", "-d", "10", "0", "10"])
.unwrap();
assert!(app
.try_get_matches_from(&["app", "-d", "a", "0", "10"])
.is_err());
}

#[test]
fn validator_all_os_error() {
let res = App::new("test")
.arg(
Arg::new("test")
.short('d')
.takes_value(true)
.multiple_values(true)
.validator_all_os(|vals| {
if vals.len() % 3 == 0 {
Ok(())
} else {
Err(format!("not % 3 == 0, == {}!", vals.len() % 3))
}
}),
)
.try_get_matches_from(&["app", "-d", "f", "f", "f", "f"]);

assert!(res.is_err());
let err = res.unwrap_err();

eprintln!("{}", err.to_string());

assert!(err
.to_string()
.contains("Invalid values for '-d <test>...': not % 3 == 0, == 1!"));
}