|
| 1 | +use colored::Colorize; |
| 2 | +use similar::{ChangeTag, TextDiff}; |
| 3 | + |
| 4 | +/// Generate a contextual diff display showing only changed blocks |
| 5 | +/// Returns a formatted string with colored additions (blue +) and deletions (red -) |
| 6 | +pub fn generate_contextual_diff(original: &str, modified: &str, context_lines: usize) -> String { |
| 7 | + let diff = TextDiff::from_lines(original, modified); |
| 8 | + let mut output = Vec::new(); |
| 9 | + |
| 10 | + for (idx, group) in diff.grouped_ops(context_lines).iter().enumerate() { |
| 11 | + if idx > 0 { |
| 12 | + // Add separator between hunks |
| 13 | + output.push("".to_string()); |
| 14 | + output.push("...".dimmed().to_string()); |
| 15 | + output.push("".to_string()); |
| 16 | + } |
| 17 | + |
| 18 | + for op in group { |
| 19 | + for change in diff.iter_changes(op) { |
| 20 | + let s: String = match change.tag() { |
| 21 | + ChangeTag::Delete => { |
| 22 | + let line = format!("- {}", change.value().trim_end()); |
| 23 | + line.on_red().black().to_string() |
| 24 | + } |
| 25 | + ChangeTag::Insert => { |
| 26 | + let line = format!("+ {}", change.value().trim_end()); |
| 27 | + line.on_blue().black().to_string() |
| 28 | + } |
| 29 | + ChangeTag::Equal => { |
| 30 | + let line = format!(" {}", change.value().trim_end()); |
| 31 | + line.normal().to_string() |
| 32 | + } |
| 33 | + }; |
| 34 | + |
| 35 | + output.push(s); |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + output.join("\n") |
| 41 | +} |
| 42 | + |
| 43 | +/// Generate a compact diff showing only changed lines with minimal context |
| 44 | +pub fn generate_compact_diff(original: &str, modified: &str) -> String { |
| 45 | + generate_contextual_diff(original, modified, 2) |
| 46 | +} |
| 47 | + |
| 48 | +#[cfg(test)] |
| 49 | +mod tests { |
| 50 | + use super::*; |
| 51 | + |
| 52 | + #[test] |
| 53 | + fn test_simple_diff() { |
| 54 | + let original = "line 1\nline 2\nline 3\n"; |
| 55 | + let modified = "line 1\nline 2 modified\nline 3\n"; |
| 56 | + |
| 57 | + let diff = generate_compact_diff(original, modified); |
| 58 | + assert!(diff.contains("line 2")); |
| 59 | + } |
| 60 | + |
| 61 | + #[test] |
| 62 | + fn test_multiple_changes() { |
| 63 | + let original = "var x = 1;\nvar y = 2;\nvar z = 3;\n"; |
| 64 | + let modified = "const x = 1;\nconst y = 2;\nconst z = 3;\n"; |
| 65 | + |
| 66 | + let diff = generate_compact_diff(original, modified); |
| 67 | + assert!(diff.contains("-")); |
| 68 | + assert!(diff.contains("+")); |
| 69 | + } |
| 70 | +} |
0 commit comments