completion.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import sys
  2. from pip.basecommand import Command
  3. BASE_COMPLETION = """
  4. # pip %(shell)s completion start%(script)s# pip %(shell)s completion end
  5. """
  6. COMPLETION_SCRIPTS = {
  7. 'bash': """
  8. _pip_completion()
  9. {
  10. COMPREPLY=( $( COMP_WORDS="${COMP_WORDS[*]}" \\
  11. COMP_CWORD=$COMP_CWORD \\
  12. PIP_AUTO_COMPLETE=1 $1 ) )
  13. }
  14. complete -o default -F _pip_completion pip
  15. """, 'zsh': """
  16. function _pip_completion {
  17. local words cword
  18. read -Ac words
  19. read -cn cword
  20. reply=( $( COMP_WORDS="$words[*]" \\
  21. COMP_CWORD=$(( cword-1 )) \\
  22. PIP_AUTO_COMPLETE=1 $words[1] ) )
  23. }
  24. compctl -K _pip_completion pip
  25. """}
  26. class CompletionCommand(Command):
  27. """A helper command to be used for command completion."""
  28. name = 'completion'
  29. summary = 'A helper command to be used for command completion'
  30. hidden = True
  31. def __init__(self, *args, **kw):
  32. super(CompletionCommand, self).__init__(*args, **kw)
  33. self.parser.add_option(
  34. '--bash', '-b',
  35. action='store_const',
  36. const='bash',
  37. dest='shell',
  38. help='Emit completion code for bash')
  39. self.parser.add_option(
  40. '--zsh', '-z',
  41. action='store_const',
  42. const='zsh',
  43. dest='shell',
  44. help='Emit completion code for zsh')
  45. def run(self, options, args):
  46. """Prints the completion code of the given shell"""
  47. shells = COMPLETION_SCRIPTS.keys()
  48. shell_options = ['--' + shell for shell in sorted(shells)]
  49. if options.shell in shells:
  50. script = COMPLETION_SCRIPTS.get(options.shell, '')
  51. print(BASE_COMPLETION % {'script': script, 'shell': options.shell})
  52. else:
  53. sys.stderr.write('ERROR: You must pass %s\n' % ' or '.join(shell_options))