CompleteCommand.php 9.4 KB

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