autocompletion.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. subcommand = create_command(subcommand_name)
  56. for opt in subcommand.parser.option_list_all:
  57. if opt.help != optparse.SUPPRESS_HELP:
  58. for opt_str in opt._long_opts + opt._short_opts:
  59. options.append((opt_str, opt.nargs))
  60. # filter out previously specified options from available options
  61. prev_opts = [x.split("=")[0] for x in cwords[1 : cword - 1]]
  62. options = [(x, v) for (x, v) in options if x not in prev_opts]
  63. # filter options by current input
  64. options = [(k, v) for k, v in options if k.startswith(current)]
  65. # get completion type given cwords and available subcommand options
  66. completion_type = get_path_completion_type(
  67. cwords,
  68. cword,
  69. subcommand.parser.option_list_all,
  70. )
  71. # get completion files and directories if ``completion_type`` is
  72. # ``<file>``, ``<dir>`` or ``<path>``
  73. if completion_type:
  74. paths = auto_complete_paths(current, completion_type)
  75. options = [(path, 0) for path in paths]
  76. for option in options:
  77. opt_label = option[0]
  78. # append '=' to options which require args
  79. if option[1] and option[0][:2] == "--":
  80. opt_label += "="
  81. print(opt_label)
  82. else:
  83. # show main parser options only when necessary
  84. opts = [i.option_list for i in parser.option_groups]
  85. opts.append(parser.option_list)
  86. flattened_opts = chain.from_iterable(opts)
  87. if current.startswith("-"):
  88. for opt in flattened_opts:
  89. if opt.help != optparse.SUPPRESS_HELP:
  90. subcommands += opt._long_opts + opt._short_opts
  91. else:
  92. # get completion type given cwords and all available options
  93. completion_type = get_path_completion_type(cwords, cword, flattened_opts)
  94. if completion_type:
  95. subcommands = list(auto_complete_paths(current, completion_type))
  96. print(" ".join([x for x in subcommands if x.startswith(current)]))
  97. sys.exit(1)
  98. def get_path_completion_type(
  99. cwords: List[str], cword: int, opts: Iterable[Any]
  100. ) -> 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") for x in opt.metavar.split("/")
  116. ):
  117. return opt.metavar
  118. return None
  119. def auto_complete_paths(current: str, completion_type: str) -> Iterable[str]:
  120. """If ``completion_type`` is ``file`` or ``path``, list all regular files
  121. and directories starting with ``current``; otherwise only list directories
  122. starting with ``current``.
  123. :param current: The word to be completed
  124. :param completion_type: path completion type(`file`, `path` or `dir`)i
  125. :return: A generator of regular files and/or directories
  126. """
  127. directory, filename = os.path.split(current)
  128. current_path = os.path.abspath(directory)
  129. # Don't complete paths if they can't be accessed
  130. if not os.access(current_path, os.R_OK):
  131. return
  132. filename = os.path.normcase(filename)
  133. # list all files that start with ``filename``
  134. file_list = (
  135. x for x in os.listdir(current_path) if os.path.normcase(x).startswith(filename)
  136. )
  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, "")