use patch::Patch;
pub fn split_file_diffs(diff_text: &str) -> Vec<&str> {
if diff_text.is_empty() {
return Vec::new();
}
let mut starts: Vec<usize> = diff_text
.match_indices("diff --git ")
.map(|(idx, _)| idx)
.filter(|&idx| idx == 0 || diff_text.as_bytes()[idx - 1] == b'\n')
.collect();
if starts.first() != Some(&0) {
starts.insert(0, 0);
}
let mut chunks = Vec::with_capacity(starts.len());
for (i, &start) in starts.iter().enumerate() {
let end = starts.get(i + 1).copied().unwrap_or(diff_text.len());
if end > start {
chunks.push(&diff_text[start..end]);
}
}
chunks
}
pub fn parse_patches_safely(diff_text: &str) -> Result<Vec<Patch<'_>>, String> {
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
Patch::from_multiple(diff_text)
}));
match result {
Ok(Ok(patches)) => Ok(patches),
Ok(Err(e)) => Err(format!("failed to parse diff: {e}")),
Err(_) => Err("diff parser panicked on unexpected input".to_string()),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn split_single_file_without_git_header_is_one_chunk() {
let diff = "--- a/f\n+++ b/f\n@@ -1,1 +1,1 @@\n-old\n+new\n";
assert_eq!(split_file_diffs(diff), vec![diff]);
}
#[test]
fn split_multiple_git_style_files() {
let diff = concat!(
"diff --git a/f1 b/f1\n",
"index 111..222 100644\n",
"--- a/f1\n",
"+++ b/f1\n",
"@@ -1,1 +1,1 @@\n",
"-old\n",
"+new\n",
"diff --git a/f2 b/f2\n",
"index 333..444 100644\n",
"--- a/f2\n",
"+++ b/f2\n",
"@@ -1,1 +1,1 @@\n",
"-foo\n",
"+bar\n",
);
let chunks = split_file_diffs(diff);
assert_eq!(chunks.len(), 2);
assert!(chunks[0].starts_with("diff --git a/f1 b/f1\n"));
assert!(chunks[0].ends_with("+new\n"));
assert!(chunks[1].starts_with("diff --git a/f2 b/f2\n"));
assert!(chunks[1].ends_with("+bar\n"));
}
#[test]
fn split_empty_input() {
assert_eq!(split_file_diffs(""), Vec::<&str>::new());
}
#[test]
fn parse_patches_safely_returns_err_on_ordinary_parse_failure() {
let not_a_diff = "this is not a unified diff at all\njust some text\n";
assert!(parse_patches_safely(not_a_diff).is_err());
}
#[test]
fn parse_patches_safely_catches_parser_panic_on_binary_file_entry() {
let diff = concat!(
"--- a/f\n+++ b/f\n@@ -1,1 +1,1 @@\n-old\n+new\n",
"Binary files a/img.png and b/img.png differ\n",
);
let err = parse_patches_safely(diff).unwrap_err();
assert_eq!(err, "diff parser panicked on unexpected input");
}
#[test]
fn parse_patches_safely_catches_parser_panic_on_mode_change_entry() {
let diff = concat!(
"--- a/f\n+++ b/f\n@@ -1,1 +1,1 @@\n-old\n+new\n",
"old mode 100644\nnew mode 100755\n",
);
let err = parse_patches_safely(diff).unwrap_err();
assert_eq!(err, "diff parser panicked on unexpected input");
}
#[test]
fn parse_patches_safely_parses_normal_diff() {
let diff = "--- a/f\n+++ b/f\n@@ -1,1 +1,1 @@\n-old\n+new\n";
let patches = parse_patches_safely(diff).unwrap();
assert_eq!(patches.len(), 1);
}
}