Skip to content
  • P
    Projects
  • G
    Groups
  • S
    Snippets
  • Help

semour / semour_admin

  • This project
    • Loading...
  • Sign in
Go to a project
  • Project
  • Repository
  • Issues 0
  • Merge Requests 0
  • Pipelines
  • Wiki
  • Snippets
  • Settings
  • Activity
  • Graph
  • Charts
  • Create a new issue
  • Jobs
  • Commits
  • Issue Boards
  • Files
  • Commits
  • Branches
  • Tags
  • Contributors
  • Graph
  • Compare
  • Charts
Find file
BlameHistoryPermalink
Switch branch/tag
  • semour_admin
  • vendor
  • sebastian
  • diff
  • tests
  • Utils
  • UnifiedDiffAssertTrait.php
  • mushishixian's avatar
    Initial commit · 585b9d09
    mushishixian committed 2 years ago
    585b9d09
UnifiedDiffAssertTrait.php 10.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
<?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;

trait UnifiedDiffAssertTrait
{
    /**
     * @param string $diff
     *
     * @throws \UnexpectedValueException
     */
    public function assertValidUnifiedDiffFormat(string $diff): void
    {
        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;

                [$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): void
    {
        $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): void
    {
        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): void
    {
        // 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),
        ];
    }
}