//! A small line-oriented unified diff: the CLI's `--diff` and the MCP //! server's `dry_run` print the same hunks through this one function. //! Moved here from `crates/lucisv/src/diff.rs` unchanged (Handshake MCP-1, //! `docs/features/mcp-edit-tools/README.md`); the CLI re-exports it. //! //! The hunks are not a minimal edit script: on a divergence the two //! sides are resynchronized with a bounded forward search. That keeps //! the code short and the memory linear, at the cost of occasionally //! reporting a coarser change than GNU `diff` would. /// Unchanged lines printed around each hunk. const CONTEXT: usize = 3; /// Unchanged lines that must line up before the sides count as resynced. const SYNC_RUN: usize = 3; /// How far ahead a resynchronization point is searched for. const MAX_SCAN: usize = 200; /// Pseudo-line standing in for a missing final newline. const NO_NEWLINE: &str = "\\ No newline at end of file"; #[derive(Clone, Copy, PartialEq)] enum Tag { Keep, Del, Ins, } /// Renders the changes from `old` to `new` as a unified-style diff. /// Returns an empty string if the two texts are equal. pub fn unified(path: &str, old: &str, new: &str) -> String { if old == new { return String::new(); } let old = split_lines(old); let new = split_lines(new); let edits = edits(&old, &new); let mut out = format!("--- {path}\n+++ {path}\n"); render_hunks(&edits, &mut out); out } /// Splits into lines *keeping* each terminator, so a final line with no /// newline compares unequal to its terminated twin and shows up as a /// change, exactly as GNU diff treats it. fn split_lines(text: &str) -> Vec<&str> { let mut lines = Vec::new(); let mut rest = text; while !rest.is_empty() { let end = rest.find('\n').map_or(rest.len(), |p| p + 1); lines.push(&rest[..end]); rest = &rest[end..]; } lines } fn edits<'a>(old: &[&'a str], new: &[&'a str]) -> Vec<(Tag, &'a str)> { let mut out = Vec::new(); let (mut i, mut j) = (0, 0); while i < old.len() && j < new.len() { if old[i] == new[j] { out.push((Tag::Keep, old[i])); i += 1; j += 1; continue; } let Some((di, dj)) = resync(old, new, i, j) else { break }; out.extend(old[i..i + di].iter().map(|l| (Tag::Del, *l))); out.extend(new[j..j + dj].iter().map(|l| (Tag::Ins, *l))); i += di; j += dj; } out.extend(old[i..].iter().map(|l| (Tag::Del, *l))); out.extend(new[j..].iter().map(|l| (Tag::Ins, *l))); out } /// Finds the smallest pair of skip counts that puts the two sides back /// in step, preferring the shortest total divergence. fn resync(old: &[&str], new: &[&str], i: usize, j: usize) -> Option<(usize, usize)> { for d in 1..=MAX_SCAN { for k in 0..=d { for (di, dj) in [(d, k), (k, d)] { if i + di <= old.len() && j + dj <= new.len() && in_step(old, new, i + di, j + dj) { return Some((di, dj)); } } } } None } fn in_step(old: &[&str], new: &[&str], i: usize, j: usize) -> bool { let available = (old.len() - i).min(new.len() - j); if available == 0 { // Both sides running out together is a valid resync point. return old.len() - i == new.len() - j; } (0..SYNC_RUN.min(available)).all(|k| old[i + k] == new[j + k]) } fn render_hunks(edits: &[(Tag, &str)], out: &mut String) { // Line numbers each edit occupies on the old and the new side. let mut rows = Vec::with_capacity(edits.len()); let (mut old_no, mut new_no) = (1usize, 1usize); for &(tag, text) in edits { rows.push((tag, text, old_no, new_no)); match tag { Tag::Keep => { old_no += 1; new_no += 1; } Tag::Del => old_no += 1, Tag::Ins => new_no += 1, } } let mut start = 0; while start < rows.len() { let Some(first) = (start..rows.len()).find(|&r| rows[r].0 != Tag::Keep) else { break }; let mut last = first; // Extend while the next change is close enough that its context // would touch this hunk's. loop { let reach = (last + 2 * CONTEXT + 1).min(rows.len()); match (last + 1..reach).find(|&r| rows[r].0 != Tag::Keep) { Some(next) => last = next, None => break, } } let from = first.saturating_sub(CONTEXT); let to = (last + CONTEXT + 1).min(rows.len()); render_one_hunk(&rows[from..to], out); start = to; } } fn render_one_hunk(rows: &[(Tag, &str, usize, usize)], out: &mut String) { let old_count = rows.iter().filter(|r| r.0 != Tag::Ins).count(); let new_count = rows.iter().filter(|r| r.0 != Tag::Del).count(); let (old_start, new_start) = (rows[0].2, rows[0].3); out.push_str(&format!("@@ -{old_start},{old_count} +{new_start},{new_count} @@\n")); for &(tag, text, _, _) in rows { let sign = match tag { Tag::Keep => ' ', Tag::Del => '-', Tag::Ins => '+', }; out.push(sign); match text.strip_suffix('\n') { Some(body) => { out.push_str(body); out.push('\n'); } None => { // patch(1) expects the marker bare, on its own line, // directly after the unterminated line. out.push_str(text); out.push('\n'); out.push_str(NO_NEWLINE); out.push('\n'); } } } } #[cfg(test)] mod tests { use super::*; #[test] fn equal_texts_produce_nothing() { assert_eq!(unified("f.sv", "a\nb\n", "a\nb\n"), ""); } #[test] fn single_line_change_keeps_context() { let old = "1\n2\n3\n4\n5\n6\n7\n8\n9\n"; let new = "1\n2\n3\n4\nX\n6\n7\n8\n9\n"; let d = unified("f.sv", old, new); assert!(d.starts_with("--- f.sv\n+++ f.sv\n@@ -2,7 +2,7 @@\n"), "{d}"); assert!(d.contains("\n-5\n+X\n"), "{d}"); // Context is bounded: the first and last lines stay out of it. assert!(!d.contains("\n 1\n"), "{d}"); assert!(!d.contains("\n 9\n"), "{d}"); } #[test] fn distant_changes_become_separate_hunks() { let old: String = (0..40).map(|i| format!("{i}\n")).collect(); let new = old.replace("\n1\n", "\nX\n").replace("\n30\n", "\nY\n"); let d = unified("f.sv", &old, &new); assert_eq!(d.matches("@@ ").count(), 2, "{d}"); assert!(d.contains("-1\n+X\n") && d.contains("-30\n+Y\n"), "{d}"); } #[test] fn insertions_and_deletions_are_reported_separately() { let d = unified("f.sv", "a\nb\nc\n", "a\nb\nb2\nc\n"); assert!(d.contains("+b2\n"), "{d}"); assert!(!d.contains("-b\n"), "{d}"); let d = unified("f.sv", "a\nb\nc\nd\n", "a\nc\nd\n"); assert!(d.contains("-b\n"), "{d}"); // No insertions in the hunk body (the `+++` header line aside). assert!(!d.lines().skip(2).any(|l| l.starts_with('+')), "{d}"); } #[test] fn missing_final_newline_matches_patch_format() { // The unterminated line is the change; the marker follows it bare. let d = unified("f.sv", "a\nb", "a\nb\n"); assert!(d.contains("-b\n\\ No newline at end of file\n+b\n"), "{d}"); let d = unified("f.sv", "a\nb\n", "a\nb"); assert!(d.contains("-b\n+b\n\\ No newline at end of file\n"), "{d}"); } #[test] fn wholly_different_texts_diff_as_replacement() { let d = unified("f.sv", "a\nb\n", "x\ny\n"); assert!(d.contains("-a\n-b\n+x\n+y\n"), "{d}"); } }