autocompletion.py 6.4 KB

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