This commit is contained in:
2026-08-22 16:57:24 +07:00
parent 9bdc3daa7e
commit 385718d74d
8 changed files with 938 additions and 128 deletions
+630
View File
@@ -604,6 +604,348 @@ fn commit_diff(repo: &gix::Repository, id: &str) -> Result<CommitDiff> {
Ok(CommitDiff { files })
}
/// Parse a `git format-patch` output (a single patch or a patch series)
/// into the same [`CommitDiff`] structure used for commit diffs.
///
/// The mbox envelope (From/Subject/… headers, commit body and diffstat)
/// is skipped; every `diff --git` section becomes one [`FileDiff`]. Paths
/// are taken from the section headers, with git's C-style quoting undone.
/// Sections without hunks (pure renames, mode changes, binary files) are
/// reported without lines.
pub fn patch_diffs(patch: &str) -> Result<CommitDiff> {
let lines: Vec<&str> = patch.lines().collect();
let mut files = Vec::new();
let mut i = 0;
while i < lines.len() {
let Some(header) = lines[i].strip_prefix("diff --git ") else {
i += 1;
continue;
};
let (file, next) = parse_diff_section(header, &lines, i + 1)?;
files.push(file);
i = next;
}
Ok(CommitDiff { files })
}
/// Parse one file's diff section: everything after its `diff --git` header
/// up to the next section (or the end of the patch). Returns the section
/// and the index of the first unconsumed line.
fn parse_diff_section(header: &str, lines: &[&str], start: usize) -> Result<(FileDiff, usize)> {
let (header_old, header_new) = header_paths(header)?;
// The `---`/`+++` lines name the two sides unambiguously (the header
// can't distinguish spaces); fall back to the header for sections
// without them (pure renames, mode changes).
let mut old_path = header_old;
let mut new_path = header_new;
let mut status = DiffStatus::Modified;
let mut binary = false;
let mut hunks = Vec::new();
let mut insertions = 0usize;
let mut deletions = 0usize;
let mut i = start;
while i < lines.len() {
let line = lines[i];
// The next file's section starts at this line.
if line.starts_with("diff --git ") {
break;
}
i += 1;
if line.starts_with("@@ -") {
let (hunk, next) = parse_hunk(lines, i - 1)?;
i = next;
insertions += hunk
.lines
.iter()
.filter(|line| line.kind == DiffLineKind::Addition)
.count();
deletions += hunk
.lines
.iter()
.filter(|line| line.kind == DiffLineKind::Deletion)
.count();
hunks.push(hunk);
} else if let Some(rest) = line.strip_prefix("--- ") {
if rest == "/dev/null" {
status = DiffStatus::Added;
} else {
old_path = diff_line_path(rest, "a/")?;
}
} else if let Some(rest) = line.strip_prefix("+++ ") {
if rest == "/dev/null" {
status = DiffStatus::Deleted;
} else {
new_path = diff_line_path(rest, "b/")?;
}
} else if line.starts_with("new file mode ") {
status = DiffStatus::Added;
} else if line.starts_with("deleted file mode ") {
status = DiffStatus::Deleted;
} else if line.starts_with("copy from ") {
status = DiffStatus::Copied;
} else if line.starts_with("rename from ") {
status = DiffStatus::Renamed;
} else if line.starts_with("Binary files ") || line.starts_with("GIT binary patch") {
binary = true;
// A literal binary patch may follow; skip it without consuming
// the next section's header.
while i < lines.len() && !lines[i].starts_with("diff --git ") {
i += 1;
}
break;
}
// Everything else (index/mode/similarity lines) is ignored.
}
Ok((
FileDiff {
path: new_path,
old_path: matches!(status, DiffStatus::Renamed | DiffStatus::Copied)
.then_some(old_path),
status,
insertions,
deletions,
binary,
hunks,
},
i,
))
}
/// Parse one hunk: the `@@ -a,b +c,d @@` header plus every body line up to
/// the next hunk header, the next `diff --git` section or the end of the
/// patch. Returns the hunk and the index of the first unconsumed line.
fn parse_hunk(lines: &[&str], start: usize) -> Result<(DiffHunk, usize)> {
let (old_start, old_lines, new_start, new_lines) = hunk_header(lines[start])?;
let mut diff_lines = Vec::new();
let mut old = old_start;
let mut new = new_start;
let mut i = start + 1;
while i < lines.len() {
let line = lines[i];
let Some(kind) = line_prefix_kind(line) else {
break;
};
i += 1;
// Context lines advance both counters, deletions only the old one
// and additions only the new one, so every line ends up with its
// real line number in both versions.
let (old_no, new_no) = match kind {
DiffLineKind::Context => {
let numbers = (Some(old), Some(new));
old += 1;
new += 1;
numbers
}
DiffLineKind::Addition => {
let number = Some(new);
new += 1;
(None, number)
}
DiffLineKind::Deletion => {
let number = Some(old);
old += 1;
(number, None)
}
};
diff_lines.push(DiffLine {
kind,
old: old_no,
new: new_no,
text: line[1..].to_owned(),
});
}
Ok((
DiffHunk {
old_start,
old_lines,
new_start,
new_lines,
lines: diff_lines,
},
i,
))
}
/// The kind of a hunk body line, from its first character; lines that don't
/// belong to the hunk (headers, `\ No newline…`, the next section) yield
/// `None`.
fn line_prefix_kind(line: &str) -> Option<DiffLineKind> {
match line.as_bytes().first()? {
b' ' => Some(DiffLineKind::Context),
b'+' => Some(DiffLineKind::Addition),
b'-' => Some(DiffLineKind::Deletion),
_ => None,
}
}
/// Parse a unified-diff hunk header `@@ -a,b +c,d @@`; omitted line counts
/// default to 1.
fn hunk_header(header: &str) -> Result<(u32, u32, u32, u32)> {
let rest = header
.strip_prefix("@@ ")
.context("malformed hunk header")?;
let (old_spec, rest) = rest.split_once(' ').context("malformed hunk header")?;
let new_spec = rest.split_once(' ').map(|(new, _)| new).unwrap_or(rest);
fn parse(spec: &str) -> Result<(u32, u32)> {
let spec = spec.strip_prefix(['-', '+']).unwrap_or(spec);
let (start, count) = match spec.split_once(',') {
Some((start, count)) => (start, count.parse::<u32>()?),
None => (spec, 1),
};
Ok((start.parse::<u32>()?, count))
}
let (old_start, old_lines) = parse(old_spec)?;
let (new_start, new_lines) = parse(new_spec)?;
Ok((old_start, old_lines, new_start, new_lines))
}
/// The old and new paths of a `diff --git a/X b/Y` header, with git's
/// C-style quoting undone.
///
/// Git only quotes paths containing characters that need escaping (non-ASCII
/// bytes, `"`, `\`); plain spaces are left unquoted, so the two sides of an
/// unquoted header are split at the last ` b/`.
fn header_paths(header: &str) -> Result<(String, String)> {
if header.starts_with('"') {
// Quoted paths include the `a/` / `b/` prefix inside the quotes.
let (old, rest) = take_quoted(header).context("unterminated quoted path")?;
let rest = rest.trim_start();
let new = if rest.starts_with('"') {
take_quoted(rest).context("unterminated quoted path")?.0
} else {
rest.split_whitespace().next().unwrap_or(rest)
};
let old = old
.strip_prefix("a/")
.context("old path without `a/` prefix")?;
let new = new
.strip_prefix("b/")
.context("new path without `b/` prefix")?;
Ok((unquote_path(old)?, unquote_path(new)?))
} else {
let (old, rest) = header
.rsplit_once(" b/")
.context("malformed diff --git header")?;
let old = old
.strip_prefix("a/")
.context("old path without `a/` prefix")?;
Ok((old.to_owned(), rest.to_owned()))
}
}
/// The path of a `--- a/X` / `+++ b/Y` line: the prefix stripped, git's
/// trailing padding tab (for paths containing spaces) removed and C-style
/// quoting undone. These lines name the two sides unambiguously, unlike the
/// `diff --git` header.
fn diff_line_path(line: &str, prefix: &str) -> Result<String> {
let line = line.trim_end_matches('\t');
if line.starts_with('"') {
let (path, _) = take_quoted(line).context("unterminated quoted path")?;
let path = path
.strip_prefix(prefix)
.context("diff line path without `a/` or `b/` prefix")?;
unquote_path(path)
} else {
Ok(line
.strip_prefix(prefix)
.context("diff line path without `a/` or `b/` prefix")?
.to_owned())
}
}
/// The content of a git C-style quoted path (opening `"`, escaped content,
/// closing `"`) and the rest of the input; `None` if unterminated.
///
/// Iterates by character so the returned slices always land on UTF-8
/// boundaries, even for non-ASCII paths.
fn take_quoted(input: &str) -> Option<(&str, &str)> {
let mut end = 1; // byte after the opening quote
let mut rest = &input[1..];
while let Some(ch) = rest.chars().next() {
let len = ch.len_utf8();
match ch {
'\\' => {
// Consume the escaped character too (it may be multi-byte).
let escaped = rest[len..].chars().next()?;
let consumed = len + escaped.len_utf8();
end += consumed;
rest = &rest[consumed..];
}
'"' => return Some((&input[1..end], &input[end + len..])),
_ => {
end += len;
rest = &rest[len..];
}
}
}
None
}
/// Undo git's C-style path quoting (`\NNN` octal escapes, `\"`, `\\`).
fn unquote_path(path: &str) -> Result<String> {
if !path.contains('\\') {
return Ok(path.to_owned());
}
let mut out = Vec::with_capacity(path.len());
let mut bytes = path.as_bytes();
while let Some((&b, rest)) = bytes.split_first() {
bytes = rest;
if b == b'\\' {
match bytes.split_first() {
Some((&b'"', rest)) | Some((&b'\\', rest)) => {
out.push(b);
bytes = rest;
}
Some((&b'n', rest)) => {
out.push(b'\n');
bytes = rest;
}
Some((&b't', rest)) => {
out.push(b'\t');
bytes = rest;
}
Some((&d1, rest)) if (b'0'..=b'7').contains(&d1) => {
let Some((&d2, rest)) = rest.split_first() else {
bail!("malformed octal escape in quoted path");
};
let Some((&d3, rest)) = rest.split_first() else {
bail!("malformed octal escape in quoted path");
};
if !(b'0'..=b'7').contains(&d2) || !(b'0'..=b'7').contains(&d3) {
bail!("malformed octal escape in quoted path");
}
let code =
(d1 - b'0') as u16 * 64 + (d2 - b'0') as u16 * 8 + (d3 - b'0') as u16;
if code > u8::MAX as u16 {
bail!("octal escape out of range in quoted path");
}
out.push(code as u8);
bytes = rest;
}
_ => bail!("malformed escape in quoted path"),
}
} else {
out.push(b);
}
}
String::from_utf8(out).context("invalid UTF-8 in quoted path")
}
/// Collects the hunks of one blob diff while tracking per-line numbers.
///
/// The unified-diff headers give the 1-based start line of the hunk in each
@@ -1401,4 +1743,292 @@ mod tests {
assert_eq!(file.insertions, 0);
assert_eq!(file.deletions, 0);
}
#[test]
fn parses_format_patch_output() {
let patch = r#"From 1f6c0c5f3f1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a Mon Sep 17 00:00:00 2001
From: A <a@b.c>
Subject: [PATCH] fix
fix the thing
---
src/lib.rs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/lib.rs b/src/lib.rs
index 1234567..89abcde 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,3 +1,3 @@
fn main() {
- println!("old");
+ println!("new");
}
"#;
let diff = patch_diffs(patch).expect("parse");
assert_eq!(diff.files.len(), 1);
let file = &diff.files[0];
assert_eq!(file.path, "src/lib.rs");
assert_eq!(file.old_path, None);
assert_eq!(file.status, DiffStatus::Modified);
assert_eq!(file.insertions, 1);
assert_eq!(file.deletions, 1);
let hunk = &file.hunks[0];
assert_eq!(hunk.old_start, 1);
assert_eq!(hunk.old_lines, 3);
assert_eq!(hunk.new_start, 1);
assert_eq!(hunk.new_lines, 3);
assert_eq!(hunk.lines.len(), 4);
assert_eq!(hunk.lines[0].kind, DiffLineKind::Context);
assert_eq!(hunk.lines[0].old, Some(1));
assert_eq!(hunk.lines[0].new, Some(1));
assert_eq!(hunk.lines[1].kind, DiffLineKind::Deletion);
assert_eq!(hunk.lines[1].old, Some(2));
assert_eq!(hunk.lines[1].new, None);
assert_eq!(hunk.lines[2].kind, DiffLineKind::Addition);
assert_eq!(hunk.lines[2].old, None);
assert_eq!(hunk.lines[2].new, Some(2));
assert_eq!(hunk.lines[3].kind, DiffLineKind::Context);
assert_eq!(hunk.lines[3].old, Some(3));
assert_eq!(hunk.lines[3].new, Some(3));
}
#[test]
fn parses_new_file_as_added() {
let patch = r#"diff --git a/README.md b/README.md
new file mode 100644
index 0000000..1234567
--- /dev/null
+++ b/README.md
@@ -0,0 +1 @@
+# hello
"#;
let diff = patch_diffs(patch).expect("parse");
let file = &diff.files[0];
assert_eq!(file.path, "README.md");
assert_eq!(file.status, DiffStatus::Added);
assert_eq!(file.old_path, None);
assert_eq!(file.insertions, 1);
assert_eq!(file.deletions, 0);
assert_eq!(file.hunks[0].old_start, 0);
assert_eq!(file.hunks[0].old_lines, 0);
assert_eq!(file.hunks[0].new_start, 1);
}
#[test]
fn parses_renames_with_old_path() {
let patch = r#"diff --git a/old.rs b/new.rs
similarity index 85%
rename from old.rs
rename to new.rs
index 123..456 100644
--- a/old.rs
+++ b/new.rs
@@ -1 +1 @@
-fn main() {}
+fn main() { println!("hi"); }
"#;
let diff = patch_diffs(patch).expect("parse");
let file = &diff.files[0];
assert_eq!(file.path, "new.rs");
assert_eq!(file.old_path.as_deref(), Some("old.rs"));
assert_eq!(file.status, DiffStatus::Renamed);
assert_eq!(file.insertions, 1);
assert_eq!(file.deletions, 1);
}
#[test]
fn parses_patch_series_and_skips_envelope() {
let patch = r#"From aaaa Mon Sep 17 00:00:00 2001
From: A <a@b.c>
Subject: [PATCH 1/2] one
---
a.txt | 1 +
1 file changed, 1 insertion(+)
diff --git a/a.txt b/a.txt
index 1..2 100644
--- a/a.txt
+++ b/a.txt
@@ -1 +1,2 @@
a
+b
From bbbb Mon Sep 17 00:00:00 2001
From: A <a@b.c>
Subject: [PATCH 2/2] two
diff --git a/b.txt b/b.txt
index 3..4 100644
--- a/b.txt
+++ b/b.txt
@@ -1 +1 @@
-x
+y
"#;
let diff = patch_diffs(patch).expect("parse");
assert_eq!(diff.files.len(), 2);
assert_eq!(diff.files[0].path, "a.txt");
assert_eq!(diff.files[0].insertions, 1);
assert_eq!(diff.files[1].path, "b.txt");
assert_eq!(diff.files[1].deletions, 1);
}
#[test]
fn marks_binary_sections() {
let patch = r#"diff --git a/img.png b/img.png
index 123..456 100644
Binary files a/img.png and b/img.png differ
"#;
let diff = patch_diffs(patch).expect("parse");
assert!(diff.files[0].binary);
assert!(diff.files[0].hunks.is_empty());
}
#[test]
fn unquotes_quoted_paths() {
let patch = r#"diff --git "a/weird file.rs" "b/weird file.rs"
index 123..456 100644
--- "a/weird file.rs"
+++ "b/weird file.rs"
@@ -1 +1 @@
-x
+y
"#;
let diff = patch_diffs(patch).expect("parse");
assert_eq!(diff.files[0].path, "weird file.rs");
assert_eq!(diff.files[0].status, DiffStatus::Modified);
}
#[test]
fn unquotes_non_ascii_quoted_paths() {
let patch = r#"diff --git "a/说明.md" "b/说明.md"
index 123..456 100644
--- "a/说明.md"
+++ "b/说明.md"
@@ -1 +1 @@
-x
+y
"#;
let diff = patch_diffs(patch).expect("parse");
assert_eq!(diff.files[0].path, "说明.md");
assert_eq!(diff.files[0].status, DiffStatus::Modified);
}
#[test]
fn unquotes_octal_escaped_paths() {
let patch = r#"diff --git "a/\345\270\226.md" "b/\345\270\226.md"
index 123..456 100644
--- "a/\345\270\226.md"
+++ "b/\345\270\226.md"
@@ -1 +1 @@
-x
+y
"#;
let diff = patch_diffs(patch).expect("parse");
assert_eq!(diff.files[0].path, "帖.md");
assert_eq!(diff.files[0].status, DiffStatus::Modified);
}
#[test]
fn empty_or_unparseable_patch_yields_no_files() {
assert_eq!(patch_diffs("").expect("parse").files.len(), 0);
assert_eq!(patch_diffs("just some text").expect("parse").files.len(), 0);
assert_eq!(
patch_diffs("---\nnot a patch\n")
.expect("parse")
.files
.len(),
0
);
}
#[test]
fn parses_real_format_patch_output() {
// Build a commit touching a mix of file kinds, then feed genuine
// `git format-patch` output through the parser: quoted paths (space
// in the name), octal-escaped paths (UTF-8 name), a rename-free
// modification, an addition and a binary deletion.
let (dir, repo) = fixture(&[
("src/main.rs", b"fn main() {\n println!(\"one\");\n}\n"),
("my file.txt", b"hello\n"),
("\u{8bf4}\u{660e}.md", "# \u{8bf4}\u{660e}\n".as_bytes()),
("img.png", b"\x89PNG\r\n\x1a\n\x00binary"),
]);
commit_all(&repo, "initial");
std::fs::write(
dir.path().join("src/main.rs"),
b"fn main() {\n println!(\"two\");\n println!(\"three\");\n}\n",
)
.expect("write");
std::fs::write(dir.path().join("my file.txt"), b"hello world\n").expect("write");
std::fs::write(
dir.path().join("\u{8bf4}\u{660e}.md"),
"# \u{8bf4}\u{660e}\nupdated\n",
)
.expect("write");
std::fs::remove_file(dir.path().join("img.png")).expect("remove");
std::fs::write(dir.path().join("new file.md"), b"# new\n").expect("write");
commit_all(&repo, "changes");
let output = Command::new("git")
.current_dir(dir.path())
.env("GIT_AUTHOR_NAME", "Test Author")
.env("GIT_AUTHOR_EMAIL", "test@example.com")
.env("GIT_COMMITTER_NAME", "Test Author")
.env("GIT_COMMITTER_EMAIL", "test@example.com")
.args(["format-patch", "-1", "--stdout"])
.output()
.expect("spawn git format-patch");
assert!(output.status.success(), "git format-patch failed");
let patch = String::from_utf8(output.stdout).expect("patch is utf-8");
let diff = patch_diffs(&patch).expect("parse real format-patch output");
let by_path = |path: &str| {
diff.files
.iter()
.find(|file| file.path == path)
.unwrap_or_else(|| panic!("missing file {path:?}"))
};
// Space in the name: git quotes the path in the header.
let file = by_path("my file.txt");
assert_eq!(file.status, DiffStatus::Modified);
assert_eq!(file.insertions, 1);
// UTF-8 name: git emits the path as octal escapes.
let file = by_path("\u{8bf4}\u{660e}.md");
assert_eq!(file.status, DiffStatus::Modified);
assert_eq!(file.insertions, 1);
let file = by_path("src/main.rs");
assert_eq!(file.status, DiffStatus::Modified);
assert_eq!(file.insertions, 2);
assert_eq!(file.deletions, 1);
assert!(!file.hunks.is_empty());
let file = by_path("new file.md");
assert_eq!(file.status, DiffStatus::Added);
assert_eq!(file.insertions, 1);
// Binary deletion: git emits no ---/+++ lines, only the mode and
// the "Binary files" marker.
let file = by_path("img.png");
assert_eq!(file.status, DiffStatus::Deleted);
assert!(file.binary);
assert!(file.hunks.is_empty());
}
}