completion.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. from __future__ import absolute_import
  2. import sys
  3. import textwrap
  4. from pip._internal.basecommand import Command
  5. from pip._internal.utils.misc import get_prog
  6. BASE_COMPLETION = """
  7. # pip %(shell)s completion start%(script)s# pip %(shell)s completion end
  8. """
  9. COMPLETION_SCRIPTS = {
  10. 'bash': """
  11. _pip_completion()
  12. {
  13. COMPREPLY=( $( COMP_WORDS="${COMP_WORDS[*]}" \\
  14. COMP_CWORD=$COMP_CWORD \\
  15. PIP_AUTO_COMPLETE=1 $1 ) )
  16. }
  17. complete -o default -F _pip_completion %(prog)s
  18. """,
  19. 'zsh': """
  20. function _pip_completion {
  21. local words cword
  22. read -Ac words
  23. read -cn cword
  24. reply=( $( COMP_WORDS="$words[*]" \\
  25. COMP_CWORD=$(( cword-1 )) \\
  26. PIP_AUTO_COMPLETE=1 $words[1] ) )
  27. }
  28. compctl -K _pip_completion %(prog)s
  29. """,
  30. 'fish': """
  31. function __fish_complete_pip
  32. set -lx COMP_WORDS (commandline -o) ""
  33. set -lx COMP_CWORD ( \\
  34. math (contains -i -- (commandline -t) $COMP_WORDS)-1 \\
  35. )
  36. set -lx PIP_AUTO_COMPLETE 1
  37. string split \\ -- (eval $COMP_WORDS[1])
  38. end
  39. complete -fa "(__fish_complete_pip)" -c %(prog)s
  40. """,
  41. }
  42. class CompletionCommand(Command):
  43. """A helper command to be used for command completion."""
  44. name = 'completion'
  45. summary = 'A helper command used for command completion.'
  46. ignore_require_venv = True
  47. def __init__(self, *args, **kw):
  48. super(CompletionCommand, self).__init__(*args, **kw)
  49. cmd_opts = self.cmd_opts
  50. cmd_opts.add_option(
  51. '--bash', '-b',
  52. action='store_const',
  53. const='bash',
  54. dest='shell',
  55. help='Emit completion code for bash')
  56. cmd_opts.add_option(
  57. '--zsh', '-z',
  58. action='store_const',
  59. const='zsh',
  60. dest='shell',
  61. help='Emit completion code for zsh')
  62. cmd_opts.add_option(
  63. '--fish', '-f',
  64. action='store_const',
  65. const='fish',
  66. dest='shell',
  67. help='Emit completion code for fish')
  68. self.parser.insert_option_group(0, cmd_opts)
  69. def run(self, options, args):
  70. """Prints the completion code of the given shell"""
  71. shells = COMPLETION_SCRIPTS.keys()
  72. shell_options = ['--' + shell for shell in sorted(shells)]
  73. if options.shell in shells:
  74. script = textwrap.dedent(
  75. COMPLETION_SCRIPTS.get(options.shell, '') % {
  76. 'prog': get_prog(),
  77. }
  78. )
  79. print(BASE_COMPLETION % {'script': script, 'shell': options.shell})
  80. else:
  81. sys.stderr.write(
  82. 'ERROR: You must pass %s\n' % ' or '.join(shell_options)
  83. )