autocompletion.py 6.5 KB

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