Skip to content
Snippets Groups Projects
Commit 00d81102 authored by SpacePossum's avatar SpacePossum Committed by Sebastian Bergmann
Browse files

- Add context lines

- Add strict udiff output format
parent 0fd4d14d
No related branches found
No related tags found
No related merge requests found
Showing
with 3175 additions and 408 deletions
- Docs
{
"name": "sebastian/diff",
"description": "Diff implementation",
"keywords": ["diff"],
"keywords": ["diff", "udiff", "unidiff", "unified diff"],
"homepage": "https://github.com/sebastianbergmann/diff",
"license": "BSD-3-Clause",
"authors": [
......@@ -18,7 +18,8 @@
"php": "^7.0"
},
"require-dev": {
"phpunit/phpunit": "^6.2"
"phpunit/phpunit": "^6.2",
"symfony/process": "^3.3"
},
"autoload": {
"classmap": [
......
......@@ -10,7 +10,6 @@
namespace SebastianBergmann\Diff;
use SebastianBergmann\Diff\InvalidArgumentException;
use SebastianBergmann\Diff\Output\DiffOutputBuilderInterface;
use SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder;
......
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff;
final class ConfigurationException extends InvalidArgumentException
{
/**
* @param string $option
* @param string $expected
* @param mixed $value
* @param int $code
* @param Exception|null $previous
*/
public function __construct(
string $option,
string $expected,
$value,
int $code = 0,
Exception $previous = null
) {
parent::__construct(
\sprintf(
'Option "%s" must be %s, got "%s".',
$option,
$expected,
\is_object($value) ? \get_class($value) : (null === $value ? '<null>' : \gettype($value) . '#' . $value)
),
$code,
$previous
);
}
}
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Output;
use SebastianBergmann\Diff\ConfigurationException;
/**
* Strict Unified diff output builder.
*
* @name Unified diff output builder
*
* @description Generates (strict) Unified diff's (unidiffs) with hunks.
*
* @author SpacePossum
*
* @api
*/
final class StrictUnifiedDiffOutputBuilder implements DiffOutputBuilderInterface
{
/**
* @var int
*/
private static $noNewlineAtOEFid = 998877;
/**
* @var bool
*/
private $changed;
/**
* @var bool
*/
private $collapseRanges;
/**
* @var int >= 0
*/
private $commonLineThreshold;
/**
* @var string
*/
private $header;
/**
* @var int >= 0
*/
private $contextLines;
private static $default = [
'collapseRanges' => true, // ranges of length one are rendered with the trailing `,1`
'commonLineThreshold' => 6, // number of same lines before ending a new hunk and creating a new one (if needed)
'contextLines' => 3, // like `diff: -u, -U NUM, --unified[=NUM]`, for patch/git apply compatibility best to keep at least @ 3
'fromFile' => null,
'fromFileDate' => null,
'toFile' => null,
'toFileDate' => null,
];
public function __construct(array $options = [])
{
$options = \array_merge(self::$default, $options);
if (!\is_bool($options['collapseRanges'])) {
throw new ConfigurationException('collapseRanges', 'a bool', $options['collapseRanges']);
}
if (!\is_int($options['contextLines']) || $options['contextLines'] < 0) {
throw new ConfigurationException('contextLines', 'an int >= 0', $options['contextLines']);
}
if (!\is_int($options['commonLineThreshold']) || $options['commonLineThreshold'] < 1) {
throw new ConfigurationException('commonLineThreshold', 'an int > 0', $options['commonLineThreshold']);
}
foreach (['fromFile', 'toFile'] as $option) {
if (!\is_string($options[$option])) {
throw new ConfigurationException($option, 'a string', $options[$option]);
}
}
foreach (['fromFileDate', 'toFileDate'] as $option) {
if (null !== $options[$option] && !\is_string($options[$option])) {
throw new ConfigurationException($option, 'a string or <null>', $options[$option]);
}
}
$this->header = \sprintf(
"--- %s%s\n+++ %s%s\n",
$options['fromFile'],
null === $options['fromFileDate'] ? '' : "\t" . $options['fromFileDate'],
$options['toFile'],
null === $options['toFileDate'] ? '' : "\t" . $options['toFileDate']
);
$this->collapseRanges = $options['collapseRanges'];
$this->commonLineThreshold = $options['commonLineThreshold'];
$this->contextLines = $options['contextLines'];
}
public function getDiff(array $diff): string
{
if (0 === \count($diff)) {
return '';
}
$this->changed = false;
$buffer = \fopen('php://memory', 'r+b');
\fwrite($buffer, $this->header);
$this->writeDiffHunks($buffer, $diff);
if (!$this->changed) {
\fclose($buffer);
return '';
}
$diff = \stream_get_contents($buffer, -1, 0);
\fclose($buffer);
// If the last char is not a linebreak: add it.
// This might happen when both the `from` and `to` do not have a trailing linebreak
$last = \substr($diff, -1);
return "\n" !== $last && "\r" !== $last
? $diff . "\n"
: $diff
;
}
private function writeDiffHunks($output, array $diff)
{
// detect "No newline at end of file" and insert into `$diff` if needed
$upperLimit = \count($diff);
if (0 === $diff[$upperLimit - 1][1]) {
$lc = \substr($diff[$upperLimit - 1][0], -1);
if ("\n" !== $lc) {
\array_splice($diff, $upperLimit, 0, [["\n\\ No newline at end of file\n", self::$noNewlineAtOEFid]]);
}
} else {
// search back for the last `+` and `-` line,
// check if has trailing linebreak, else add under it warning under it
$toFind = [1 => true, 2 => true];
for ($i = $upperLimit - 1; $i >= 0; --$i) {
if (isset($toFind[$diff[$i][1]])) {
unset($toFind[$diff[$i][1]]);
$lc = \substr($diff[$i][0], -1);
if ("\n" !== $lc) {
\array_splice($diff, $i + 1, 0, [["\n\\ No newline at end of file\n", self::$noNewlineAtOEFid]]);
}
if (!\count($toFind)) {
break;
}
}
}
}
// write hunks to output buffer
$cutOff = \max($this->commonLineThreshold, $this->contextLines);
$hunkCapture = false;
$sameCount = $toRange = $fromRange = 0;
$toStart = $fromStart = 1;
foreach ($diff as $i => $entry) {
if (0 === $entry[1]) { // same
if (false === $hunkCapture) {
++$fromStart;
++$toStart;
continue;
}
++$sameCount;
++$toRange;
++$fromRange;
if ($sameCount === $cutOff) {
$contextStartOffset = ($hunkCapture - $this->contextLines) < 0
? $hunkCapture
: $this->contextLines
;
// note: $contextEndOffset = $this->contextLines;
//
// because we never go beyond the end of the diff.
// with the cutoff/contextlines here the follow is never true;
//
// if ($i - $cutOff + $this->contextLines + 1 > \count($diff)) {
// $contextEndOffset = count($diff) - 1;
// }
//
// ; that would be true for a trailing incomplete hunk case which is dealt with after this loop
$this->writeHunk(
$diff,
$hunkCapture - $contextStartOffset,
$i - $cutOff + $this->contextLines + 1,
$fromStart - $contextStartOffset,
$fromRange - $cutOff + $contextStartOffset + $this->contextLines,
$toStart - $contextStartOffset,
$toRange - $cutOff + $contextStartOffset + $this->contextLines,
$output
);
$fromStart += $fromRange;
$toStart += $toRange;
$hunkCapture = false;
$sameCount = $toRange = $fromRange = 0;
}
continue;
}
$sameCount = 0;
if ($entry[1] === self::$noNewlineAtOEFid) {
continue;
}
$this->changed = true;
if (false === $hunkCapture) {
$hunkCapture = $i;
}
if (1 === $entry[1]) { // added
++$toRange;
}
if (2 === $entry[1]) { // removed
++$fromRange;
}
}
if (false === $hunkCapture) {
return;
}
// we end here when cutoff (commonLineThreshold) was not reached, but we where capturing a hunk,
// do not render hunk till end automatically because the number of context lines might be less than the commonLineThreshold
$contextStartOffset = $hunkCapture - $this->contextLines < 0
? $hunkCapture
: $this->contextLines
;
// prevent trying to write out more common lines than there are in the diff _and_
// do not write more than configured through the context lines
$contextEndOffset = \min($sameCount, $this->contextLines);
$fromRange -= $sameCount;
$toRange -= $sameCount;
$this->writeHunk(
$diff,
$hunkCapture - $contextStartOffset,
$i - $sameCount + $contextEndOffset + 1,
$fromStart - $contextStartOffset,
$fromRange + $contextStartOffset + $contextEndOffset,
$toStart - $contextStartOffset,
$toRange + $contextStartOffset + $contextEndOffset,
$output
);
}
private function writeHunk(
array $diff,
int $diffStartIndex,
int $diffEndIndex,
int $fromStart,
int $fromRange,
int $toStart,
int $toRange,
$output
) {
\fwrite($output, '@@ -' . $fromStart);
if (!$this->collapseRanges || 1 !== $fromRange) {
\fwrite($output, ',' . $fromRange);
}
\fwrite($output, ' +' . $toStart);
if (!$this->collapseRanges || 1 !== $toRange) {
\fwrite($output, ',' . $toRange);
}
\fwrite($output, " @@\n");
for ($i = $diffStartIndex; $i < $diffEndIndex; ++$i) {
if ($diff[$i][1] === 1) { // added
$this->changed = true;
\fwrite($output, '+' . $diff[$i][0]);
} elseif ($diff[$i][1] === 2) { // removed
$this->changed = true;
\fwrite($output, '-' . $diff[$i][0]);
} elseif ($diff[$i][1] === 0) { // same
\fwrite($output, ' ' . $diff[$i][0]);
} elseif ($diff[$i][1] === self::$noNewlineAtOEFid) {
$this->changed = true;
\fwrite($output, $diff[$i][0]);
}
//} elseif ($diff[$i][1] === 3) { // custom comment inserted by PHPUnit/diff package
// skip
//} else {
// unknown/invalid
//}
}
}
}
......@@ -15,6 +15,26 @@ namespace SebastianBergmann\Diff\Output;
*/
final class UnifiedDiffOutputBuilder extends AbstractChunkOutputBuilder
{
/**
* @var int
*/
private static $noNewlineAtOEFid = 998877;
/**
* @var bool
*/
private $collapseRanges = true;
/**
* @var int >= 0
*/
private $commonLineThreshold = 6;
/**
* @var int >= 0
*/
private $contextLines = 3;
/**
* @var string
*/
......@@ -42,84 +62,181 @@ final class UnifiedDiffOutputBuilder extends AbstractChunkOutputBuilder
}
}
$this->writeDiffChunked($buffer, $diff, $this->getCommonChunks($diff));
if (0 !== \count($diff)) {
$this->writeDiffHunks($buffer, $diff);
}
$diff = \stream_get_contents($buffer, -1, 0);
\fclose($buffer);
return $diff;
// If the last char is not a linebreak: add it.
// This might happen when both the `from` and `to` do not have a trailing linebreak
$last = \substr($diff, -1);
return "\n" !== $last && "\r" !== $last
? $diff . "\n"
: $diff
;
}
// `old` is an array with key => value pairs . Each pair represents a start and end index of `diff`
// of a list of elements all containing `same` (0) entries.
private function writeDiffChunked($output, array $diff, array $old)
private function writeDiffHunks($output, array $diff)
{
// detect "No newline at end of file" and insert into `$diff` if needed
$upperLimit = \count($diff);
$start = 0;
$fromStart = 0;
$toStart = 0;
if (\count($old)) { // no common parts, list all diff entries
\reset($old);
if (0 === $diff[$upperLimit - 1][1]) {
$lc = \substr($diff[$upperLimit - 1][0], -1);
if ("\n" !== $lc) {
\array_splice($diff, $upperLimit, 0, [["\n\\ No newline at end of file\n", self::$noNewlineAtOEFid]]);
}
} else {
// search back for the last `+` and `-` line,
// check if has trailing linebreak, else add under it warning under it
$toFind = [1 => true, 2 => true];
for ($i = $upperLimit - 1; $i >= 0; --$i) {
if (isset($toFind[$diff[$i][1]])) {
unset($toFind[$diff[$i][1]]);
$lc = \substr($diff[$i][0], -1);
if ("\n" !== $lc) {
\array_splice($diff, $i + 1, 0, [["\n\\ No newline at end of file\n", self::$noNewlineAtOEFid]]);
}
// iterate the diff, go from chunk to chunk skipping common chunk of lines between those
do {
$commonStart = \key($old);
$commonEnd = \current($old);
if (!\count($toFind)) {
break;
}
}
}
}
// write hunks to output buffer
$cutOff = \max($this->commonLineThreshold, $this->contextLines);
$hunkCapture = false;
$sameCount = $toRange = $fromRange = 0;
$toStart = $fromStart = 1;
if ($commonStart !== $start) {
list($fromRange, $toRange) = $this->getChunkRange($diff, $start, $commonStart);
$this->writeChunk($output, $diff, $start, $commonStart, $fromStart, $fromRange, $toStart, $toRange);
foreach ($diff as $i => $entry) {
if (0 === $entry[1]) { // same
if (false === $hunkCapture) {
++$fromStart;
++$toStart;
continue;
}
++$sameCount;
++$toRange;
++$fromRange;
if ($sameCount === $cutOff) {
$contextStartOffset = ($hunkCapture - $this->contextLines) < 0
? $hunkCapture
: $this->contextLines
;
// note: $contextEndOffset = $this->contextLines;
//
// because we never go beyond the end of the diff.
// with the cutoff/contextlines here the follow is never true;
//
// if ($i - $cutOff + $this->contextLines + 1 > \count($diff)) {
// $contextEndOffset = count($diff) - 1;
// }
//
// ; that would be true for a trailing incomplete hunk case which is dealt with after this loop
$this->writeHunk(
$diff,
$hunkCapture - $contextStartOffset,
$i - $cutOff + $this->contextLines + 1,
$fromStart - $contextStartOffset,
$fromRange - $cutOff + $contextStartOffset + $this->contextLines,
$toStart - $contextStartOffset,
$toRange - $cutOff + $contextStartOffset + $this->contextLines,
$output
);
$fromStart += $fromRange;
$toStart += $toRange;
$hunkCapture = false;
$sameCount = $toRange = $fromRange = 0;
}
$start = $commonEnd + 1;
$commonLength = $commonEnd - $commonStart + 1; // calculate number of non-change lines in the common part
$fromStart += $commonLength;
$toStart += $commonLength;
} while (false !== \next($old));
\end($old); // short cut for finding possible last `change entry`
$tmp = \key($old);
\reset($old);
if ($old[$tmp] === $upperLimit - 1) {
$upperLimit = $tmp;
continue;
}
$sameCount = 0;
if ($entry[1] === self::$noNewlineAtOEFid) {
continue;
}
if (false === $hunkCapture) {
$hunkCapture = $i;
}
}
if ($start < $upperLimit - 1) { // check for trailing (non) diff entries
do {
--$upperLimit;
} while (isset($diff[$upperLimit][1]) && $diff[$upperLimit][1] === 0);
++$upperLimit;
if (1 === $entry[1]) { // added
++$toRange;
}
if (2 === $entry[1]) { // removed
++$fromRange;
}
}
list($fromRange, $toRange) = $this->getChunkRange($diff, $start, $upperLimit);
$this->writeChunk($output, $diff, $start, $upperLimit, $fromStart, $fromRange, $toStart, $toRange);
if (false === $hunkCapture) {
return;
}
// we end here when cutoff (commonLineThreshold) was not reached, but we where capturing a hunk,
// do not render hunk till end automatically because the number of context lines might be less than the commonLineThreshold
$contextStartOffset = $hunkCapture - $this->contextLines < 0
? $hunkCapture
: $this->contextLines
;
// prevent trying to write out more common lines than there are in the diff _and_
// do not write more than configured through the context lines
$contextEndOffset = \min($sameCount, $this->contextLines);
$fromRange -= $sameCount;
$toRange -= $sameCount;
$this->writeHunk(
$diff,
$hunkCapture - $contextStartOffset,
$i - $sameCount + $contextEndOffset + 1,
$fromStart - $contextStartOffset,
$fromRange + $contextStartOffset + $contextEndOffset,
$toStart - $contextStartOffset,
$toRange + $contextStartOffset + $contextEndOffset,
$output
);
}
private function writeChunk(
$output,
private function writeHunk(
array $diff,
int $diffStartIndex,
int $diffEndIndex,
int $fromStart,
int $fromRange,
int $toStart,
int $toRange
int $toRange,
$output
) {
if ($this->addLineNumbers) {
\fwrite($output, '@@ -' . (1 + $fromStart));
\fwrite($output, '@@ -' . $fromStart);
if ($fromRange !== 1) {
if (!$this->collapseRanges || 1 !== $fromRange) {
\fwrite($output, ',' . $fromRange);
}
\fwrite($output, ' +' . (1 + $toStart));
if ($toRange !== 1) {
\fwrite($output, ' +' . $toStart);
if (!$this->collapseRanges || 1 !== $toRange) {
\fwrite($output, ',' . $toRange);
}
......@@ -129,37 +246,17 @@ final class UnifiedDiffOutputBuilder extends AbstractChunkOutputBuilder
}
for ($i = $diffStartIndex; $i < $diffEndIndex; ++$i) {
if ($diff[$i][1] === 1 /* ADDED */) {
if ($diff[$i][1] === 1) { // added
\fwrite($output, '+' . $diff[$i][0]);
} elseif ($diff[$i][1] === 2 /* REMOVED */) {
} elseif ($diff[$i][1] === 2) { // removed
\fwrite($output, '-' . $diff[$i][0]);
} elseif ($diff[$i][1] === 0) { // same
\fwrite($output, ' ' . $diff[$i][0]);
} elseif ($diff[$i][1] === self::$noNewlineAtOEFid) {
\fwrite($output, "\n"); // $diff[$i][0]
} else { /* Not changed (old) 0 or Warning 3 */
\fwrite($output, ' ' . $diff[$i][0]);
}
$lc = \substr($diff[$i][0], -1);
if ($lc !== "\n" && $lc !== "\r") {
\fwrite($output, "\n"); // \No newline at end of file
}
}
}
private function getChunkRange(array $diff, int $diffStartIndex, int $diffEndIndex): array
{
$toRange = 0;
$fromRange = 0;
for ($i = $diffStartIndex; $i < $diffEndIndex; ++$i) {
if ($diff[$i][1] === 1) { // added
++$toRange;
} elseif ($diff[$i][1] === 2) { // removed
++$fromRange;
} elseif ($diff[$i][1] === 0) { // same
++$fromRange;
++$toRange;
}
}
return [$fromRange, $toRange];
}
}
......@@ -99,7 +99,7 @@ final class DifferTest extends TestCase
-one
+two
',
$this->differ->diff(array('one'), array('two'))
$this->differ->diff(['one'], ['two'])
);
}
......@@ -273,42 +273,7 @@ final class DifferTest extends TestCase
'b',
],
[
"--- Original\n+++ New\n@@ @@\n-ba\n+bc\n",
'ba',
'bc',
],
[
"--- Original\n+++ New\n@@ @@\n-ab\n+cb\n",
'ab',
'cb',
],
[
"--- Original\n+++ New\n@@ @@\n-abc\n+adc\n",
'abc',
'adc',
],
[
"--- Original\n+++ New\n@@ @@\n-ab\n+abc\n",
'ab',
'abc',
],
[
"--- Original\n+++ New\n@@ @@\n-bc\n+abc\n",
'bc',
'abc',
],
[
"--- Original\n+++ New\n@@ @@\n-abc\n+abbc\n",
'abc',
'abbc',
],
[
"--- Original\n+++ New\n@@ @@\n-abcdde\n+abcde\n",
'abcdde',
'abcde',
],
[
"--- Original\n+++ New\n@@ @@\n-A\n+A1\n",
"--- Original\n+++ New\n@@ @@\n-A\n+A1\n B\n",
"A\nB",
"A1\nB",
],
......@@ -320,14 +285,21 @@ final class DifferTest extends TestCase
a
-b
+p
c
d
e
@@ @@
g
h
i
-j
+w
k
EOF
,
"a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk",
"a\np\nc\nd\ne\nf\ng\nh\ni\nw\nk",
"a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\n",
"a\np\nc\nd\ne\nf\ng\nh\ni\nw\nk\n",
],
[
<<<EOF
......@@ -336,19 +308,22 @@ EOF
@@ @@
-A
+B
1
2
3
EOF
,
"A\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1",
"B\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1",
"A\n1\n2\n3\n4\n5\n6\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n",
"B\n1\n2\n3\n4\n5\n6\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n",
],
[
"--- Original\n+++ New\n@@ @@\n #Warning: Strings contain different line endings!\n-<?php\r\n+<?php\n",
"--- Original\n+++ New\n@@ @@\n #Warning: Strings contain different line endings!\n-<?php\r\n+<?php\n A\n",
"<?php\r\nA\n",
"<?php\nA\n",
],
[
"--- Original\n+++ New\n@@ @@\n #Warning: Strings contain different line endings!\n-a\r\n+\n+c\r",
"--- Original\n+++ New\n@@ @@\n #Warning: Strings contain different line endings!\n-a\r\n+\n+c\r\n",
"a\r\n",
"\nc\r",
],
......
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff;
use PHPUnit\Framework\TestCase;
/**
* @author SpacePossum
*
* @covers SebastianBergmann\Diff\ConfigurationException
*
* @internal
*/
final class ConfigurationExceptionTest extends TestCase
{
public function testConstruct()
{
$e = new ConfigurationException('test', 'A', 'B');
$this->assertSame(0, $e->getCode());
$this->assertNull($e->getPrevious());
$this->assertSame('Option "test" must be A, got "string#B".', $e->getMessage());
}
}
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Output;
use PHPUnit\Framework\TestCase;
use SebastianBergmann\Diff\Differ;
use SebastianBergmann\Diff\Utils\UnifiedDiffAssertTrait;
use Symfony\Component\Process\Process;
/**
* @author SpacePossum
*
* @requires OS Linux
*
* @coversNothing
*
* @internal
*/
final class StrictUnifiedDiffOutputBuilderIntegrationTest extends TestCase
{
use UnifiedDiffAssertTrait;
private $dir;
private $fileFrom;
private $fileTo;
private $filePatch;
protected function setUp()
{
$this->dir = realpath(__DIR__ . '/../../fixtures/out').'/';
$this->fileFrom = $this->dir . 'from.txt';
$this->fileTo = $this->dir . 'to.txt';
$this->filePatch = $this->dir . 'diff.patch';
if (!is_dir($this->dir)) {
throw new \RuntimeException('Integration test working directory not found.');
}
$this->cleanUpTempFiles();
}
/**
* Integration test
*
* - get a file pair
* - create a `diff` between the files
* - test applying the diff using `git apply`
* - test applying the diff using `patch`
*
* @param string $fileFrom
* @param string $fileTo
*
* @dataProvider provideFilePairs
*/
public function testIntegrationUsingPHPFileInVendorGitApply(string $fileFrom, string $fileTo)
{
$from = self::getFileContent($fileFrom);
$to = self::getFileContent($fileTo);
$diff = (new Differ(new StrictUnifiedDiffOutputBuilder(['fromFile' => 'Original', 'toFile' => 'New'])))->diff($from, $to);
if ('' === $diff && $from === $to) {
// odd case: test after executing as it is more efficient than to read the files and check the contents every time
$this->addToAssertionCount(1);
return;
}
$this->doIntegrationTestGitApply($diff, $from, $to);
}
/**
* Integration test
*
* - get a file pair
* - create a `diff` between the files
* - test applying the diff using `git apply`
* - test applying the diff using `patch`
*
* @param string $fileFrom
* @param string $fileTo
*
* @dataProvider provideFilePairs
*/
public function testIntegrationUsingPHPFileInVendorPatch(string $fileFrom, string $fileTo)
{
$from = self::getFileContent($fileFrom);
$to = self::getFileContent($fileTo);
$diff = (new Differ(new StrictUnifiedDiffOutputBuilder(['fromFile' => 'Original', 'toFile' => 'New'])))->diff($from, $to);
if ('' === $diff && $from === $to) {
// odd case: test after executing as it is more efficient than to read the files and check the contents every time
$this->addToAssertionCount(1);
return;
}
$this->doIntegrationTestPatch($diff, $from, $to);
}
/**
* @param string $expected
* @param string $from
* @param string $to
*
* @dataProvider provideOutputBuildingCases
* @dataProvider provideSample
* @dataProvider provideBasicDiffGeneration
*/
public function testIntegrationOfUnitTestCasesGitApply(string $expected, string $from, string $to)
{
$this->doIntegrationTestGitApply($expected, $from, $to);
}
/**
* @param string $expected
* @param string $from
* @param string $to
*
* @dataProvider provideOutputBuildingCases
* @dataProvider provideSample
* @dataProvider provideBasicDiffGeneration
*/
public function testIntegrationOfUnitTestCasesPatch(string $expected, string $from, string $to)
{
$this->doIntegrationTestPatch($expected, $from, $to);
}
public function provideOutputBuildingCases(): array
{
return StrictUnifiedDiffOutputBuilderDataProvider::provideOutputBuildingCases();
}
public function provideSample(): array
{
return StrictUnifiedDiffOutputBuilderDataProvider::provideSample();
}
public function provideBasicDiffGeneration(): array
{
return StrictUnifiedDiffOutputBuilderDataProvider::provideBasicDiffGeneration();
}
public function provideFilePairs(): array
{
$cases = [];
$fromFile = __FILE__;
$vendorDir = \realpath(__DIR__ . '/../../../vendor');
$fileIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($vendorDir, \RecursiveDirectoryIterator::SKIP_DOTS));
/** @var \SplFileInfo $file */
foreach ($fileIterator as $file) {
if ('php' !== $file->getExtension()) {
continue;
}
$toFile = $file->getPathname();
$cases[\sprintf("Diff file:\n\"%s\"\nvs.\n\"%s\"\n", \realpath($fromFile), \realpath($toFile))] = [$fromFile, $toFile];
$fromFile = $toFile;
}
return $cases;
}
/**
* Compare diff create by builder and against one create by `diff` command.
*
* @param string $diff
* @param string $from
* @param string $to
*
* @dataProvider provideBasicDiffGeneration
*/
public function testIntegrationDiffOutputBuilderVersusDiffCommand(string $diff, string $from, string $to)
{
$this->assertNotSame('', $diff);
$this->assertValidUnifiedDiffFormat($diff);
$this->assertNotFalse(\file_put_contents($this->fileFrom, $from));
$this->assertNotFalse(\file_put_contents($this->fileTo, $to));
$p = new Process(\sprintf('diff -u %s %s', \escapeshellarg($this->fileFrom), \escapeshellarg($this->fileTo)));
$p->run();
$this->assertSame(1, $p->getExitCode()); // note: Process assumes exit code 0 for `isSuccessful`, however `diff` uses the exit code `1` for success with diff
$output = $p->getOutput();
$diffLines = \preg_split('/(.*\R)/', $diff, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$diffLines[0] = \preg_replace('#^\-\-\- .*#', '--- /' . $this->fileFrom, $diffLines[0], 1);
$diffLines[1] = \preg_replace('#^\+\+\+ .*#', '+++ /' . $this->fileFrom, $diffLines[1], 1);
$diff = \implode('', $diffLines);
$outputLines = \preg_split('/(.*\R)/', $output, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$outputLines[0] = \preg_replace('#^\-\-\- .*#', '--- /' . $this->fileFrom, $outputLines[0], 1);
$outputLines[1] = \preg_replace('#^\+\+\+ .*#', '+++ /' . $this->fileFrom, $outputLines[1], 1);
$output = \implode('', $outputLines);
$this->assertSame($diff, $output);
}
private function doIntegrationTestGitApply(string $diff, string $from, string $to)
{
$this->assertNotSame('', $diff);
$this->assertValidUnifiedDiffFormat($diff);
$diff = self::setDiffFileHeader($diff, $this->fileFrom);
$this->assertNotFalse(\file_put_contents($this->fileFrom, $from));
$this->assertNotFalse(\file_put_contents($this->filePatch, $diff));
$p = new Process(\sprintf(
'git --git-dir %s apply --check -v --unsafe-paths --ignore-whitespace %s',
\escapeshellarg($this->dir),
\escapeshellarg($this->filePatch)
));
$p->run();
$this->assertProcessSuccessful($p);
}
private function doIntegrationTestPatch(string $diff, string $from, string $to)
{
$this->assertNotSame('', $diff);
$this->assertValidUnifiedDiffFormat($diff);
$diff = self::setDiffFileHeader($diff, $this->fileFrom);
$this->assertNotFalse(\file_put_contents($this->fileFrom, $from));
$this->assertNotFalse(\file_put_contents($this->filePatch, $diff));
$command = \sprintf(
'patch -u --verbose --posix %s < %s',
\escapeshellarg($this->fileFrom),
\escapeshellarg($this->filePatch)
);
$p = new Process($command);
$p->run();
$this->assertProcessSuccessful($p);
$this->assertStringEqualsFile(
$this->fileFrom,
$to,
\sprintf('Patch command "%s".', $command)
);
}
protected function tearDown()
{
$this->cleanUpTempFiles();
}
private function assertProcessSuccessful(Process $p)
{
$this->assertTrue(
$p->isSuccessful(),
\sprintf(
"Command exec. was not successful:\n\"%s\"\nOutput:\n\"%s\"\nStdErr:\n\"%s\"\nExit code %d.\n",
$p->getCommandLine(),
$p->getOutput(),
$p->getErrorOutput(),
$p->getExitCode()
)
);
}
private function cleanUpTempFiles()
{
@\unlink($this->fileFrom . '.orig');
@\unlink($this->fileFrom . '.rej');
@\unlink($this->fileFrom);
@\unlink($this->fileTo);
@\unlink($this->filePatch);
}
private static function setDiffFileHeader(string $diff, string $file): string
{
$diffLines = \preg_split('/(.*\R)/', $diff, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$diffLines[0] = \preg_replace('#^\-\-\- .*#', '--- /' . $file, $diffLines[0], 1);
$diffLines[1] = \preg_replace('#^\+\+\+ .*#', '+++ /' . $file, $diffLines[1], 1);
return \implode('', $diffLines);
}
private static function getFileContent(string $file): string
{
$content = @\file_get_contents($file);
if (false === $content) {
$error = \error_get_last();
throw new \RuntimeException(\sprintf(
'Failed to read content of file "%s".%s',
$file,
$error ? ' ' . $error['message'] : ''
));
}
return $content;
}
}
......@@ -11,6 +11,8 @@
namespace SebastianBergmann\Diff\Output;
use PHPUnit\Framework\TestCase;
use SebastianBergmann\Diff\Utils\UnifiedDiffAssertTrait;
use Symfony\Component\Process\Process;
/**
* @covers SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder
......@@ -21,68 +23,134 @@ use PHPUnit\Framework\TestCase;
*
* @requires OS Linux
*/
final class UnifiedDiffOutputBuilderTestTest extends TestCase
final class UnifiedDiffOutputBuilderIntegrationTest extends TestCase
{
use UnifiedDiffAssertTrait;
private $dir;
private $fileFrom;
private $filePatch;
protected function setUp()
{
$dir = \realpath(__DIR__ . '/../../') . '/';
$this->fileFrom = $dir . 'from.txt';
$this->filePatch = $dir . 'patch.txt';
$this->dir = \realpath(__DIR__ . '/../../fixtures/out/') . '/';
$this->fileFrom = $this->dir . 'from.txt';
$this->filePatch = $this->dir . 'patch.txt';
$this->cleanUpTempFiles();
}
/**
* @dataProvider provideDiffWithLineNumbers
*/
public function testDiffWithLineNumbersPath($expected, $from, $to)
{
$this->doIntegrationTestPatch($expected, $from, $to);
}
/**
* @dataProvider provideDiffWithLineNumbers
*/
public function testTheTestProvideDiffWithLineNumbers($expected, $from, $to)
public function testDiffWithLineNumbersGitApply($expected, $from, $to)
{
$this->runThisTest($expected, $from, $to);
$this->doIntegrationTestGitApply($expected, $from, $to);
}
public function provideDiffWithLineNumbers()
{
require_once __DIR__ . '/UnifiedDiffOutputBuilderTest.php';
$test = new UnifiedDiffOutputBuilderTest();
$tests = $test->provideDiffWithLineNumbers();
$tests = \array_filter(
$tests,
function ($key) {
return \array_filter(
UnifiedDiffOutputBuilderDataProvider::provideDiffWithLineNumbers(),
static function ($key) {
return !\is_string($key) || false === \strpos($key, 'non_patch_compat');
},
ARRAY_FILTER_USE_KEY
);
}
return $tests;
protected function tearDown()
{
$this->cleanUpTempFiles();
}
private function runThisTest(string $expected, string $from, string $to)
private function doIntegrationTestPatch(string $diff, string $from, string $to)
{
$expected = \str_replace('--- Original', '--- from.txt', $expected);
$expected = \str_replace('+++ New', '+++ from.txt', $expected);
$this->assertNotSame('', $diff);
$this->assertValidUnifiedDiffFormat($diff);
@\unlink($this->fileFrom);
@\unlink($this->filePatch);
$diff = self::setDiffFileHeader($diff, $this->fileFrom);
$this->assertNotFalse(\file_put_contents($this->fileFrom, $from));
$this->assertNotFalse(\file_put_contents($this->filePatch, $expected));
$this->assertNotFalse(\file_put_contents($this->filePatch, $diff));
$command = \sprintf(
'patch -u --verbose %s < %s', // --posix
'patch -u --verbose --posix %s < %s', // --posix
\escapeshellarg($this->fileFrom),
\escapeshellarg($this->filePatch)
);
\exec($command, $output, $d);
$p = new Process($command);
$p->run();
$this->assertProcessSuccessful($p);
$this->assertSame(0, $d, \sprintf('%s | %s', $command, \implode("\n", $output)));
$this->assertStringEqualsFile(
$this->fileFrom,
$to,
\sprintf('Patch command "%s".', $command)
);
}
private function doIntegrationTestGitApply(string $diff, string $from, string $to)
{
$this->assertNotSame('', $diff);
$this->assertValidUnifiedDiffFormat($diff);
$patched = \file_get_contents($this->fileFrom);
$this->assertSame($patched, $to);
$diff = self::setDiffFileHeader($diff, $this->fileFrom);
$this->assertNotFalse(\file_put_contents($this->fileFrom, $from));
$this->assertNotFalse(\file_put_contents($this->filePatch, $diff));
$command = \sprintf(
'git --git-dir %s apply --check -v --unsafe-paths --ignore-whitespace %s',
\escapeshellarg($this->dir),
\escapeshellarg($this->filePatch)
);
$p = new Process($command);
$p->run();
$this->assertProcessSuccessful($p);
}
private function assertProcessSuccessful(Process $p)
{
$this->assertTrue(
$p->isSuccessful(),
\sprintf(
"Command exec. was not successful:\n\"%s\"\nOutput:\n\"%s\"\nStdErr:\n\"%s\"\nExit code %d.\n",
$p->getCommandLine(),
$p->getOutput(),
$p->getErrorOutput(),
$p->getExitCode()
)
);
}
private function cleanUpTempFiles()
{
@\unlink($this->fileFrom . '.orig');
@\unlink($this->fileFrom);
@\unlink($this->filePatch);
}
private static function setDiffFileHeader(string $diff, string $file): string
{
$diffLines = \preg_split('/(.*\R)/', $diff, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$diffLines[0] = \preg_replace('#^\-\-\- .*#', '--- /' . $file, $diffLines[0], 1);
$diffLines[1] = \preg_replace('#^\+\+\+ .*#', '+++ /' . $file, $diffLines[1], 1);
return \implode('', $diffLines);
}
}
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Output;
/**
* @author SpacePossum
*
* @coversNothing
*
* @internal
*/
final class StrictUnifiedDiffOutputBuilderDataProvider
{
public static function provideOutputBuildingCases(): array
{
return [
[
'--- input.txt
+++ output.txt
@@ -1,3 +1,4 @@
+b
' . '
' . '
' . '
@@ -16,5 +17,4 @@
' . '
' . '
' . '
-
-B
+A
',
"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nB\n",
"b\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nA\n",
[
'fromFile' => 'input.txt',
'toFile' => 'output.txt',
],
],
[
'--- ' . __FILE__ . "\t2017-10-02 17:38:11.586413675 +0100
+++ output1.txt\t2017-10-03 12:09:43.086719482 +0100
@@ -1,1 +1,1 @@
-B
+X
",
"B\n",
"X\n",
[
'fromFile' => __FILE__,
'fromFileDate' => '2017-10-02 17:38:11.586413675 +0100',
'toFile' => 'output1.txt',
'toFileDate' => '2017-10-03 12:09:43.086719482 +0100',
'collapseRanges' => false,
],
],
[
'--- input.txt
+++ output.txt
@@ -1 +1 @@
-B
+X
',
"B\n",
"X\n",
[
'fromFile' => 'input.txt',
'toFile' => 'output.txt',
'collapseRanges' => true,
],
],
];
}
public static function provideSample(): array
{
return [
[
'--- input.txt
+++ output.txt
@@ -1,6 +1,6 @@
1
2
3
-4
+X
5
6
',
"1\n2\n3\n4\n5\n6\n",
"1\n2\n3\nX\n5\n6\n",
[
'fromFile' => 'input.txt',
'toFile' => 'output.txt',
],
],
];
}
public static function provideBasicDiffGeneration(): array
{
return [
[
"--- input.txt
+++ output.txt
@@ -1,2 +1 @@
-A
-B
+A\rB
",
"A\nB\n",
"A\rB\n",
],
[
"--- input.txt
+++ output.txt
@@ -1 +1 @@
-
+\r
\\ No newline at end of file
",
"\n",
"\r",
],
[
"--- input.txt
+++ output.txt
@@ -1 +1 @@
-\r
\\ No newline at end of file
+
",
"\r",
"\n",
],
[
'--- input.txt
+++ output.txt
@@ -1,3 +1,3 @@
X
A
-A
+B
',
"X\nA\nA\n",
"X\nA\nB\n",
],
[
'--- input.txt
+++ output.txt
@@ -1,3 +1,3 @@
X
A
-A
\ No newline at end of file
+B
',
"X\nA\nA",
"X\nA\nB\n",
],
[
'--- input.txt
+++ output.txt
@@ -1,3 +1,3 @@
A
A
-A
+B
\ No newline at end of file
',
"A\nA\nA\n",
"A\nA\nB",
],
[
'--- input.txt
+++ output.txt
@@ -1 +1 @@
-A
\ No newline at end of file
+B
\ No newline at end of file
',
'A',
'B',
],
];
}
}
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Output;
use PHPUnit\Framework\TestCase;
use SebastianBergmann\Diff\ConfigurationException;
use SebastianBergmann\Diff\Differ;
use SebastianBergmann\Diff\Utils\UnifiedDiffAssertTrait;
/**
* @author SpacePossum
*
* @covers SebastianBergmann\Diff\Output\StrictUnifiedDiffOutputBuilder
*
* @internal
*/
final class StrictUnifiedDiffOutputBuilderTest extends TestCase
{
use UnifiedDiffAssertTrait;
/**
* @param string $expected
* @param string $from
* @param string $to
* @param array $options
*
* @dataProvider provideOutputBuildingCases
*/
public function testOutputBuilding(string $expected, string $from, string $to, array $options)
{
$diff = $this->getDiffer($options)->diff($from, $to);
$this->assertValidDiffFormat($diff);
$this->assertSame($expected, $diff);
}
/**
* @param string $expected
* @param string $from
* @param string $to
* @param array $options
*
* @dataProvider provideSample
*/
public function testSample(string $expected, string $from, string $to, array $options)
{
$diff = $this->getDiffer($options)->diff($from, $to);
$this->assertValidDiffFormat($diff);
$this->assertSame($expected, $diff);
}
/**
* {@inheritdoc}
*/
public function assertValidDiffFormat(string $diff)
{
$this->assertValidUnifiedDiffFormat($diff);
}
/**
* {@inheritdoc}
*/
public function provideOutputBuildingCases(): array
{
return StrictUnifiedDiffOutputBuilderDataProvider::provideOutputBuildingCases();
}
/**
* {@inheritdoc}
*/
public function provideSample(): array
{
return StrictUnifiedDiffOutputBuilderDataProvider::provideSample();
}
/**
* @param string $expected
* @param string $from
* @param string $to
*
* @dataProvider provideBasicDiffGeneration
*/
public function testBasicDiffGeneration(string $expected, string $from, string $to)
{
$diff = $this->getDiffer([
'fromFile' => 'input.txt',
'toFile' => 'output.txt',
])->diff($from, $to);
$this->assertValidDiffFormat($diff);
$this->assertSame($expected, $diff);
}
public function provideBasicDiffGeneration(): array
{
return StrictUnifiedDiffOutputBuilderDataProvider::provideBasicDiffGeneration();
}
/**
* @param string $expected
* @param string $from
* @param string $to
* @param array $config
*
* @dataProvider provideConfiguredDiffGeneration
*/
public function testConfiguredDiffGeneration(string $expected, string $from, string $to, array $config = [])
{
$diff = $this->getDiffer(\array_merge([
'fromFile' => 'input.txt',
'toFile' => 'output.txt',
], $config))->diff($from, $to);
$this->assertValidDiffFormat($diff);
$this->assertSame($expected, $diff);
}
public function provideConfiguredDiffGeneration(): array
{
return [
[
'--- input.txt
+++ output.txt
@@ -1 +1 @@
-a
\ No newline at end of file
+b
\ No newline at end of file
',
'a',
'b',
],
[
'',
"1\n2",
"1\n2",
],
[
'',
"1\n",
"1\n",
],
[
'--- input.txt
+++ output.txt
@@ -4 +4 @@
-X
+4
',
"1\n2\n3\nX\n5\n6\n7\n8\n9\n0\n",
"1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n",
[
'contextLines' => 0,
],
],
[
'--- input.txt
+++ output.txt
@@ -3,3 +3,3 @@
3
-X
+4
5
',
"1\n2\n3\nX\n5\n6\n7\n8\n9\n0\n",
"1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n",
[
'contextLines' => 1,
],
],
[
'--- input.txt
+++ output.txt
@@ -1,10 +1,10 @@
1
2
3
-X
+4
5
6
7
8
9
0
',
"1\n2\n3\nX\n5\n6\n7\n8\n9\n0\n",
"1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n",
[
'contextLines' => 999,
],
],
[
'--- input.txt
+++ output.txt
@@ -1,0 +1,2 @@
+
+A
',
'',
"\nA\n",
],
[
'--- input.txt
+++ output.txt
@@ -1,2 +1,0 @@
-
-A
',
"\nA\n",
'',
],
[
'--- input.txt
+++ output.txt
@@ -1,5 +1,5 @@
1
-X
+2
3
-Y
+4
5
@@ -8,3 +8,3 @@
8
-X
+9
0
',
"1\nX\n3\nY\n5\n6\n7\n8\nX\n0\n",
"1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n",
[
'commonLineThreshold' => 2,
'contextLines' => 1,
],
],
[
'--- input.txt
+++ output.txt
@@ -2 +2 @@
-X
+2
@@ -4 +4 @@
-Y
+4
@@ -9 +9 @@
-X
+9
',
"1\nX\n3\nY\n5\n6\n7\n8\nX\n0\n",
"1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n",
[
'commonLineThreshold' => 1,
'contextLines' => 0,
],
],
];
}
public function testReUseBuilder()
{
$differ = $this->getDiffer([
'fromFile' => 'input.txt',
'toFile' => 'output.txt',
]);
$diff = $differ->diff("A\nB\n", "A\nX\n");
$this->assertSame(
'--- input.txt
+++ output.txt
@@ -1,2 +1,2 @@
A
-B
+X
',
$diff
);
$diff = $differ->diff("A\n", "A\n");
$this->assertSame(
'',
$diff
);
}
public function testEmptyDiff()
{
$builder = new StrictUnifiedDiffOutputBuilder([
'fromFile' => 'input.txt',
'toFile' => 'output.txt',
]);
$this->assertSame(
'',
$builder->getDiff([])
);
}
/**
* @param array $options
* @param string $message
*
* @dataProvider provideInvalidConfiguration
*/
public function testInvalidConfiguration(array $options, string $message)
{
$this->expectException(ConfigurationException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote($message, '#')));
new StrictUnifiedDiffOutputBuilder($options);
}
public function provideInvalidConfiguration(): array
{
$time = \time();
return [
[
['collapseRanges' => 1],
'Option "collapseRanges" must be a bool, got "integer#1".',
],
[
['contextLines' => 'a'],
'Option "contextLines" must be an int >= 0, got "string#a".',
],
[
['commonLineThreshold' => -2],
'Option "commonLineThreshold" must be an int > 0, got "integer#-2".',
],
[
['commonLineThreshold' => 0],
'Option "commonLineThreshold" must be an int > 0, got "integer#0".',
],
[
['fromFile' => new \SplFileInfo(__FILE__)],
'Option "fromFile" must be a string, got "SplFileInfo".',
],
[
['fromFile' => null],
'Option "fromFile" must be a string, got "<null>".',
],
[
[
'fromFile' => __FILE__,
'toFile' => 1,
],
'Option "toFile" must be a string, got "integer#1".',
],
[
[
'fromFile' => __FILE__,
'toFile' => __FILE__,
'toFileDate' => $time,
],
'Option "toFileDate" must be a string or <null>, got "integer#' . $time . '".',
],
[
[],
'Option "fromFile" must be a string, got "<null>".',
],
];
}
/**
* @param string $expected
* @param string $from
* @param string $to
* @param int $threshold
*
* @dataProvider provideCommonLineThresholdCases
*/
public function testCommonLineThreshold(string $expected, string $from, string $to, int $threshold)
{
$diff = $this->getDiffer([
'fromFile' => 'input.txt',
'toFile' => 'output.txt',
'commonLineThreshold' => $threshold,
'contextLines' => 0,
])->diff($from, $to);
$this->assertValidDiffFormat($diff);
$this->assertSame($expected, $diff);
}
public function provideCommonLineThresholdCases(): array
{
return [
[
'--- input.txt
+++ output.txt
@@ -2,3 +2,3 @@
-X
+B
C12
-Y
+D
@@ -7 +7 @@
-X
+Z
',
"A\nX\nC12\nY\nA\nA\nX\n",
"A\nB\nC12\nD\nA\nA\nZ\n",
2,
],
[
'--- input.txt
+++ output.txt
@@ -2 +2 @@
-X
+B
@@ -4 +4 @@
-Y
+D
',
"A\nX\nV\nY\n",
"A\nB\nV\nD\n",
1,
],
];
}
/**
* @param string $expected
* @param string $from
* @param string $to
* @param int $contextLines
* @param int $commonLineThreshold
*
* @dataProvider provideContextLineConfigurationCases
*/
public function testContextLineConfiguration(string $expected, string $from, string $to, int $contextLines, int $commonLineThreshold = 6)
{
$diff = $this->getDiffer([
'fromFile' => 'input.txt',
'toFile' => 'output.txt',
'contextLines' => $contextLines,
'commonLineThreshold' => $commonLineThreshold,
])->diff($from, $to);
$this->assertValidDiffFormat($diff);
$this->assertSame($expected, $diff);
}
public function provideContextLineConfigurationCases(): array
{
$from = "A\nB\nC\nD\nE\nF\nX\nG\nH\nI\nJ\nK\nL\nM\n";
$to = "A\nB\nC\nD\nE\nF\nY\nG\nH\nI\nJ\nK\nL\nM\n";
return [
'EOF 0' => [
"--- input.txt\n+++ output.txt\n@@ -3 +3 @@
-X
\\ No newline at end of file
+Y
\\ No newline at end of file
",
"A\nB\nX",
"A\nB\nY",
0,
],
'EOF 1' => [
"--- input.txt\n+++ output.txt\n@@ -2,2 +2,2 @@
B
-X
\\ No newline at end of file
+Y
\\ No newline at end of file
",
"A\nB\nX",
"A\nB\nY",
1,
],
'EOF 2' => [
"--- input.txt\n+++ output.txt\n@@ -1,3 +1,3 @@
A
B
-X
\\ No newline at end of file
+Y
\\ No newline at end of file
",
"A\nB\nX",
"A\nB\nY",
2,
],
'EOF 200' => [
"--- input.txt\n+++ output.txt\n@@ -1,3 +1,3 @@
A
B
-X
\\ No newline at end of file
+Y
\\ No newline at end of file
",
"A\nB\nX",
"A\nB\nY",
200,
],
'n/a 0' => [
"--- input.txt\n+++ output.txt\n@@ -7 +7 @@\n-X\n+Y\n",
$from,
$to,
0,
],
'G' => [
"--- input.txt\n+++ output.txt\n@@ -6,3 +6,3 @@\n F\n-X\n+Y\n G\n",
$from,
$to,
1,
],
'H' => [
"--- input.txt\n+++ output.txt\n@@ -5,5 +5,5 @@\n E\n F\n-X\n+Y\n G\n H\n",
$from,
$to,
2,
],
'I' => [
"--- input.txt\n+++ output.txt\n@@ -4,7 +4,7 @@\n D\n E\n F\n-X\n+Y\n G\n H\n I\n",
$from,
$to,
3,
],
'J' => [
"--- input.txt\n+++ output.txt\n@@ -3,9 +3,9 @@\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n",
$from,
$to,
4,
],
'K' => [
"--- input.txt\n+++ output.txt\n@@ -2,11 +2,11 @@\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n",
$from,
$to,
5,
],
'L' => [
"--- input.txt\n+++ output.txt\n@@ -1,13 +1,13 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n",
$from,
$to,
6,
],
'M' => [
"--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n M\n",
$from,
$to,
7,
],
'M no linebreak EOF .1' => [
"--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n-M\n+M\n\\ No newline at end of file\n",
$from,
\substr($to, 0, -1),
7,
],
'M no linebreak EOF .2' => [
"--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n-M\n\\ No newline at end of file\n+M\n",
\substr($from, 0, -1),
$to,
7,
],
'M no linebreak EOF .3' => [
"--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n M\n",
\substr($from, 0, -1),
\substr($to, 0, -1),
7,
],
'M no linebreak EOF .4' => [
"--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n M\n\\ No newline at end of file\n",
\substr($from, 0, -1),
\substr($to, 0, -1),
10000,
10000,
],
'M+1' => [
"--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n M\n",
$from,
$to,
8,
],
'M+100' => [
"--- input.txt\n+++ output.txt\n@@ -1,14 +1,14 @@\n A\n B\n C\n D\n E\n F\n-X\n+Y\n G\n H\n I\n J\n K\n L\n M\n",
$from,
$to,
107,
],
'0 II' => [
"--- input.txt\n+++ output.txt\n@@ -12 +12 @@\n-X\n+Y\n",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nM\n",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nM\n",
0,
999,
],
'0\' II' => [
"--- input.txt\n+++ output.txt\n@@ -12 +12 @@\n-X\n+Y\n",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nM\nA\nA\nA\nA\nA\n",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nM\nA\nA\nA\nA\nA\n",
0,
999,
],
'0\'\' II' => [
"--- input.txt\n+++ output.txt\n@@ -12,2 +12,2 @@\n-X\n-M\n\\ No newline at end of file\n+Y\n+M\n",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nM",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nM\n",
0,
],
'0\'\'\' II' => [
"--- input.txt\n+++ output.txt\n@@ -12,2 +12,2 @@\n-X\n-X1\n+Y\n+Y2\n",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nX1\nM\nA\nA\nA\nA\nA\n",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nY2\nM\nA\nA\nA\nA\nA\n",
0,
999,
],
'1 II' => [
"--- input.txt\n+++ output.txt\n@@ -11,3 +11,3 @@\n K\n-X\n+Y\n M\n",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nM\n",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nM\n",
1,
],
'5 II' => [
"--- input.txt\n+++ output.txt\n@@ -7,7 +7,7 @@\n G\n H\n I\n J\n K\n-X\n+Y\n M\n",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nX\nM\n",
"A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nY\nM\n",
5,
],
[
'--- input.txt
+++ output.txt
@@ -1,28 +1,28 @@
A
-X
+B
V
-Y
+D
1
A
2
A
3
A
4
A
8
A
9
A
5
A
A
A
A
A
A
A
A
A
A
A
',
"A\nX\nV\nY\n1\nA\n2\nA\n3\nA\n4\nA\n8\nA\n9\nA\n5\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\n",
"A\nB\nV\nD\n1\nA\n2\nA\n3\nA\n4\nA\n8\nA\n9\nA\n5\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\n",
9999,
99999,
],
];
}
/**
* Returns a new instance of a Differ with a new instance of the class (DiffOutputBuilderInterface) under test.
*
* @param array $options
*
* @return Differ
*/
private function getDiffer(array $options = []): Differ
{
return new Differ(new StrictUnifiedDiffOutputBuilder($options));
}
}
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Output;
/**
* @author SpacePossum
*
* @coversNothing
*
* @internal
*/
final class UnifiedDiffOutputBuilderDataProvider
{
public static function provideDiffWithLineNumbers(): array
{
return [
'diff line 1 non_patch_compat' => [
'--- Original
+++ New
@@ -1 +1 @@
-AA
+BA
',
'AA',
'BA',
],
'diff line +1 non_patch_compat' => [
'--- Original
+++ New
@@ -1 +1,2 @@
-AZ
+
+B
',
'AZ',
"\nB",
],
'diff line -1 non_patch_compat' => [
'--- Original
+++ New
@@ -1,2 +1 @@
-
-AF
+B
',
"\nAF",
'B',
],
'II non_patch_compat' => [
'--- Original
+++ New
@@ -1,4 +1,2 @@
-
-
A
1
'
,
"\n\nA\n1",
"A\n1",
],
'diff last line II - no trailing linebreak non_patch_compat' => [
'--- Original
+++ New
@@ -5,4 +5,4 @@
' . '
' . '
' . '
-E
+B
',
"A\n\n\n\n\n\n\nE",
"A\n\n\n\n\n\n\nB",
],
[
"--- Original\n+++ New\n@@ -1,2 +1 @@\n \n-\n",
"\n\n",
"\n",
],
'diff line endings non_patch_compat' => [
"--- Original\n+++ New\n@@ -1 +1 @@\n #Warning: Strings contain different line endings!\n-<?php\r\n+<?php\n",
"<?php\r\n",
"<?php\n",
],
'same non_patch_compat' => [
'--- Original
+++ New
',
"AT\n",
"AT\n",
],
[
'--- Original
+++ New
@@ -1,4 +1,4 @@
-b
+a
' . '
' . '
' . '
',
"b\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
"a\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
],
'diff line @1' => [
'--- Original
+++ New
@@ -1,2 +1,2 @@
' . '
-AG
+B
',
"\nAG\n",
"\nB\n",
],
'same multiple lines' => [
'--- Original
+++ New
@@ -1,4 +1,4 @@
' . '
' . '
-V
+B
C213
',
"\n\nV\nC213",
"\n\nB\nC213",
],
'diff last line I' => [
'--- Original
+++ New
@@ -5,4 +5,4 @@
' . '
' . '
' . '
-E
+B
',
"A\n\n\n\n\n\n\nE\n",
"A\n\n\n\n\n\n\nB\n",
],
'diff line middle' => [
'--- Original
+++ New
@@ -5,7 +5,7 @@
' . '
' . '
' . '
-X
+Z
' . '
' . '
' . '
',
"A\n\n\n\n\n\n\nX\n\n\n\n\n\n\nAY",
"A\n\n\n\n\n\n\nZ\n\n\n\n\n\n\nAY",
],
'diff last line III' => [
'--- Original
+++ New
@@ -12,4 +12,4 @@
' . '
' . '
' . '
-A
+B
',
"A\n\n\n\n\n\n\nA\n\n\n\n\n\n\nA\n",
"A\n\n\n\n\n\n\nA\n\n\n\n\n\n\nB\n",
],
[
'--- Original
+++ New
@@ -1,8 +1,8 @@
A
-B
+B1
D
E
EE
F
-G
+G1
H
',
"A\nB\nD\nE\nEE\nF\nG\nH",
"A\nB1\nD\nE\nEE\nF\nG1\nH",
],
[
'--- Original
+++ New
@@ -1,4 +1,5 @@
Z
+
a
b
c
@@ -7,5 +8,5 @@
f
g
h
-i
+x
j
',
'Z
a
b
c
d
e
f
g
h
i
j
',
'Z
a
b
c
d
e
f
g
h
x
j
',
],
[
'--- Original
+++ New
@@ -1,7 +1,5 @@
-
-a
+b
A
-X
-
+Y
' . '
A
',
"\na\nA\nX\n\n\nA\n",
"b\nA\nY\n\nA\n",
],
[
<<<EOF
--- Original
+++ New
@@ -1,7 +1,5 @@
-
-
a
-b
+p
c
d
e
@@ -9,5 +7,5 @@
g
h
i
-j
+w
k
EOF
,
"\n\na\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\n",
"a\np\nc\nd\ne\nf\ng\nh\ni\nw\nk\n",
],
[
'--- Original
+++ New
@@ -8,7 +8,7 @@
' . '
' . '
' . '
-A
+C
' . '
' . '
' . '
',
"E\n\n\n\n\nB\n\n\n\n\nA\n\n\n\n\n\n\n\n\nD1",
"E\n\n\n\n\nB\n\n\n\n\nC\n\n\n\n\n\n\n\n\nD1",
],
[
'--- Original
+++ New
@@ -5,7 +5,7 @@
' . '
' . '
' . '
-Z
+U
' . '
' . '
' . '
@@ -12,7 +12,7 @@
' . '
' . '
' . '
-X
+V
' . '
' . '
' . '
@@ -19,7 +19,7 @@
' . '
' . '
' . '
-Y
+W
' . '
' . '
' . '
@@ -26,7 +26,7 @@
' . '
' . '
' . '
-W
+X
' . '
' . '
' . '
@@ -33,7 +33,7 @@
' . '
' . '
' . '
-V
+Y
' . '
' . '
' . '
@@ -40,4 +40,4 @@
' . '
' . '
' . '
-U
+Z
',
"\n\n\n\n\n\n\nZ\n\n\n\n\n\n\nX\n\n\n\n\n\n\nY\n\n\n\n\n\n\nW\n\n\n\n\n\n\nV\n\n\n\n\n\n\nU\n",
"\n\n\n\n\n\n\nU\n\n\n\n\n\n\nV\n\n\n\n\n\n\nW\n\n\n\n\n\n\nX\n\n\n\n\n\n\nY\n\n\n\n\n\n\nZ\n",
],
[
<<<EOF
--- Original
+++ New
@@ -1,5 +1,5 @@
a
-b
+p
c
d
e
@@ -7,5 +7,5 @@
g
h
i
-j
+w
k
EOF
,
"a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\n",
"a\np\nc\nd\ne\nf\ng\nh\ni\nw\nk\n",
],
[
<<<EOF
--- Original
+++ New
@@ -1,4 +1,4 @@
-A
+B
1
2
3
EOF
,
"A\n1\n2\n3\n4\n5\n6\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1",
"B\n1\n2\n3\n4\n5\n6\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1",
],
[
"--- Original\n+++ New\n@@ -4,7 +4,7 @@\n D\n E\n F\n-X\n+Y\n G\n H\n I\n",
"A\nB\nC\nD\nE\nF\nX\nG\nH\nI\nJ\nK\nL\nM\n",
"A\nB\nC\nD\nE\nF\nY\nG\nH\nI\nJ\nK\nL\nM\n",
],
];
}
}
......@@ -39,7 +39,7 @@ final class UnifiedDiffOutputBuilderTest extends TestCase
);
}
public function headerProvider()
public function headerProvider(): array
{
return [
[
......@@ -83,297 +83,6 @@ final class UnifiedDiffOutputBuilderTest extends TestCase
public function provideDiffWithLineNumbers(): array
{
return [
'diff line 1 non_patch_compat' => [
'--- Original
+++ New
@@ -1 +1 @@
-AA
+BA
',
'AA',
'BA',
],
'diff line +1 non_patch_compat' => [
'--- Original
+++ New
@@ -1 +1,2 @@
-AZ
+
+B
',
'AZ',
"\nB",
],
'diff line -1 non_patch_compat' => [
'--- Original
+++ New
@@ -1,2 +1 @@
-
-AF
+B
',
"\nAF",
'B',
],
'II non_patch_compat' => [
'--- Original
+++ New
@@ -1,2 +1,0 @@
-
-
'
,
"\n\nA\n1",
"A\n1",
],
'diff last line II - no trailing linebreak non_patch_compat' => [
'--- Original
+++ New
@@ -8 +8 @@
-E
+B
',
"A\n\n\n\n\n\n\nE",
"A\n\n\n\n\n\n\nB",
],
[
"--- Original\n+++ New\n@@ -1,2 +1 @@\n \n-\n",
"\n\n",
"\n",
],
'diff line endings non_patch_compat' => [
"--- Original\n+++ New\n@@ -1 +1 @@\n #Warning: Strings contain different line endings!\n-<?php\r\n+<?php\n",
"<?php\r\n",
"<?php\n",
],
'same non_patch_compat' => [
'--- Original
+++ New
',
"AT\n",
"AT\n",
],
[
'--- Original
+++ New
@@ -1 +1 @@
-b
+a
',
"b\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
"a\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
],
'diff line @1' => [
'--- Original
+++ New
@@ -1,2 +1,2 @@
' . '
-AG
+B
',
"\nAG\n",
"\nB\n",
],
'same multiple lines' => [
'--- Original
+++ New
@@ -1,3 +1,3 @@
' . '
' . '
-V
+B
'
,
"\n\nV\nC213",
"\n\nB\nC213",
],
'diff last line I' => [
'--- Original
+++ New
@@ -8 +8 @@
-E
+B
',
"A\n\n\n\n\n\n\nE\n",
"A\n\n\n\n\n\n\nB\n",
],
'diff line middle' => [
'--- Original
+++ New
@@ -8 +8 @@
-X
+Z
',
"A\n\n\n\n\n\n\nX\n\n\n\n\n\n\nAY",
"A\n\n\n\n\n\n\nZ\n\n\n\n\n\n\nAY",
],
'diff last line III' => [
'--- Original
+++ New
@@ -15 +15 @@
-A
+B
',
"A\n\n\n\n\n\n\nA\n\n\n\n\n\n\nA\n",
"A\n\n\n\n\n\n\nA\n\n\n\n\n\n\nB\n",
],
[
'--- Original
+++ New
@@ -1,7 +1,7 @@
A
-B
+B1
D
E
EE
F
-G
+G1
',
"A\nB\nD\nE\nEE\nF\nG\nH",
"A\nB1\nD\nE\nEE\nF\nG1\nH",
],
[
'--- Original
+++ New
@@ -1 +1,2 @@
Z
+
@@ -10 +11 @@
-i
+x
',
'Z
a
b
c
d
e
f
g
h
i
j',
'Z
a
b
c
d
e
f
g
h
x
j',
],
[
'--- Original
+++ New
@@ -1,5 +1,3 @@
-
-a
+b
A
-a
-
+b
',
"\na\nA\na\n\n\nA",
"b\nA\nb\n\nA",
],
[
<<<EOF
--- Original
+++ New
@@ -1,4 +1,2 @@
-
-
a
-b
+p
@@ -12 +10 @@
-j
+w
EOF
,
"\n\na\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk",
"a\np\nc\nd\ne\nf\ng\nh\ni\nw\nk",
],
[
'--- Original
+++ New
@@ -11 +11 @@
-A
+C
',
"E\n\n\n\n\nB\n\n\n\n\nA\n\n\n\n\n\n\n\n\nD1",
"E\n\n\n\n\nB\n\n\n\n\nC\n\n\n\n\n\n\n\n\nD1",
],
[
'--- Original
+++ New
@@ -8 +8 @@
-Z
+U
@@ -15 +15 @@
-X
+V
@@ -22 +22 @@
-Y
+W
@@ -29 +29 @@
-W
+X
@@ -36 +36 @@
-V
+Y
@@ -43 +43 @@
-U
+Z
',
"\n\n\n\n\n\n\nZ\n\n\n\n\n\n\nX\n\n\n\n\n\n\nY\n\n\n\n\n\n\nW\n\n\n\n\n\n\nV\n\n\n\n\n\n\nU\n",
"\n\n\n\n\n\n\nU\n\n\n\n\n\n\nV\n\n\n\n\n\n\nW\n\n\n\n\n\n\nX\n\n\n\n\n\n\nY\n\n\n\n\n\n\nZ\n",
],
[
<<<EOF
--- Original
+++ New
@@ -1,2 +1,2 @@
a
-b
+p
@@ -10 +10 @@
-j
+w
EOF
,
"a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk",
"a\np\nc\nd\ne\nf\ng\nh\ni\nw\nk",
],
[
<<<EOF
--- Original
+++ New
@@ -1 +1 @@
-A
+B
EOF
,
"A\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1",
"B\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1",
],
[
"--- Original\n+++ New\n@@ -7 +7 @@\n-X\n+B\n",
"A\nA\nA\nA\nA\nA\nX\nC\nC\nC\nC\nC\nC",
"A\nA\nA\nA\nA\nA\nB\nC\nC\nC\nC\nC\nC",
],
];
return UnifiedDiffOutputBuilderDataProvider::provideDiffWithLineNumbers();
}
}
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Utils;
/**
* @author SpacePossum
*
* @internal
*/
trait UnifiedDiffAssertTrait
{
/**
* @param string $diff
*
* @throws \UnexpectedValueException
*/
public function assertValidUnifiedDiffFormat(string $diff)
{
if ('' === $diff) {
$this->addToAssertionCount(1);
return;
}
// test diff ends with a line break
$last = \substr($diff, -1);
if ("\n" !== $last && "\r" !== $last) {
throw new \UnexpectedValueException(\sprintf('Expected diff to end with a line break, got "%s".', $last));
}
$lines = \preg_split('/(.*\R)/', $diff, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$lineCount = \count($lines);
$lineNumber = $diffLineFromNumber = $diffLineToNumber = 1;
$fromStart = $fromTillOffset = $toStart = $toTillOffset = -1;
$expectHunkHeader = true;
// check for header
if ($lineCount > 1) {
$this->unifiedDiffAssertLinePrefix($lines[0], 'Line 1.');
$this->unifiedDiffAssertLinePrefix($lines[1], 'Line 2.');
if ('---' === \substr($lines[0], 0, 3)) {
if ('+++' !== \substr($lines[1], 0, 3)) {
throw new \UnexpectedValueException(\sprintf("Line 1 indicates a header, so line 2 must start with \"+++\".\nLine 1: \"%s\"\nLine 2: \"%s\".", $lines[0], $lines[1]));
}
$this->unifiedDiffAssertHeaderLine($lines[0], '--- ', 'Line 1.');
$this->unifiedDiffAssertHeaderLine($lines[1], '+++ ', 'Line 2.');
$lineNumber = 3;
}
}
$endOfLineTypes = [];
$diffClosed = false;
// assert format of lines, get all hunks, test the line numbers
for (; $lineNumber <= $lineCount; ++$lineNumber) {
if ($diffClosed) {
throw new \UnexpectedValueException(\sprintf('Unexpected line as 2 "No newline" markers have found, ". Line %d.', $lineNumber));
}
$line = $lines[$lineNumber - 1]; // line numbers start by 1, array index at 0
$type = $this->unifiedDiffAssertLinePrefix($line, \sprintf('Line %d.', $lineNumber));
if ($expectHunkHeader && '@' !== $type && '\\' !== $type) {
throw new \UnexpectedValueException(\sprintf('Expected hunk start (\'@\'), got "%s". Line %d.', $type, $lineNumber));
}
if ('@' === $type) {
if (!$expectHunkHeader) {
throw new \UnexpectedValueException(\sprintf('Unexpected hunk start (\'@\'). Line %d.', $lineNumber));
}
$previousHunkFromEnd = $fromStart + $fromTillOffset;
$previousHunkTillEnd = $toStart + $toTillOffset;
list($fromStart, $fromTillOffset, $toStart, $toTillOffset) = $this->unifiedDiffAssertHunkHeader($line, \sprintf('Line %d.', $lineNumber));
// detect overlapping hunks
if ($fromStart < $previousHunkFromEnd) {
throw new \UnexpectedValueException(\sprintf('Unexpected new hunk; "from" (\'-\') start overlaps previous hunk. Line %d.', $lineNumber));
}
if ($toStart < $previousHunkTillEnd) {
throw new \UnexpectedValueException(\sprintf('Unexpected new hunk; "to" (\'+\') start overlaps previous hunk. Line %d.', $lineNumber));
}
/* valid states; hunks touches against each other:
$fromStart === $previousHunkFromEnd
$toStart === $previousHunkTillEnd
*/
$diffLineFromNumber = $fromStart;
$diffLineToNumber = $toStart;
$expectHunkHeader = false;
continue;
}
if ('-' === $type) {
if (isset($endOfLineTypes['-'])) {
throw new \UnexpectedValueException(\sprintf('Not expected from (\'-\'), already closed by "\\ No newline at end of file". Line %d.', $lineNumber));
}
++$diffLineFromNumber;
} elseif ('+' === $type) {
if (isset($endOfLineTypes['+'])) {
throw new \UnexpectedValueException(\sprintf('Not expected to (\'+\'), already closed by "\\ No newline at end of file". Line %d.', $lineNumber));
}
++$diffLineToNumber;
} elseif (' ' === $type) {
if (isset($endOfLineTypes['-'])) {
throw new \UnexpectedValueException(\sprintf('Not expected same (\' \'), \'-\' already closed by "\\ No newline at end of file". Line %d.', $lineNumber));
}
if (isset($endOfLineTypes['+'])) {
throw new \UnexpectedValueException(\sprintf('Not expected same (\' \'), \'+\' already closed by "\\ No newline at end of file". Line %d.', $lineNumber));
}
++$diffLineFromNumber;
++$diffLineToNumber;
} elseif ('\\' === $type) {
if (!isset($lines[$lineNumber - 2])) {
throw new \UnexpectedValueException(\sprintf('Unexpected "\\ No newline at end of file", it must be preceded by \'+\' or \'-\' line. Line %d.', $lineNumber));
}
$previousType = $this->unifiedDiffAssertLinePrefix($lines[$lineNumber - 2], \sprintf('Preceding line of "\\ No newline at end of file" of unexpected format. Line %d.', $lineNumber));
if (isset($endOfLineTypes[$previousType])) {
throw new \UnexpectedValueException(\sprintf('Unexpected "\\ No newline at end of file", "%s" was already closed. Line %d.', $type, $lineNumber));
}
$endOfLineTypes[$previousType] = true;
$diffClosed = \count($endOfLineTypes) > 1;
} else {
// internal state error
throw new \RuntimeException(\sprintf('Unexpected line type "%s" Line %d.', $type, $lineNumber));
}
$expectHunkHeader =
$diffLineFromNumber === ($fromStart + $fromTillOffset)
&& $diffLineToNumber === ($toStart + $toTillOffset)
;
}
if (
$diffLineFromNumber !== ($fromStart + $fromTillOffset)
&& $diffLineToNumber !== ($toStart + $toTillOffset)
) {
throw new \UnexpectedValueException(\sprintf('Unexpected EOF, number of lines in hunk "from" (\'-\')) and "to" (\'+\') mismatched. Line %d.', $lineNumber));
}
if ($diffLineFromNumber !== ($fromStart + $fromTillOffset)) {
throw new \UnexpectedValueException(\sprintf('Unexpected EOF, number of lines in hunk "from" (\'-\')) mismatched. Line %d.', $lineNumber));
}
if ($diffLineToNumber !== ($toStart + $toTillOffset)) {
throw new \UnexpectedValueException(\sprintf('Unexpected EOF, number of lines in hunk "to" (\'+\')) mismatched. Line %d.', $lineNumber));
}
$this->addToAssertionCount(1);
}
/**
* @param string $line
* @param string $message
*
* @return string '+', '-', '@', ' ' or '\'
*/
private function unifiedDiffAssertLinePrefix(string $line, string $message): string
{
$this->unifiedDiffAssertStrLength($line, 2, $message); // 2: line type indicator ('+', '-', ' ' or '\') and a line break
$firstChar = $line[0];
if ('+' === $firstChar || '-' === $firstChar || '@' === $firstChar || ' ' === $firstChar) {
return $firstChar;
}
if ("\\ No newline at end of file\n" === $line) {
return '\\';
}
throw new \UnexpectedValueException(\sprintf('Expected line to start with \'@\', \'-\' or \'+\', got "%s". %s', $line, $message));
}
private function unifiedDiffAssertStrLength(string $line, int $min, string $message)
{
$length = \strlen($line);
if ($length < $min) {
throw new \UnexpectedValueException(\sprintf('Expected string length of minimal %d, got %d. %s', $min, $length, $message));
}
}
/**
* Assert valid unified diff header line
*
* Samples:
* - "+++ from1.txt\t2017-08-24 19:51:29.383985722 +0200"
* - "+++ from1.txt"
*
* @param string $line
* @param string $start
* @param string $message
*/
private function unifiedDiffAssertHeaderLine(string $line, string $start, string $message)
{
if (0 !== \strpos($line, $start)) {
throw new \UnexpectedValueException(\sprintf('Expected header line to start with "%s", got "%s". %s', $start . ' ', $line, $message));
}
// sample "+++ from1.txt\t2017-08-24 19:51:29.383985722 +0200\n"
$match = \preg_match(
"/^([^\t]*)(?:[\t]([\\S].*[\\S]))?\n$/",
\substr($line, 4), // 4 === string length of "+++ " / "--- "
$matches
);
if (1 !== $match) {
throw new \UnexpectedValueException(\sprintf('Header line does not match expected pattern, got "%s". %s', $line, $message));
}
// $file = $matches[1];
if (\count($matches) > 2) {
$this->unifiedDiffAssertHeaderDate($matches[2], $message);
}
}
private function unifiedDiffAssertHeaderDate(string $date, string $message)
{
// sample "2017-08-24 19:51:29.383985722 +0200"
$match = \preg_match(
'/^([\d]{4})-([01]?[\d])-([0123]?[\d])(:? [\d]{1,2}:[\d]{1,2}(?::[\d]{1,2}(:?\.[\d]+)?)?(?: ([\+\-][\d]{4}))?)?$/',
$date,
$matches
);
if (1 !== $match || ($matchesCount = \count($matches)) < 4) {
throw new \UnexpectedValueException(\sprintf('Date of header line does not match expected pattern, got "%s". %s', $date, $message));
}
// [$full, $year, $month, $day, $time] = $matches;
}
/**
* @param string $line
* @param string $message
*
* @return int[]
*/
private function unifiedDiffAssertHunkHeader(string $line, string $message): array
{
if (1 !== \preg_match('#^@@ -([\d]+)((?:,[\d]+)?) \+([\d]+)((?:,[\d]+)?) @@\n$#', $line, $matches)) {
throw new \UnexpectedValueException(
\sprintf(
'Hunk header line does not match expected pattern, got "%s". %s',
$line,
$message
)
);
}
return [
(int) $matches[1],
empty($matches[2]) ? 1 : (int) \substr($matches[2], 1),
(int) $matches[3],
empty($matches[4]) ? 1 : (int) \substr($matches[4], 1),
];
}
}
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Utils;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Process\Process;
/**
* @author SpacePossum
*
* @requires OS Linux
*
* @coversNothing
*
* @internal
*/
final class UnifiedDiffAssertTraitIntegrationTest extends TestCase
{
use UnifiedDiffAssertTrait;
private $filePatch;
protected function setUp()
{
$this->filePatch = __DIR__ . '/../fixtures/out/patch.txt';
$this->cleanUpTempFiles();
}
/**
* @param string $fileFrom
* @param string $fileTo
*
* @dataProvider provideFilePairsCases
*/
public function testValidPatches(string $fileFrom, string $fileTo)
{
$command = \sprintf(
'diff -u %s %s > %s',
\escapeshellarg(\realpath($fileFrom)),
\escapeshellarg(\realpath($fileTo)),
\escapeshellarg($this->filePatch)
);
$p = new Process($command);
$p->run();
$exitCode = $p->getExitCode();
if (0 === $exitCode) {
// odd case when two files have the same content. Test after executing as it is more efficient than to read the files and check the contents every time.
$this->addToAssertionCount(1);
return;
}
$this->assertSame(
1, // means `diff` found a diff between the files we gave it
$exitCode,
\sprintf(
"Command exec. was not successful:\n\"%s\"\nOutput:\n\"%s\"\nStdErr:\n\"%s\"\nExit code %d.\n",
$command,
$p->getOutput(),
$p->getErrorOutput(),
$p->getExitCode()
)
);
$this->assertValidUnifiedDiffFormat(\file_get_contents($this->filePatch));
}
/**
* @return array<string, array<string, string>>
*/
public function provideFilePairsCases(): array
{
$cases = [];
// created cases based on dedicated fixtures
$dir = \realpath(__DIR__ . '/../fixtures/UnifiedDiffAssertTraitIntegrationTest');
$dirLength = \strlen($dir);
for ($i = 1;; ++$i) {
$fromFile = \sprintf('%s/%d_a.txt', $dir, $i);
$toFile = \sprintf('%s/%d_b.txt', $dir, $i);
if (!\file_exists($fromFile)) {
break;
}
$this->assertFileExists($toFile);
$cases[\sprintf("Diff file:\n\"%s\"\nvs.\n\"%s\"\n", \substr(\realpath($fromFile), $dirLength), \substr(\realpath($toFile), $dirLength))] = [$fromFile, $toFile];
}
// create cases based on PHP files within the vendor directory for integration testing
$dir = \realpath(__DIR__ . '/../../vendor');
$dirLength = \strlen($dir);
$fileIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS));
$fromFile = __FILE__;
/** @var \SplFileInfo $file */
foreach ($fileIterator as $file) {
if ('php' !== $file->getExtension()) {
continue;
}
$toFile = $file->getPathname();
$cases[\sprintf("Diff file:\n\"%s\"\nvs.\n\"%s\"\n", \substr(\realpath($fromFile), $dirLength), \substr(\realpath($toFile), $dirLength))] = [$fromFile, $toFile];
$fromFile = $toFile;
}
return $cases;
}
protected function tearDown()
{
$this->cleanUpTempFiles();
}
private function cleanUpTempFiles()
{
@\unlink($this->filePatch);
}
}
<?php declare(strict_types=1);
/*
* This file is part of sebastian/diff.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\Diff\Utils;
use PHPUnit\Framework\TestCase;
/**
* @author SpacePossum
*
* @covers SebastianBergmann\Diff\UnifiedDiffAssertTrait
*
* @internal
*/
final class UnifiedDiffAssertTraitTest extends TestCase
{
use UnifiedDiffAssertTrait;
/**
* @param string $diff
*
* @dataProvider provideValidCases
*/
public function testValidCases(string $diff)
{
$this->assertValidUnifiedDiffFormat($diff);
}
public function provideValidCases(): array
{
return [
[
'--- Original
+++ New
@@ -8 +8 @@
-Z
+U
',
],
[
'--- Original
+++ New
@@ -8 +8 @@
-Z
+U
@@ -15 +15 @@
-X
+V
',
],
'empty diff. is valid' => [
'',
],
];
}
public function testNoLinebreakEnd()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Expected diff to end with a line break, got "C".', '#')));
$this->assertValidUnifiedDiffFormat("A\nB\nC");
}
public function testInvalidStartWithoutHeader()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Expected line to start with '@', '-' or '+', got \"A\n\". Line 1.", '#')));
$this->assertValidUnifiedDiffFormat("A\n");
}
public function testInvalidStartHeader1()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Line 1 indicates a header, so line 2 must start with \"+++\".\nLine 1: \"--- A\n\"\nLine 2: \"+ 1\n\".", '#')));
$this->assertValidUnifiedDiffFormat("--- A\n+ 1\n");
}
public function testInvalidStartHeader2()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Header line does not match expected pattern, got \"+++ file X\n\". Line 2.", '#')));
$this->assertValidUnifiedDiffFormat("--- A\n+++ file\tX\n");
}
public function testInvalidStartHeader3()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Date of header line does not match expected pattern, got "[invalid date]". Line 1.', '#')));
$this->assertValidUnifiedDiffFormat(
"--- Original\t[invalid date]
+++ New
@@ -1,2 +1,2 @@
-A
+B
" . '
');
}
public function testInvalidStartHeader4()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Expected header line to start with \"+++ \", got \"+++INVALID\n\". Line 2.", '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++INVALID
@@ -1,2 +1,2 @@
-A
+B
' . '
');
}
public function testInvalidLine1()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Expected line to start with '@', '-' or '+', got \"1\n\". Line 5.", '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8 +8 @@
-Z
1
+U
');
}
public function testInvalidLine2()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Expected string length of minimal 2, got 1. Line 4.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8 +8 @@
');
}
public function testHunkInvalidFormat()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote("Hunk header line does not match expected pattern, got \"@@ INVALID -1,1 +1,1 @@\n\". Line 3.", '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ INVALID -1,1 +1,1 @@
-Z
+U
');
}
public function testHunkOverlapFrom()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected new hunk; "from" (\'-\') start overlaps previous hunk. Line 6.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,1 +8,1 @@
-Z
+U
@@ -7,1 +9,1 @@
-Z
+U
');
}
public function testHunkOverlapTo()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected new hunk; "to" (\'+\') start overlaps previous hunk. Line 6.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,1 +8,1 @@
-Z
+U
@@ -17,1 +7,1 @@
-Z
+U
');
}
public function testExpectHunk1()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Expected hunk start (\'@\'), got "+". Line 6.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8 +8 @@
-Z
+U
+O
');
}
public function testExpectHunk2()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected hunk start (\'@\'). Line 6.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,12 +8,12 @@
' . '
' . '
@@ -38,12 +48,12 @@
');
}
public function testMisplacedLineAfterComments1()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected line as 2 "No newline" markers have found, ". Line 8.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8 +8 @@
-Z
\ No newline at end of file
+U
\ No newline at end of file
+A
');
}
public function testMisplacedLineAfterComments2()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected line as 2 "No newline" markers have found, ". Line 7.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8 +8 @@
+U
\ No newline at end of file
\ No newline at end of file
\ No newline at end of file
');
}
public function testMisplacedLineAfterComments3()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected line as 2 "No newline" markers have found, ". Line 7.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8 +8 @@
+U
\ No newline at end of file
\ No newline at end of file
+A
');
}
public function testMisplacedComment()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected "\ No newline at end of file", it must be preceded by \'+\' or \'-\' line. Line 1.', '#')));
$this->assertValidUnifiedDiffFormat(
'\ No newline at end of file
');
}
public function testUnexpectedDuplicateNoNewLineEOF()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected "\\ No newline at end of file", "\\" was already closed. Line 8.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,12 +8,12 @@
' . '
' . '
\ No newline at end of file
' . '
\ No newline at end of file
');
}
public function testFromAfterClose()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Not expected from (\'-\'), already closed by "\ No newline at end of file". Line 6.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,12 +8,12 @@
-A
\ No newline at end of file
-A
\ No newline at end of file
');
}
public function testSameAfterFromClose()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Not expected same (\' \'), \'-\' already closed by "\ No newline at end of file". Line 6.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,12 +8,12 @@
-A
\ No newline at end of file
A
\ No newline at end of file
');
}
public function testToAfterClose()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Not expected to (\'+\'), already closed by "\ No newline at end of file". Line 6.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,12 +8,12 @@
+A
\ No newline at end of file
+A
\ No newline at end of file
');
}
public function testSameAfterToClose()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Not expected same (\' \'), \'+\' already closed by "\ No newline at end of file". Line 6.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,12 +8,12 @@
+A
\ No newline at end of file
A
\ No newline at end of file
');
}
public function testUnexpectedEOFFromMissingLines()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected EOF, number of lines in hunk "from" (\'-\')) mismatched. Line 7.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,19 +7,2 @@
-A
+B
' . '
');
}
public function testUnexpectedEOFToMissingLines()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected EOF, number of lines in hunk "to" (\'+\')) mismatched. Line 7.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -8,2 +7,3 @@
-A
+B
' . '
');
}
public function testUnexpectedEOFBothFromAndToMissingLines()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp(\sprintf('#^%s$#', \preg_quote('Unexpected EOF, number of lines in hunk "from" (\'-\')) and "to" (\'+\') mismatched. Line 7.', '#')));
$this->assertValidUnifiedDiffFormat(
'--- Original
+++ New
@@ -1,12 +1,14 @@
-A
+B
' . '
');
}
}
root = true
a
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment