Skip to content

Commit 709f825

Browse files
Zach Baileysebastianbergmann
authored andcommitted
Do not add additional newline to unified diff when completely empty
1 parent 249d2b1 commit 709f825

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

src/Output/UnifiedDiffOutputBuilder.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,11 +67,11 @@ public function getDiff(array $diff): string
6767

6868
\fclose($buffer);
6969

70-
// If the last char is not a linebreak: add it.
70+
// If the diff is non-empty and last char is not a linebreak: add it.
7171
// This might happen when both the `from` and `to` do not have a trailing linebreak
7272
$last = \substr($diff, -1);
7373

74-
return "\n" !== $last && "\r" !== $last
74+
return 0 !== \strlen($diff) && "\n" !== $last && "\r" !== $last
7575
? $diff . "\n"
7676
: $diff;
7777
}

tests/Output/UnifiedDiffOutputBuilderTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,4 +81,28 @@ public function provideDiffWithLineNumbers(): array
8181
{
8282
return UnifiedDiffOutputBuilderDataProvider::provideDiffWithLineNumbers();
8383
}
84+
85+
/**
86+
* @param string $from
87+
* @param string $to
88+
*
89+
* @dataProvider provideStringsThatAreTheSame
90+
*/
91+
public function testEmptyDiffProducesEmptyOutput(string $from, string $to): void
92+
{
93+
$differ = new Differ(new UnifiedDiffOutputBuilder('', false));
94+
$output = $differ->diff($from, $to);
95+
$this->assertEmpty($output);
96+
}
97+
98+
public function provideStringsThatAreTheSame(): array
99+
{
100+
return [
101+
['', ''],
102+
['a', 'a'],
103+
['these strings are the same', 'these strings are the same'],
104+
["\n", "\n"],
105+
["multi-line strings\nare the same", "multi-line strings\nare the same"]
106+
];
107+
}
84108
}

0 commit comments

Comments
 (0)