CompleteCommand.php 9.1 KB

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