public function testCreate() { $before = <<<'EOD' unchanged replaced unchanged removed EOD; $after = <<<'EOD' added unchanged replacement unchanged EOD; $diff = [['added', 1], ['unchanged', 0], ['replaced', 2], ['replacement', 1], ['unchanged', 0], ['removed', 2]]; $lines = [new Line(Line::ADDED, 'added', -1), new Line(Line::UNCHANGED, 'unchanged', 0), new Line(Line::REMOVED, 'replaced', 1), new Line(Line::ADDED, 'replacement', 1), new Line(Line::UNCHANGED, 'unchanged', 2), new Line(Line::REMOVED, 'removed', 3)]; $differ = new Differ(); $array_diff = $differ->diffToArray($before, $after); $this->assertEquals($diff, $array_diff); $result = Line::createArray($diff); $this->assertEquals($lines, $result); try { $diff[] = ['invalid', 3]; Line::createArray($diff); $this->assertTrue(false, 'An exception was not thrown'); } catch (\RuntimeException $e) { $this->assertEquals('Unsupported diff line type.', $e->getMessage()); } }
public function difObj($obj1, $obj2) { $differ = new Differ(); $arr = []; foreach ($obj1 as $a => $v) { if ($v != $obj2[$a]) { if (is_numeric($v) && is_numeric($obj2[$a])) { $arr[$a] = $v; } else { /* if (substr_count( $v, "\n" ) > 1 && substr_count( $obj2[$a], "\n" ) > 1) { $arr[$a] = $differ->diff($v,$obj2[$a]); } else { $arr[$a] = $differ->diff(self::strLine($v),self::strLine($obj2[$a])); } */ $arr[$a] = $differ->diff($v, $obj2[$a]); } } } return $arr; }
protected function execute(array $arguments) { if (isset($arguments[0]) && isset($arguments[1])) { $differ = new Differ(); return $differ->diff($arguments[0], $arguments[1]); } throw new InvalidArgumentException('strings invalid'); }
/** * @param string $expected * @param string $actual * @return string */ private function getDiff($expected = '', $actual = '') { if (!$actual && !$expected) { return ''; } $differ = new Differ(''); return $differ->diff($expected, $actual); }
/** * @inheritdoc */ public function diffTemplate(Stack $stack) { $actual_template = $stack->provisioned ? $this->cfn($stack)->getTemplate(['StackName' => $stack->get('name')])->get('TemplateBody') : '{}'; $new_template = $this->createTemplate($stack); $arr_diff = new Differ(); $diff = $arr_diff->diff(json_encode(json_decode($actual_template, true), JSON_PRETTY_PRINT), json_encode(json_decode($new_template, true), JSON_PRETTY_PRINT)); return $diff; }
/** * Get difference of two variables. * * @param mixed $actual * * @return string */ protected function getDiff($actual) { if (is_array($actual) or is_array($this->expected)) { $diff = new Diff\Differ('--- Expected' . PHP_EOL . '+++ Actual' . PHP_EOL); return $diff->diff(var_export($this->expected, true), var_export($actual, true)); } else { return 'expected ' . $this->formatter($this->expected) . ', but given ' . $this->formatter($actual); } }
private function diffFiles($path, $from, $to) { if (!$this->compareFiles($from, $to)) { $differ = new Differ(); $this->filesystem->put($path, $differ->diff($from, $to)); $this->diffedFiles[] = $path; } else { $this->filesystem->put($path, $to); } }
/** * {@inheritdoc} */ public function diff($old, $new) { return implode(PHP_EOL, array_map(function ($string) { $string = preg_replace('/^(\\+){3}/', '<info>+++</info>', $string); $string = preg_replace('/^(\\+){1}/', '<info>+</info>', $string); $string = preg_replace('/^(\\-){3}/', '<error>---</error>', $string); $string = preg_replace('/^(\\-){1}/', '<error>-</error>', $string); return $string; }, explode(PHP_EOL, $this->differ->diff($old, $new)))); }
public function diff($t1, $t2) { $t1 = str_replace(['<dd>', '</dd>'], [PHP_EOL, ''], $t1); $t2 = str_replace(['<dd>', '</dd>'], [PHP_EOL, ''], $t2); $differ = new Differ(); $diffs = $differ->diffToArray($t1, $t2); $folders = [new ContextFolder(), new ReplacesFolder(), new TypeFolder(PHP_EOL), new DiffFolder()]; foreach ($folders as $folder) { $diffs = $folder->fold($diffs); } return $diffs; }
/** * Returns the diff between two arrays or strings as string. * * @param array|string $from * @param array|string $to * @param int $contextLines * * @return string */ public function difference($from, $to, $contextLines = 3) { $tool = new Differ(''); $diff = $tool->diffToArray($from, $to); $inOld = false; $i = 0; $old = array(); foreach ($diff as $line) { if ($line[1] === 0) { if ($inOld === false) { $inOld = $i; } } else { if ($inOld !== false) { if ($i - $inOld > $contextLines) { $old[$inOld] = $i - 1; } $inOld = false; } } ++$i; } $start = isset($old[0]) ? $old[0] : 0; $end = count($diff); if ($tmp = array_search($end, $old)) { $end = $tmp; } $contextLinesCounter = 0; $contextPreSet = false; $buffer = $this->initBuffer(); for ($i = $start; $i < $end; $i++) { if (isset($old[$i])) { $i = $old[$i]; } if ($diff[$i][1] === 1) { $buffer[] = $this->highlightAdded($diff[$i][0]); } else { if ($diff[$i][1] === 2) { $buffer[] = $this->highlightRemoved($diff[$i][0]); $contextPreSet = true; } else { if ($contextPreSet && $contextLinesCounter >= $contextLines) { break; } $buffer[] = $this->highlightContext($diff[$i][0]); ++$contextLinesCounter; } } } return $this->implodeBuffer($buffer); }
protected function additionalFailureDescription($other) { $from = preg_split('(\\r\\n|\\r|\\n)', $this->string); $to = preg_split('(\\r\\n|\\r|\\n)', $other); foreach ($from as $index => $line) { if (isset($to[$index]) && $line !== $to[$index]) { $line = $this->createPatternFromFormat($line); if (preg_match($line, $to[$index]) > 0) { $from[$index] = $to[$index]; } } } $this->string = implode("\n", $from); $other = implode("\n", $to); $differ = new Differ("--- Expected\n+++ Actual\n"); return $differ->diff($this->string, $other); }
/** * @inheritDoc */ public function merge($base, $remote, $local) { // Skip merging if there is nothing to do. if ($merged = PhpMergeBase::simpleMerge($base, $remote, $local)) { return $merged; } $remoteDiff = Line::createArray($this->differ->diffToArray($base, $remote)); $localDiff = Line::createArray($this->differ->diffToArray($base, $local)); $baseLines = Line::createArray(array_map(function ($l) { return [$l, 0]; }, explode("\n", $base))); $remoteHunks = Hunk::createArray($remoteDiff); $localHunks = Hunk::createArray($localDiff); $conflicts = []; $merged = PhpMerge::mergeHunks($baseLines, $remoteHunks, $localHunks, $conflicts); if ($conflicts) { throw new MergeException('A merge conflict has occured.', $conflicts, $merged); } return $merged; }
protected function stringDiff($old, $new) { $diff = $this->diff->diff($old, $new); $diff = implode(PHP_EOL, array_map(function ($string) { $string = preg_replace('/^(\\+){3}/', '<info>+++</info>', $string); $string = preg_replace('/^(\\+){1}/', '<info>+</info>', $string); $string = preg_replace('/^(\\-){3}/', '<error>---</error>', $string); $string = preg_replace('/^(\\-){1}/', '<error>-</error>', $string); $string = str_repeat(' ', 6) . $string; return $string; }, explode(PHP_EOL, $diff))); return $diff; }
/** * @see Command */ protected function execute(InputInterface $input, OutputInterface $output) { $files = $this->getResource($input); if (count($files) != 2) { throw new \InvalidArgumentException('You have to define 2 files.'); } $results = array(); foreach ($files as $file) { if ($file->isCrypted()) { $file = $this->getBackend($input->getOption('configuration-file'))->setIO($this->getIO())->decrypt($file); } } $it = $files->getIterator(); $output->writeln(sprintf('<info>Diff between <comment>%s</comment> and <comment>%s</comment></info>', $it[0]->getSourceFile(), $it[1]->getSourceFile())); $from = $this->clean($it[0]->isCrypted() ? $it[0]->getTargetContent() : $it[0]->getSourceContent()); $to = $this->clean($it[1]->isCrypted() ? $it[1]->getTargetContent() : $it[1]->getSourceContent()); if ($from == $to) { $output->writeln('no diff.'); } else { $differ = new Differ(); echo $differ->diff($from, $to); } }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $finder = (new Finder())->in($input->getArgument('input'))->exclude($input->getOption('exclude'))->name('*.php')->files(); $files = []; foreach ($finder as $file) { $files[] = $file->getRealpath(); } $project = ProjectFactory::createInstance()->create('current', $files); $converter = new Converter(); $output->writeln('<comment>Running the PHPDoc to Type Hint converter. Brought to you by Kévin Dunglas and Les-Tilleuls.coop.</comment>'); $output->writeln(''); $progress = new ProgressBar($output, count($files)); $changed = []; foreach ($project->getFiles() as $file) { $old = $file->getSource(); $new = $converter->convert($project, $file); if ($new !== $old) { if ($input->getOption('dry-run')) { $changed[] = ['path' => $file->getPath(), 'diff' => $this->differ->diff($old, $new)]; } else { file_put_contents($file->getPath(), $new); } } $progress->advance(); } $progress->finish(); $output->writeln(''); $output->writeln(''); foreach ($changed as $i => $file) { $output->writeln(sprintf('<fg=blue>%d) %s</>', $i + 1, $file['path'])); $output->writeln(''); $output->writeln($file['diff']); $output->writeln(''); } $output->writeln('<info>Conversion done.</info>'); }
public function getPrettyDiff() { $prettyDiff = []; $differ = new Differ(); $diffArr = $differ->diffToArray($this->fileChanges[0], $this->fileChanges[1]); $buffer = []; $lastMutation = false; foreach ($diffArr as $i => $diffToken) { if ($lastMutation !== false && $i - 3 === $lastMutation) { $prettyDiff = array_merge($prettyDiff, $buffer); $buffer = []; } if ($diffToken[1] !== 0) { $prettyDiff = array_merge($prettyDiff, $buffer); $buffer = []; $prettyDiff[] = $this->getPrettyMutation($diffToken); $lastMutation = $i; } else { $buffer[] = $this->getPrettyMutation($diffToken); } $buffer = array_slice($buffer, -3); } return implode("\n", $prettyDiff); }
public function foldReplaces() { $marker = chr(1); $marker2 = chr(2); $del = $this->foldChunks($this->delete, $marker); $ins = $this->foldChunks($this->insert, $marker); $replacer = function ($match) use($marker2) { return str_replace(' ', $marker2, $match[1]); }; $del = preg_replace_callback('#(<\\w+([^>]+)>)#i', $replacer, $del); $ins = preg_replace_callback('#(<\\w+([^>]+)>)#i', $replacer, $ins); $del = str_replace([' ', '><'], [PHP_EOL, '>' . PHP_EOL . '<'], $del); $ins = str_replace([' ', '><'], [PHP_EOL, '>' . PHP_EOL . '<'], $ins); $differ = new \SebastianBergmann\Diff\Differ(); $diffs = $differ->diffToArray($del, $ins); $folded = FolderChain::fold([new TypeFolder(' '), new ContextTypeRemover(), new DiffFolder(' ')], $diffs); $folded = str_replace($marker, PHP_EOL, $folded); $folded = str_replace($marker2, ' ', $folded); $this->chunk(3, $folded); $this->clearBuffer('delete'); $this->clearBuffer('insert'); }
/** * * @return string */ public function getDiff() { if (!$this->actualAsString && !$this->expectedAsString) { return ''; } $differ = new Differ("\n--- Expected\n+++ Actual\n"); return $differ->diff($this->expectedAsString, $this->actualAsString); }
/** * @Then the file :file should contain: */ public function theFileShouldContain($file, PyStringNode $contents) { $this->throwExceptionIfFalse(file_exists($file), sprintf('Expected file exist: %s', $file)); $writtenContent = preg_replace("/humbug-behat[0-9A-Za-z]+\\//", 'humbug-behatJ6Dj5I/', file_get_contents($file)); $this->throwExceptionIfFalse(trim($writtenContent) == trim((string) $contents), sprintf('Actual file content differs:%s%s', PHP_EOL, $this->differ->diff((string) $contents, $writtenContent))); }
/** * Get the conflicts from a file which is left with merge conflicts. * * @param string $file * The file name. * @param string $baseText * The original text used for merging. * @param string $remoteText * The first chaned text. * @param string $localText * The second changed text. * @param MergeConflict[] $conflicts * The merge conflicts will be apended to this array. * @param string[] $merged * The merged text resolving conflicts by using the first set of changes. */ protected static function getConflicts($file, $baseText, $remoteText, $localText, &$conflicts, &$merged) { $raw = new \ArrayObject(explode("\n", file_get_contents($file))); $lineIterator = $raw->getIterator(); $state = 'unchanged'; $conflictIndicator = ['<<<<<<< HEAD' => 'local', '||||||| merged common ancestors' => 'base', '=======' => 'remote', '>>>>>>> original' => 'end conflict']; // Create hunks from the text diff. $differ = new Differ(); $remoteDiff = Line::createArray($differ->diffToArray($baseText, $remoteText)); $localDiff = Line::createArray($differ->diffToArray($baseText, $localText)); $remote_hunks = new \ArrayObject(Hunk::createArray($remoteDiff)); $local_hunks = new \ArrayObject(Hunk::createArray($localDiff)); $remoteIterator = $remote_hunks->getIterator(); $localIterator = $local_hunks->getIterator(); $base = []; $remote = []; $local = []; $lineNumber = -1; $newLine = 0; $skipedLines = 0; $addingConflict = false; // Loop over all the lines in the file. while ($lineIterator->valid()) { $line = $lineIterator->current(); if (array_key_exists(trim($line), $conflictIndicator)) { // Check for a line matching a conflict indicator. $state = $conflictIndicator[trim($line)]; $skipedLines++; if ($state == 'end conflict') { // We just treated a merge conflict. $conflicts[] = new MergeConflict($base, $remote, $local, $lineNumber, $newLine); if ($lineNumber == -1) { $lineNumber = 0; } $lineNumber += count($base); $newLine += count($remote); $base = []; $remote = []; $local = []; $remoteIterator->next(); $localIterator->next(); if ($addingConflict) { // Advance the counter for conflicts with adding. $lineNumber++; $newLine++; $addingConflict = false; } $state = 'unchanged'; } } else { switch ($state) { case 'local': $local[] = $line; $skipedLines++; break; case 'base': $base[] = $line; $skipedLines++; if ($lineNumber == -1) { $lineNumber = 0; } break; case 'remote': $remote[] = $line; $merged[] = $line; break; case 'unchanged': if ($lineNumber == -1) { $lineNumber = 0; } $merged[] = $line; /** @var Hunk $r */ $r = $remoteIterator->current(); /** @var Hunk $l */ $l = $localIterator->current(); if ($r == $l) { // If they are the same, treat only one. $localIterator->next(); $l = $localIterator->current(); } // A hunk has been successfully merged, so we can just // tally the lines added and removed and skip forward. if ($r && $r->getStart() == $lineNumber) { if (!$r->hasIntersection($l)) { $lineNumber += count($r->getRemovedLines()); $newLine += count($r->getAddedLines()); $lineIterator->seek($newLine + $skipedLines - 1); $remoteIterator->next(); } else { // If the conflict occurs on added lines, the // next line in the merge will deal with it. if ($r->getType() == Hunk::ADDED && $l->getType() == Hunk::ADDED) { $addingConflict = true; } else { $lineNumber++; $newLine++; } } } elseif ($l && $l->getStart() == $lineNumber) { if (!$l->hasIntersection($r)) { $lineNumber += count($l->getRemovedLines()); $newLine += count($l->getAddedLines()); $lineIterator->seek($newLine + $skipedLines - 1); $localIterator->next(); } else { $lineNumber++; $newLine++; } } else { $lineNumber++; $newLine++; } break; } } $lineIterator->next(); } }
public function testTypesOtherThanArrayAndStringCanBePassed() { $this->assertEquals("--- Original\n+++ New\n@@ @@\n-1\n+2\n", $this->differ->diff(1, 2)); }
/** * @deprecated Will be removed in the 2.0 * * @param string $old * @param string $new * * @return string */ protected function stringDiff($old, $new) { return $this->diff->diff($old, $new); }
/** * Get diff. * * @return string */ public function diff() { return $this->differ->diff($this->wrappedObject->old_value, $this->wrappedObject->new_value); }
/** * {@inheritDoc} * * @throws \InvalidArgumentException * @throws \RuntimeException * @throws ParserException */ protected function execute(InputInterface $input, OutputInterface $output) { $align = $input->getOption('align') === Step::ALIGN_TO_LEFT ? Step::ALIGN_TO_LEFT : Step::ALIGN_TO_RIGHT; $directory = $input->getArgument('directory'); $finder = (new FeatureResolve($directory))->__invoke(); $output->writeln("\nFinding files on <info>" . $directory . "</info>\n"); $tagFormatter = new Tags(); $featureDescription = new FeatureDescription(); $background = new Background($align); $scenario = new Scenario($align); /* @var $file \Symfony\Component\Finder\SplFileInfo */ foreach ($finder as $file) { $fileContent = $file->getContents(); $contentWithoutComments = $this->removeComments($fileContent); $feature = $this->parser->parse($fileContent); $formatted = $feature->hasTags() ? $tagFormatter->format($feature->getTags()) . "\n" : ''; $formatted .= $featureDescription->format($feature) . "\n\n"; $formatted .= $feature->hasBackground() ? $background->format($feature->getBackground()) . "\n" : ''; $formatted .= $feature->hasScenarios() ? $scenario->format($feature->getScenarios()) : ''; if ($formatted !== $contentWithoutComments) { if (!defined('FAILED')) { define('FAILED', true); } $diff = new Differ("--- Original\n+++ Expected\n", false); $output->writeln('<error>Wrong style: ' . $file->getRealPath() . '</error>'); $output->writeln($diff->diff($contentWithoutComments, $formatted)); } } if (defined('FAILED')) { return 1; } $output->writeln('<bg=green;fg=white> Everything is OK! </>'); }
/** * @param $text */ public function __construct($old, $new) { $differ = new Differ(''); $this->diff = $differ->diff($old, $new); }
/** * {@inheritdoc} */ public function diff($old, $new) { return $this->differ->diff($old, $new); }
/** * @param array $before * @param array $after * @param string $header * @throws PHPUnit_Framework_RiskyTestError */ private function compareGlobalStateSnapshotPart(array $before, array $after, $header) { if ($before != $after) { $differ = new Differ($header); $exporter = new Exporter(); $diff = $differ->diff($exporter->export($before), $exporter->export($after)); throw new PHPUnit_Framework_RiskyTestError($diff); } }
/** * @covers SebastianBergmann\Diff\Differ::diff */ public function testCustomHeaderCanBeUsed() { $differ = new Differ('CUSTOM HEADER'); $this->assertEquals("CUSTOM HEADER@@ @@\n-a\n+b\n", $differ->diff('a', 'b')); }