菜谱项目

Parser.php 2.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. /*
  3. * This file is part of sebastian/diff.
  4. *
  5. * (c) Sebastian Bergmann <sebastian@phpunit.de>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace SebastianBergmann\Diff;
  11. /**
  12. * Unified diff parser.
  13. */
  14. class Parser
  15. {
  16. /**
  17. * @param string $string
  18. *
  19. * @return Diff[]
  20. */
  21. public function parse($string)
  22. {
  23. $lines = \preg_split('(\r\n|\r|\n)', $string);
  24. if (!empty($lines) && $lines[\count($lines) - 1] == '') {
  25. \array_pop($lines);
  26. }
  27. $lineCount = \count($lines);
  28. $diffs = array();
  29. $diff = null;
  30. $collected = array();
  31. for ($i = 0; $i < $lineCount; ++$i) {
  32. if (\preg_match('(^---\\s+(?P<file>\\S+))', $lines[$i], $fromMatch) &&
  33. \preg_match('(^\\+\\+\\+\\s+(?P<file>\\S+))', $lines[$i + 1], $toMatch)) {
  34. if ($diff !== null) {
  35. $this->parseFileDiff($diff, $collected);
  36. $diffs[] = $diff;
  37. $collected = array();
  38. }
  39. $diff = new Diff($fromMatch['file'], $toMatch['file']);
  40. ++$i;
  41. } else {
  42. if (\preg_match('/^(?:diff --git |index [\da-f\.]+|[+-]{3} [ab])/', $lines[$i])) {
  43. continue;
  44. }
  45. $collected[] = $lines[$i];
  46. }
  47. }
  48. if ($diff !== null && \count($collected)) {
  49. $this->parseFileDiff($diff, $collected);
  50. $diffs[] = $diff;
  51. }
  52. return $diffs;
  53. }
  54. /**
  55. * @param Diff $diff
  56. * @param array $lines
  57. */
  58. private function parseFileDiff(Diff $diff, array $lines)
  59. {
  60. $chunks = array();
  61. $chunk = null;
  62. foreach ($lines as $line) {
  63. if (\preg_match('/^@@\s+-(?P<start>\d+)(?:,\s*(?P<startrange>\d+))?\s+\+(?P<end>\d+)(?:,\s*(?P<endrange>\d+))?\s+@@/', $line, $match)) {
  64. $chunk = new Chunk(
  65. $match['start'],
  66. isset($match['startrange']) ? \max(1, $match['startrange']) : 1,
  67. $match['end'],
  68. isset($match['endrange']) ? \max(1, $match['endrange']) : 1
  69. );
  70. $chunks[] = $chunk;
  71. $diffLines = array();
  72. continue;
  73. }
  74. if (\preg_match('/^(?P<type>[+ -])?(?P<line>.*)/', $line, $match)) {
  75. $type = Line::UNCHANGED;
  76. if ($match['type'] === '+') {
  77. $type = Line::ADDED;
  78. } elseif ($match['type'] === '-') {
  79. $type = Line::REMOVED;
  80. }
  81. $diffLines[] = new Line($type, $match['line']);
  82. if (null !== $chunk) {
  83. $chunk->setLines($diffLines);
  84. }
  85. }
  86. }
  87. $diff->setChunks($chunks);
  88. }
  89. }