CompleteCommand.php 8.7 KB

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