LintCommand.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  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 Symfony\Component\Yaml\Command;
  11. use Symfony\Component\Console\CI\GithubActionReporter;
  12. use Symfony\Component\Console\Command\Command;
  13. use Symfony\Component\Console\Exception\InvalidArgumentException;
  14. use Symfony\Component\Console\Exception\RuntimeException;
  15. use Symfony\Component\Console\Input\InputArgument;
  16. use Symfony\Component\Console\Input\InputInterface;
  17. use Symfony\Component\Console\Input\InputOption;
  18. use Symfony\Component\Console\Output\OutputInterface;
  19. use Symfony\Component\Console\Style\SymfonyStyle;
  20. use Symfony\Component\Yaml\Exception\ParseException;
  21. use Symfony\Component\Yaml\Parser;
  22. use Symfony\Component\Yaml\Yaml;
  23. /**
  24. * Validates YAML files syntax and outputs encountered errors.
  25. *
  26. * @author Grégoire Pineau <lyrixx@lyrixx.info>
  27. * @author Robin Chalas <robin.chalas@gmail.com>
  28. */
  29. class LintCommand extends Command
  30. {
  31. protected static $defaultName = 'lint:yaml';
  32. protected static $defaultDescription = 'Lint a YAML file and outputs encountered errors';
  33. private $parser;
  34. private $format;
  35. private $displayCorrectFiles;
  36. private $directoryIteratorProvider;
  37. private $isReadableProvider;
  38. public function __construct(string $name = null, callable $directoryIteratorProvider = null, callable $isReadableProvider = null)
  39. {
  40. parent::__construct($name);
  41. $this->directoryIteratorProvider = $directoryIteratorProvider;
  42. $this->isReadableProvider = $isReadableProvider;
  43. }
  44. /**
  45. * {@inheritdoc}
  46. */
  47. protected function configure()
  48. {
  49. $this
  50. ->setDescription(self::$defaultDescription)
  51. ->addArgument('filename', InputArgument::IS_ARRAY, 'A file, a directory or "-" for reading from STDIN')
  52. ->addOption('format', null, InputOption::VALUE_REQUIRED, 'The output format')
  53. ->addOption('parse-tags', null, InputOption::VALUE_NONE, 'Parse custom tags')
  54. ->setHelp(<<<EOF
  55. The <info>%command.name%</info> command lints a YAML file and outputs to STDOUT
  56. the first encountered syntax error.
  57. You can validates YAML contents passed from STDIN:
  58. <info>cat filename | php %command.full_name% -</info>
  59. You can also validate the syntax of a file:
  60. <info>php %command.full_name% filename</info>
  61. Or of a whole directory:
  62. <info>php %command.full_name% dirname</info>
  63. <info>php %command.full_name% dirname --format=json</info>
  64. EOF
  65. )
  66. ;
  67. }
  68. protected function execute(InputInterface $input, OutputInterface $output)
  69. {
  70. $io = new SymfonyStyle($input, $output);
  71. $filenames = (array) $input->getArgument('filename');
  72. $this->format = $input->getOption('format');
  73. if ('github' === $this->format && !class_exists(GithubActionReporter::class)) {
  74. throw new \InvalidArgumentException('The "github" format is only available since "symfony/console" >= 5.3.');
  75. }
  76. if (null === $this->format) {
  77. // Autodetect format according to CI environment
  78. $this->format = class_exists(GithubActionReporter::class) && GithubActionReporter::isGithubActionEnvironment() ? 'github' : 'txt';
  79. }
  80. $this->displayCorrectFiles = $output->isVerbose();
  81. $flags = $input->getOption('parse-tags') ? Yaml::PARSE_CUSTOM_TAGS : 0;
  82. if (['-'] === $filenames) {
  83. return $this->display($io, [$this->validate(file_get_contents('php://stdin'), $flags)]);
  84. }
  85. if (!$filenames) {
  86. throw new RuntimeException('Please provide a filename or pipe file content to STDIN.');
  87. }
  88. $filesInfo = [];
  89. foreach ($filenames as $filename) {
  90. if (!$this->isReadable($filename)) {
  91. throw new RuntimeException(sprintf('File or directory "%s" is not readable.', $filename));
  92. }
  93. foreach ($this->getFiles($filename) as $file) {
  94. $filesInfo[] = $this->validate(file_get_contents($file), $flags, $file);
  95. }
  96. }
  97. return $this->display($io, $filesInfo);
  98. }
  99. private function validate(string $content, int $flags, string $file = null)
  100. {
  101. $prevErrorHandler = set_error_handler(function ($level, $message, $file, $line) use (&$prevErrorHandler) {
  102. if (\E_USER_DEPRECATED === $level) {
  103. throw new ParseException($message, $this->getParser()->getRealCurrentLineNb() + 1);
  104. }
  105. return $prevErrorHandler ? $prevErrorHandler($level, $message, $file, $line) : false;
  106. });
  107. try {
  108. $this->getParser()->parse($content, Yaml::PARSE_CONSTANT | $flags);
  109. } catch (ParseException $e) {
  110. return ['file' => $file, 'line' => $e->getParsedLine(), 'valid' => false, 'message' => $e->getMessage()];
  111. } finally {
  112. restore_error_handler();
  113. }
  114. return ['file' => $file, 'valid' => true];
  115. }
  116. private function display(SymfonyStyle $io, array $files): int
  117. {
  118. switch ($this->format) {
  119. case 'txt':
  120. return $this->displayTxt($io, $files);
  121. case 'json':
  122. return $this->displayJson($io, $files);
  123. case 'github':
  124. return $this->displayTxt($io, $files, true);
  125. default:
  126. throw new InvalidArgumentException(sprintf('The format "%s" is not supported.', $this->format));
  127. }
  128. }
  129. private function displayTxt(SymfonyStyle $io, array $filesInfo, bool $errorAsGithubAnnotations = false): int
  130. {
  131. $countFiles = \count($filesInfo);
  132. $erroredFiles = 0;
  133. $suggestTagOption = false;
  134. if ($errorAsGithubAnnotations) {
  135. $githubReporter = new GithubActionReporter($io);
  136. }
  137. foreach ($filesInfo as $info) {
  138. if ($info['valid'] && $this->displayCorrectFiles) {
  139. $io->comment('<info>OK</info>'.($info['file'] ? sprintf(' in %s', $info['file']) : ''));
  140. } elseif (!$info['valid']) {
  141. ++$erroredFiles;
  142. $io->text('<error> ERROR </error>'.($info['file'] ? sprintf(' in %s', $info['file']) : ''));
  143. $io->text(sprintf('<error> >> %s</error>', $info['message']));
  144. if (false !== strpos($info['message'], 'PARSE_CUSTOM_TAGS')) {
  145. $suggestTagOption = true;
  146. }
  147. if ($errorAsGithubAnnotations) {
  148. $githubReporter->error($info['message'], $info['file'] ?? 'php://stdin', $info['line']);
  149. }
  150. }
  151. }
  152. if (0 === $erroredFiles) {
  153. $io->success(sprintf('All %d YAML files contain valid syntax.', $countFiles));
  154. } else {
  155. $io->warning(sprintf('%d YAML files have valid syntax and %d contain errors.%s', $countFiles - $erroredFiles, $erroredFiles, $suggestTagOption ? ' Use the --parse-tags option if you want parse custom tags.' : ''));
  156. }
  157. return min($erroredFiles, 1);
  158. }
  159. private function displayJson(SymfonyStyle $io, array $filesInfo): int
  160. {
  161. $errors = 0;
  162. array_walk($filesInfo, function (&$v) use (&$errors) {
  163. $v['file'] = (string) $v['file'];
  164. if (!$v['valid']) {
  165. ++$errors;
  166. }
  167. if (isset($v['message']) && false !== strpos($v['message'], 'PARSE_CUSTOM_TAGS')) {
  168. $v['message'] .= ' Use the --parse-tags option if you want parse custom tags.';
  169. }
  170. });
  171. $io->writeln(json_encode($filesInfo, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES));
  172. return min($errors, 1);
  173. }
  174. private function getFiles(string $fileOrDirectory): iterable
  175. {
  176. if (is_file($fileOrDirectory)) {
  177. yield new \SplFileInfo($fileOrDirectory);
  178. return;
  179. }
  180. foreach ($this->getDirectoryIterator($fileOrDirectory) as $file) {
  181. if (!\in_array($file->getExtension(), ['yml', 'yaml'])) {
  182. continue;
  183. }
  184. yield $file;
  185. }
  186. }
  187. private function getParser(): Parser
  188. {
  189. if (!$this->parser) {
  190. $this->parser = new Parser();
  191. }
  192. return $this->parser;
  193. }
  194. private function getDirectoryIterator(string $directory): iterable
  195. {
  196. $default = function ($directory) {
  197. return new \RecursiveIteratorIterator(
  198. new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS),
  199. \RecursiveIteratorIterator::LEAVES_ONLY
  200. );
  201. };
  202. if (null !== $this->directoryIteratorProvider) {
  203. return ($this->directoryIteratorProvider)($directory, $default);
  204. }
  205. return $default($directory);
  206. }
  207. private function isReadable(string $fileOrDirectory): bool
  208. {
  209. $default = function ($fileOrDirectory) {
  210. return is_readable($fileOrDirectory);
  211. };
  212. if (null !== $this->isReadableProvider) {
  213. return ($this->isReadableProvider)($fileOrDirectory, $default);
  214. }
  215. return $default($fileOrDirectory);
  216. }
  217. }