From 3baca1b457e9adde60f31ae9c24b7488f8daf2bc Mon Sep 17 00:00:00 2001 From: Ilya Grigoriev Date: Mon, 7 Aug 2023 16:40:10 -0700 Subject: [PATCH] merge_tools: function to extract all variables from tool arguments To be used in the next commit --- cli/src/merge_tools/external.rs | 55 ++++++++++++++++++++++++++------- 1 file changed, 44 insertions(+), 11 deletions(-) diff --git a/cli/src/merge_tools/external.rs b/cli/src/merge_tools/external.rs index 68bbfa9d56..a25870e406 100644 --- a/cli/src/merge_tools/external.rs +++ b/cli/src/merge_tools/external.rs @@ -344,27 +344,41 @@ pub fn run_mergetool_external( Ok(tree_builder.write_tree()) } +// Not interested in $UPPER_CASE_VARIABLES +static VARIABLE_REGEX: once_cell::sync::Lazy> = + once_cell::sync::Lazy::new(|| Regex::new(r"\$([a-z0-9_]+)\b")); + fn interpolate_variables>( args: &[String], variables: &HashMap<&str, V>, ) -> Vec { - // Not interested in $UPPER_CASE_VARIABLES - let re = Regex::new(r"\$([a-z0-9_]+)\b").unwrap(); args.iter() .map(|arg| { - re.replace_all(arg, |caps: &Captures| { - let name = &caps[1]; - if let Some(subst) = variables.get(name) { - subst.as_ref().to_owned() - } else { - caps[0].to_owned() - } - }) - .into_owned() + VARIABLE_REGEX + .as_ref() + .unwrap() + .replace_all(arg, |caps: &Captures| { + let name = &caps[1]; + if let Some(subst) = variables.get(name) { + subst.as_ref().to_owned() + } else { + caps[0].to_owned() + } + }) + .into_owned() }) .collect() } +/// Return all variable names found in the args, without the dollar sign +#[allow(unused)] +fn find_all_variables(args: &[String]) -> Vec { + args.iter() + .flat_map(|arg| VARIABLE_REGEX.as_ref().unwrap().find_iter(arg)) + .map(|single_match| single_match.as_str()[1..].to_owned()) + .collect() +} + pub fn edit_diff_external( editor: ExternalMergeTool, left_tree: &Tree, @@ -515,4 +529,23 @@ mod tests { ["$left $right"], ); } + + #[test] + fn test_find_all_variables() { + assert_eq!( + find_all_variables( + &[ + "$left", + "$1", + "$right", + "$2", + "--can-be-part-of-string=$output", + "$NOT_CAPITALS", + "--can-repeat=$right" + ] + .map(ToOwned::to_owned), + ), + ["left", "1", "right", "2", "output", "right"], + ); + } }