#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
Context,
Added,
Removed,
}
#[derive(Clone, Debug)]
pub struct Line {
pub kind: Kind,
pub text: String,
pub old_no: Option<u32>,
pub new_no: Option<u32>,
}
#[derive(Clone, Debug, Default)]
pub struct Hunk {
pub lines: Vec<Line>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Status {
Added,
Deleted,
Modified,
Renamed,
Copied,
}
#[derive(Clone, Debug)]
pub struct FileDiff {
pub path: String,
pub old_path: Option<String>,
pub status: Status,
pub binary: bool,
pub old_mode: Option<String>,
pub new_mode: Option<String>,
pub hunks: Vec<Hunk>,
}
#[derive(Clone, Debug, Default)]
pub struct Diff {
pub files: Vec<FileDiff>,
}
impl FileDiff {
pub fn lines(&self) -> impl Iterator<Item = &Line> {
self.hunks.iter().flat_map(|h| h.lines.iter())
}
pub fn added(&self) -> impl Iterator<Item = &Line> {
self.lines().filter(|l| l.kind == Kind::Added)
}
pub fn removed(&self) -> impl Iterator<Item = &Line> {
self.lines().filter(|l| l.kind == Kind::Removed)
}
pub fn added_count(&self) -> usize {
self.added().count()
}
pub fn removed_count(&self) -> usize {
self.removed().count()
}
}
impl Diff {
pub fn added_count(&self) -> usize {
self.files.iter().map(FileDiff::added_count).sum()
}
pub fn removed_count(&self) -> usize {
self.files.iter().map(FileDiff::removed_count).sum()
}
}
struct Builder {
file: FileDiff,
git: bool,
old_null: bool,
new_null: bool,
new_file: bool,
deleted_file: bool,
renamed: bool,
copied: bool,
}
impl Builder {
fn new(path: String, old: Option<String>, git: bool) -> Self {
let old_path = old.filter(|o| *o != path);
Builder {
file: FileDiff {
path,
old_path,
status: Status::Modified,
binary: false,
old_mode: None,
new_mode: None,
hunks: Vec::new(),
},
git,
old_null: false,
new_null: false,
new_file: false,
deleted_file: false,
renamed: false,
copied: false,
}
}
fn finish(mut self) -> FileDiff {
self.file.status = if self.renamed {
Status::Renamed
} else if self.copied {
Status::Copied
} else if self.new_file || self.old_null {
Status::Added
} else if self.deleted_file || self.new_null {
Status::Deleted
} else {
Status::Modified
};
self.file
}
}
struct HunkState {
hunk: Hunk,
old_left: u32,
new_left: u32,
old_no: u32,
new_no: u32,
}
#[derive(Default)]
struct Parser {
files: Vec<FileDiff>,
cur: Option<Builder>,
hunk: Option<HunkState>,
skipping: bool,
}
pub fn parse(text: &str) -> Diff {
let mut p = Parser::default();
for raw in text.lines() {
p.line(raw);
}
p.finish_file();
Diff { files: p.files }
}
impl Parser {
fn finish_hunk(&mut self) {
if let (Some(h), Some(cur)) = (self.hunk.take(), self.cur.as_mut()) {
cur.file.hunks.push(h.hunk);
}
}
fn finish_file(&mut self) {
self.finish_hunk();
if let Some(cur) = self.cur.take() {
self.files.push(cur.finish());
}
}
fn hunk_line(&mut self, raw: &str) -> bool {
let Some(h) = self.hunk.as_mut() else { return false };
if h.old_left == 0 && h.new_left == 0 {
return false;
}
let (kind, text) = match raw.as_bytes().first() {
Some(b'\\') => return true, Some(b'+') if h.new_left > 0 => (Kind::Added, &raw[1..]),
Some(b'-') if h.old_left > 0 => (Kind::Removed, &raw[1..]),
Some(b' ') => (Kind::Context, &raw[1..]),
None => (Kind::Context, ""),
_ => {
self.finish_hunk();
return false;
}
};
let (old_no, new_no) = match kind {
Kind::Added => (None, Some(h.new_no)),
Kind::Removed => (Some(h.old_no), None),
Kind::Context => (Some(h.old_no), Some(h.new_no)),
};
if kind != Kind::Added {
h.old_left = h.old_left.saturating_sub(1);
h.old_no += 1;
}
if kind != Kind::Removed {
h.new_left = h.new_left.saturating_sub(1);
h.new_no += 1;
}
h.hunk.lines.push(Line { kind, text: text.to_string(), old_no, new_no });
true
}
fn line(&mut self, raw: &str) {
if self.hunk_line(raw) {
return;
}
if let Some(rest) = raw.strip_prefix("diff --git ") {
self.finish_file();
self.skipping = false;
let (old, new) = split_git_header(rest).unzip();
let path = new.or_else(|| old.clone()).unwrap_or_default();
self.cur = Some(Builder::new(path, old, true));
return;
}
if raw.starts_with("diff --cc ") || raw.starts_with("diff --combined ") {
self.finish_file();
self.skipping = true;
return;
}
if self.skipping {
return;
}
if let Some(rest) = raw.strip_prefix("@@ ") {
self.finish_hunk();
if self.cur.is_none() {
return;
}
if let Some((old_start, old_len, new_start, new_len)) = parse_hunk_header(rest) {
self.hunk = Some(HunkState {
hunk: Hunk::default(),
old_left: old_len,
new_left: new_len,
old_no: old_start,
new_no: new_start,
});
}
return;
}
if let Some(rest) = raw.strip_prefix("--- ") {
if self.cur.as_ref().is_none_or(|c| !c.git || !c.file.hunks.is_empty()) {
self.finish_file();
self.cur = Some(Builder::new(String::new(), None, false));
}
let cur = self.cur.as_mut().unwrap();
let (path, null) = header_path(rest, cur.git, "a/");
if null {
cur.old_null = true;
} else {
if cur.file.old_path.is_none() && !cur.git {
cur.file.old_path = Some(path.clone());
}
if cur.file.path.is_empty() {
cur.file.path = path;
}
}
return;
}
if let Some(rest) = raw.strip_prefix("+++ ") {
let Some(cur) = self.cur.as_mut() else { return };
let (path, null) = header_path(rest, cur.git, "b/");
if null {
cur.new_null = true;
} else if !path.is_empty() {
cur.file.path = path;
if cur.file.old_path.as_deref() == Some(cur.file.path.as_str()) {
cur.file.old_path = None;
}
}
return;
}
let Some(cur) = self.cur.as_mut() else { return };
if let Some(mode) = raw.strip_prefix("new file mode ") {
cur.new_file = true;
cur.file.new_mode = Some(mode.trim().to_string());
} else if let Some(mode) = raw.strip_prefix("deleted file mode ") {
cur.deleted_file = true;
cur.file.old_mode = Some(mode.trim().to_string());
} else if let Some(mode) = raw.strip_prefix("old mode ") {
cur.file.old_mode = Some(mode.trim().to_string());
} else if let Some(mode) = raw.strip_prefix("new mode ") {
cur.file.new_mode = Some(mode.trim().to_string());
} else if let Some(p) = raw.strip_prefix("rename from ") {
cur.renamed = true;
cur.file.old_path = Some(unquote(p));
} else if let Some(p) = raw.strip_prefix("rename to ") {
cur.renamed = true;
cur.file.path = unquote(p);
} else if let Some(p) = raw.strip_prefix("copy from ") {
cur.copied = true;
cur.file.old_path = Some(unquote(p));
} else if let Some(p) = raw.strip_prefix("copy to ") {
cur.copied = true;
cur.file.path = unquote(p);
} else if raw.starts_with("Binary files ") || raw.starts_with("GIT binary patch") {
cur.file.binary = true;
}
}
}
fn parse_hunk_header(rest: &str) -> Option<(u32, u32, u32, u32)> {
let rest = rest.strip_prefix('-')?;
let (old, rest) = rest.split_once(" +")?;
let new = rest.split(" @@").next()?;
let range = |r: &str| -> Option<(u32, u32)> {
match r.split_once(',') {
Some((a, b)) => Some((a.parse().ok()?, b.parse().ok()?)),
None => Some((r.parse().ok()?, 1)),
}
};
let (os, ol) = range(old)?;
let (ns, nl) = range(new)?;
Some((os, ol, ns, nl))
}
fn header_path(rest: &str, git: bool, prefix: &str) -> (String, bool) {
let rest = rest.trim_end_matches(['\r', '\n']);
let rest = if rest.starts_with('"') { rest } else { rest.split('\t').next().unwrap_or(rest) };
let path = unquote(rest.trim_end());
if path == "/dev/null" {
return (String::new(), true);
}
let path = if git { path.strip_prefix(prefix).unwrap_or(&path).to_string() } else { path };
(path, false)
}
fn split_git_header(rest: &str) -> Option<(String, String)> {
let strip = |s: String| s.strip_prefix("a/").or_else(|| s.strip_prefix("b/")).map(str::to_string).unwrap_or(s);
if rest.starts_with('"') {
let end = quoted_end(rest)?;
let first = unquote(&rest[..=end]);
let second = unquote(rest[end + 1..].trim_start());
return Some((strip(first), strip(second)));
}
let mut fallback = None;
for (i, _) in rest.match_indices(" b/") {
let (a, b) = (&rest[..i], &rest[i + 1..]);
if let (Some(a2), Some(b2)) = (a.strip_prefix("a/"), b.strip_prefix("b/")) {
if a2 == b2 {
return Some((a2.to_string(), b2.to_string()));
}
fallback = Some((a2.to_string(), b2.to_string()));
}
}
if fallback.is_some() {
return fallback;
}
let (a, b) = rest.split_once(' ')?;
Some((strip(a.to_string()), strip(b.to_string())))
}
fn quoted_end(s: &str) -> Option<usize> {
let mut escaped = false;
for (i, c) in s.char_indices().skip(1) {
match c {
_ if escaped => escaped = false,
'\\' => escaped = true,
'"' => return Some(i),
_ => {}
}
}
None
}
pub fn unquote(s: &str) -> String {
let Some(inner) = s.strip_prefix('"').and_then(|s| s.strip_suffix('"')) else {
return s.to_string();
};
let bytes = inner.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] != b'\\' || i + 1 >= bytes.len() {
out.push(bytes[i]);
i += 1;
continue;
}
i += 1;
match bytes[i] {
b'n' => out.push(b'\n'),
b't' => out.push(b'\t'),
b'r' => out.push(b'\r'),
b'a' => out.push(7),
b'b' => out.push(8),
b'f' => out.push(12),
b'v' => out.push(11),
b'0'..=b'7' => {
let mut v = 0u32;
let mut n = 0;
while n < 3 && i < bytes.len() && (b'0'..=b'7').contains(&bytes[i]) {
v = v * 8 + u32::from(bytes[i] - b'0');
i += 1;
n += 1;
}
out.push(v as u8);
continue;
}
other => out.push(other),
}
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
#[cfg(test)]
mod tests {
use super::*;
const BASIC: &str = "\
diff --git a/src/a.rs b/src/a.rs
index 1111111..2222222 100644
--- a/src/a.rs
+++ b/src/a.rs
@@ -1,4 +1,5 @@ fn main
one
-two
+TWO
+two and a half
three
four
diff --git a/new.txt b/new.txt
new file mode 100644
index 0000000..3333333
--- /dev/null
+++ b/new.txt
@@ -0,0 +1,2 @@
+hello
+world
\\ No newline at end of file
diff --git a/gone.txt b/gone.txt
deleted file mode 100644
index 4444444..0000000
--- a/gone.txt
+++ /dev/null
@@ -1 +0,0 @@
-bye
";
#[test]
fn reads_files_statuses_and_line_numbers() {
let d = parse(BASIC);
assert_eq!(d.files.len(), 3);
let a = &d.files[0];
assert_eq!((a.path.as_str(), a.status), ("src/a.rs", Status::Modified));
assert_eq!((a.added_count(), a.removed_count()), (2, 1));
let lines = &a.hunks[0].lines;
assert_eq!(lines[0].old_no, Some(1));
assert_eq!(lines[1].kind, Kind::Removed);
assert_eq!((lines[1].old_no, lines[1].new_no), (Some(2), None));
assert_eq!((lines[2].old_no, lines[2].new_no), (None, Some(2)));
assert_eq!(lines[4].new_no, Some(4));
assert_eq!(d.files[1].status, Status::Added);
assert_eq!(d.files[1].added_count(), 2);
assert_eq!((d.files[2].status, d.files[2].path.as_str()), (Status::Deleted, "gone.txt"));
assert_eq!((d.added_count(), d.removed_count()), (4, 2));
}
#[test]
fn content_that_looks_like_headers_is_content() {
let d = parse(
"diff --git a/x.sql b/x.sql\n--- a/x.sql\n+++ b/x.sql\n@@ -1,3 +1,3 @@\n -- a comment\n--- removed dashes\n+++ added pluses\n+diff --git a/fake b/fake\n ok\n",
);
assert_eq!(d.files.len(), 1);
let l = &d.files[0].hunks[0].lines;
assert_eq!(l.len(), 5);
assert_eq!(l[1].text, "-- removed dashes");
assert_eq!(l[2].text, "++ added pluses");
assert_eq!(l[3].text, "diff --git a/fake b/fake");
}
#[test]
fn renames_copies_modes_and_binaries() {
let d = parse(
"diff --git a/old name.txt b/new name.txt\nsimilarity index 90%\nrename from old name.txt\nrename to new name.txt\n\
diff --git a/run.sh b/run.sh\nold mode 100644\nnew mode 100755\n\
diff --git a/logo.png b/logo.png\nBinary files a/logo.png and b/logo.png differ\n",
);
assert_eq!(d.files.len(), 3);
assert_eq!(d.files[0].status, Status::Renamed);
assert_eq!(d.files[0].path, "new name.txt");
assert_eq!(d.files[0].old_path.as_deref(), Some("old name.txt"));
assert_eq!((d.files[1].old_mode.as_deref(), d.files[1].new_mode.as_deref()), (Some("100644"), Some("100755")));
assert!(d.files[2].binary);
}
#[test]
fn quoted_and_spaced_paths() {
let d = parse(
"diff --git \"a/caf\\303\\251 \\\"x\\\".txt\" \"b/caf\\303\\251 \\\"x\\\".txt\"\n--- \"a/caf\\303\\251 \\\"x\\\".txt\"\n+++ \"b/caf\\303\\251 \\\"x\\\".txt\"\n@@ -1 +1 @@\n-a\n+b\n\
diff --git a/my file.txt b/my file.txt\n--- a/my file.txt\t\n+++ b/my file.txt\t\n@@ -1 +1 @@\n-a\n+b\n",
);
assert_eq!(d.files[0].path, "café \"x\".txt");
assert_eq!(d.files[1].path, "my file.txt");
assert_eq!(d.files[1].added_count(), 1);
}
#[test]
fn plain_unified_diffs_and_stripped_context_lines() {
let d = parse(
"--- a.txt\t2024-01-01\n+++ a.txt\t2024-01-02\n@@ -1,3 +1,3 @@\n x\n\n-y\n+z\n--- b.txt\n+++ b.txt\n@@ -1 +1 @@\n-1\n+2\n",
);
assert_eq!(d.files.len(), 2);
assert_eq!(d.files[0].path, "a.txt");
assert_eq!(d.files[0].hunks[0].lines.len(), 4);
assert_eq!(d.files[1].path, "b.txt");
}
#[test]
fn garbage_and_empty_input_do_not_panic() {
assert!(parse("").files.is_empty());
assert!(parse("hello\nworld\n@@ nonsense\n+x\n").files.is_empty());
let d = parse("diff --git a/x b/x\n@@ -1,2 +1,2 @@\n a\n?what\n+b\n");
assert_eq!(d.files.len(), 1);
let d = parse("diff --cc x\n@@@ -1,1 -1,1 +1,1 @@@\n+++ b/x\n");
assert!(d.files.is_empty());
}
#[test]
fn multiple_hunks_keep_their_own_numbers() {
let d = parse(
"diff --git a/x b/x\n--- a/x\n+++ b/x\n@@ -1,2 +1,2 @@\n a\n-b\n+B\n@@ -10,2 +10,3 @@\n j\n+new\n k\n",
);
let h = &d.files[0].hunks;
assert_eq!(h.len(), 2);
assert_eq!(h[1].lines[1].new_no, Some(11));
}
}