diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a11f5d..e03bd67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ All notable changes to similar are documented here. * Added virtual newline handling to `iter_changes`. * Made unified diff support more flexible through the introduction of the `UnifiedDiff` type. +* Fixed grouped diff operation to return an empty result if the diff + does not show any changes. ## 0.4.0 diff --git a/examples/udiff.rs b/examples/udiff.rs new file mode 100644 index 0000000..8d62071 --- /dev/null +++ b/examples/udiff.rs @@ -0,0 +1,22 @@ +use std::fs::read_to_string; +use std::process::exit; + +use similar::text::TextDiff; + +fn main() { + let args: Vec<_> = std::env::args_os().collect(); + if args.len() != 3 { + eprintln!("usage: udiff [old] [new]"); + exit(1); + } + + let old = read_to_string(&args[1]).unwrap(); + let new = read_to_string(&args[2]).unwrap(); + print!( + "{}", + TextDiff::from_lines(&old, &new).unified_diff().header( + &args[1].as_os_str().to_string_lossy(), + &args[2].as_os_str().to_string_lossy() + ) + ); +} diff --git a/src/algorithms/capture.rs b/src/algorithms/capture.rs index 537026d..f2663bf 100644 --- a/src/algorithms/capture.rs +++ b/src/algorithms/capture.rs @@ -222,8 +222,9 @@ pub fn group_diff_ops(mut ops: Vec, n: usize) -> Vec> { pending_group.push(op); } - if !pending_group.is_empty() { - rv.push(pending_group); + match &pending_group[..] { + &[] | &[DiffOp::Equal { .. }] => {} + _ => rv.push(pending_group), } rv diff --git a/src/text/snapshots/similar__text__udiff__unified_diff.snap b/src/text/snapshots/similar__text__udiff__unified_diff.snap new file mode 100644 index 0000000..74d419d --- /dev/null +++ b/src/text/snapshots/similar__text__udiff__unified_diff.snap @@ -0,0 +1,25 @@ +--- +source: src/text/udiff.rs +expression: "&diff.unified_diff().header(\"a.txt\", \"b.txt\").to_string()" +--- +--- a.txt ++++ b.txt +@@ -15,3 +19,3 @@ + p + q + r +-s ++S + t + u + v +@@ -37,3 +41,3 @@ + L + M + N +-O ++o + P + Q + R + diff --git a/src/text/udiff.rs b/src/text/udiff.rs index d8f12c7..9112391 100644 --- a/src/text/udiff.rs +++ b/src/text/udiff.rs @@ -178,8 +178,12 @@ impl<'diff, 'old, 'new, 'bufs> fmt::Display for UnifiedDiffHunk<'diff, 'old, 'ne } else { "\n" }; - writeln!(f, "{}", self.header())?; + let mut wrote_header = false; for change in self.iter_changes() { + if !wrote_header { + writeln!(f, "{}", self.header())?; + wrote_header = true; + } write!( f, "{}{}{}", @@ -238,3 +242,8 @@ fn test_unified_diff() { ); insta::assert_snapshot!(&diff.unified_diff().header("a.txt", "b.txt").to_string()); } +#[test] +fn test_empty_unified_diff() { + let diff = TextDiff::from_lines("abc", "abc"); + assert_eq!(diff.unified_diff().header("a.txt", "b.txt").to_string(), ""); +}