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