autocompletion.py 7.0 KB

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