|
| 1 | +#!/usr/bin/env php |
| 2 | +<?php |
| 3 | +/** |
| 4 | + * Run PHPCS tests against a PR. |
| 5 | + * |
| 6 | + * The only argument is for the PR's base branch, which is then compared to the HEAD of the PR to retrieve the list |
| 7 | + * of changed files. The PHPCS tests are only run against these changed files, to speed up the tests. |
| 8 | + */ |
| 9 | +if (empty($argv[1])) { |
| 10 | + echo 'You must provide a base branch to check this PR against.'; |
| 11 | + echo "\n"; |
| 12 | + exit(1); |
| 13 | +} |
| 14 | + |
| 15 | +// Get a changelist of files from Git for this PR. |
| 16 | +$fileList = shell_exec('git diff --name-only --diff-filter=ACMR origin/' . $argv[1] . ' HEAD'); |
| 17 | +$files = array_filter(explode("\n", $fileList)); |
| 18 | + |
| 19 | +foreach ($files as &$file) { |
| 20 | + if (strpos($file, ' ') !== false) { |
| 21 | + $file = str_replace(' ', '\\ ', $file); |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +// Run all changed files through the PHPCS code sniffer and generate a CSV report |
| 26 | +$csv = shell_exec('phpcs --colors -nq --report="csv" --extensions="php" ' . implode(' ', $files)); |
| 27 | +$lines = array_map(function ($row) { |
| 28 | + return array_map(function ($column) { |
| 29 | + return trim($column, '"'); |
| 30 | + }, explode(',', $row)); |
| 31 | +}, array_filter(explode("\n", $csv))); |
| 32 | + |
| 33 | +// Remove header row |
| 34 | +array_shift($lines); |
| 35 | + |
| 36 | +if (!count($lines)) { |
| 37 | + echo "\e[0;32mFound no issues with code quality.\e[0m"; |
| 38 | + echo "\n"; |
| 39 | + exit(0); |
| 40 | +} else { |
| 41 | + // Group errors by file |
| 42 | + $files = []; |
| 43 | + |
| 44 | + foreach ($lines as $line) { |
| 45 | + $filename = str_replace(dirname(dirname(dirname(__DIR__))), '', $line[0]); |
| 46 | + |
| 47 | + if (empty($files[$filename])) { |
| 48 | + $files[$filename] = []; |
| 49 | + } |
| 50 | + |
| 51 | + $files[$filename][] = [ |
| 52 | + 'warning' => ($line[3] === 'warning'), |
| 53 | + 'message' => $line[4], |
| 54 | + 'line' => $line[1], |
| 55 | + ]; |
| 56 | + } |
| 57 | + |
| 58 | + // Render report |
| 59 | + echo "\e[0;31mFound " |
| 60 | + . ((count($lines) === 1) |
| 61 | + ? '1 issue' |
| 62 | + : count($lines) . ' issues') |
| 63 | + . " with code quality.\e[0m"; |
| 64 | + echo "\n"; |
| 65 | + |
| 66 | + foreach ($files as $file => $errors) { |
| 67 | + echo "\n"; |
| 68 | + echo "\e[1;37m" . str_replace('"', '', $file) . "\e[0m"; |
| 69 | + echo "\n\n"; |
| 70 | + |
| 71 | + foreach ($errors as $error) { |
| 72 | + echo "\e[2m" . str_pad(' L' . $error['line'], 7) . " | \e[0m"; |
| 73 | + if ($error['warning'] === false) { |
| 74 | + echo "\e[0;31mERR:\e[0m "; |
| 75 | + } else { |
| 76 | + echo "\e[1;33mWARN:\e[0m "; |
| 77 | + } |
| 78 | + echo $error['message']; |
| 79 | + echo "\n"; |
| 80 | + } |
| 81 | + } |
| 82 | + exit(1); |
| 83 | +} |
0 commit comments