autocompletion.py 6.0 KB

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