DumpCompletionCommand.php 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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\Input\InputArgument;
  13. use Symfony\Component\Console\Input\InputInterface;
  14. use Symfony\Component\Console\Input\InputOption;
  15. use Symfony\Component\Console\Output\ConsoleOutputInterface;
  16. use Symfony\Component\Console\Output\OutputInterface;
  17. use Symfony\Component\Process\Process;
  18. /**
  19. * Dumps the completion script for the current shell.
  20. *
  21. * @author Wouter de Jong <wouter@wouterj.nl>
  22. */
  23. final class DumpCompletionCommand extends Command
  24. {
  25. /**
  26. * @deprecated since Symfony 6.1
  27. */
  28. protected static $defaultName = 'completion';
  29. /**
  30. * @deprecated since Symfony 6.1
  31. */
  32. protected static $defaultDescription = 'Dump the shell completion script';
  33. /**
  34. * @var mixed[]
  35. */
  36. private $supportedShells;
  37. protected function configure()
  38. {
  39. $fullCommand = $_SERVER['PHP_SELF'];
  40. $commandName = basename($fullCommand);
  41. $fullCommand = @realpath($fullCommand) ?: $fullCommand;
  42. $shell = $this->guessShell();
  43. switch ($shell) {
  44. case 'fish':
  45. [$rcFile, $completionFile] = ['~/.config/fish/config.fish', "/etc/fish/completions/$commandName.fish"];
  46. break;
  47. case 'zsh':
  48. [$rcFile, $completionFile] = ['~/.zshrc', '$fpath[1]/_'.$commandName];
  49. break;
  50. default:
  51. [$rcFile, $completionFile] = ['~/.bashrc', "/etc/bash_completion.d/$commandName"];
  52. break;
  53. }
  54. $supportedShells = implode(', ', $this->getSupportedShells());
  55. $this
  56. ->setHelp(<<<EOH
  57. The <info>%command.name%</> command dumps the shell completion script required
  58. to use shell autocompletion (currently, {$supportedShells} completion are supported).
  59. <comment>Static installation
  60. -------------------</>
  61. Dump the script to a global completion file and restart your shell:
  62. <info>%command.full_name% {$shell} | sudo tee {$completionFile}</>
  63. Or dump the script to a local file and source it:
  64. <info>%command.full_name% {$shell} > completion.sh</>
  65. <comment># source the file whenever you use the project</>
  66. <info>source completion.sh</>
  67. <comment># or add this line at the end of your "{$rcFile}" file:</>
  68. <info>source /path/to/completion.sh</>
  69. <comment>Dynamic installation
  70. --------------------</>
  71. Add this to the end of your shell configuration file (e.g. <info>"{$rcFile}"</>):
  72. <info>eval "$({$fullCommand} completion {$shell})"</>
  73. EOH
  74. )
  75. ->addArgument('shell', InputArgument::OPTIONAL, 'The shell type (e.g. "bash"), the value of the "$SHELL" env var will be used if this is not given', null, \Closure::fromCallable([$this, 'getSupportedShells']))
  76. ->addOption('debug', null, InputOption::VALUE_NONE, 'Tail the completion debug log')
  77. ;
  78. }
  79. /**
  80. * @param \Symfony\Component\Console\Input\InputInterface $input
  81. * @param \Symfony\Component\Console\Output\OutputInterface $output
  82. */
  83. protected function execute($input, $output)
  84. {
  85. $commandName = basename($_SERVER['argv'][0]);
  86. if ($input->getOption('debug')) {
  87. $this->tailDebugLog($commandName, $output);
  88. return 0;
  89. }
  90. $shell = $input->getArgument('shell') ?? self::guessShell();
  91. $completionFile = __DIR__.'/../Resources/completion.'.$shell;
  92. if (!file_exists($completionFile)) {
  93. $supportedShells = $this->getSupportedShells();
  94. if ($output instanceof ConsoleOutputInterface) {
  95. $output = $output->getErrorOutput();
  96. }
  97. if ($shell) {
  98. $output->writeln(sprintf('<error>Detected shell "%s", which is not supported by Symfony shell completion (supported shells: "%s").</>', $shell, implode('", "', $supportedShells)));
  99. } else {
  100. $output->writeln(sprintf('<error>Shell not detected, Symfony shell completion only supports "%s").</>', implode('", "', $supportedShells)));
  101. }
  102. return 2;
  103. }
  104. $output->write(str_replace(['{{ COMMAND_NAME }}', '{{ VERSION }}'], [$commandName, CompleteCommand::COMPLETION_API_VERSION], file_get_contents($completionFile)));
  105. return 0;
  106. }
  107. private static function guessShell()
  108. {
  109. return basename($_SERVER['SHELL'] ?? '');
  110. }
  111. /**
  112. * @param string $commandName
  113. * @param \Symfony\Component\Console\Output\OutputInterface $output
  114. */
  115. private function tailDebugLog($commandName, $output)
  116. {
  117. $debugFile = sys_get_temp_dir().'/sf_'.$commandName.'.log';
  118. if (!file_exists($debugFile)) {
  119. touch($debugFile);
  120. }
  121. $process = new Process(['tail', '-f', $debugFile], null, null, null, 0);
  122. $process->run(function (string $type, string $line) use ($output): void {
  123. $output->write($line);
  124. });
  125. }
  126. /**
  127. * @return string[]
  128. */
  129. private function getSupportedShells()
  130. {
  131. if (isset($this->supportedShells)) {
  132. return $this->supportedShells;
  133. }
  134. $shells = [];
  135. foreach (new \DirectoryIterator(__DIR__.'/../Resources/') as $file) {
  136. if (strncmp($file->getBasename(), 'completion.', strlen('completion.')) === 0 && $file->isFile()) {
  137. $shells[] = $file->getExtension();
  138. }
  139. }
  140. sort($shells);
  141. return $this->supportedShells = $shells;
  142. }
  143. }