diff --git a/cli/src/diff_util.rs b/cli/src/diff_util.rs index cae30c6d57..ec2b736fb1 100644 --- a/cli/src/diff_util.rs +++ b/cli/src/diff_util.rs @@ -771,7 +771,8 @@ fn unified_diff_hunks<'content>( lines: vec![], }; let diff = Diff::for_tokenizer(&[left_content, right_content], diff::find_line_ranges); - for hunk in diff.hunks() { + let mut diff_hunks = diff.hunks().peekable(); + while let Some(hunk) = diff_hunks.next() { match hunk { DiffHunk::Matching(content) => { let mut lines = content.split_inclusive(|b| *b == b'\n').fuse(); @@ -779,7 +780,11 @@ fn unified_diff_hunks<'content>( // The previous hunk line should be either removed/added. current_hunk.extend_context_lines(lines.by_ref().take(num_context_lines)); } - let before_lines = lines.by_ref().rev().take(num_context_lines).collect_vec(); + let before_lines = if diff_hunks.peek().is_some() { + lines.by_ref().rev().take(num_context_lines).collect() + } else { + vec![] // No more hunks + }; let num_skip_lines = lines.count(); if num_skip_lines > 0 { let removed_start = current_hunk.removed_line_range.end + num_skip_lines; @@ -804,12 +809,7 @@ fn unified_diff_hunks<'content>( } } } - // The last unified hunk might contain redundant "before" context lines. - if !current_hunk - .lines - .iter() - .all(|(diff_type, _line)| *diff_type == DiffLineType::Context) - { + if !current_hunk.lines.is_empty() { hunks.push(current_hunk); } hunks diff --git a/cli/tests/test_diff_command.rs b/cli/tests/test_diff_command.rs index 8945c74cac..10f51008d3 100644 --- a/cli/tests/test_diff_command.rs +++ b/cli/tests/test_diff_command.rs @@ -909,14 +909,13 @@ fn test_diff_leading_trailing_context() { "###); // N <= 2 * num_context_lines - // FIXME: trailing context lines should be trimmed let stdout = test_env.jj_cmd_success(&repo_path, &["diff", "--git", "--context=3"]); insta::assert_snapshot!(stdout, @r###" diff --git a/file1 b/file1 index 1bf57dee4a...69b3e1865c 100644 --- a/file1 +++ b/file1 - @@ -3,10 +3,10 @@ + @@ -3,8 +3,8 @@ 3 4 5 @@ -926,8 +925,6 @@ fn test_diff_leading_trailing_context() { 7 8 9 - 10 - 11 "###); // N > 2 * num_context_lines