Skip to content

Commit

Permalink
str_util: extract function that constructs StringPattern from string
Browse files Browse the repository at this point in the history
  • Loading branch information
yuja committed Oct 21, 2023
1 parent 5707a19 commit 2d80f07
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 10 deletions.
12 changes: 2 additions & 10 deletions lib/src/revset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()),
};
Expand Down
19 changes: 19 additions & 0 deletions lib/src/str_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand All @@ -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.
Expand Down

0 comments on commit 2d80f07

Please sign in to comment.