ok/jj
1
0
Fork 0
forked from mirrors/jj

str_util: extract function that constructs StringPattern from string

This commit is contained in:
Yuya Nishihara 2023-10-20 02:05:25 +09:00
parent 5707a194d5
commit 2d80f071de
2 changed files with 21 additions and 10 deletions

View file

@ -1478,16 +1478,8 @@ fn parse_function_argument_to_string_pattern(
else {
return Err(make_type_error());
};
match kind.as_ref() {
"exact" => StringPattern::Exact(needle.clone()),
"substring" => StringPattern::Substring(needle.clone()),
_ => {
// TODO: error span can be narrowed to the lhs node
return Err(make_error(format!(
r#"Invalid string pattern kind "{kind}""#
)));
}
}
// TODO: error span can be narrowed to the lhs node
StringPattern::from_str_kind(needle, kind).map_err(|err| make_error(err.to_string()))?
}
_ => return Err(make_type_error()),
};

View file

@ -14,6 +14,16 @@
//! String helpers.
use thiserror::Error;
/// Error occurred during pattern string parsing.
#[derive(Debug, Error)]
pub enum StringPatternParseError {
/// Unknown pattern kind is specified.
#[error(r#"Invalid string pattern kind "{0}""#)]
InvalidKind(String),
}
/// Pattern to be tested against string property like commit description or
/// branch name.
#[derive(Clone, Debug, Eq, PartialEq)]
@ -30,6 +40,15 @@ impl StringPattern {
StringPattern::Substring(String::new())
}
/// Parses the given string as pattern of the specified `kind`.
pub fn from_str_kind(src: &str, kind: &str) -> Result<Self, StringPatternParseError> {
match kind {
"exact" => Ok(StringPattern::Exact(src.to_owned())),
"substring" => Ok(StringPattern::Substring(src.to_owned())),
_ => Err(StringPatternParseError::InvalidKind(kind.to_owned())),
}
}
/// Returns a literal pattern if this should match input strings exactly.
///
/// This can be used to optimize map lookup by exact key.