LintCommand.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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\Attribute\AsCommand;
  12. use Symfony\Component\Console\CI\GithubActionReporter;
  13. use Symfony\Component\Console\Command\Command;
  14. use Symfony\Component\Console\Completion\CompletionInput;
  15. use Symfony\Component\Console\Completion\CompletionSuggestions;
  16. use Symfony\Component\Console\Exception\InvalidArgumentException;
  17. use Symfony\Component\Console\Exception\RuntimeException;
  18. use Symfony\Component\Console\Input\InputArgument;
  19. use Symfony\Component\Console\Input\InputInterface;
  20. use Symfony\Component\Console\Input\InputOption;
  21. use Symfony\Component\Console\Output\OutputInterface;
  22. use Symfony\Component\Console\Style\SymfonyStyle;
  23. use Symfony\Component\Yaml\Exception\ParseException;
  24. use Symfony\Component\Yaml\Parser;
  25. use Symfony\Component\Yaml\Yaml;
  26. /**
  27. * Validates YAML files syntax and outputs encountered errors.
  28. *
  29. * @author Grégoire Pineau <lyrixx@lyrixx.info>
  30. * @author Robin Chalas <robin.chalas@gmail.com>
  31. */
  32. class LintCommand extends Command
  33. {
  34. /**
  35. * @var \Symfony\Component\Yaml\Parser
  36. */
  37. private $parser;
  38. /**
  39. * @var string|null
  40. */
  41. private $format;
  42. /**
  43. * @var bool
  44. */
  45. private $displayCorrectFiles;
  46. /**
  47. * @var \Closure|null
  48. */
  49. private $directoryIteratorProvider;
  50. /**
  51. * @var \Closure|null
  52. */
  53. private $isReadableProvider;
  54. /**
  55. * @param string|null $name
  56. * @param callable|null $directoryIteratorProvider
  57. * @param callable|null $isReadableProvider
  58. */
  59. public function __construct($name = null, $directoryIteratorProvider = null, $isReadableProvider = null)
  60. {
  61. parent::__construct($name);
  62. $this->directoryIteratorProvider = null === $directoryIteratorProvider ? null : \Closure::fromCallable($directoryIteratorProvider);
  63. $this->isReadableProvider = null === $isReadableProvider ? null : \Closure::fromCallable($isReadableProvider);
  64. }
  65. /**
  66. * @return void
  67. */
  68. protected function configure()
  69. {
  70. $this
  71. ->addArgument('filename', InputArgument::IS_ARRAY, 'A file, a directory or "-" for reading from STDIN')
  72. ->addOption('format', null, InputOption::VALUE_REQUIRED, sprintf('The output format ("%s")', implode('", "', $this->getAvailableFormatOptions())))
  73. ->addOption('exclude', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Path(s) to exclude')
  74. ->addOption('parse-tags', null, InputOption::VALUE_NEGATABLE, 'Parse custom tags', null)
  75. ->setHelp(<<<EOF
  76. The <info>%command.name%</info> command lints a YAML file and outputs to STDOUT
  77. the first encountered syntax error.
  78. You can validates YAML contents passed from STDIN:
  79. <info>cat filename | php %command.full_name% -</info>
  80. You can also validate the syntax of a file:
  81. <info>php %command.full_name% filename</info>
  82. Or of a whole directory:
  83. <info>php %command.full_name% dirname</info>
  84. <info>php %command.full_name% dirname --format=json</info>
  85. You can also exclude one or more specific files:
  86. <info>php %command.full_name% dirname --exclude="dirname/foo.yaml" --exclude="dirname/bar.yaml"</info>
  87. EOF
  88. )
  89. ;
  90. }
  91. /**
  92. * @param \Symfony\Component\Console\Input\InputInterface $input
  93. * @param \Symfony\Component\Console\Output\OutputInterface $output
  94. */
  95. protected function execute($input, $output)
  96. {
  97. $io = new SymfonyStyle($input, $output);
  98. $filenames = (array) $input->getArgument('filename');
  99. $excludes = $input->getOption('exclude');
  100. $this->format = $input->getOption('format');
  101. $flags = $input->getOption('parse-tags');
  102. if (null === $this->format) {
  103. // Autodetect format according to CI environment
  104. $this->format = class_exists(GithubActionReporter::class) && GithubActionReporter::isGithubActionEnvironment() ? 'github' : 'txt';
  105. }
  106. $flags = $flags ? Yaml::PARSE_CUSTOM_TAGS : 0;
  107. $this->displayCorrectFiles = $output->isVerbose();
  108. if (['-'] === $filenames) {
  109. return $this->display($io, [$this->validate(file_get_contents('php://stdin'), $flags)]);
  110. }
  111. if (!$filenames) {
  112. throw new RuntimeException('Please provide a filename or pipe file content to STDIN.');
  113. }
  114. $filesInfo = [];
  115. foreach ($filenames as $filename) {
  116. if (!$this->isReadable($filename)) {
  117. throw new RuntimeException(sprintf('File or directory "%s" is not readable.', $filename));
  118. }
  119. foreach ($this->getFiles($filename) as $file) {
  120. if (!\in_array($file->getPathname(), $excludes, true)) {
  121. $filesInfo[] = $this->validate(file_get_contents($file), $flags, $file);
  122. }
  123. }
  124. }
  125. return $this->display($io, $filesInfo);
  126. }
  127. /**
  128. * @param string $content
  129. * @param int $flags
  130. * @param string|null $file
  131. */
  132. private function validate($content, $flags, $file = null)
  133. {
  134. $prevErrorHandler = set_error_handler(function ($level, $message, $file, $line) use (&$prevErrorHandler) {
  135. if (\E_USER_DEPRECATED === $level) {
  136. throw new ParseException($message, $this->getParser()->getRealCurrentLineNb() + 1);
  137. }
  138. return $prevErrorHandler ? $prevErrorHandler($level, $message, $file, $line) : false;
  139. });
  140. try {
  141. $this->getParser()->parse($content, Yaml::PARSE_CONSTANT | $flags);
  142. } catch (ParseException $e) {
  143. return ['file' => $file, 'line' => $e->getParsedLine(), 'valid' => false, 'message' => $e->getMessage()];
  144. } finally {
  145. restore_error_handler();
  146. }
  147. return ['file' => $file, 'valid' => true];
  148. }
  149. /**
  150. * @param \Symfony\Component\Console\Style\SymfonyStyle $io
  151. * @param mixed[] $files
  152. */
  153. private function display($io, $files)
  154. {
  155. switch ($this->format) {
  156. case 'txt':
  157. return $this->displayTxt($io, $files);
  158. case 'json':
  159. return $this->displayJson($io, $files);
  160. case 'github':
  161. return $this->displayTxt($io, $files, true);
  162. default:
  163. throw new InvalidArgumentException(sprintf('Supported formats are "%s".', implode('", "', $this->getAvailableFormatOptions())));
  164. }
  165. }
  166. /**
  167. * @param \Symfony\Component\Console\Style\SymfonyStyle $io
  168. * @param mixed[] $filesInfo
  169. * @param bool $errorAsGithubAnnotations
  170. */
  171. private function displayTxt($io, $filesInfo, $errorAsGithubAnnotations = false)
  172. {
  173. $countFiles = \count($filesInfo);
  174. $erroredFiles = 0;
  175. $suggestTagOption = false;
  176. if ($errorAsGithubAnnotations) {
  177. $githubReporter = new GithubActionReporter($io);
  178. }
  179. foreach ($filesInfo as $info) {
  180. if ($info['valid'] && $this->displayCorrectFiles) {
  181. $io->comment('<info>OK</info>'.($info['file'] ? sprintf(' in %s', $info['file']) : ''));
  182. } elseif (!$info['valid']) {
  183. ++$erroredFiles;
  184. $io->text('<error> ERROR </error>'.($info['file'] ? sprintf(' in %s', $info['file']) : ''));
  185. $io->text(sprintf('<error> >> %s</error>', $info['message']));
  186. if (strpos($info['message'], 'PARSE_CUSTOM_TAGS') !== false) {
  187. $suggestTagOption = true;
  188. }
  189. if ($errorAsGithubAnnotations) {
  190. $githubReporter->error($info['message'], $info['file'] ?? 'php://stdin', $info['line']);
  191. }
  192. }
  193. }
  194. if (0 === $erroredFiles) {
  195. $io->success(sprintf('All %d YAML files contain valid syntax.', $countFiles));
  196. } else {
  197. $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.' : ''));
  198. }
  199. return min($erroredFiles, 1);
  200. }
  201. /**
  202. * @param \Symfony\Component\Console\Style\SymfonyStyle $io
  203. * @param mixed[] $filesInfo
  204. */
  205. private function displayJson($io, $filesInfo)
  206. {
  207. $errors = 0;
  208. array_walk($filesInfo, function (&$v) use (&$errors) {
  209. $v['file'] = (string) $v['file'];
  210. if (!$v['valid']) {
  211. ++$errors;
  212. }
  213. if (isset($v['message']) && strpos($v['message'], 'PARSE_CUSTOM_TAGS') !== false) {
  214. $v['message'] .= ' Use the --parse-tags option if you want parse custom tags.';
  215. }
  216. });
  217. $io->writeln(json_encode($filesInfo, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES));
  218. return min($errors, 1);
  219. }
  220. /**
  221. * @param string $fileOrDirectory
  222. */
  223. private function getFiles($fileOrDirectory)
  224. {
  225. if (is_file($fileOrDirectory)) {
  226. yield new \SplFileInfo($fileOrDirectory);
  227. return;
  228. }
  229. foreach ($this->getDirectoryIterator($fileOrDirectory) as $file) {
  230. if (!\in_array($file->getExtension(), ['yml', 'yaml'])) {
  231. continue;
  232. }
  233. yield $file;
  234. }
  235. }
  236. private function getParser()
  237. {
  238. return $this->parser = $this->parser ?? new Parser();
  239. }
  240. /**
  241. * @param string $directory
  242. */
  243. private function getDirectoryIterator($directory)
  244. {
  245. $default = function ($directory) {
  246. return new \RecursiveIteratorIterator(
  247. new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS),
  248. \RecursiveIteratorIterator::LEAVES_ONLY
  249. );
  250. };
  251. if (null !== $this->directoryIteratorProvider) {
  252. return ($this->directoryIteratorProvider)($directory, $default);
  253. }
  254. return $default($directory);
  255. }
  256. /**
  257. * @param string $fileOrDirectory
  258. */
  259. private function isReadable($fileOrDirectory)
  260. {
  261. $default = \Closure::fromCallable('is_readable');
  262. if (null !== $this->isReadableProvider) {
  263. return ($this->isReadableProvider)($fileOrDirectory, $default);
  264. }
  265. return $default($fileOrDirectory);
  266. }
  267. /**
  268. * @param \Symfony\Component\Console\Completion\CompletionInput $input
  269. * @param \Symfony\Component\Console\Completion\CompletionSuggestions $suggestions
  270. */
  271. public function complete($input, $suggestions)
  272. {
  273. if ($input->mustSuggestOptionValuesFor('format')) {
  274. $suggestions->suggestValues($this->getAvailableFormatOptions());
  275. }
  276. }
  277. private function getAvailableFormatOptions()
  278. {
  279. return ['txt', 'json', 'github'];
  280. }
  281. }