diff --git a/lib/src/revset.rs b/lib/src/revset.rs index 43200d532c..d0161b8f01 100644 --- a/lib/src/revset.rs +++ b/lib/src/revset.rs @@ -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()), }; diff --git a/lib/src/str_util.rs b/lib/src/str_util.rs index e7b6cf67f0..8b3d4841ac 100644 --- a/lib/src/str_util.rs +++ b/lib/src/str_util.rs @@ -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 { + 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.