Path: blob/main/test/lib/python3.9/site-packages/pip/_internal/cli/autocompletion.py
4804 views
"""Logic that powers autocompletion installed by ``pip completion``.1"""23import optparse4import os5import sys6from itertools import chain7from typing import Any, Iterable, List, Optional89from pip._internal.cli.main_parser import create_main_parser10from pip._internal.commands import commands_dict, create_command11from pip._internal.metadata import get_default_environment121314def autocomplete() -> None:15"""Entry Point for completion of main and subcommand options."""16# Don't complete if user hasn't sourced bash_completion file.17if "PIP_AUTO_COMPLETE" not in os.environ:18return19cwords = os.environ["COMP_WORDS"].split()[1:]20cword = int(os.environ["COMP_CWORD"])21try:22current = cwords[cword - 1]23except IndexError:24current = ""2526parser = create_main_parser()27subcommands = list(commands_dict)28options = []2930# subcommand31subcommand_name: Optional[str] = None32for word in cwords:33if word in subcommands:34subcommand_name = word35break36# subcommand options37if subcommand_name is not None:38# special case: 'help' subcommand has no options39if subcommand_name == "help":40sys.exit(1)41# special case: list locally installed dists for show and uninstall42should_list_installed = not current.startswith("-") and subcommand_name in [43"show",44"uninstall",45]46if should_list_installed:47env = get_default_environment()48lc = current.lower()49installed = [50dist.canonical_name51for dist in env.iter_installed_distributions(local_only=True)52if dist.canonical_name.startswith(lc)53and dist.canonical_name not in cwords[1:]54]55# if there are no dists installed, fall back to option completion56if installed:57for dist in installed:58print(dist)59sys.exit(1)6061should_list_installables = (62not current.startswith("-") and subcommand_name == "install"63)64if should_list_installables:65for path in auto_complete_paths(current, "path"):66print(path)67sys.exit(1)6869subcommand = create_command(subcommand_name)7071for opt in subcommand.parser.option_list_all:72if opt.help != optparse.SUPPRESS_HELP:73for opt_str in opt._long_opts + opt._short_opts:74options.append((opt_str, opt.nargs))7576# filter out previously specified options from available options77prev_opts = [x.split("=")[0] for x in cwords[1 : cword - 1]]78options = [(x, v) for (x, v) in options if x not in prev_opts]79# filter options by current input80options = [(k, v) for k, v in options if k.startswith(current)]81# get completion type given cwords and available subcommand options82completion_type = get_path_completion_type(83cwords,84cword,85subcommand.parser.option_list_all,86)87# get completion files and directories if ``completion_type`` is88# ``<file>``, ``<dir>`` or ``<path>``89if completion_type:90paths = auto_complete_paths(current, completion_type)91options = [(path, 0) for path in paths]92for option in options:93opt_label = option[0]94# append '=' to options which require args95if option[1] and option[0][:2] == "--":96opt_label += "="97print(opt_label)98else:99# show main parser options only when necessary100101opts = [i.option_list for i in parser.option_groups]102opts.append(parser.option_list)103flattened_opts = chain.from_iterable(opts)104if current.startswith("-"):105for opt in flattened_opts:106if opt.help != optparse.SUPPRESS_HELP:107subcommands += opt._long_opts + opt._short_opts108else:109# get completion type given cwords and all available options110completion_type = get_path_completion_type(cwords, cword, flattened_opts)111if completion_type:112subcommands = list(auto_complete_paths(current, completion_type))113114print(" ".join([x for x in subcommands if x.startswith(current)]))115sys.exit(1)116117118def get_path_completion_type(119cwords: List[str], cword: int, opts: Iterable[Any]120) -> Optional[str]:121"""Get the type of path completion (``file``, ``dir``, ``path`` or None)122123:param cwords: same as the environmental variable ``COMP_WORDS``124:param cword: same as the environmental variable ``COMP_CWORD``125:param opts: The available options to check126:return: path completion type (``file``, ``dir``, ``path`` or None)127"""128if cword < 2 or not cwords[cword - 2].startswith("-"):129return None130for opt in opts:131if opt.help == optparse.SUPPRESS_HELP:132continue133for o in str(opt).split("/"):134if cwords[cword - 2].split("=")[0] == o:135if not opt.metavar or any(136x in ("path", "file", "dir") for x in opt.metavar.split("/")137):138return opt.metavar139return None140141142def auto_complete_paths(current: str, completion_type: str) -> Iterable[str]:143"""If ``completion_type`` is ``file`` or ``path``, list all regular files144and directories starting with ``current``; otherwise only list directories145starting with ``current``.146147:param current: The word to be completed148:param completion_type: path completion type(``file``, ``path`` or ``dir``)149:return: A generator of regular files and/or directories150"""151directory, filename = os.path.split(current)152current_path = os.path.abspath(directory)153# Don't complete paths if they can't be accessed154if not os.access(current_path, os.R_OK):155return156filename = os.path.normcase(filename)157# list all files that start with ``filename``158file_list = (159x for x in os.listdir(current_path) if os.path.normcase(x).startswith(filename)160)161for f in file_list:162opt = os.path.join(current_path, f)163comp_file = os.path.normcase(os.path.join(directory, f))164# complete regular files when there is not ``<dir>`` after option165# complete directories when there is ``<file>``, ``<path>`` or166# ``<dir>``after option167if completion_type != "dir" and os.path.isfile(opt):168yield comp_file169elif os.path.isdir(opt):170yield os.path.join(comp_file, "")171172173