CompleteCommand.php 8.3 KB

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