LintCommand.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. #[AsCommand(name: 'lint:yaml', description: 'Lint a YAML file and outputs encountered errors')]
  33. class LintCommand extends Command
  34. {
  35. private Parser $parser;
  36. private ?string $format = null;
  37. private bool $displayCorrectFiles;
  38. private ?\Closure $directoryIteratorProvider;
  39. private ?\Closure $isReadableProvider;
  40. public function __construct(?string $name = null, ?callable $directoryIteratorProvider = null, ?callable $isReadableProvider = null)
  41. {
  42. parent::__construct($name);
  43. $this->directoryIteratorProvider = null === $directoryIteratorProvider ? null : $directoryIteratorProvider(...);
  44. $this->isReadableProvider = null === $isReadableProvider ? null : $isReadableProvider(...);
  45. }
  46. protected function configure(): void
  47. {
  48. $this
  49. ->addArgument('filename', InputArgument::IS_ARRAY, 'A file, a directory or "-" for reading from STDIN')
  50. ->addOption('format', null, InputOption::VALUE_REQUIRED, \sprintf('The output format ("%s")', implode('", "', $this->getAvailableFormatOptions())))
  51. ->addOption('exclude', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Path(s) to exclude')
  52. ->addOption('parse-tags', null, InputOption::VALUE_NEGATABLE, 'Parse custom tags', null)
  53. ->setHelp(<<<EOF
  54. The <info>%command.name%</info> command lints a YAML file and outputs to STDOUT
  55. the first encountered syntax error.
  56. You can validates YAML contents passed from STDIN:
  57. <info>cat filename | php %command.full_name% -</info>
  58. You can also validate the syntax of a file:
  59. <info>php %command.full_name% filename</info>
  60. Or of a whole directory:
  61. <info>php %command.full_name% dirname</info>
  62. The <info>--format</info> option specifies the format of the command output:
  63. <info>php %command.full_name% dirname --format=json</info>
  64. You can also exclude one or more specific files:
  65. <info>php %command.full_name% dirname --exclude="dirname/foo.yaml" --exclude="dirname/bar.yaml"</info>
  66. EOF
  67. )
  68. ;
  69. }
  70. protected function execute(InputInterface $input, OutputInterface $output): int
  71. {
  72. $io = new SymfonyStyle($input, $output);
  73. $filenames = (array) $input->getArgument('filename');
  74. $excludes = $input->getOption('exclude');
  75. $this->format = $input->getOption('format');
  76. $flags = $input->getOption('parse-tags');
  77. if (null === $this->format) {
  78. // Autodetect format according to CI environment
  79. $this->format = class_exists(GithubActionReporter::class) && GithubActionReporter::isGithubActionEnvironment() ? 'github' : 'txt';
  80. }
  81. $flags = $flags ? Yaml::PARSE_CUSTOM_TAGS : 0;
  82. $this->displayCorrectFiles = $output->isVerbose();
  83. if (['-'] === $filenames) {
  84. return $this->display($io, [$this->validate(file_get_contents('php://stdin'), $flags)]);
  85. }
  86. if (!$filenames) {
  87. throw new RuntimeException('Please provide a filename or pipe file content to STDIN.');
  88. }
  89. $filesInfo = [];
  90. foreach ($filenames as $filename) {
  91. if (!$this->isReadable($filename)) {
  92. throw new RuntimeException(\sprintf('File or directory "%s" is not readable.', $filename));
  93. }
  94. foreach ($this->getFiles($filename) as $file) {
  95. if (!\in_array($file->getPathname(), $excludes, true)) {
  96. $filesInfo[] = $this->validate(file_get_contents($file), $flags, $file);
  97. }
  98. }
  99. }
  100. return $this->display($io, $filesInfo);
  101. }
  102. private function validate(string $content, int $flags, ?string $file = null): array
  103. {
  104. $prevErrorHandler = set_error_handler(function ($level, $message, $file, $line) use (&$prevErrorHandler) {
  105. if (\E_USER_DEPRECATED === $level) {
  106. throw new ParseException($message, $this->getParser()->getRealCurrentLineNb() + 1);
  107. }
  108. return $prevErrorHandler ? $prevErrorHandler($level, $message, $file, $line) : false;
  109. });
  110. try {
  111. $this->getParser()->parse($content, Yaml::PARSE_CONSTANT | $flags);
  112. } catch (ParseException $e) {
  113. return ['file' => $file, 'line' => $e->getParsedLine(), 'valid' => false, 'message' => $e->getMessage()];
  114. } finally {
  115. restore_error_handler();
  116. }
  117. return ['file' => $file, 'valid' => true];
  118. }
  119. private function display(SymfonyStyle $io, array $files): int
  120. {
  121. return match ($this->format) {
  122. 'txt' => $this->displayTxt($io, $files),
  123. 'json' => $this->displayJson($io, $files),
  124. 'github' => $this->displayTxt($io, $files, true),
  125. default => throw new InvalidArgumentException(\sprintf('Supported formats are "%s".', implode('", "', $this->getAvailableFormatOptions()))),
  126. };
  127. }
  128. private function displayTxt(SymfonyStyle $io, array $filesInfo, bool $errorAsGithubAnnotations = false): int
  129. {
  130. $countFiles = \count($filesInfo);
  131. $erroredFiles = 0;
  132. $suggestTagOption = false;
  133. if ($errorAsGithubAnnotations) {
  134. $githubReporter = new GithubActionReporter($io);
  135. }
  136. foreach ($filesInfo as $info) {
  137. if ($info['valid'] && $this->displayCorrectFiles) {
  138. $io->comment('<info>OK</info>'.($info['file'] ? \sprintf(' in %s', $info['file']) : ''));
  139. } elseif (!$info['valid']) {
  140. ++$erroredFiles;
  141. $io->text('<error> ERROR </error>'.($info['file'] ? \sprintf(' in %s', $info['file']) : ''));
  142. $io->text(\sprintf('<error> >> %s</error>', $info['message']));
  143. if (str_contains($info['message'], 'PARSE_CUSTOM_TAGS')) {
  144. $suggestTagOption = true;
  145. }
  146. if ($errorAsGithubAnnotations) {
  147. $githubReporter->error($info['message'], $info['file'] ?? 'php://stdin', $info['line']);
  148. }
  149. }
  150. }
  151. if (0 === $erroredFiles) {
  152. $io->success(\sprintf('All %d YAML files contain valid syntax.', $countFiles));
  153. } else {
  154. $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.' : ''));
  155. }
  156. return min($erroredFiles, 1);
  157. }
  158. private function displayJson(SymfonyStyle $io, array $filesInfo): int
  159. {
  160. $errors = 0;
  161. array_walk($filesInfo, function (&$v) use (&$errors) {
  162. $v['file'] = (string) $v['file'];
  163. if (!$v['valid']) {
  164. ++$errors;
  165. }
  166. if (isset($v['message']) && str_contains($v['message'], 'PARSE_CUSTOM_TAGS')) {
  167. $v['message'] .= ' Use the --parse-tags option if you want parse custom tags.';
  168. }
  169. });
  170. $io->writeln(json_encode($filesInfo, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES));
  171. return min($errors, 1);
  172. }
  173. private function getFiles(string $fileOrDirectory): iterable
  174. {
  175. if (is_file($fileOrDirectory)) {
  176. yield new \SplFileInfo($fileOrDirectory);
  177. return;
  178. }
  179. foreach ($this->getDirectoryIterator($fileOrDirectory) as $file) {
  180. if (!\in_array($file->getExtension(), ['yml', 'yaml'])) {
  181. continue;
  182. }
  183. yield $file;
  184. }
  185. }
  186. private function getParser(): Parser
  187. {
  188. return $this->parser ??= new Parser();
  189. }
  190. private function getDirectoryIterator(string $directory): iterable
  191. {
  192. $default = fn ($directory) => new \RecursiveIteratorIterator(
  193. new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS),
  194. \RecursiveIteratorIterator::LEAVES_ONLY
  195. );
  196. if (null !== $this->directoryIteratorProvider) {
  197. return ($this->directoryIteratorProvider)($directory, $default);
  198. }
  199. return $default($directory);
  200. }
  201. private function isReadable(string $fileOrDirectory): bool
  202. {
  203. $default = is_readable(...);
  204. if (null !== $this->isReadableProvider) {
  205. return ($this->isReadableProvider)($fileOrDirectory, $default);
  206. }
  207. return $default($fileOrDirectory);
  208. }
  209. public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void
  210. {
  211. if ($input->mustSuggestOptionValuesFor('format')) {
  212. $suggestions->suggestValues($this->getAvailableFormatOptions());
  213. }
  214. }
  215. /** @return string[] */
  216. private function getAvailableFormatOptions(): array
  217. {
  218. return ['txt', 'json', 'github'];
  219. }
  220. }