Skip to content

Commit 8ab502f

Browse files
committed
Fix Unified line numbers when context is 0
Signed-off-by: Jack Cherng <[email protected]>
1 parent 795628f commit 8ab502f

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

src/Renderer/Text/Unified.php

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -47,19 +47,29 @@ protected function renderHunkHeader(Differ $differ, array $hunk): string
4747
{
4848
$lastBlockIdx = \count($hunk) - 1;
4949

50+
// note that these line number variables are 0-based
5051
$i1 = $hunk[0][1];
5152
$i2 = $hunk[$lastBlockIdx][2];
5253
$j1 = $hunk[0][3];
5354
$j2 = $hunk[$lastBlockIdx][4];
5455

55-
if ($i1 === 0 && $i2 === 0) {
56-
$i1 = $i2 = -1; // trick
57-
}
56+
$oldLinesCount = $i2 - $i1;
57+
$newLinesCount = $j2 - $j1;
5858

5959
return
6060
'@@ ' .
61-
'-' . ($i1 + 1) . ',' . ($i2 - $i1) . ' ' .
62-
'+' . ($j1 + 1) . ',' . ($j2 - $j1) . ' ' .
61+
'-' .
62+
// the line number in GNU diff is 1-based, so we add 1
63+
// a special case is when a hunk has only changed blocks,
64+
// i.e., context is set to 0, we do not need the adding
65+
($i1 === $i2 ? $i1 : $i1 + 1) .
66+
// if the line counts is 1, it can (and mostly) be omitted
67+
($oldLinesCount === 1 ? '' : ",{$oldLinesCount}") .
68+
' ' .
69+
'+' .
70+
($j1 === $j2 ? $j1 : $j1 + 1) .
71+
($newLinesCount === 1 ? '' : ",{$newLinesCount}") .
72+
' ' .
6373
"@@\n";
6474
}
6575

0 commit comments

Comments
 (0)