Debian Codegraph @

vendor/symfony/yaml/Command/LintCommand.php

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