Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
merge_tools: function to extract all variables from tool arguments
Browse files Browse the repository at this point in the history
To be used in the next commit
ilyagr committed Aug 21, 2023
1 parent 7668ab3 commit 3baca1b
Showing 1 changed file with 44 additions and 11 deletions.
55 changes: 44 additions & 11 deletions cli/src/merge_tools/external.rs
Original file line number Diff line number Diff line change
@@ -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<Result<Regex, regex::Error>> =
once_cell::sync::Lazy::new(|| Regex::new(r"\$([a-z0-9_]+)\b"));

fn interpolate_variables<V: AsRef<str>>(
args: &[String],
variables: &HashMap<&str, V>,
) -> Vec<String> {
// 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<String> {
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"],
);
}
}

0 comments on commit 3baca1b

Please sign in to comment.