completion.py 2.5 KB

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