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