You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

autocompletion.py 5.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. """Logic that powers autocompletion installed by ``pip completion``.
  2. """
  3. import optparse
  4. import os
  5. import sys
  6. from pip._internal.cli.main_parser import create_main_parser
  7. from pip._internal.commands import commands_dict, get_summaries
  8. from pip._internal.utils.misc import get_installed_distributions
  9. def autocomplete():
  10. """Entry Point for completion of main and subcommand options.
  11. """
  12. # Don't complete if user hasn't sourced bash_completion file.
  13. if 'PIP_AUTO_COMPLETE' not in os.environ:
  14. return
  15. cwords = os.environ['COMP_WORDS'].split()[1:]
  16. cword = int(os.environ['COMP_CWORD'])
  17. try:
  18. current = cwords[cword - 1]
  19. except IndexError:
  20. current = ''
  21. subcommands = [cmd for cmd, summary in get_summaries()]
  22. options = []
  23. # subcommand
  24. try:
  25. subcommand_name = [w for w in cwords if w in subcommands][0]
  26. except IndexError:
  27. subcommand_name = None
  28. parser = create_main_parser()
  29. # subcommand options
  30. if subcommand_name:
  31. # special case: 'help' subcommand has no options
  32. if subcommand_name == 'help':
  33. sys.exit(1)
  34. # special case: list locally installed dists for show and uninstall
  35. should_list_installed = (
  36. subcommand_name in ['show', 'uninstall'] and
  37. not current.startswith('-')
  38. )
  39. if should_list_installed:
  40. installed = []
  41. lc = current.lower()
  42. for dist in get_installed_distributions(local_only=True):
  43. if dist.key.startswith(lc) and dist.key not in cwords[1:]:
  44. installed.append(dist.key)
  45. # if there are no dists installed, fall back to option completion
  46. if installed:
  47. for dist in installed:
  48. print(dist)
  49. sys.exit(1)
  50. subcommand = commands_dict[subcommand_name]()
  51. for opt in subcommand.parser.option_list_all:
  52. if opt.help != optparse.SUPPRESS_HELP:
  53. for opt_str in opt._long_opts + opt._short_opts:
  54. options.append((opt_str, opt.nargs))
  55. # filter out previously specified options from available options
  56. prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]]
  57. options = [(x, v) for (x, v) in options if x not in prev_opts]
  58. # filter options by current input
  59. options = [(k, v) for k, v in options if k.startswith(current)]
  60. # get completion type given cwords and available subcommand options
  61. completion_type = get_path_completion_type(
  62. cwords, cword, subcommand.parser.option_list_all,
  63. )
  64. # get completion files and directories if ``completion_type`` is
  65. # ``<file>``, ``<dir>`` or ``<path>``
  66. if completion_type:
  67. options = auto_complete_paths(current, completion_type)
  68. options = ((opt, 0) for opt in options)
  69. for option in options:
  70. opt_label = option[0]
  71. # append '=' to options which require args
  72. if option[1] and option[0][:2] == "--":
  73. opt_label += '='
  74. print(opt_label)
  75. else:
  76. # show main parser options only when necessary
  77. opts = [i.option_list for i in parser.option_groups]
  78. opts.append(parser.option_list)
  79. opts = (o for it in opts for o in it)
  80. if current.startswith('-'):
  81. for opt in opts:
  82. if opt.help != optparse.SUPPRESS_HELP:
  83. subcommands += opt._long_opts + opt._short_opts
  84. else:
  85. # get completion type given cwords and all available options
  86. completion_type = get_path_completion_type(cwords, cword, opts)
  87. if completion_type:
  88. subcommands = auto_complete_paths(current, completion_type)
  89. print(' '.join([x for x in subcommands if x.startswith(current)]))
  90. sys.exit(1)
  91. def get_path_completion_type(cwords, cword, opts):
  92. """Get the type of path completion (``file``, ``dir``, ``path`` or None)
  93. :param cwords: same as the environmental variable ``COMP_WORDS``
  94. :param cword: same as the environmental variable ``COMP_CWORD``
  95. :param opts: The available options to check
  96. :return: path completion type (``file``, ``dir``, ``path`` or None)
  97. """
  98. if cword < 2 or not cwords[cword - 2].startswith('-'):
  99. return
  100. for opt in opts:
  101. if opt.help == optparse.SUPPRESS_HELP:
  102. continue
  103. for o in str(opt).split('/'):
  104. if cwords[cword - 2].split('=')[0] == o:
  105. if not opt.metavar or any(
  106. x in ('path', 'file', 'dir')
  107. for x in opt.metavar.split('/')):
  108. return opt.metavar
  109. def auto_complete_paths(current, completion_type):
  110. """If ``completion_type`` is ``file`` or ``path``, list all regular files
  111. and directories starting with ``current``; otherwise only list directories
  112. starting with ``current``.
  113. :param current: The word to be completed
  114. :param completion_type: path completion type(`file`, `path` or `dir`)i
  115. :return: A generator of regular files and/or directories
  116. """
  117. directory, filename = os.path.split(current)
  118. current_path = os.path.abspath(directory)
  119. # Don't complete paths if they can't be accessed
  120. if not os.access(current_path, os.R_OK):
  121. return
  122. filename = os.path.normcase(filename)
  123. # list all files that start with ``filename``
  124. file_list = (x for x in os.listdir(current_path)
  125. if os.path.normcase(x).startswith(filename))
  126. for f in file_list:
  127. opt = os.path.join(current_path, f)
  128. comp_file = os.path.normcase(os.path.join(directory, f))
  129. # complete regular files when there is not ``<dir>`` after option
  130. # complete directories when there is ``<file>``, ``<path>`` or
  131. # ``<dir>``after option
  132. if completion_type != 'dir' and os.path.isfile(opt):
  133. yield comp_file
  134. elif os.path.isdir(opt):
  135. yield os.path.join(comp_file, '')