use thiserror::Error;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChangedHunk {
pub path: String,
pub added: Vec<AddedLine>,
pub removed: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AddedLine {
pub line: u32,
pub text: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Diff {
pub hunks: Vec<ChangedHunk>,
}
impl Diff {
pub fn added_lines(&self) -> impl Iterator<Item = (&str, &AddedLine)> {
self.hunks
.iter()
.flat_map(|h| h.added.iter().map(move |a| (h.path.as_str(), a)))
}
pub fn removed_lines(&self) -> impl Iterator<Item = (&str, &str)> {
self.hunks
.iter()
.flat_map(|h| h.removed.iter().map(move |r| (h.path.as_str(), r.as_str())))
}
}
#[derive(Debug, Error, PartialEq, Eq)]
pub enum DiffError {
#[error("malformed hunk header: {0}")]
BadHunkHeader(String),
#[error("body line before file header: {0}")]
OrphanBody(String),
}
pub fn parse_unified_diff(input: &str) -> Result<Diff, DiffError> {
let mut diff = Diff::default();
let mut current_path: Option<String> = None;
let mut current_hunk: Option<ChangedHunk> = None;
let mut new_line_cursor: u32 = 0;
for line in input.lines() {
if let Some(rest) = line.strip_prefix("+++ ") {
flush_hunk(&mut diff, &mut current_hunk);
current_path = Some(strip_diff_prefix(rest).to_string());
continue;
}
if line.starts_with("--- ") || line.starts_with("diff --git ") || line.starts_with("index ")
{
continue;
}
if let Some(rest) = line.strip_prefix("@@ ") {
flush_hunk(&mut diff, &mut current_hunk);
let Some(path) = current_path.clone() else {
return Err(DiffError::OrphanBody(line.to_string()));
};
new_line_cursor = parse_hunk_header(rest)?;
current_hunk = Some(ChangedHunk {
path,
added: Vec::new(),
removed: Vec::new(),
});
continue;
}
let Some(hunk) = current_hunk.as_mut() else {
continue;
};
if let Some(added) = line.strip_prefix('+') {
hunk.added.push(AddedLine {
line: new_line_cursor,
text: added.to_string(),
});
new_line_cursor += 1;
} else if let Some(removed) = line.strip_prefix('-') {
hunk.removed.push(removed.to_string());
} else if let Some(_ctx) = line.strip_prefix(' ') {
new_line_cursor += 1;
}
}
flush_hunk(&mut diff, &mut current_hunk);
Ok(diff)
}
fn flush_hunk(diff: &mut Diff, current: &mut Option<ChangedHunk>) {
if let Some(h) = current.take() {
if !h.added.is_empty() || !h.removed.is_empty() {
diff.hunks.push(h);
}
}
}
fn strip_diff_prefix(header: &str) -> &str {
let path = header.split('\t').next().unwrap_or(header).trim();
path.strip_prefix("b/").unwrap_or(path)
}
fn parse_hunk_header(rest: &str) -> Result<u32, DiffError> {
let body = rest
.split_once("@@")
.map_or(rest, |(before, _)| before)
.trim();
for part in body.split_whitespace() {
if let Some(new_part) = part.strip_prefix('+') {
let start = new_part
.split(',')
.next()
.ok_or_else(|| DiffError::BadHunkHeader(rest.to_string()))?;
return start
.parse::<u32>()
.map_err(|_| DiffError::BadHunkHeader(rest.to_string()));
}
}
Err(DiffError::BadHunkHeader(rest.to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
const SIMPLE: &str = "\
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,3 +1,4 @@
fn a() {}
-fn b() {}
+fn b_renamed() {}
+fn c() {}
";
#[test]
fn parses_file_path_without_prefix() {
let d = parse_unified_diff(SIMPLE).unwrap();
assert_eq!(d.hunks.len(), 1);
assert_eq!(d.hunks[0].path, "src/lib.rs");
}
#[test]
fn tracks_added_line_numbers_in_new_file() {
let d = parse_unified_diff(SIMPLE).unwrap();
let added = &d.hunks[0].added;
assert_eq!(added.len(), 2);
assert_eq!(added[0].line, 2);
assert_eq!(added[0].text, "fn b_renamed() {}");
assert_eq!(added[1].line, 3);
}
#[test]
fn collects_removed_lines() {
let d = parse_unified_diff(SIMPLE).unwrap();
assert_eq!(d.hunks[0].removed, vec!["fn b() {}".to_string()]);
}
#[test]
fn single_line_hunk_header_is_accepted() {
let input = "\
--- a/foo.rs
+++ b/foo.rs
@@ -1 +1 @@
-old
+new
";
let d = parse_unified_diff(input).unwrap();
assert_eq!(d.hunks[0].added[0].line, 1);
assert_eq!(d.hunks[0].removed, vec!["old".to_string()]);
}
#[test]
fn malformed_hunk_header_is_reported() {
let input = "\
+++ b/foo.rs
@@ not-a-header @@
+x
";
assert!(matches!(
parse_unified_diff(input),
Err(DiffError::BadHunkHeader(_))
));
}
#[test]
fn empty_diff_is_ok() {
let d = parse_unified_diff("").unwrap();
assert!(d.hunks.is_empty());
}
#[test]
fn multi_file_diff() {
let input = "\
--- a/a.rs
+++ b/a.rs
@@ -1 +1 @@
-a1
+a2
--- a/b.rs
+++ b/b.rs
@@ -1 +1 @@
-b1
+b2
";
let d = parse_unified_diff(input).unwrap();
assert_eq!(d.hunks.len(), 2);
assert_eq!(d.hunks[0].path, "a.rs");
assert_eq!(d.hunks[1].path, "b.rs");
}
}