From 2d80f071de6e0813ab7d153bf07fcbe5a35caa0b Mon Sep 17 00:00:00 2001 From: Yuya Nishihara Date: Fri, 20 Oct 2023 02:05:25 +0900 Subject: [PATCH] str_util: extract function that constructs StringPattern from string --- lib/src/revset.rs | 12 ++---------- lib/src/str_util.rs | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/lib/src/revset.rs b/lib/src/revset.rs index 43200d532..d0161b8f0 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 e7b6cf67f..8b3d4841a 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.