autocompletion.py 6.2 KB

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