Debian Codegraph @

vendor/symfony/console/Command/CompleteCommand.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\Console\Command;
13
14 use Symfony\Component\Console\Attribute\AsCommand;
15 use Symfony\Component\Console\Completion\CompletionInput;
16 use Symfony\Component\Console\Completion\CompletionSuggestions;
17 use Symfony\Component\Console\Completion\Output\BashCompletionOutput;
18 use Symfony\Component\Console\Completion\Output\CompletionOutputInterface;
19 use Symfony\Component\Console\Completion\Output\FishCompletionOutput;
20 use Symfony\Component\Console\Completion\Output\ZshCompletionOutput;
21 use Symfony\Component\Console\Exception\CommandNotFoundException;
22 use Symfony\Component\Console\Exception\ExceptionInterface;
23 use Symfony\Component\Console\Input\InputInterface;
24 use Symfony\Component\Console\Input\InputOption;
25 use Symfony\Component\Console\Output\OutputInterface;
26
27 /**
28 * Responsible for providing the values to the shell completion.
29 *
30 * @author Wouter de Jong <[email protected]>
31 */
32 #[AsCommand(name: '|_complete', description: 'Internal command to provide shell completion suggestions')]
33 final class CompleteCommand extends Command
34 {
35 public const COMPLETION_API_VERSION = '1';
36
37 private array $completionOutputs;
38 private bool $isDebug = false;
39
40 /**
41 * @param array<string, class-string<CompletionOutputInterface>> $completionOutputs A list of additional completion outputs, with shell name as key and FQCN as value
42 */
43 public function __construct(array $completionOutputs = [])
44 {
45 // must be set before the parent constructor, as the property value is used in configure()
46 $this->completionOutputs = $completionOutputs + [
47 'bash' => BashCompletionOutput::class,
48 'fish' => FishCompletionOutput::class,
49 'zsh' => ZshCompletionOutput::class,
50 ];
51
52 parent::__construct();
53 }
54
55 protected function configure(): void
56 {
57 $this
58 ->addOption('shell', 's', InputOption::VALUE_REQUIRED, 'The shell type ("'.implode('", "', array_keys($this->completionOutputs)).'")')
59 ->addOption('input', 'i', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'An array of input tokens (e.g. COMP_WORDS or argv)')
60 ->addOption('current', 'c', InputOption::VALUE_REQUIRED, 'The index of the "input" array that the cursor is in (e.g. COMP_CWORD)')
61 ->addOption('api-version', 'a', InputOption::VALUE_REQUIRED, 'The API version of the completion script')
62 ->addOption('symfony', 'S', InputOption::VALUE_REQUIRED, 'deprecated')
63 ;
64 }
65
66 protected function initialize(InputInterface $input, OutputInterface $output): void
67 {
68 $this->isDebug = filter_var(getenv('SYMFONY_COMPLETION_DEBUG'), \FILTER_VALIDATE_BOOL);
69 }
70
71 protected function execute(InputInterface $input, OutputInterface $output): int
72 {
73 try {
74 // "symfony" must be kept for compat with the shell scripts generated by Symfony Console 5.4 - 6.1
75 $version = $input->getOption('symfony') ? '1' : $input->getOption('api-version');
76 if ($version && version_compare($version, self::COMPLETION_API_VERSION, '<')) {
77 $message = \sprintf('Completion script version is not supported ("%s" given, ">=%s" required).', $version, self::COMPLETION_API_VERSION);
78 $this->log($message);
79
80 $output->writeln($message.' Install the Symfony completion script again by using the "completion" command.');
81
82 return 126;
83 }
84
85 $shell = $input->getOption('shell');
86 if (!$shell) {
87 throw new \RuntimeException('The "--shell" option must be set.');
88 }
89
90 if (!$completionOutput = $this->completionOutputs[$shell] ?? false) {
91 throw new \RuntimeException(\sprintf('Shell completion is not supported for your shell: "%s" (supported: "%s").', $shell, implode('", "', array_keys($this->completionOutputs))));
92 }
93
94 $completionInput = $this->createCompletionInput($input);
95 $suggestions = new CompletionSuggestions();
96
97 $this->log([
98 '',
99 '<comment>'.date('Y-m-d H:i:s').'</>',
100 '<info>Input:</> <comment>("|" indicates the cursor position)</>',
101 ' '.$completionInput,
102 '<info>Command:</>',
103 ' '.implode(' ', $_SERVER['argv']),
104 '<info>Messages:</>',
105 ]);
106
107 if ($command = $this->findCommand($completionInput)) {
108 $command->mergeApplicationDefinition();
109 $completionInput->bind($command->getDefinition());
110 }
111 if (null === $command) {
112 $this->log(' No command found, completing using the Application class.');
113
114 $this->getApplication()->complete($completionInput, $suggestions);
115 } elseif (
116 $completionInput->mustSuggestArgumentValuesFor('command')
117 ) {
118 $this->log(' Command found, completing command name.');
119
120 // expand shortcut names ("cache:cl<TAB>") into their full name ("cache:clear")
121 $commandNames = array_filter(array_merge([$command->getName()], $command->getAliases()));
122 foreach ($commandNames as $name) {
123 if (str_starts_with($name, $completionInput->getCompletionValue())) {
124 $commandNames = [$name];
125 break;
126 }
127 }
128 $suggestions->suggestValues($commandNames);
129 } else {
130 if (CompletionInput::TYPE_OPTION_NAME === $completionInput->getCompletionType()) {
131 $this->log(' Completing option names for the <comment>'.($command instanceof LazyCommand ? $command->getCommand() : $command)::class.'</> command.');
132
133 $suggestions->suggestOptions($command->getDefinition()->getOptions());
134 } else {
135 $this->log([
136 ' Completing using the <comment>'.($command instanceof LazyCommand ? $command->getCommand() : $command)::class.'</> class.',
137 ' Completing <comment>'.$completionInput->getCompletionType().'</> for <comment>'.$completionInput->getCompletionName().'</>',
138 ]);
139 if (null !== $compval = $completionInput->getCompletionValue()) {
140 $this->log(' Current value: <comment>'.$compval.'</>');
141 }
142
143 $command->complete($completionInput, $suggestions);
144 }
145 }
146
147 /** @var CompletionOutputInterface $completionOutput */
148 $completionOutput = new $completionOutput();
149
150 $this->log('<info>Suggestions:</>');
151 if ($options = $suggestions->getOptionSuggestions()) {
152 $this->log(' --'.implode(' --', array_map(static fn ($o) => $o->getName(), $options)));
153 } elseif ($values = $suggestions->getValueSuggestions()) {
154 $this->log(' '.implode(' ', $values));
155 } else {
156 $this->log(' <comment>No suggestions were provided</>');
157 }
158
159 $completionOutput->write($suggestions, $output);
160 } catch (\Throwable $e) {
161 $this->log([
162 '<error>Error!</error>',
163 (string) $e,
164 ]);
165
166 if ($output->isDebug()) {
167 throw $e;
168 }
169
170 return 2;
171 }
172
173 return 0;
174 }
175
176 private function createCompletionInput(InputInterface $input): CompletionInput
177 {
178 $currentIndex = $input->getOption('current');
179 if (!$currentIndex || !ctype_digit($currentIndex)) {
180 throw new \RuntimeException('The "--current" option must be set and it must be an integer.');
181 }
182
183 $completionInput = CompletionInput::fromTokens($input->getOption('input'), (int) $currentIndex);
184
185 try {
186 $completionInput->bind($this->getApplication()->getDefinition());
187 } catch (ExceptionInterface) {
188 }
189
190 return $completionInput;
191 }
192
193 private function findCommand(CompletionInput $completionInput): ?Command
194 {
195 try {
196 $inputName = $completionInput->getFirstArgument();
197 if (null === $inputName) {
198 return null;
199 }
200
201 return $this->getApplication()->find($inputName);
202 } catch (CommandNotFoundException) {
203 }
204
205 return null;
206 }
207
208 private function log($messages): void
209 {
210 if (!$this->isDebug) {
211 return;
212 }
213
214 $commandName = basename($_SERVER['argv'][0]);
215 file_put_contents(sys_get_temp_dir().'/sf_'.$commandName.'.log', implode(\PHP_EOL, (array) $messages).\PHP_EOL, \FILE_APPEND);
216 }
217 }