Skip to main content

tinyharness_ui/ui/
diff.rs

1use std::{error::Error, io::Write};
2
3use crate::style::*;
4
5// ── Diff computation (LCS-based algorithm) ─────────────────────────────────
6
7/// A single line in a diff hunk — either kept, removed, or added.
8#[derive(Debug, Clone, PartialEq)]
9pub enum DiffLine<'a> {
10    /// Line present in both old and new (unchanged).
11    Keep(&'a str),
12    /// Line present only in old (removed).
13    Remove(&'a str),
14    /// Line present only in new (added).
15    Add(&'a str),
16}
17
18/// Compute the shortest edit script between `old` and `new`.
19///
20/// Uses a standard LCS (Longest Common Subsequence) dynamic programming approach
21/// to find the optimal alignment, then walks the DP table to produce the diff.
22/// This produces the same quality of diff as `git diff` for line-level changes.
23pub fn compute_diff<'a>(old: &'a [&str], new: &'a [&str]) -> Vec<DiffLine<'a>> {
24    let n = old.len();
25    let m = new.len();
26
27    // Trivial cases
28    if n == 0 && m == 0 {
29        return vec![];
30    }
31    if n == 0 {
32        return new.iter().map(|l| DiffLine::Add(l)).collect();
33    }
34    if m == 0 {
35        return old.iter().map(|l| DiffLine::Remove(l)).collect();
36    }
37    if old == new {
38        return old.iter().map(|l| DiffLine::Keep(l)).collect();
39    }
40
41    // Build LCS length table using O(n) space (rolling rows).
42    // dp[j] = LCS length for old[0..i] and new[0..j]
43    let mut dp = vec![0usize; m + 1];
44    let mut prev = vec![0usize; m + 1];
45
46    // We also need to store the full table for backtracking.
47    // For correctness we store the full (n+1) x (m+1) table.
48    // This is fine since diffs are typically small (file previews in confirmation prompts).
49    let mut table = vec![vec![0usize; m + 1]; n + 1];
50
51    for i in 1..=n {
52        prev.copy_from_slice(&dp);
53        for j in 1..=m {
54            if old[i - 1] == new[j - 1] {
55                dp[j] = prev[j - 1] + 1;
56            } else {
57                dp[j] = dp[j - 1].max(prev[j]);
58            }
59        }
60        table[i].copy_from_slice(&dp);
61    }
62
63    // Backtrack through the full table to reconstruct the diff
64    let mut result = Vec::with_capacity(n + m);
65    let mut i = n;
66    let mut j = m;
67
68    while i > 0 || j > 0 {
69        if i > 0 && j > 0 && old[i - 1] == new[j - 1] {
70            result.push(DiffLine::Keep(old[i - 1]));
71            i -= 1;
72            j -= 1;
73        } else if j > 0 && (i == 0 || table[i][j - 1] >= table[i - 1][j]) {
74            result.push(DiffLine::Add(new[j - 1]));
75            j -= 1;
76        } else {
77            result.push(DiffLine::Remove(old[i - 1]));
78            i -= 1;
79        }
80    }
81
82    result.reverse();
83    result
84}
85
86/// Context lines to show around each change in unified diff output.
87const DIFF_CONTEXT_LINES: usize = 3;
88
89/// Render a [`DiffLine`] sequence into unified-diff-style output with line
90/// numbers, `+`/`-`/` ` prefixes, and configurable context around changes.
91#[allow(unused_assignments)]
92fn render_diff_lines<W: Write>(
93    stdout: &mut W,
94    diff: &[DiffLine],
95    old_lines: &[&str],
96    new_lines: &[&str],
97    show_line_numbers: bool,
98) -> Result<(), Box<dyn Error>> {
99    if diff.is_empty() {
100        return Ok(());
101    }
102
103    // Compute line number width
104    let max_line = old_lines.len().max(new_lines.len()).max(1);
105    let num_width = if show_line_numbers {
106        max_line.to_string().len().max(2)
107    } else {
108        0
109    };
110
111    // Find hunks: groups of changes with context around them.
112    let change_indices: Vec<usize> = diff
113        .iter()
114        .enumerate()
115        .filter_map(|(i, l)| matches!(l, DiffLine::Remove(_) | DiffLine::Add(_)).then_some(i))
116        .collect();
117
118    if change_indices.is_empty() {
119        return Ok(());
120    }
121
122    // Merge overlapping/adjacent hunks
123    let mut hunk_ranges: Vec<(usize, usize)> = Vec::new();
124    let mut hunk_start = change_indices[0].saturating_sub(DIFF_CONTEXT_LINES);
125    let mut hunk_end = (change_indices[0] + DIFF_CONTEXT_LINES + 1).min(diff.len());
126
127    for &idx in &change_indices[1..] {
128        let new_start = idx.saturating_sub(DIFF_CONTEXT_LINES);
129        let new_end = (idx + DIFF_CONTEXT_LINES + 1).min(diff.len());
130
131        if new_start <= hunk_end {
132            hunk_end = hunk_end.max(new_end);
133        } else {
134            hunk_ranges.push((hunk_start, hunk_end));
135            hunk_start = new_start;
136            hunk_end = new_end;
137        }
138    }
139    hunk_ranges.push((hunk_start, hunk_end));
140
141    // Render each hunk
142    for (hunk_idx, &(start, end)) in hunk_ranges.iter().enumerate() {
143        // Add separator between hunks
144        if hunk_idx > 0 {
145            let sep_line = format!(
146                "{}  {}{}",
147                DIM,
148                BOX_COLOR,
149                "·".repeat(if show_line_numbers {
150                    num_width + 1 + 3 + 60
151                } else {
152                    3 + 60
153                })
154            );
155            writeln!(stdout, "{}{}", sep_line, RESET)?;
156        }
157
158        // Count line numbers up to the start of this hunk
159        let mut old_num: usize = 0;
160        #[allow(unused_variables)]
161        let mut new_num: usize = 0;
162        for item in diff.iter().take(start) {
163            match item {
164                DiffLine::Keep(_) => {
165                    old_num += 1;
166                    new_num += 1;
167                }
168                DiffLine::Remove(_) => {
169                    old_num += 1;
170                }
171                DiffLine::Add(_) => {
172                    new_num += 1;
173                }
174            }
175        }
176
177        for i in start..end {
178            if i >= diff.len() {
179                break;
180            }
181            match &diff[i] {
182                DiffLine::Keep(line) => {
183                    old_num += 1;
184                    new_num += 1;
185                    if show_line_numbers {
186                        writeln!(
187                            stdout,
188                            "  {:>width$} {} {}",
189                            old_num,
190                            DIM,
191                            line,
192                            width = num_width,
193                        )?;
194                    } else {
195                        writeln!(stdout, "  {} {}{}", DIM, line, RESET)?;
196                    }
197                }
198                DiffLine::Remove(line) => {
199                    old_num += 1;
200                    if show_line_numbers {
201                        writeln!(
202                            stdout,
203                            "{}  {:<width$} {}{} {}",
204                            RED,
205                            "-",
206                            RESET,
207                            RED,
208                            line,
209                            width = num_width
210                        )?;
211                    } else {
212                        writeln!(stdout, "{}  - {}{}", RED, RESET, line)?;
213                    }
214                }
215                DiffLine::Add(line) => {
216                    new_num += 1;
217                    if show_line_numbers {
218                        writeln!(
219                            stdout,
220                            "{}  {:<width$} {}{} {}",
221                            GREEN,
222                            "+",
223                            RESET,
224                            GREEN,
225                            line,
226                            width = num_width
227                        )?;
228                    } else {
229                        writeln!(stdout, "{}  + {}{}", GREEN, RESET, line)?;
230                    }
231                }
232            }
233        }
234    }
235
236    Ok(())
237}
238
239// ── Public API ─────────────────────────────────────────────────────────────
240
241/// Show a unified-diff-style view of a write operation (full file).
242/// If the file already exists, reads it and shows a line-by-line diff
243/// with removed lines in red and added lines in green.
244/// If the file is new, shows a preview of the content that will be written.
245pub fn show_write_preview<W: Write>(
246    stdout: &mut W,
247    path: &str,
248    new_content: &str,
249) -> Result<(), Box<dyn Error>> {
250    let existing = std::fs::read_to_string(path);
251
252    let old_lines: Vec<&str> = match &existing {
253        Ok(content) => content.lines().collect(),
254        Err(_) => {
255            // File doesn't exist — show a green preview
256            writeln!(
257                stdout,
258                "\n{}  ── {}New file: {}{} ──{}",
259                BOLD, BOX_COLOR, path, BOLD, RESET
260            )?;
261            writeln!(
262                stdout,
263                "{}     {}{} {}",
264                DIM,
265                BOX_COLOR,
266                "┄".repeat(60),
267                RESET
268            )?;
269            for line in new_content.lines() {
270                writeln!(stdout, "{}  + {}{}", GREEN, RESET, line)?;
271            }
272            writeln!(stdout, "{}     {} {}", DIM, "┄".repeat(60), RESET)?;
273            return Ok(());
274        }
275    };
276
277    let new_lines: Vec<&str> = new_content.lines().collect();
278
279    // Compute the diff
280    let diff = compute_diff(&old_lines, &new_lines);
281
282    // If the file is identical, show a note
283    let has_changes = diff.iter().any(|l| !matches!(l, DiffLine::Keep(_)));
284
285    if !has_changes {
286        writeln!(
287            stdout,
288            "\n{}  ── {}No changes in {}{} ──{}",
289            BOLD, BOX_COLOR, path, BOLD, RESET
290        )?;
291        return Ok(());
292    }
293
294    // Count additions and removals for the header
295    let removals = diff
296        .iter()
297        .filter(|l| matches!(l, DiffLine::Remove(_)))
298        .count();
299    let additions = diff
300        .iter()
301        .filter(|l| matches!(l, DiffLine::Add(_)))
302        .count();
303
304    writeln!(
305        stdout,
306        "\n{}  ── {}Diff for {}{} ── {}{}-{}{}+{}{}",
307        BOLD, BOX_COLOR, path, BOLD, RED, removals, GREEN, additions, RESET, RESET,
308    )?;
309
310    let max_line = old_lines.len().max(new_lines.len()).max(1);
311    let num_width = max_line.to_string().len().max(2);
312
313    // Separator line
314    writeln!(
315        stdout,
316        "{}  {}{} {} {}",
317        DIM,
318        BOX_COLOR,
319        " ".repeat(num_width),
320        "┄".repeat(60),
321        RESET
322    )?;
323
324    // Render the diff with line numbers
325    render_diff_lines(stdout, &diff, &old_lines, &new_lines, true)?;
326
327    // Ending separator
328    writeln!(
329        stdout,
330        "{}  {}{} {} {}",
331        DIM,
332        BOX_COLOR,
333        " ".repeat(num_width),
334        "┄".repeat(60),
335        RESET
336    )?;
337
338    Ok(())
339}
340
341/// Show a unified-diff-style view of an edit operation.
342/// Reads the file, locates `old_str`, and prints context lines
343/// with the removed text in red and the replacement in green.
344pub fn show_edit_diff<W: Write>(
345    stdout: &mut W,
346    path: &str,
347    old_str: &str,
348    new_str: &str,
349) -> Result<(), Box<dyn Error>> {
350    let content =
351        std::fs::read_to_string(path).map_err(|e| format!("Failed to read '{}': {}", path, e))?;
352
353    // Find the byte offset of old_str in the content
354    let offset = match content.find(old_str) {
355        Some(o) => o,
356        None => {
357            writeln!(
358                stdout,
359                "  {}[diff error: 'old_str' not found in file]{}",
360                RED, RESET
361            )?;
362            return Ok(());
363        }
364    };
365
366    // Count newlines before the match to get the line number (0-based)
367    let line_number = content[..offset].matches('\n').count();
368    let lines: Vec<&str> = content.lines().collect();
369
370    // Split old_str and new_str into lines
371    let old_lines: Vec<&str> = old_str.lines().collect();
372    let new_lines: Vec<&str> = new_str.lines().collect();
373
374    // Determine context window (show up to 2 lines before and after)
375    let before_ctx = 2usize;
376    let after_ctx = 2usize;
377    let start_line = line_number.saturating_sub(before_ctx);
378    let end_line = (line_number + old_lines.len() + after_ctx).min(lines.len());
379    let line_num_width = (end_line + 1).to_string().len().max(2);
380
381    writeln!(
382        stdout,
383        "\n{}  ── {}Diff for {}{} ──{}",
384        BOLD, BOX_COLOR, path, BOLD, RESET
385    )?;
386
387    // Separator line
388    writeln!(
389        stdout,
390        "{}  {}{} {} {}",
391        DIM,
392        BOX_COLOR,
393        " ".repeat(line_num_width),
394        "┄".repeat(60),
395        RESET
396    )?;
397
398    // Lines before the change
399    for (i, line) in lines.iter().enumerate().take(line_number).skip(start_line) {
400        writeln!(
401            stdout,
402            "  {:>width$} {} {}",
403            i + 1,
404            DIM,
405            line,
406            width = line_num_width,
407        )?;
408    }
409
410    // Removed lines (old_str) – shown in red with '-'
411    for line in old_lines.iter() {
412        writeln!(
413            stdout,
414            "{}  {:<width$} {}{} {}",
415            RED,
416            "-",
417            RESET,
418            RED,
419            line,
420            width = line_num_width
421        )?;
422    }
423
424    // Added lines (new_str) – shown in green with '+'
425    for line in new_lines.iter() {
426        writeln!(
427            stdout,
428            "{}  {:<width$} {}{} {}",
429            GREEN,
430            "+",
431            RESET,
432            GREEN,
433            line,
434            width = line_num_width
435        )?;
436    }
437
438    // Lines after the change
439    let after_start = line_number + old_lines.len();
440    for i in after_start..end_line {
441        if i < lines.len() {
442            writeln!(
443                stdout,
444                "  {:>width$} {} {}",
445                i + 1,
446                DIM,
447                lines[i],
448                width = line_num_width,
449            )?;
450        }
451    }
452
453    // Ending separator
454    writeln!(
455        stdout,
456        "{}  {}{} {} {}",
457        DIM,
458        BOX_COLOR,
459        " ".repeat(line_num_width),
460        "┄".repeat(60),
461        RESET
462    )?;
463
464    Ok(())
465}
466
467/// Render a [`DiffLine`] sequence into a plain-text string (no ANSI codes),
468/// suitable for display in the TUI cell-based renderer.
469///
470/// Returns a string with lines prefixed by `  ` (keep), `- ` (remove), or `+ ` (add),
471/// and line numbers if requested.
472pub fn render_diff_plain(
473    old_lines: &[&str],
474    new_lines: &[&str],
475    diff: &[DiffLine],
476    show_line_numbers: bool,
477) -> String {
478    if diff.is_empty() {
479        return String::new();
480    }
481
482    let max_line = old_lines.len().max(new_lines.len()).max(1);
483    let num_width = if show_line_numbers {
484        max_line.to_string().len().max(2)
485    } else {
486        0
487    };
488
489    let mut result = String::new();
490    let mut old_num: usize = 0;
491    let mut new_num: usize = 0;
492
493    // Find change positions to determine hunks with context
494    let change_indices: Vec<usize> = diff
495        .iter()
496        .enumerate()
497        .filter_map(|(i, l)| matches!(l, DiffLine::Remove(_) | DiffLine::Add(_)).then_some(i))
498        .collect();
499
500    if change_indices.is_empty() {
501        return result;
502    }
503
504    // Merge overlapping/adjacent hunks
505    let mut hunk_ranges: Vec<(usize, usize)> = Vec::new();
506    let mut hunk_start = change_indices[0].saturating_sub(DIFF_CONTEXT_LINES);
507    let mut hunk_end = (change_indices[0] + DIFF_CONTEXT_LINES + 1).min(diff.len());
508
509    for &idx in &change_indices[1..] {
510        let ns = idx.saturating_sub(DIFF_CONTEXT_LINES);
511        let ne = (idx + DIFF_CONTEXT_LINES + 1).min(diff.len());
512        if ns <= hunk_end {
513            hunk_end = hunk_end.max(ne);
514        } else {
515            hunk_ranges.push((hunk_start, hunk_end));
516            hunk_start = ns;
517            hunk_end = ne;
518        }
519    }
520    hunk_ranges.push((hunk_start, hunk_end));
521
522    for (hunk_idx, &(start, end)) in hunk_ranges.iter().enumerate() {
523        // Separator between hunks
524        if hunk_idx > 0 {
525            result.push_str("  ┈\n");
526        }
527
528        // Count line numbers up to the start of this hunk
529        for item in diff.iter().take(start) {
530            match item {
531                DiffLine::Keep(_) => {
532                    old_num += 1;
533                    new_num += 1;
534                }
535                DiffLine::Remove(_) => {
536                    old_num += 1;
537                }
538                DiffLine::Add(_) => {
539                    new_num += 1;
540                }
541            }
542        }
543
544        for i in start..end {
545            if i >= diff.len() {
546                break;
547            }
548            match &diff[i] {
549                DiffLine::Keep(line) => {
550                    old_num += 1;
551                    new_num += 1;
552                    if show_line_numbers {
553                        result.push_str(&format!(
554                            "  {:>width$} │ {}\n",
555                            old_num,
556                            line,
557                            width = num_width
558                        ));
559                    } else {
560                        result.push_str(&format!("    {}\n", line));
561                    }
562                }
563                DiffLine::Remove(line) => {
564                    old_num += 1;
565                    if show_line_numbers {
566                        result.push_str(&format!(
567                            "-  {:>width$} │ {}\n",
568                            old_num,
569                            line,
570                            width = num_width
571                        ));
572                    } else {
573                        result.push_str(&format!("-   {}\n", line));
574                    }
575                }
576                DiffLine::Add(line) => {
577                    new_num += 1;
578                    if show_line_numbers {
579                        result.push_str(&format!(
580                            "+  {:>width$} │ {}\n",
581                            new_num,
582                            line,
583                            width = num_width
584                        ));
585                    } else {
586                        result.push_str(&format!("+   {}\n", line));
587                    }
588                }
589            }
590        }
591    }
592
593    result
594}
595
596/// Compute a unified diff between old and new content and return it as
597/// a plain-text string (no ANSI codes). Returns an empty string if the
598/// contents are identical.
599pub fn compute_edit_diff_plain(old_content: &str, new_content: &str) -> String {
600    let old_lines: Vec<&str> = old_content.lines().collect();
601    let new_lines: Vec<&str> = new_content.lines().collect();
602    let diff = compute_diff(&old_lines, &new_lines);
603
604    if diff.iter().all(|l| matches!(l, DiffLine::Keep(_))) {
605        return String::new();
606    }
607
608    render_diff_plain(&old_lines, &new_lines, &diff, true)
609}
610
611/// Compute a diff for a write operation (file creation or modification) and
612/// return it as a plain-text string (no ANSI codes).
613pub fn compute_write_diff_plain(path: &str, new_content: &str) -> String {
614    let existing = std::fs::read_to_string(path);
615
616    match existing {
617        Ok(old_content) => {
618            let old_lines: Vec<&str> = old_content.lines().collect();
619            let new_lines: Vec<&str> = new_content.lines().collect();
620            let diff = compute_diff(&old_lines, &new_lines);
621
622            if diff.iter().all(|l| matches!(l, DiffLine::Keep(_))) {
623                return String::new();
624            }
625
626            render_diff_plain(&old_lines, &new_lines, &diff, true)
627        }
628        Err(_) => {
629            // New file — show all lines as additions
630            let new_lines: Vec<&str> = new_content.lines().collect();
631            let num_width = new_lines.len().to_string().len().max(2);
632            let mut result = String::new();
633            for (i, line) in new_lines.iter().enumerate() {
634                result.push_str(&format!(
635                    "+  {:>width$} │ {}\n",
636                    i + 1,
637                    line,
638                    width = num_width
639                ));
640            }
641            result
642        }
643    }
644}
645
646/// Compute a diff for an edit operation and return it as a plain-text string
647/// (no ANSI codes). Reads the current file content to locate the edit.
648pub fn compute_edit_diff_from_path(path: &str, old_str: &str, new_str: &str) -> String {
649    let content = match std::fs::read_to_string(path) {
650        Ok(c) => c,
651        Err(_) => return String::new(),
652    };
653
654    let lines: Vec<&str> = content.lines().collect();
655
656    // Find the line number of old_str
657    let offset = match content.find(old_str) {
658        Some(o) => o,
659        None => return String::new(),
660    };
661    let line_number = content[..offset].matches('\n').count();
662
663    let old_lines: Vec<&str> = old_str.lines().collect();
664    let new_lines: Vec<&str> = new_str.lines().collect();
665
666    // Show context (2 lines before and after)
667    let before_ctx = 2usize;
668    let after_ctx = 2usize;
669    let start_line = line_number.saturating_sub(before_ctx);
670    let end_line = (line_number + old_lines.len() + after_ctx).min(lines.len());
671    let num_width = end_line.to_string().len().max(2);
672
673    let mut result = String::new();
674
675    // Context lines before
676    for (i, line) in lines.iter().enumerate().take(line_number).skip(start_line) {
677        result.push_str(&format!(
678            "  {:>width$} │ {}\n",
679            i + 1,
680            line,
681            width = num_width
682        ));
683    }
684
685    // Removed lines (old)
686    for line in old_lines.iter() {
687        result.push_str(&format!("-       │ {}\n", line));
688    }
689
690    // Added lines (new)
691    for line in new_lines.iter() {
692        result.push_str(&format!("+       │ {}\n", line));
693    }
694
695    // Context lines after
696    let after_start = line_number + old_lines.len();
697    for i in after_start..end_line {
698        if i < lines.len() {
699            result.push_str(&format!(
700                "  {:>width$} │ {}\n",
701                i + 1,
702                lines[i],
703                width = num_width
704            ));
705        }
706    }
707
708    result
709}
710
711#[cfg(test)]
712mod tests {
713    use super::*;
714
715    #[test]
716    fn test_compute_diff_identical() {
717        let old = vec!["a", "b", "c"];
718        let new = vec!["a", "b", "c"];
719        let diff = compute_diff(&old, &new);
720        assert_eq!(
721            diff,
722            vec![
723                DiffLine::Keep("a"),
724                DiffLine::Keep("b"),
725                DiffLine::Keep("c"),
726            ]
727        );
728    }
729
730    #[test]
731    fn test_compute_diff_empty_to_lines() {
732        let old: Vec<&str> = vec![];
733        let new = vec!["a", "b"];
734        let diff = compute_diff(&old, &new);
735        assert_eq!(diff, vec![DiffLine::Add("a"), DiffLine::Add("b")]);
736    }
737
738    #[test]
739    fn test_compute_diff_lines_to_empty() {
740        let old = vec!["a", "b"];
741        let new: Vec<&str> = vec![];
742        let diff = compute_diff(&old, &new);
743        assert_eq!(diff, vec![DiffLine::Remove("a"), DiffLine::Remove("b")]);
744    }
745
746    #[test]
747    fn test_compute_diff_simple_insertion() {
748        let old = vec!["a", "c"];
749        let new = vec!["a", "b", "c"];
750        let diff = compute_diff(&old, &new);
751        assert_eq!(
752            diff,
753            vec![DiffLine::Keep("a"), DiffLine::Add("b"), DiffLine::Keep("c"),]
754        );
755    }
756
757    #[test]
758    fn test_compute_diff_simple_deletion() {
759        let old = vec!["a", "b", "c"];
760        let new = vec!["a", "c"];
761        let diff = compute_diff(&old, &new);
762        assert_eq!(
763            diff,
764            vec![
765                DiffLine::Keep("a"),
766                DiffLine::Remove("b"),
767                DiffLine::Keep("c"),
768            ]
769        );
770    }
771
772    #[test]
773    fn test_compute_diff_replace() {
774        let old = vec!["a", "old", "c"];
775        let new = vec!["a", "new", "c"];
776        let diff = compute_diff(&old, &new);
777        assert_eq!(
778            diff,
779            vec![
780                DiffLine::Keep("a"),
781                DiffLine::Remove("old"),
782                DiffLine::Add("new"),
783                DiffLine::Keep("c"),
784            ]
785        );
786    }
787
788    #[test]
789    fn test_compute_diff_multiple_changes() {
790        let old = vec!["a", "b", "c", "d", "e"];
791        let new = vec!["a", "x", "c", "y", "e"];
792        let diff = compute_diff(&old, &new);
793        assert_eq!(
794            diff,
795            vec![
796                DiffLine::Keep("a"),
797                DiffLine::Remove("b"),
798                DiffLine::Add("x"),
799                DiffLine::Keep("c"),
800                DiffLine::Remove("d"),
801                DiffLine::Add("y"),
802                DiffLine::Keep("e"),
803            ]
804        );
805    }
806
807    #[test]
808    fn test_compute_diff_large_shift() {
809        // Lines rearranged: the old "middle" section is removed and new lines added
810        let old = vec!["keep1", "remove1", "remove2", "remove3", "keep2"];
811        let new = vec!["keep1", "add1", "add2", "keep2"];
812        let diff = compute_diff(&old, &new);
813        let keeps: Vec<_> = diff
814            .iter()
815            .filter(|l| matches!(l, DiffLine::Keep(_)))
816            .collect();
817        let removes: Vec<_> = diff
818            .iter()
819            .filter(|l| matches!(l, DiffLine::Remove(_)))
820            .collect();
821        let adds: Vec<_> = diff
822            .iter()
823            .filter(|l| matches!(l, DiffLine::Add(_)))
824            .collect();
825        assert_eq!(keeps.len(), 2);
826        assert_eq!(removes.len(), 3);
827        assert_eq!(adds.len(), 2);
828        // Keep lines should be in order
829        assert!(matches!(keeps[0], DiffLine::Keep("keep1")));
830        assert!(matches!(keeps[1], DiffLine::Keep("keep2")));
831    }
832
833    #[test]
834    fn test_compute_diff_both_empty() {
835        let old: Vec<&str> = vec![];
836        let new: Vec<&str> = vec![];
837        let diff = compute_diff(&old, &new);
838        assert!(diff.is_empty());
839    }
840
841    #[test]
842    fn test_compute_diff_single_line_change() {
843        let old = vec!["hello world"];
844        let new = vec!["hello rust"];
845        let diff = compute_diff(&old, &new);
846        assert_eq!(
847            diff,
848            vec![DiffLine::Remove("hello world"), DiffLine::Add("hello rust")]
849        );
850    }
851
852    #[test]
853    fn test_compute_diff_prepend_and_append() {
854        let old = vec!["b", "c"];
855        let new = vec!["a", "b", "c", "d"];
856        let diff = compute_diff(&old, &new);
857        assert_eq!(
858            diff,
859            vec![
860                DiffLine::Add("a"),
861                DiffLine::Keep("b"),
862                DiffLine::Keep("c"),
863                DiffLine::Add("d"),
864            ]
865        );
866    }
867
868    #[test]
869    fn test_compute_diff_minimality() {
870        // The diff should produce the minimum number of edits
871        let old = vec!["a", "b", "c", "d", "e", "f"];
872        let new = vec!["a", "c", "d", "e", "g"];
873        let diff = compute_diff(&old, &new);
874        let removes = diff
875            .iter()
876            .filter(|l| matches!(l, DiffLine::Remove(_)))
877            .count();
878        let adds = diff
879            .iter()
880            .filter(|l| matches!(l, DiffLine::Add(_)))
881            .count();
882        // Minimum: remove b, remove f, add g = 2 removes + 1 add = 3 edits
883        assert_eq!(removes, 2);
884        assert_eq!(adds, 1);
885    }
886
887    #[test]
888    fn test_compute_diff_longer_file() {
889        // A more realistic scenario with many lines
890        let old: Vec<String> = (0..50).map(|i| format!("line {}", i)).collect();
891        let mut new = old.clone();
892        // Change lines 10, 20, remove line 30, insert after line 40
893        new[10] = "line 10 modified".to_string();
894        new[20] = "line 20 modified".to_string();
895        new.remove(30);
896        new.insert(41, "inserted line".to_string());
897
898        let old_refs: Vec<&str> = old.iter().map(|s| s.as_str()).collect();
899        let new_refs: Vec<&str> = new.iter().map(|s| s.as_str()).collect();
900
901        let diff = compute_diff(&old_refs, &new_refs);
902
903        let removes = diff
904            .iter()
905            .filter(|l| matches!(l, DiffLine::Remove(_)))
906            .count();
907        let adds = diff
908            .iter()
909            .filter(|l| matches!(l, DiffLine::Add(_)))
910            .count();
911        // 3 removals (line 10 original, line 20 original, line 30) and 3 additions
912        // (modified 10, modified 20, inserted)
913        assert_eq!(removes, 3);
914        assert_eq!(adds, 3);
915    }
916
917    #[test]
918    fn test_compute_diff_reorder() {
919        // Swapping two unique lines
920        let old = vec!["alpha", "beta"];
921        let new = vec!["beta", "alpha"];
922        let diff = compute_diff(&old, &new);
923        // Both lines exist in both files, so one should be kept.
924        // The minimal diff removes and re-adds the reordered line.
925        let keeps = diff
926            .iter()
927            .filter(|l| matches!(l, DiffLine::Keep(_)))
928            .count();
929        assert!(keeps >= 1, "At least one line should be kept in a reorder");
930    }
931
932    #[test]
933    fn test_compute_diff_all_same_then_change() {
934        // Large common prefix, then a change
935        let old: Vec<&str> = vec!["line1", "line2", "line3", "line4", "line5", "old_ending"];
936        let new: Vec<&str> = vec!["line1", "line2", "line3", "line4", "line5", "new_ending"];
937        let diff = compute_diff(&old, &new);
938        assert_eq!(
939            diff,
940            vec![
941                DiffLine::Keep("line1"),
942                DiffLine::Keep("line2"),
943                DiffLine::Keep("line3"),
944                DiffLine::Keep("line4"),
945                DiffLine::Keep("line5"),
946                DiffLine::Remove("old_ending"),
947                DiffLine::Add("new_ending"),
948            ]
949        );
950    }
951}