use std::path::Path;
use crate::tools::fs::FsError;
pub(crate) fn apply_unified_diff(
content: &str,
diff_text: &str,
path: &Path,
) -> Result<String, FsError> {
let hunks = parse_hunks(diff_text)?;
if hunks.is_empty() {
return Err(FsError::DiffHunkHeader {
reason: "no '@@ -l,s +l,s @@' hunk header found in diff".to_string(),
});
}
let had_trailing_newline = content.ends_with('\n');
let orig_lines: Vec<&str> = content.lines().collect();
let mut out: Vec<String> = Vec::with_capacity(orig_lines.len());
let mut cursor = 0usize;
let mut trailing_newline_override: Option<bool> = None;
let last_hunk_idx = hunks.len() - 1;
for (idx, hunk) in hunks.iter().enumerate() {
let start = hunk.old_start.saturating_sub(1); if start < cursor || start > orig_lines.len() {
return Err(FsError::DiffContextMismatch {
path: path.to_path_buf(),
line: hunk.old_start,
reason: "hunk start is out of order or past end of file".to_string(),
});
}
out.extend(orig_lines[cursor..start].iter().map(|s| s.to_string()));
cursor = start;
for line in &hunk.lines {
match line {
HunkLine::Context(text) => {
verify_line(orig_lines.get(cursor), text, hunk.old_start, path)?;
out.push(text.clone());
cursor += 1;
}
HunkLine::Removal(text) => {
verify_line(orig_lines.get(cursor), text, hunk.old_start, path)?;
cursor += 1;
}
HunkLine::Addition(text) => {
out.push(text.clone());
}
}
}
if idx == last_hunk_idx && cursor == orig_lines.len() {
trailing_newline_override = match (hunk.new_tail_no_newline, hunk.old_tail_no_newline) {
(true, _) => Some(false),
(false, true) => Some(true),
(false, false) => None,
};
}
}
out.extend(orig_lines[cursor..].iter().map(|s| s.to_string()));
let mut result = out.join("\n");
if trailing_newline_override.unwrap_or(had_trailing_newline) {
result.push('\n');
}
Ok(result)
}
fn verify_line(
actual: Option<&&str>,
expected: &str,
hunk_line: usize,
path: &Path,
) -> Result<(), FsError> {
match actual {
Some(a) if *a == expected => Ok(()),
Some(a) => Err(FsError::DiffContextMismatch {
path: path.to_path_buf(),
line: hunk_line,
reason: format!("expected {expected:?}, found {a:?}"),
}),
None => Err(FsError::DiffContextMismatch {
path: path.to_path_buf(),
line: hunk_line,
reason: format!("expected {expected:?}, found end of file"),
}),
}
}
#[derive(Debug, Clone, PartialEq)]
enum HunkLine {
Context(String),
Removal(String),
Addition(String),
}
#[derive(Debug, Clone, PartialEq)]
struct Hunk {
old_start: usize,
lines: Vec<HunkLine>,
old_tail_no_newline: bool,
new_tail_no_newline: bool,
}
fn parse_hunks(diff_text: &str) -> Result<Vec<Hunk>, FsError> {
let mut hunks = Vec::new();
let mut current: Option<Hunk> = None;
for raw_line in diff_text.lines() {
if let Some(header) = raw_line.strip_prefix("@@ ") {
if let Some(hunk) = current.take() {
hunks.push(hunk);
}
let old_start = parse_hunk_header(header)?;
current = Some(Hunk {
old_start,
lines: Vec::new(),
old_tail_no_newline: false,
new_tail_no_newline: false,
});
continue;
}
if current.is_none()
&& (raw_line.starts_with("--- ")
|| raw_line.starts_with("+++ ")
|| raw_line.starts_with("diff --git")
|| raw_line.starts_with("index "))
{
continue;
}
let Some(hunk) = current.as_mut() else {
continue; };
if raw_line.is_empty() {
hunk.lines.push(HunkLine::Context(String::new()));
continue;
}
match raw_line.as_bytes()[0] {
b' ' => hunk
.lines
.push(HunkLine::Context(raw_line[1..].to_string())),
b'-' => hunk
.lines
.push(HunkLine::Removal(raw_line[1..].to_string())),
b'+' => hunk
.lines
.push(HunkLine::Addition(raw_line[1..].to_string())),
b'\\' => {
match hunk.lines.last() {
Some(HunkLine::Context(_)) => {
hunk.old_tail_no_newline = true;
hunk.new_tail_no_newline = true;
}
Some(HunkLine::Removal(_)) => hunk.old_tail_no_newline = true,
Some(HunkLine::Addition(_)) => hunk.new_tail_no_newline = true,
None => {}
}
continue;
}
_ => {
return Err(FsError::DiffHunkHeader {
reason: format!("unrecognised hunk line prefix: {raw_line:?}"),
});
}
}
}
if let Some(hunk) = current.take() {
hunks.push(hunk);
}
Ok(hunks)
}
fn parse_hunk_header(header: &str) -> Result<usize, FsError> {
let old_range = header
.split_whitespace()
.next()
.and_then(|tok| tok.strip_prefix('-'))
.ok_or_else(|| FsError::DiffHunkHeader {
reason: format!("missing '-old_start' range in header: {header:?}"),
})?;
let old_start_str = old_range.split(',').next().unwrap_or(old_range);
old_start_str
.parse::<usize>()
.map_err(|_| FsError::DiffHunkHeader {
reason: format!("non-numeric old_start in header: {header:?}"),
})
}
#[cfg(test)]
mod tests {
use std::path::Path;
use super::*;
#[test]
fn apply_single_hunk() {
let content = "line1\nline2\nline3\n";
let diff = "@@ -2,1 +2,1 @@\n-line2\n+line2-changed\n";
let updated = apply_unified_diff(content, diff, Path::new("f.py")).expect("must apply");
assert_eq!(updated, "line1\nline2-changed\nline3\n");
}
#[test]
fn apply_multiple_hunks() {
let content = "a\nb\nc\nd\ne\n";
let diff = "@@ -1,1 +1,1 @@\n-a\n+A\n@@ -4,1 +4,1 @@\n-d\n+D\n";
let updated = apply_unified_diff(content, diff, Path::new("f.py")).expect("must apply");
assert_eq!(updated, "A\nb\nc\nD\ne\n");
}
#[test]
fn apply_pure_addition_hunk() {
let content = "a\nb\n";
let diff = "@@ -1,1 +1,2 @@\n a\n+inserted\n b\n";
let updated = apply_unified_diff(content, diff, Path::new("f.py")).expect("must apply");
assert_eq!(updated, "a\ninserted\nb\n");
}
#[test]
fn apply_context_mismatch_errors() {
let content = "line1\nline2\nline3\n";
let diff = "@@ -2,1 +2,1 @@\n-not-line2\n+x\n";
let err = apply_unified_diff(content, diff, Path::new("f.py")).expect_err("must mismatch");
assert!(matches!(err, FsError::DiffContextMismatch { .. }));
}
#[test]
fn apply_no_hunks_errors() {
let err = apply_unified_diff("content\n", "not a diff at all", Path::new("f.py"))
.expect_err("must error");
assert!(matches!(err, FsError::DiffHunkHeader { .. }));
}
#[test]
fn apply_bad_header_errors() {
let err = apply_unified_diff(
"content\n",
"@@ -x,y +1,1 @@\n-content\n+x\n",
Path::new("f.py"),
)
.expect_err("must error on bad header");
assert!(matches!(err, FsError::DiffHunkHeader { .. }));
}
#[test]
fn apply_ignores_file_header_lines() {
let content = "a\nb\n";
let diff = "--- a/f.py\n+++ b/f.py\n@@ -1,1 +1,1 @@\n-a\n+A\n";
let updated = apply_unified_diff(content, diff, Path::new("f.py")).expect("must apply");
assert_eq!(updated, "A\nb\n");
}
#[test]
fn apply_footer_marker_after_removal_only_forces_trailing_newline() {
let content = "a\nb"; let diff = "@@ -1,2 +1,2 @@\n a\n-b\n\\ No newline at end of file\n+B\n";
let updated = apply_unified_diff(content, diff, Path::new("f.py")).expect("must apply");
assert_eq!(updated, "a\nB\n");
}
#[test]
fn apply_footer_marker_after_addition_removes_trailing_newline() {
let content = "a\nb\n"; let diff = "@@ -1,2 +1,2 @@\n a\n-b\n+B\n\\ No newline at end of file\n";
let updated = apply_unified_diff(content, diff, Path::new("f.py")).expect("must apply");
assert_eq!(updated, "a\nB");
}
#[test]
fn apply_footer_marker_on_both_sides_keeps_no_trailing_newline() {
let content = "a\nb"; let diff = "@@ -1,2 +1,2 @@\n a\n-b\n\\ No newline at end of file\n+B\n\\ No newline at end of file\n";
let updated = apply_unified_diff(content, diff, Path::new("f.py")).expect("must apply");
assert_eq!(updated, "a\nB");
}
}