DumpCompletionCommand.php 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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. #[AsCommand(name: 'completion', description: 'Dump the shell completion script')]
  24. final class DumpCompletionCommand extends Command
  25. {
  26. private array $supportedShells;
  27. protected function configure(): void
  28. {
  29. $fullCommand = $_SERVER['PHP_SELF'];
  30. $commandName = basename($fullCommand);
  31. $fullCommand = @realpath($fullCommand) ?: $fullCommand;
  32. $shell = self::guessShell();
  33. [$rcFile, $completionFile] = match ($shell) {
  34. 'fish' => ['~/.config/fish/config.fish', "/etc/fish/completions/$commandName.fish"],
  35. 'zsh' => ['~/.zshrc', '$fpath[1]/_'.$commandName],
  36. default => ['~/.bashrc', "/etc/bash_completion.d/$commandName"],
  37. };
  38. $supportedShells = implode(', ', $this->getSupportedShells());
  39. $this
  40. ->setHelp(<<<EOH
  41. The <info>%command.name%</> command dumps the shell completion script required
  42. to use shell autocompletion (currently, {$supportedShells} completion are supported).
  43. <comment>Static installation
  44. -------------------</>
  45. Dump the script to a global completion file and restart your shell:
  46. <info>%command.full_name% {$shell} | sudo tee {$completionFile}</>
  47. Or dump the script to a local file and source it:
  48. <info>%command.full_name% {$shell} > completion.sh</>
  49. <comment># source the file whenever you use the project</>
  50. <info>source completion.sh</>
  51. <comment># or add this line at the end of your "{$rcFile}" file:</>
  52. <info>source /path/to/completion.sh</>
  53. <comment>Dynamic installation
  54. --------------------</>
  55. Add this to the end of your shell configuration file (e.g. <info>"{$rcFile}"</>):
  56. <info>eval "$({$fullCommand} completion {$shell})"</>
  57. EOH
  58. )
  59. ->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, $this->getSupportedShells(...))
  60. ->addOption('debug', null, InputOption::VALUE_NONE, 'Tail the completion debug log')
  61. ;
  62. }
  63. protected function execute(InputInterface $input, OutputInterface $output): int
  64. {
  65. $commandName = basename($_SERVER['argv'][0]);
  66. if ($input->getOption('debug')) {
  67. $this->tailDebugLog($commandName, $output);
  68. return 0;
  69. }
  70. $shell = $input->getArgument('shell') ?? self::guessShell();
  71. $completionFile = __DIR__.'/../Resources/completion.'.$shell;
  72. if (!file_exists($completionFile)) {
  73. $supportedShells = $this->getSupportedShells();
  74. if ($output instanceof ConsoleOutputInterface) {
  75. $output = $output->getErrorOutput();
  76. }
  77. if ($shell) {
  78. $output->writeln(\sprintf('<error>Detected shell "%s", which is not supported by Symfony shell completion (supported shells: "%s").</>', $shell, implode('", "', $supportedShells)));
  79. } else {
  80. $output->writeln(\sprintf('<error>Shell not detected, Symfony shell completion only supports "%s").</>', implode('", "', $supportedShells)));
  81. }
  82. return 2;
  83. }
  84. $output->write(str_replace(['{{ COMMAND_NAME }}', '{{ VERSION }}'], [$commandName, CompleteCommand::COMPLETION_API_VERSION], file_get_contents($completionFile)));
  85. return 0;
  86. }
  87. private static function guessShell(): string
  88. {
  89. return basename($_SERVER['SHELL'] ?? '');
  90. }
  91. private function tailDebugLog(string $commandName, OutputInterface $output): void
  92. {
  93. $debugFile = sys_get_temp_dir().'/sf_'.$commandName.'.log';
  94. if (!file_exists($debugFile)) {
  95. touch($debugFile);
  96. }
  97. $process = new Process(['tail', '-f', $debugFile], null, null, null, 0);
  98. $process->run(function (string $type, string $line) use ($output): void {
  99. $output->write($line);
  100. });
  101. }
  102. /**
  103. * @return string[]
  104. */
  105. private function getSupportedShells(): array
  106. {
  107. if (isset($this->supportedShells)) {
  108. return $this->supportedShells;
  109. }
  110. $shells = [];
  111. foreach (new \DirectoryIterator(__DIR__.'/../Resources/') as $file) {
  112. if (str_starts_with($file->getBasename(), 'completion.') && $file->isFile()) {
  113. $shells[] = $file->getExtension();
  114. }
  115. }
  116. sort($shells);
  117. return $this->supportedShells = $shells;
  118. }
  119. }