#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Hunk {
pub header: String,
pub body: Vec<u8>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileDiff {
pub header: Vec<u8>,
pub hunks: Vec<Hunk>,
}
fn split_lines(raw: &[u8]) -> Vec<&[u8]> {
raw.split_inclusive(|b| *b == b'\n').collect()
}
fn text_of(line: &[u8]) -> String {
let text = String::from_utf8_lossy(line);
text.trim_end_matches(['\n', '\r']).to_string()
}
pub fn parse_diff(raw: &[u8]) -> Vec<FileDiff> {
let mut files: Vec<FileDiff> = Vec::new();
for line in split_lines(raw) {
let starts_file = line.starts_with(b"diff --git ");
if starts_file || files.is_empty() {
files.push(FileDiff {
header: Vec::new(),
hunks: Vec::new(),
});
}
let Some(file) = files.last_mut() else {
continue;
};
if line.starts_with(b"@@") {
file.hunks.push(Hunk {
header: text_of(line),
body: line.to_vec(),
});
} else if let Some(hunk) = file.hunks.last_mut() {
hunk.body.extend_from_slice(line);
} else {
file.header.extend_from_slice(line);
}
}
files
}
pub fn hunk_patch(fd: &FileDiff, idx: usize) -> Vec<u8> {
let mut patch = fd.header.clone();
if let Some(hunk) = fd.hunks.get(idx) {
patch.extend_from_slice(&hunk.body);
}
patch
}
pub fn hunk_count(files: &[FileDiff]) -> usize {
files.iter().map(|f| f.hunks.len()).sum()
}
pub fn locate_hunk(files: &[FileDiff], global: usize) -> Option<(usize, usize)> {
let mut left = global;
for (fi, file) in files.iter().enumerate() {
if left < file.hunks.len() {
return Some((fi, left));
}
left -= file.hunks.len();
}
None
}
pub fn display_lines(files: &[FileDiff], cap: usize) -> Vec<String> {
let mut lines = Vec::new();
for file in files {
let parts = std::iter::once(&file.header[..]).chain(file.hunks.iter().map(|h| &h.body[..]));
for part in parts {
for line in split_lines(part) {
if lines.len() >= cap {
lines.push("(truncated)".to_string());
return lines;
}
lines.push(text_of(line));
}
}
}
lines
}
#[cfg(test)]
mod tests {
use super::*;
const TWO: &[u8] = b"diff --git a/f.txt b/f.txt\nindex 111..222 100644\n--- a/f.txt\n+++ b/f.txt\n@@ -1,3 +1,3 @@\n a\n-b\n+B\n c\n@@ -20,3 +20,3 @@\n x\n-y\n+Y\n z\n";
#[test]
fn two_hunks_parse() {
let files = parse_diff(TWO);
assert_eq!(files.len(), 1);
assert_eq!(files[0].hunks.len(), 2);
assert_eq!(files[0].hunks[0].header, "@@ -1,3 +1,3 @@");
assert_eq!(files[0].hunks[1].header, "@@ -20,3 +20,3 @@");
assert!(files[0].header.ends_with(b"+++ b/f.txt\n"));
}
#[test]
fn hunk_patch_is_exact() {
let files = parse_diff(TWO);
let p1 = hunk_patch(&files[0], 1);
let expect = [&files[0].header[..], b"@@ -20,3 +20,3 @@\n x\n-y\n+Y\n z\n"].concat();
assert_eq!(p1, expect);
let p0 = hunk_patch(&files[0], 0);
let h = files[0].header.len();
assert_eq!([&p0[..], &p1[h..]].concat(), TWO);
}
#[test]
fn crlf_is_kept() {
let raw = b"diff --git a/w.txt b/w.txt\nindex 1..2 100644\n--- a/w.txt\n+++ b/w.txt\n@@ -1,2 +1,2 @@\n a\r\n-b\r\n+c\r\n";
let files = parse_diff(raw);
assert_eq!(hunk_patch(&files[0], 0), raw.to_vec());
assert_eq!(files[0].hunks[0].header, "@@ -1,2 +1,2 @@");
assert!(display_lines(&files, 100).iter().all(|l| !l.contains('\r')));
}
#[test]
fn no_newline_marker_kept() {
let raw = b"diff --git a/n b/n\n--- a/n\n+++ b/n\n@@ -1 +1 @@\n-a\n\\ No newline at end of file\n+b\n\\ No newline at end of file\n";
let files = parse_diff(raw);
assert_eq!(files[0].hunks.len(), 1);
assert_eq!(hunk_patch(&files[0], 0), raw.to_vec());
}
#[test]
fn missing_final_newline_in_input() {
let raw = b"diff --git a/n b/n\n--- a/n\n+++ b/n\n@@ -1 +1 @@\n-a\n+b";
let files = parse_diff(raw);
assert_eq!(hunk_patch(&files[0], 0), raw.to_vec());
}
#[test]
fn rename_header() {
let raw = b"diff --git a/old.txt b/new.txt\nsimilarity index 80%\nrename from old.txt\nrename to new.txt\nindex 1..2 100644\n--- a/old.txt\n+++ b/new.txt\n@@ -1 +1 @@\n-a\n+b\n";
let files = parse_diff(raw);
assert!(files[0]
.header
.starts_with(b"diff --git a/old.txt b/new.txt\nsimilarity"));
assert!(files[0].header.windows(15).any(|w| w == b"rename from old"));
assert_eq!(hunk_patch(&files[0], 0), raw.to_vec());
}
#[test]
fn rename_without_hunks() {
let raw = b"diff --git a/o b/n\nsimilarity index 100%\nrename from o\nrename to n\n";
let files = parse_diff(raw);
assert_eq!(files.len(), 1);
assert!(files[0].hunks.is_empty());
assert_eq!(hunk_patch(&files[0], 0), raw.to_vec());
}
#[test]
fn binary_has_no_hunks() {
let raw = b"diff --git a/i.png b/i.png\nindex 1..2 100644\nBinary files a/i.png and b/i.png differ\n";
let files = parse_diff(raw);
assert_eq!(files.len(), 1);
assert!(files[0].hunks.is_empty());
assert_eq!(hunk_count(&files), 0);
assert!(display_lines(&files, 10)
.iter()
.any(|l| l.starts_with("Binary files")));
}
#[test]
fn mode_change_then_hunk() {
let raw = b"diff --git a/s.sh b/s.sh\nold mode 100644\nnew mode 100755\nindex 1..2\n--- a/s.sh\n+++ b/s.sh\n@@ -1 +1 @@\n-a\n+b\n";
let files = parse_diff(raw);
assert!(files[0]
.header
.starts_with(b"diff --git a/s.sh b/s.sh\nold mode"));
assert_eq!(files[0].hunks.len(), 1);
let only_mode = parse_diff(b"diff --git a/s b/s\nold mode 100644\nnew mode 100755\n");
assert!(only_mode[0].hunks.is_empty());
}
#[test]
fn multiple_files_and_locate() {
let raw = [
TWO,
b"diff --git a/g b/g\n--- a/g\n+++ b/g\n@@ -1 +1 @@\n-1\n+2\n",
]
.concat();
let files = parse_diff(&raw);
assert_eq!(files.len(), 2);
assert_eq!(hunk_count(&files), 3);
assert_eq!(locate_hunk(&files, 0), Some((0, 0)));
assert_eq!(locate_hunk(&files, 1), Some((0, 1)));
assert_eq!(locate_hunk(&files, 2), Some((1, 0)));
assert_eq!(locate_hunk(&files, 3), None);
}
#[test]
fn empty_and_out_of_range() {
assert!(parse_diff(b"").is_empty());
let fd = FileDiff {
header: b"h\n".to_vec(),
hunks: vec![],
};
assert_eq!(hunk_patch(&fd, 5), b"h\n".to_vec());
assert_eq!(locate_hunk(&[], 0), None);
}
#[test]
fn non_utf8_bytes_survive() {
let raw = b"diff --git a/b b/b\n--- a/b\n+++ b/b\n@@ -1 +1 @@\n-\xff\xfe\n+ok\n";
let files = parse_diff(raw);
assert_eq!(hunk_patch(&files[0], 0), raw.to_vec());
}
#[test]
fn display_is_capped() {
let mut raw = b"diff --git a/b b/b\n--- a/b\n+++ b/b\n@@ -1,9 +1,9 @@\n".to_vec();
for i in 0..50 {
raw.extend_from_slice(format!("+line {i}\n").as_bytes());
}
let files = parse_diff(&raw);
let lines = display_lines(&files, 10);
assert_eq!(lines.len(), 11);
assert_eq!(lines[10], "(truncated)");
assert_eq!(display_lines(&files, 1000).len(), 54);
}
}