~matthiasbeyer/imag

61ade452de4694e8347be01db4914509847f8aba — Matthias Beyer 1 year, 11 months ago 164880d
Make tag-checking error message more explicit about what is wrong

Signed-off-by: Matthias Beyer <mail@beyermatthias.de>
1 files changed, 12 insertions(+), 6 deletions(-)

M lib/entry/libimagentrytag/src/tag.rs
M lib/entry/libimagentrytag/src/tag.rs => lib/entry/libimagentrytag/src/tag.rs +12 -6
@@ 26,21 26,27 @@ pub type TagSlice<'a> = &'a str;

/// validator which can be used by clap to validate that a string is a valid tag
pub fn is_tag(s: String) -> Result<(), String> {
    is_tag_str(&s).map_err(|_| format!("The string '{}' is not a valid tag", s))
    check_tag_string(&s)
}

pub fn is_tag_str(s: &str) -> Result<(), Error> {
    use filters::filter::Filter;
    check_tag_string(s).map_err(|s| format_err!("{}", s))
}

fn check_tag_string(s: &str) -> Result<(), String> {
    trace!("Checking whether '{}' is a valid tag", s);

    let is_lower      = |s: &&str| s.chars().all(|c| c.is_lowercase());
    let no_whitespace = |s: &&str| s.chars().all(|c| !c.is_whitespace());
    let is_alphanum   = |s: &&str| s.chars().all(|c| c.is_alphanumeric());

    if is_lower.and(no_whitespace).and(is_alphanum).filter(&s) {
        Ok(())
    } else {
        Err(format_err!("The string '{}' is not a valid tag", s))
    match (is_lower(&s), no_whitespace(&s), is_alphanum(&s)) {
        (true, true, true) => Ok(()),
        (false, false, false) => Err(format!("The string '{}' is not valid, because it is not all-lowercase, has whitespace and is not alphanumeric", s)),
        (false, false, _ )    => Err(format!("The string '{}' is not valid, because it is not all-lowercase and has whitespace", s)),
        (false, _, _ )        => Err(format!("The string '{}' is not valid, because it is not all-lowercase", s)),
        (_, false, _ )        => Err(format!("The string '{}' is not valid, because it has whitespace", s)),
        (_, _, false)         => Err(format!("The string '{}' is not valid, because it is not alphanumeric", s)),
    }
}