m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

172 lines
6.5 KiB

6 months ago
  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. options += [
  66. (opt_str, opt.nargs) for opt_str in opt._long_opts + opt._short_opts
  67. ]
  68. # filter out previously specified options from available options
  69. prev_opts = [x.split("=")[0] for x in cwords[1 : cword - 1]]
  70. options = [(x, v) for (x, v) in options if x not in prev_opts]
  71. # filter options by current input
  72. options = [(k, v) for k, v in options if k.startswith(current)]
  73. # get completion type given cwords and available subcommand options
  74. completion_type = get_path_completion_type(
  75. cwords,
  76. cword,
  77. subcommand.parser.option_list_all,
  78. )
  79. # get completion files and directories if ``completion_type`` is
  80. # ``<file>``, ``<dir>`` or ``<path>``
  81. if completion_type:
  82. paths = auto_complete_paths(current, completion_type)
  83. options = [(path, 0) for path in paths]
  84. for option in options:
  85. opt_label = option[0]
  86. # append '=' to options which require args
  87. if option[1] and option[0][:2] == "--":
  88. opt_label += "="
  89. print(opt_label)
  90. else:
  91. # show main parser options only when necessary
  92. opts = [i.option_list for i in parser.option_groups]
  93. opts.append(parser.option_list)
  94. flattened_opts = chain.from_iterable(opts)
  95. if current.startswith("-"):
  96. for opt in flattened_opts:
  97. if opt.help != optparse.SUPPRESS_HELP:
  98. subcommands += opt._long_opts + opt._short_opts
  99. else:
  100. # get completion type given cwords and all available options
  101. completion_type = get_path_completion_type(cwords, cword, flattened_opts)
  102. if completion_type:
  103. subcommands = list(auto_complete_paths(current, completion_type))
  104. print(" ".join([x for x in subcommands if x.startswith(current)]))
  105. sys.exit(1)
  106. def get_path_completion_type(
  107. cwords: List[str], cword: int, opts: Iterable[Any]
  108. ) -> Optional[str]:
  109. """Get the type of path completion (``file``, ``dir``, ``path`` or None)
  110. :param cwords: same as the environmental variable ``COMP_WORDS``
  111. :param cword: same as the environmental variable ``COMP_CWORD``
  112. :param opts: The available options to check
  113. :return: path completion type (``file``, ``dir``, ``path`` or None)
  114. """
  115. if cword < 2 or not cwords[cword - 2].startswith("-"):
  116. return None
  117. for opt in opts:
  118. if opt.help == optparse.SUPPRESS_HELP:
  119. continue
  120. for o in str(opt).split("/"):
  121. if cwords[cword - 2].split("=")[0] == o:
  122. if not opt.metavar or any(
  123. x in ("path", "file", "dir") for x in opt.metavar.split("/")
  124. ):
  125. return opt.metavar
  126. return None
  127. def auto_complete_paths(current: str, completion_type: str) -> Iterable[str]:
  128. """If ``completion_type`` is ``file`` or ``path``, list all regular files
  129. and directories starting with ``current``; otherwise only list directories
  130. starting with ``current``.
  131. :param current: The word to be completed
  132. :param completion_type: path completion type(``file``, ``path`` or ``dir``)
  133. :return: A generator of regular files and/or directories
  134. """
  135. directory, filename = os.path.split(current)
  136. current_path = os.path.abspath(directory)
  137. # Don't complete paths if they can't be accessed
  138. if not os.access(current_path, os.R_OK):
  139. return
  140. filename = os.path.normcase(filename)
  141. # list all files that start with ``filename``
  142. file_list = (
  143. x for x in os.listdir(current_path) if os.path.normcase(x).startswith(filename)
  144. )
  145. for f in file_list:
  146. opt = os.path.join(current_path, f)
  147. comp_file = os.path.normcase(os.path.join(directory, f))
  148. # complete regular files when there is not ``<dir>`` after option
  149. # complete directories when there is ``<file>``, ``<path>`` or
  150. # ``<dir>``after option
  151. if completion_type != "dir" and os.path.isfile(opt):
  152. yield comp_file
  153. elif os.path.isdir(opt):
  154. yield os.path.join(comp_file, "")