Skip to main content

git_internal/
diff.rs

1//! Unified diff generation utilities that compare blobs/trees, map deltas back to line numbers,
2//! and emit Myers-based unified diffs for Git objects while guarding against pathological inputs.
3
4use std::{
5    collections::{HashMap, HashSet, VecDeque},
6    fmt::Write,
7    path::{Path, PathBuf},
8};
9
10use path_absolutize::Absolutize;
11use similar::{Algorithm, ChangeTag, TextDiff};
12
13use crate::hash::ObjectHash;
14
15/// Result item for a single file diff:
16/// - `path`: logical file path
17/// - `data`: unified diff text or a large-file marker
18#[derive(Debug, Clone)]
19pub struct DiffItem {
20    /// The file path being diffed.
21    pub path: String,
22    /// The complete unified diff output string for that file, or a large-file marker if the file is too large to diff.
23    pub data: String,
24}
25
26/// Unified diff generator and helpers.
27pub struct Diff;
28
29/// Diff line operation types primarily used by blame computation to map parent/child lines.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub enum DiffOperation {
32    Insert { line: usize, content: String },
33    Delete { line: usize },
34    Equal { old_line: usize, new_line: usize },
35}
36
37/// Internal representation of diff lines used while assembling unified hunks.
38#[derive(Debug, Clone, Copy)]
39enum EditLine<'a> {
40    // old_line, new_line, text
41    Context(Option<usize>, Option<usize>, &'a str),
42    // old_line, text
43    Delete(usize, &'a str),
44    // new_line, text
45    Insert(usize, &'a str),
46}
47
48impl Diff {
49    /// Compute Myers line-level operations (equal/insert/delete) for blame/line mapping.
50    fn compute_line_operations(old_lines: &[String], new_lines: &[String]) -> Vec<DiffOperation> {
51        if old_lines.is_empty() && new_lines.is_empty() {
52            return Vec::new();
53        }
54
55        let old_refs: Vec<&str> = old_lines.iter().map(|s| s.as_str()).collect();
56        let new_refs: Vec<&str> = new_lines.iter().map(|s| s.as_str()).collect();
57
58        let diff = TextDiff::configure()
59            .algorithm(Algorithm::Myers)
60            .diff_slices(&old_refs, &new_refs);
61
62        let mut operations = Vec::with_capacity(old_lines.len() + new_lines.len());
63        let mut old_line_no = 1usize;
64        let mut new_line_no = 1usize;
65
66        for change in diff.iter_all_changes() {
67            match change.tag() {
68                ChangeTag::Equal => {
69                    operations.push(DiffOperation::Equal {
70                        old_line: old_line_no,
71                        new_line: new_line_no,
72                    });
73                    old_line_no += 1;
74                    new_line_no += 1;
75                }
76                ChangeTag::Delete => {
77                    operations.push(DiffOperation::Delete { line: old_line_no });
78                    old_line_no += 1;
79                }
80                ChangeTag::Insert => {
81                    operations.push(DiffOperation::Insert {
82                        line: new_line_no,
83                        content: change.value().to_string(),
84                    });
85                    new_line_no += 1;
86                }
87            }
88        }
89
90        operations
91    }
92
93    const MAX_DIFF_LINES: usize = 10_000; // safety cap for pathological inputs
94    const LARGE_FILE_MARKER: &'static str = "<LargeFile>";
95    const LARGE_FILE_END: &'static str = "</LargeFile>";
96    const SHORT_HASH_LEN: usize = 7;
97
98    /// Compute diffs for a set of files, honoring an optional filter and emitting unified diffs.
99    pub fn diff<F>(
100        old_blobs: Vec<(PathBuf, ObjectHash)>,
101        new_blobs: Vec<(PathBuf, ObjectHash)>,
102        filter: Vec<PathBuf>,
103        read_content: F,
104    ) -> Vec<DiffItem>
105    where
106        F: Fn(&PathBuf, &ObjectHash) -> Vec<u8>,
107    {
108        let (processed_files, old_blobs_map, new_blobs_map) =
109            Self::prepare_diff_data(old_blobs, new_blobs, &filter);
110
111        let mut diff_results: Vec<DiffItem> = Vec::with_capacity(processed_files.len());
112        for file in processed_files {
113            // Read bytes once per file to avoid duplicate IO and conversions.
114            let old_hash = old_blobs_map.get(&file);
115            let new_hash = new_blobs_map.get(&file);
116            let old_bytes = old_hash.map_or_else(Vec::new, |h| read_content(&file, h));
117            let new_bytes = new_hash.map_or_else(Vec::new, |h| read_content(&file, h));
118
119            if let Some(large_file_marker) =
120                Self::is_large_file_bytes(&file, &old_bytes, &new_bytes)
121            {
122                diff_results.push(DiffItem {
123                    path: file.to_string_lossy().to_string(),
124                    data: large_file_marker,
125                });
126            } else {
127                let diff = Self::diff_for_file_preloaded(
128                    &file, old_hash, new_hash, &old_bytes, &new_bytes,
129                );
130                diff_results.push(DiffItem {
131                    path: file.to_string_lossy().to_string(),
132                    data: diff,
133                });
134            }
135        }
136
137        diff_results
138    }
139
140    /// Large-file detection without re-reading: counts lines from already-loaded bytes.
141    fn is_large_file_bytes(file: &Path, old_bytes: &[u8], new_bytes: &[u8]) -> Option<String> {
142        let old_lines = String::from_utf8_lossy(old_bytes).lines().count();
143        let new_lines = String::from_utf8_lossy(new_bytes).lines().count();
144        let total_lines = old_lines + new_lines;
145        if total_lines > Self::MAX_DIFF_LINES {
146            Some(format!(
147                "{}{}:{}:{}{}\n",
148                Self::LARGE_FILE_MARKER,
149                file.display(),
150                total_lines,
151                Self::MAX_DIFF_LINES,
152                Self::LARGE_FILE_END
153            ))
154        } else {
155            None
156        }
157    }
158
159    /// Build maps, union file set, and apply filter/path checks.
160    fn prepare_diff_data(
161        old_blobs: Vec<(PathBuf, ObjectHash)>,
162        new_blobs: Vec<(PathBuf, ObjectHash)>,
163        filter: &[PathBuf],
164    ) -> (
165        Vec<PathBuf>,
166        HashMap<PathBuf, ObjectHash>,
167        HashMap<PathBuf, ObjectHash>,
168    ) {
169        let old_blobs_map: HashMap<PathBuf, ObjectHash> = old_blobs.into_iter().collect();
170        let new_blobs_map: HashMap<PathBuf, ObjectHash> = new_blobs.into_iter().collect();
171        // union set
172        let union_files: HashSet<PathBuf> = old_blobs_map
173            .keys()
174            .chain(new_blobs_map.keys())
175            .cloned()
176            .collect();
177
178        // filter files that should be processed
179        let processed_files: Vec<PathBuf> = union_files
180            .into_iter()
181            .filter(|file| Self::should_process(file, filter, &old_blobs_map, &new_blobs_map))
182            .collect();
183
184        (processed_files, old_blobs_map, new_blobs_map)
185    }
186
187    /// Filter by path and hash equality; only process differing or unmatched files.
188    fn should_process(
189        file: &PathBuf,
190        filter: &[PathBuf],
191        old_blobs: &HashMap<PathBuf, ObjectHash>,
192        new_blobs: &HashMap<PathBuf, ObjectHash>,
193    ) -> bool {
194        if !filter.is_empty()
195            && !filter
196                .iter()
197                .any(|path| Self::sub_of(file, path).unwrap_or(false))
198        {
199            return false;
200        }
201
202        old_blobs.get(file) != new_blobs.get(file)
203    }
204
205    /// Check whether `path` is under `parent` (absolutized).
206    fn sub_of(path: &PathBuf, parent: &PathBuf) -> Result<bool, std::io::Error> {
207        let path_abs: PathBuf = path.absolutize()?.to_path_buf();
208        let parent_abs: PathBuf = parent.absolutize()?.to_path_buf();
209        Ok(path_abs.starts_with(parent_abs))
210    }
211
212    /// Shorten hash to 7 chars for diff headers; return zeros if missing.
213    fn short_hash(hash: Option<&ObjectHash>) -> String {
214        hash.map(|h| {
215            let hex = h.to_string();
216            let take = Self::SHORT_HASH_LEN.min(hex.len());
217            hex[..take].to_string()
218        })
219        .unwrap_or_else(|| "0".repeat(Self::SHORT_HASH_LEN))
220    }
221
222    /// Format a single file's unified diff string.
223    pub fn diff_for_file_string(
224        file: &PathBuf,
225        old_blobs: &HashMap<PathBuf, ObjectHash>,
226        new_blobs: &HashMap<PathBuf, ObjectHash>,
227        read_content: &dyn Fn(&PathBuf, &ObjectHash) -> Vec<u8>,
228    ) -> String {
229        let new_hash = new_blobs.get(file);
230        let old_hash = old_blobs.get(file);
231        let old_bytes = old_hash.map_or_else(Vec::new, |h| read_content(file, h));
232        let new_bytes = new_hash.map_or_else(Vec::new, |h| read_content(file, h));
233
234        Self::diff_for_file_preloaded(file, old_hash, new_hash, &old_bytes, &new_bytes)
235    }
236
237    /// Format a single file's unified diff using preloaded bytes to avoid re-reading.
238    fn diff_for_file_preloaded(
239        file: &Path,
240        old_hash: Option<&ObjectHash>,
241        new_hash: Option<&ObjectHash>,
242        old_bytes: &[u8],
243        new_bytes: &[u8],
244    ) -> String {
245        let mut out = String::new();
246
247        // It's safe to ignore the Result when writing into a String; allocation errors panic elsewhere.
248        let _ = writeln!(out, "diff --git a/{} b/{}", file.display(), file.display());
249
250        if old_hash.is_none() {
251            let _ = writeln!(out, "new file mode 100644");
252        } else if new_hash.is_none() {
253            let _ = writeln!(out, "deleted file mode 100644");
254        }
255
256        let old_index = Self::short_hash(old_hash);
257        let new_index = Self::short_hash(new_hash);
258        let _ = writeln!(out, "index {old_index}..{new_index} 100644");
259
260        match (
261            std::str::from_utf8(old_bytes),
262            std::str::from_utf8(new_bytes),
263        ) {
264            (Ok(old_text), Ok(new_text)) => {
265                let (old_pref, new_pref) = if old_text.is_empty() {
266                    ("/dev/null".to_string(), format!("b/{}", file.display()))
267                } else if new_text.is_empty() {
268                    (format!("a/{}", file.display()), "/dev/null".to_string())
269                } else {
270                    (
271                        format!("a/{}", file.display()),
272                        format!("b/{}", file.display()),
273                    )
274                };
275
276                let _ = writeln!(out, "--- {old_pref}");
277                let _ = writeln!(out, "+++ {new_pref}");
278
279                let unified = Self::compute_unified_diff(old_text, new_text, 3);
280                out.push_str(&unified);
281            }
282            _ => {
283                let _ = writeln!(out, "Binary files differ");
284            }
285        }
286
287        out
288    }
289
290    /// Streaming unified diff that minimizes allocations by borrowing lines
291    fn compute_unified_diff(old_text: &str, new_text: &str, context: usize) -> String {
292        // Myers line diff
293        let diff = TextDiff::configure()
294            .algorithm(Algorithm::Myers)
295            .diff_lines(old_text, new_text);
296
297        // Reserve capacity heuristic to reduce allocations
298        let mut out = String::with_capacity(((old_text.len() + new_text.len()) / 16).max(4096));
299
300        // Rolling prefix context (last `context` equal lines when outside a hunk)
301        let mut prefix_ctx: VecDeque<EditLine> = VecDeque::with_capacity(context);
302        let mut cur_hunk: Vec<EditLine> = Vec::new();
303        let mut eq_run: Vec<EditLine> = Vec::new(); // accumulating equal lines while in hunk
304        let mut in_hunk = false;
305
306        let mut last_old_seen = 0usize;
307        let mut last_new_seen = 0usize;
308        let mut old_line_no = 1usize;
309        let mut new_line_no = 1usize;
310
311        for change in diff.iter_all_changes() {
312            let line = change.value().trim_end_matches(['\r', '\n']);
313            match change.tag() {
314                ChangeTag::Equal => {
315                    let entry = EditLine::Context(Some(old_line_no), Some(new_line_no), line);
316                    old_line_no += 1;
317                    new_line_no += 1;
318                    if in_hunk {
319                        eq_run.push(entry);
320                        // Flush once trailing equal lines exceed 2*context
321                        if eq_run.len() > context * 2 {
322                            Self::flush_hunk_to_out(
323                                &mut out,
324                                &mut cur_hunk,
325                                &mut eq_run,
326                                &mut prefix_ctx,
327                                context,
328                                &mut last_old_seen,
329                                &mut last_new_seen,
330                            );
331                            in_hunk = false;
332                        }
333                    } else {
334                        if prefix_ctx.len() == context {
335                            prefix_ctx.pop_front();
336                        }
337                        prefix_ctx.push_back(entry);
338                    }
339                }
340                ChangeTag::Delete => {
341                    let entry = EditLine::Delete(old_line_no, line);
342                    old_line_no += 1;
343                    if !in_hunk {
344                        cur_hunk.extend(prefix_ctx.iter().copied());
345                        prefix_ctx.clear();
346                        in_hunk = true;
347                    }
348                    if !eq_run.is_empty() {
349                        cur_hunk.append(&mut eq_run);
350                    }
351                    cur_hunk.push(entry);
352                }
353                ChangeTag::Insert => {
354                    let entry = EditLine::Insert(new_line_no, line);
355                    new_line_no += 1;
356                    if !in_hunk {
357                        cur_hunk.extend(prefix_ctx.iter().copied());
358                        prefix_ctx.clear();
359                        in_hunk = true;
360                    }
361                    if !eq_run.is_empty() {
362                        cur_hunk.append(&mut eq_run);
363                    }
364                    cur_hunk.push(entry);
365                }
366            }
367        }
368
369        if in_hunk {
370            Self::flush_hunk_to_out(
371                &mut out,
372                &mut cur_hunk,
373                &mut eq_run,
374                &mut prefix_ctx,
375                context,
376                &mut last_old_seen,
377                &mut last_new_seen,
378            );
379        }
380
381        out
382    }
383
384    // Flush the current hunk into the output; trailing context is in `eq_run`
385    fn flush_hunk_to_out<'a>(
386        out: &mut String,
387        cur_hunk: &mut Vec<EditLine<'a>>,
388        eq_run: &mut Vec<EditLine<'a>>,
389        prefix_ctx: &mut VecDeque<EditLine<'a>>,
390        context: usize,
391        last_old_seen: &mut usize,
392        last_new_seen: &mut usize,
393    ) {
394        // 1. Append up to `context` trailing equal lines to the current hunk.
395        let trail_to_take = eq_run.len().min(context);
396        for entry in eq_run.iter().take(trail_to_take) {
397            cur_hunk.push(*entry);
398        }
399
400        // 2. Compute header numbers (line ranges/counts) by scanning the hunk.
401        let mut old_first: Option<usize> = None;
402        let mut old_count: usize = 0;
403        let mut new_first: Option<usize> = None;
404        let mut new_count: usize = 0;
405
406        for e in cur_hunk.iter() {
407            match *e {
408                EditLine::Context(o, n, _) => {
409                    if let Some(o) = o {
410                        if old_first.is_none() {
411                            old_first = Some(o);
412                        }
413                        old_count += 1;
414                    }
415                    if let Some(n) = n {
416                        if new_first.is_none() {
417                            new_first = Some(n);
418                        }
419                        new_count += 1;
420                    }
421                }
422                EditLine::Delete(o, _) => {
423                    if old_first.is_none() {
424                        old_first = Some(o);
425                    }
426                    old_count += 1;
427                }
428                EditLine::Insert(n, _) => {
429                    if new_first.is_none() {
430                        new_first = Some(n);
431                    }
432                    new_count += 1;
433                }
434            }
435        }
436
437        if old_count == 0 && new_count == 0 {
438            cur_hunk.clear();
439            eq_run.clear();
440            return;
441        }
442
443        let old_start = old_first.unwrap_or(*last_old_seen + 1);
444        let new_start = new_first.unwrap_or(*last_new_seen + 1);
445
446        let _ = writeln!(
447            out,
448            "@@ -{old_start},{old_count} +{new_start},{new_count} @@"
449        );
450
451        // 3. Output the hunk according to Myers change order
452        for &e in cur_hunk.iter() {
453            match e {
454                EditLine::Context(o, n, txt) => {
455                    let _ = writeln!(out, " {txt}");
456                    if let Some(o) = o {
457                        *last_old_seen = (*last_old_seen).max(o);
458                    }
459                    if let Some(n) = n {
460                        *last_new_seen = (*last_new_seen).max(n);
461                    }
462                }
463                EditLine::Delete(o, txt) => {
464                    let _ = writeln!(out, "-{txt}");
465                    *last_old_seen = (*last_old_seen).max(o);
466                }
467                EditLine::Insert(n, txt) => {
468                    let _ = writeln!(out, "+{txt}");
469                    *last_new_seen = (*last_new_seen).max(n);
470                }
471            }
472        }
473
474        // 4. Preserve last `context` equal lines from eq_run for prefix of next hunk.
475        prefix_ctx.clear();
476        if context > 0 {
477            let keep_start = eq_run.len().saturating_sub(context);
478            for entry in eq_run.iter().skip(keep_start) {
479                prefix_ctx.push_back(*entry);
480            }
481        }
482
483        cur_hunk.clear();
484        eq_run.clear();
485    }
486}
487
488/// Compute Myers diff operations for blame/line-mapping scenarios.
489pub fn compute_diff(old_lines: &[String], new_lines: &[String]) -> Vec<DiffOperation> {
490    Diff::compute_line_operations(old_lines, new_lines)
491}
492
493#[cfg(test)]
494mod tests {
495    use std::{collections::HashMap, fs, path::PathBuf, process::Command};
496
497    use tempfile::tempdir;
498
499    use super::{Diff, DiffOperation, compute_diff};
500    use crate::hash::{HashKind, ObjectHash, set_hash_kind_for_test};
501
502    /// Helper: run our diff on in-memory blobs and return diff text plus their hashes.
503    fn run_diff(
504        logical_path: &str,
505        old_bytes: &[u8],
506        new_bytes: &[u8],
507    ) -> (String, ObjectHash, ObjectHash) {
508        let file = PathBuf::from(logical_path);
509        let old_hash = ObjectHash::new(old_bytes);
510        let new_hash = ObjectHash::new(new_bytes);
511
512        let mut blob_store: HashMap<ObjectHash, Vec<u8>> = HashMap::new();
513        blob_store.insert(old_hash, old_bytes.to_vec());
514        blob_store.insert(new_hash, new_bytes.to_vec());
515
516        let mut old_map = HashMap::new();
517        let mut new_map = HashMap::new();
518        old_map.insert(file.clone(), old_hash);
519        new_map.insert(file.clone(), new_hash);
520
521        let reader = |_: &PathBuf, h: &ObjectHash| -> Vec<u8> {
522            blob_store.get(h).cloned().unwrap_or_default()
523        };
524
525        let diff = Diff::diff_for_file_string(&file, &old_map, &new_map, &reader);
526        (diff, old_hash, new_hash)
527    }
528
529    /// Helper: shorten hash to 7 chars for diff header normalization.
530    fn short_hash(hash: &ObjectHash) -> String {
531        hash.to_string().chars().take(7).collect()
532    }
533
534    /// Apply a unified diff (as produced by `Diff` or by `git diff`) to `old` and return the
535    /// resulting text, including its terminal-newline state.
536    ///
537    /// Header lines before the first hunk are skipped. Every hunk header
538    /// `@@ -a[,b] +c[,d] @@` is checked against the position actually reached on both sides
539    /// (so hunks must be in order on old *and* new coordinates) and against the number of
540    /// old/new lines the hunk body really contains. Inside a hunk, `' '` context and `'-'`
541    /// lines must match `old` exactly and `'+'` lines are inserted. Each output line carries
542    /// its own newline flag: a line copied from `old` keeps old's (only old's last line can
543    /// lack one), an inserted line has one unless a `\ No newline at end of file` marker
544    /// follows it, and a marker after an old-side line must agree with `old`.
545    fn apply_unified_diff(old: &str, diff: &str) -> Result<String, String> {
546        // Strict `start[,count]`: exactly one or two decimal fields, and a start of 0 is
547        // only meaningful together with a count of 0 (the "before line 1" position).
548        fn parse_range(spec: &str) -> Result<(usize, usize), String> {
549            let parts: Vec<&str> = spec.split(',').collect();
550            let (start, count): (usize, usize) = match parts.as_slice() {
551                [start] => (
552                    start
553                        .parse()
554                        .map_err(|_| format!("bad hunk range: {spec}"))?,
555                    1,
556                ),
557                [start, count] => (
558                    start
559                        .parse()
560                        .map_err(|_| format!("bad hunk range: {spec}"))?,
561                    count
562                        .parse()
563                        .map_err(|_| format!("bad hunk range: {spec}"))?,
564                ),
565                _ => return Err(format!("bad hunk range: {spec}")),
566            };
567            if start == 0 && count != 0 {
568                return Err(format!("bad hunk range: {spec}"));
569            }
570            Ok((start, count))
571        }
572
573        let old_lines: Vec<&str> = old.lines().collect();
574        let old_ends_nl = old.ends_with('\n');
575        // Newline flag of old line `k`: every line but the last certainly ends with one.
576        let old_nl = |k: usize| k + 1 < old_lines.len() || old_ends_nl;
577        let mut out: Vec<(String, bool)> = Vec::new();
578        let mut cursor = 0usize;
579        // Set once a marker declared EOF on the new side: no further new-side line may follow.
580        let mut new_eof_marked = false;
581        let mut seen_hunk = false;
582        let mut lines = diff.lines().peekable();
583        while let Some(line) = lines.next() {
584            let Some(rest) = line.strip_prefix("@@ -") else {
585                // Anything before the first hunk is the file header; after a hunk, only
586                // another hunk header may follow (single-file patches only).
587                if seen_hunk {
588                    return Err(format!("unexpected line after hunk: {line}"));
589                }
590                continue;
591            };
592            seen_hunk = true;
593            let (old_spec, tail) = rest
594                .split_once(" +")
595                .ok_or_else(|| format!("bad hunk header: {line}"))?;
596            // `<new-range> @@[ section heading]`: the closing `@@` is mandatory.
597            let (new_spec, closing) = tail
598                .split_once(' ')
599                .ok_or_else(|| format!("bad hunk header: {line}"))?;
600            if closing != "@@" && !closing.starts_with("@@ ") {
601                return Err(format!("bad hunk header: {line}"));
602            }
603            let (old_start, old_count) = parse_range(old_spec)?;
604            let (new_start, new_count) = parse_range(new_spec)?;
605            // Ranges are 1-based; a count of 0 names the line *before* the hunk.
606            let hunk_start = if old_count == 0 {
607                old_start
608            } else {
609                old_start.saturating_sub(1)
610            };
611            if hunk_start < cursor || hunk_start > old_lines.len() {
612                return Err(format!("hunk out of order on the old side: {line}"));
613            }
614            for (k, line) in old_lines.iter().enumerate().take(hunk_start).skip(cursor) {
615                out.push((line.to_string(), old_nl(k)));
616            }
617            cursor = hunk_start;
618            let expected_new_start = if new_count == 0 {
619                out.len()
620            } else {
621                out.len() + 1
622            };
623            if new_start != expected_new_start {
624                return Err(format!(
625                    "hunk out of order on the new side: {line} (expected +{expected_new_start})"
626                ));
627            }
628            let (mut consumed_old, mut produced_new) = (0usize, 0usize);
629            let mut last_kind: Option<char> = None;
630            while let Some(&body) = lines.peek() {
631                if body.starts_with("@@ ") || body.starts_with("diff --git ") {
632                    break;
633                }
634                lines.next();
635                if let Some(ctx) = body.strip_prefix(' ') {
636                    if new_eof_marked {
637                        return Err("new-side line after a no-newline marker".to_string());
638                    }
639                    if old_lines.get(cursor) != Some(&ctx) {
640                        return Err(format!("context mismatch at old line {}", cursor + 1));
641                    }
642                    out.push((ctx.to_string(), old_nl(cursor)));
643                    cursor += 1;
644                    consumed_old += 1;
645                    produced_new += 1;
646                    last_kind = Some(' ');
647                } else if let Some(del) = body.strip_prefix('-') {
648                    if old_lines.get(cursor) != Some(&del) {
649                        return Err(format!("delete mismatch at old line {}", cursor + 1));
650                    }
651                    cursor += 1;
652                    consumed_old += 1;
653                    last_kind = Some('-');
654                } else if let Some(ins) = body.strip_prefix('+') {
655                    if new_eof_marked {
656                        return Err("new-side line after a no-newline marker".to_string());
657                    }
658                    out.push((ins.to_string(), true));
659                    produced_new += 1;
660                    last_kind = Some('+');
661                } else if body.starts_with('\\') {
662                    // Only git's canonical marker text is a marker; anything else that
663                    // starts with a backslash is malformed.
664                    if body != "\\ No newline at end of file" {
665                        return Err(format!("unexpected hunk line: {body}"));
666                    }
667                    // The marker describes the line just before it.
668                    match last_kind {
669                        Some('+') => {
670                            if let Some(last) = out.last_mut() {
671                                last.1 = false;
672                            }
673                            new_eof_marked = true;
674                        }
675                        Some(' ') | Some('-') => {
676                            // Old-side line: it must be old's last line and old must lack
677                            // the final newline (the context line's own flag already says so).
678                            if cursor != old_lines.len() || old_ends_nl {
679                                return Err("newline marker does not match old".to_string());
680                            }
681                            if last_kind == Some(' ') {
682                                new_eof_marked = true;
683                            }
684                        }
685                        _ => return Err("newline marker without a line".to_string()),
686                    }
687                    // The marker itself must be the last line of its hunk on that side; a
688                    // second marker is malformed too.
689                    last_kind = Some('\\');
690                } else {
691                    return Err(format!("unexpected hunk line: {body}"));
692                }
693            }
694            if consumed_old != old_count || produced_new != new_count {
695                return Err(format!(
696                    "hunk body has {consumed_old}/{produced_new} old/new lines but the header says {old_count}/{new_count}: {line}"
697                ));
698            }
699        }
700        // A new-side EOF marker forbids an implicitly copied tail as much as explicit lines.
701        if new_eof_marked && cursor != old_lines.len() {
702            return Err("old lines remain after a new-side no-newline marker".to_string());
703        }
704        for (k, line) in old_lines.iter().enumerate().skip(cursor) {
705            out.push((line.to_string(), old_nl(k)));
706        }
707        let mut text = String::new();
708        let last = out.len().checked_sub(1);
709        for (i, (line, nl)) in out.iter().enumerate() {
710            text.push_str(line);
711            // Only the last line may lack its newline; a missing one earlier would mean
712            // two lines were glued together, which `lines()` can never produce.
713            if *nl || Some(i) != last {
714                text.push('\n');
715            }
716        }
717        Ok(text)
718    }
719
720    /// The property a unified diff must satisfy, independent of which (equally valid) edit
721    /// script a particular algorithm picks for ambiguous regions: applying it to `old`
722    /// reproduces `new`, and every emitted `-`/`+` line really comes from `old`/`new`. The
723    /// same check is run on git's own output as a harness sanity test.
724    fn assert_diff_equivalent_to_git(
725        diff_output: &str,
726        git_output: &str,
727        old_text: &str,
728        new_text: &str,
729    ) {
730        // FIX-05 (registered candidate): the `Diff` engine never emits a
731        // `\ No newline at end of file` marker, so its output cannot express a missing
732        // terminal newline. The equivalence property is therefore only claimed for
733        // newline-terminated inputs, which this precondition makes explicit.
734        assert!(
735            old_text.ends_with('\n') && new_text.ends_with('\n'),
736            "equivalence harness requires newline-terminated inputs (see FIX-05)"
737        );
738        let ours = apply_unified_diff(old_text, diff_output).expect("our diff must apply");
739        assert_eq!(
740            ours, new_text,
741            "applying our diff to old must reproduce new"
742        );
743        let theirs = apply_unified_diff(old_text, git_output).expect("git diff must apply");
744        assert_eq!(
745            theirs, new_text,
746            "harness sanity: git's diff must reproduce new"
747        );
748
749        use std::collections::HashSet;
750        let old_set: HashSet<&str> = old_text.lines().collect();
751        let new_set: HashSet<&str> = new_text.lines().collect();
752        let mut in_hunk = false;
753        let (mut deleted, mut inserted) = (0usize, 0usize);
754        for line in diff_output.lines() {
755            if line.starts_with("@@ ") {
756                in_hunk = true;
757                continue;
758            }
759            if !in_hunk {
760                continue;
761            }
762            if let Some(del) = line.strip_prefix('-') {
763                assert!(old_set.contains(del), "deleted line not in old: {del:?}");
764                deleted += 1;
765            } else if let Some(ins) = line.strip_prefix('+') {
766                assert!(new_set.contains(ins), "inserted line not in new: {ins:?}");
767                inserted += 1;
768            }
769        }
770        assert!(
771            deleted + inserted > 0,
772            "a diff of different inputs must change something"
773        );
774    }
775
776    /// Helper: run `git diff --no-index` on temp files and normalize headers for comparison.
777    fn normalized_git_diff(
778        logical_path: &str,
779        old_bytes: &[u8],
780        new_bytes: &[u8],
781        old_hash: &ObjectHash,
782        new_hash: &ObjectHash,
783    ) -> Option<String> {
784        let temp_dir = tempdir().ok()?;
785        let old_file = temp_dir.path().join("old.txt");
786        let new_file = temp_dir.path().join("new.txt");
787
788        fs::write(&old_file, old_bytes).ok()?;
789        fs::write(&new_file, new_bytes).ok()?;
790
791        let output = Command::new("git")
792            .current_dir(temp_dir.path())
793            .args(["diff", "--no-index", "--unified=3", "old.txt", "new.txt"])
794            .output()
795            .ok()?;
796
797        let stdout = String::from_utf8_lossy(&output.stdout);
798        if stdout.is_empty() {
799            return None;
800        }
801
802        let short_old = short_hash(old_hash);
803        let short_new = short_hash(new_hash);
804
805        let mut normalized = Vec::new();
806        for line in stdout.lines() {
807            let rewritten = if line.starts_with("diff --git ") {
808                format!("diff --git a/{logical_path} b/{logical_path}")
809            } else if line.starts_with("index ") {
810                format!("index {short_old}..{short_new} 100644")
811            } else if line.starts_with("--- ") {
812                format!("--- a/{logical_path}")
813            } else if line.starts_with("+++ ") {
814                format!("+++ b/{logical_path}")
815            } else if line.starts_with("@@") {
816                match line.rfind("@@") {
817                    Some(pos) if pos + 2 <= line.len() => line[..pos + 2].to_string(),
818                    _ => line.to_string(),
819                }
820            } else {
821                line.to_string()
822            };
823            normalized.push(rewritten);
824        }
825
826        Some(normalized.join("\n") + "\n")
827    }
828
829    /// Basic text diff should include headers and expected +/- markers.
830    #[test]
831    fn unified_diff_basic_changes() {
832        let _guard = set_hash_kind_for_test(HashKind::Sha256);
833        let old = b"a\nb\nc\n" as &[u8];
834        let new = b"a\nB\nc\nd\n" as &[u8];
835        let (diff, _, _) = run_diff("foo.txt", old, new);
836
837        assert!(diff.contains("diff --git a/foo.txt b/foo.txt"));
838        assert!(diff.contains("index "));
839        assert!(diff.contains("--- a/foo.txt"));
840        assert!(diff.contains("+++ b/foo.txt"));
841        assert!(diff.contains("@@"));
842        assert!(diff.contains("-b"));
843        assert!(diff.contains("+B"));
844        assert!(diff.contains("+d"));
845    }
846
847    /// Non-text inputs should yield a binary files notice.
848    #[test]
849    fn binary_files_detection() {
850        let _guard = set_hash_kind_for_test(HashKind::Sha256);
851        let old_bytes = vec![0u8, 159, 146, 150];
852        let new_bytes = vec![0xFF, 0x00, 0x01];
853        let (diff, _, _) = run_diff("bin.dat", &old_bytes, &new_bytes);
854        assert!(diff.contains("Binary files differ"));
855    }
856
857    /// The equivalence harness is not vacuous: wrong deleted/context lines, hunks out of order
858    /// on either side, wrong header counts, a wrong terminal-newline state, or a patch that
859    /// applies but yields the wrong text are all rejected.
860    #[test]
861    fn apply_unified_diff_rejects_wrong_patches() {
862        let old = "a\nb\nc\n";
863        let good = "--- a/f\n+++ b/f\n@@ -1,3 +1,3 @@\n a\n-b\n+B\n c\n";
864        assert_eq!(apply_unified_diff(old, good).unwrap(), "a\nB\nc\n");
865        // Deleted line does not exist at that position in old.
866        assert!(apply_unified_diff(old, "@@ -1,3 +1,3 @@\n a\n-x\n+B\n c\n").is_err());
867        // Context line does not match old.
868        assert!(apply_unified_diff(old, "@@ -1,3 +1,3 @@\n z\n-b\n+B\n c\n").is_err());
869        // Hunks out of order on the old side.
870        assert!(apply_unified_diff(old, "@@ -3 +3 @@\n-c\n+C\n@@ -1 +1 @@\n-a\n+A\n").is_err());
871        // Hunks ordered on the old side but inconsistent on the new side.
872        assert!(apply_unified_diff(old, "@@ -1 +3 @@\n-a\n+A\n@@ -3 +1 @@\n-c\n+C\n").is_err());
873        // Malformed headers: extra range fields, a 0 start with a nonzero count, a missing
874        // closing `@@`, or a new-side 0 start with count 1.
875        for bad in [
876            "@@ -1,3,9 +1,3 @@\n a\n-b\n+B\n c\n",
877            "@@ -0,3 +1,3 @@\n a\n-b\n+B\n c\n",
878            "@@ -1,3 +1,3\n a\n-b\n+B\n c\n",
879            "@@ -1,3 +0 @@\n a\n-b\n+B\n c\n",
880            "@@ -1,3 +1,x @@\n a\n-b\n+B\n c\n",
881        ] {
882            assert!(apply_unified_diff(old, bad).is_err(), "{bad:?}");
883        }
884        // Header counts that do not match the hunk body.
885        assert!(apply_unified_diff(old, "@@ -1,2 +1,3 @@\n a\n-b\n+B\n c\n").is_err());
886        assert!(apply_unified_diff(old, "@@ -1,3 +1,2 @@\n a\n-b\n+B\n c\n").is_err());
887        // Terminal-newline state is part of the result: removing or adding the final newline
888        // is a visible change, and a marker that contradicts old is rejected.
889        let drop_newline = "@@ -3 +3 @@\n-c\n+c\n\\ No newline at end of file\n";
890        assert_eq!(apply_unified_diff(old, drop_newline).unwrap(), "a\nb\nc");
891        let old_no_nl = "a\nb\nc";
892        let add_newline = "@@ -3 +3 @@\n-c\n\\ No newline at end of file\n+c\n";
893        assert_eq!(
894            apply_unified_diff(old_no_nl, add_newline).unwrap(),
895            "a\nb\nc\n"
896        );
897        assert!(apply_unified_diff(old, add_newline).is_err());
898        // A hunk in the middle: the copied tail keeps old's newline state.
899        let mid = "@@ -1,2 +1,2 @@\n-a\n+A\n b\n";
900        assert_eq!(apply_unified_diff(old, mid).unwrap(), "A\nb\nc\n");
901        assert_eq!(apply_unified_diff(old_no_nl, mid).unwrap(), "A\nb\nc");
902        // Deleting the final line that lacks a newline: the new last line ("a") keeps the
903        // newline it had in old.
904        let delete_last = "@@ -1,2 +1 @@\n a\n-b\n\\ No newline at end of file\n";
905        assert_eq!(apply_unified_diff("a\nb", delete_last).unwrap(), "a\n");
906        // Appending after a last line that lacks a newline: git emits the marker after the
907        // deleted copy of that line, then re-adds it with a newline.
908        let append = "@@ -2 +2,2 @@\n-b\n\\ No newline at end of file\n+b\n+c\n";
909        assert_eq!(apply_unified_diff("a\nb", append).unwrap(), "a\nb\nc\n");
910        // A marker means EOF for its side: a further new-side line (in the same or a later
911        // hunk) or a second marker is malformed.
912        for bad in [
913            "@@ -1 +1,2 @@\n-a\n+b\n\\ No newline at end of file\n+c\n",
914            "@@ -1 +1,2 @@\n-a\n+b\n\\ No newline at end of file\n c\n",
915            "@@ -1 +1 @@\n-a\n+b\n\\ No newline at end of file\n\\ No newline at end of file\n",
916            // Only the canonical marker text counts; other backslash lines are malformed.
917            "@@ -1 +1 @@\n-a\n+b\n\\ no newline\n",
918            // `@@@` is not a valid closing.
919            "@@ -1 +1 @@@\n-a\n+b\n",
920            // After a hunk only another hunk header may follow.
921            "@@ -1 +1 @@\n-a\n+b\n@@ bogus\n",
922            "@@ -1 +1 @@\n-a\n+b\ntrailing garbage\n",
923        ] {
924            assert!(apply_unified_diff("a\n", bad).is_err(), "{bad:?}");
925        }
926        // Blank context lines must carry their space prefix; an unprefixed empty line is
927        // malformed (git and this crate both emit " ").
928        assert_eq!(
929            apply_unified_diff("a\n\nc\n", "@@ -1,3 +1,3 @@\n a\n \n-c\n+C\n").unwrap(),
930            "a\n\nC\n"
931        );
932        assert!(apply_unified_diff("a\n\nc\n", "@@ -1,3 +1,3 @@\n a\n\n-c\n+C\n").is_err());
933        // A new-side marker followed by a later hunk, or by an implicitly copied old tail,
934        // is malformed: the marker declared EOF.
935        for bad in [
936            "@@ -1 +1 @@\n-a\n+A\n\\ No newline at end of file\n@@ -2 +2 @@\n-b\n+B\n",
937            "@@ -1 +1 @@\n-a\n+A\n\\ No newline at end of file\n",
938        ] {
939            assert!(apply_unified_diff("a\nb\n", bad).is_err(), "{bad:?}");
940        }
941        // Context at EOF without a newline: the marker agrees with old and the result keeps
942        // the missing newline.
943        let ctx_eof = "@@ -1,2 +1,2 @@\n-a\n+A\n b\n\\ No newline at end of file\n";
944        assert_eq!(apply_unified_diff("a\nb", ctx_eof).unwrap(), "A\nb");
945        // A patch that applies but yields the wrong text fails the equivalence assertion,
946        // and so does one whose result differs only in the terminal newline.
947        assert!(
948            std::panic::catch_unwind(|| {
949                assert_diff_equivalent_to_git(good, good, old, "a\nb\nc\n");
950            })
951            .is_err()
952        );
953        assert!(
954            std::panic::catch_unwind(|| {
955                assert_diff_equivalent_to_git(good, good, old, "a\nB\nc");
956            })
957            .is_err()
958        );
959    }
960
961    /// Pins the limitation registered as FIX-05: the engine emits no
962    /// `\ No newline at end of file` marker, so a change that only touches the terminal
963    /// newline is not representable in its output (applying it yields a newline-terminated
964    /// file), and the equivalence harness refuses such inputs. Update when FIX-05 lands.
965    #[test]
966    fn fix05_diff_engine_drops_terminal_newline_state() {
967        let _guard = set_hash_kind_for_test(HashKind::Sha256);
968        let (diff_output, _, _) = run_diff("nl.txt", b"a\nb", b"a\nB");
969        assert!(!diff_output.contains("\\ No newline"), "{diff_output}");
970        assert_eq!(apply_unified_diff("a\nb", &diff_output).unwrap(), "a\nB\n");
971        assert!(
972            std::panic::catch_unwind(|| {
973                assert_diff_equivalent_to_git(&diff_output, &diff_output, "a\nb", "a\nB");
974            })
975            .is_err()
976        );
977    }
978
979    /// Fixture diff must be patch-equivalent to git's (both reproduce `new` from `old`).
980    #[test]
981    fn diff_matches_git_for_fixture() {
982        let base: PathBuf = [env!("CARGO_MANIFEST_DIR"), "tests", "diff"]
983            .iter()
984            .collect();
985        let old_bytes = fs::read(base.join("old.txt")).expect("read old.txt");
986        let new_bytes = fs::read(base.join("new.txt")).expect("read new.txt");
987        // GC-07: the property must hold under both standard object formats (the hash kind
988        // only changes the `index` header line, but the whole path is exercised for each).
989        for kind in [HashKind::Sha1, HashKind::Sha256] {
990            let _guard = set_hash_kind_for_test(kind);
991            let (diff_output, old_hash, new_hash) = run_diff("fixture.txt", &old_bytes, &new_bytes);
992            assert_eq!(old_hash.kind(), kind);
993            let git_output =
994                normalized_git_diff("fixture.txt", &old_bytes, &new_bytes, &old_hash, &new_hash)
995                    .expect("git diff output");
996            check_fixture(&diff_output, &git_output, &old_bytes, &new_bytes);
997        }
998    }
999
1000    fn check_fixture(diff_output: &str, git_output: &str, old_bytes: &[u8], new_bytes: &[u8]) {
1001        // Different diff algorithms may legitimately choose different edit scripts for
1002        // ambiguous regions (e.g. which of several identical `}` lines is "deleted"), so the
1003        // comparison with git is by patch equivalence, not by textual identity of the
1004        // deleted/inserted line sets.
1005        let old_text = String::from_utf8(old_bytes.to_vec()).expect("old.txt is UTF-8");
1006        let new_text = String::from_utf8(new_bytes.to_vec()).expect("new.txt is UTF-8");
1007        assert_diff_equivalent_to_git(diff_output, git_output, &old_text, &new_text);
1008    }
1009
1010    /// Large input must still be patch-equivalent to git's output.
1011    #[test]
1012    fn diff_matches_git_for_large_change() {
1013        for kind in [HashKind::Sha1, HashKind::Sha256] {
1014            let _guard = set_hash_kind_for_test(kind);
1015            large_change_case();
1016        }
1017    }
1018
1019    fn large_change_case() {
1020        let old_lines: Vec<String> = (0..5_000).map(|i| format!("line {i}")).collect();
1021        let mut new_lines = old_lines.clone();
1022        for idx in [10, 499, 1_234, 3_210, 4_999] {
1023            new_lines[idx] = format!("updated line {idx}");
1024        }
1025        new_lines.insert(2_500, "inserted middle line".into());
1026        new_lines.push("new tail line".into());
1027
1028        let old_text = old_lines.join("\n") + "\n";
1029        let new_text = new_lines.join("\n") + "\n";
1030
1031        let (diff_output, old_hash, new_hash) = run_diff(
1032            "large_fixture.txt",
1033            old_text.as_bytes(),
1034            new_text.as_bytes(),
1035        );
1036        let git_output = normalized_git_diff(
1037            "large_fixture.txt",
1038            old_text.as_bytes(),
1039            new_text.as_bytes(),
1040            &old_hash,
1041            &new_hash,
1042        )
1043        .expect("git diff output");
1044
1045        assert_diff_equivalent_to_git(&diff_output, &git_output, &old_text, &new_text);
1046    }
1047
1048    /// Line mapping operations should match expected Equal/Delete/Insert sequence.
1049    #[test]
1050    fn compute_diff_operations_basic_mapping() {
1051        let _guard = set_hash_kind_for_test(HashKind::Sha256);
1052        let old_lines = vec!["a".to_string(), "b".to_string(), "c".to_string()];
1053        let new_lines = vec![
1054            "a".to_string(),
1055            "B".to_string(),
1056            "c".to_string(),
1057            "d".to_string(),
1058        ];
1059
1060        let ops = compute_diff(&old_lines, &new_lines);
1061
1062        let expected = vec![
1063            DiffOperation::Equal {
1064                old_line: 1,
1065                new_line: 1,
1066            },
1067            DiffOperation::Delete { line: 2 },
1068            DiffOperation::Insert {
1069                line: 2,
1070                content: "B".to_string(),
1071            },
1072            DiffOperation::Equal {
1073                old_line: 3,
1074                new_line: 3,
1075            },
1076            DiffOperation::Insert {
1077                line: 4,
1078                content: "d".to_string(),
1079            },
1080        ];
1081
1082        assert_eq!(ops, expected);
1083    }
1084}