finders.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. # Copyright 2012-2023, Andrey Kislyuk and argcomplete contributors. Licensed under the terms of the
  2. # `Apache License, Version 2.0 <http://www.apache.org/licenses/LICENSE-2.0>`_. Distribution of the LICENSE and NOTICE
  3. # files with source copies of this package and derivative works is **REQUIRED** as specified by the Apache License.
  4. # See https://github.com/kislyuk/argcomplete for more info.
  5. import argparse
  6. import os
  7. import sys
  8. from collections.abc import Mapping
  9. from typing import Callable, Dict, List, Optional, Sequence, TextIO, Union
  10. from . import io as _io
  11. from .completers import BaseCompleter, ChoicesCompleter, FilesCompleter, SuppressCompleter
  12. from .io import debug, mute_stderr
  13. from .lexers import split_line
  14. from .packages._argparse import IntrospectiveArgumentParser, action_is_greedy, action_is_open, action_is_satisfied
  15. safe_actions = {
  16. argparse._StoreAction,
  17. argparse._StoreConstAction,
  18. argparse._StoreTrueAction,
  19. argparse._StoreFalseAction,
  20. argparse._AppendAction,
  21. argparse._AppendConstAction,
  22. argparse._CountAction,
  23. }
  24. def default_validator(completion, prefix):
  25. return completion.startswith(prefix)
  26. class CompletionFinder(object):
  27. """
  28. Inherit from this class if you wish to override any of the stages below. Otherwise, use
  29. ``argcomplete.autocomplete()`` directly (it's a convenience instance of this class). It has the same signature as
  30. :meth:`CompletionFinder.__call__()`.
  31. """
  32. def __init__(
  33. self,
  34. argument_parser=None,
  35. always_complete_options=True,
  36. exclude=None,
  37. validator=None,
  38. print_suppressed=False,
  39. default_completer=FilesCompleter(),
  40. append_space=None,
  41. ):
  42. self._parser = argument_parser
  43. self.always_complete_options = always_complete_options
  44. self.exclude = exclude
  45. if validator is None:
  46. validator = default_validator
  47. self.validator = validator
  48. self.print_suppressed = print_suppressed
  49. self.completing = False
  50. self._display_completions: Dict[str, str] = {}
  51. self.default_completer = default_completer
  52. if append_space is None:
  53. append_space = os.environ.get("_ARGCOMPLETE_SUPPRESS_SPACE") != "1"
  54. self.append_space = append_space
  55. def __call__(
  56. self,
  57. argument_parser: argparse.ArgumentParser,
  58. always_complete_options: Union[bool, str] = True,
  59. exit_method: Callable = os._exit,
  60. output_stream: Optional[TextIO] = None,
  61. exclude: Optional[Sequence[str]] = None,
  62. validator: Optional[Callable] = None,
  63. print_suppressed: bool = False,
  64. append_space: Optional[bool] = None,
  65. default_completer: BaseCompleter = FilesCompleter(),
  66. ) -> None:
  67. """
  68. :param argument_parser: The argument parser to autocomplete on
  69. :param always_complete_options:
  70. Controls the autocompletion of option strings if an option string opening character (normally ``-``) has not
  71. been entered. If ``True`` (default), both short (``-x``) and long (``--x``) option strings will be
  72. suggested. If ``False``, no option strings will be suggested. If ``long``, long options and short options
  73. with no long variant will be suggested. If ``short``, short options and long options with no short variant
  74. will be suggested.
  75. :param exit_method:
  76. Method used to stop the program after printing completions. Defaults to :meth:`os._exit`. If you want to
  77. perform a normal exit that calls exit handlers, use :meth:`sys.exit`.
  78. :param exclude: List of strings representing options to be omitted from autocompletion
  79. :param validator:
  80. Function to filter all completions through before returning (called with two string arguments, completion
  81. and prefix; return value is evaluated as a boolean)
  82. :param print_suppressed:
  83. Whether or not to autocomplete options that have the ``help=argparse.SUPPRESS`` keyword argument set.
  84. :param append_space:
  85. Whether to append a space to unique matches. The default is ``True``.
  86. .. note::
  87. If you are not subclassing CompletionFinder to override its behaviors,
  88. use :meth:`argcomplete.autocomplete()` directly. It has the same signature as this method.
  89. Produces tab completions for ``argument_parser``. See module docs for more info.
  90. Argcomplete only executes actions if their class is known not to have side effects. Custom action classes can be
  91. added to argcomplete.safe_actions, if their values are wanted in the ``parsed_args`` completer argument, or
  92. their execution is otherwise desirable.
  93. """
  94. self.__init__( # type: ignore
  95. argument_parser,
  96. always_complete_options=always_complete_options,
  97. exclude=exclude,
  98. validator=validator,
  99. print_suppressed=print_suppressed,
  100. append_space=append_space,
  101. default_completer=default_completer,
  102. )
  103. if "_ARGCOMPLETE" not in os.environ:
  104. # not an argument completion invocation
  105. return
  106. self._init_debug_stream()
  107. if output_stream is None:
  108. filename = os.environ.get("_ARGCOMPLETE_STDOUT_FILENAME")
  109. if filename is not None:
  110. debug("Using output file {}".format(filename))
  111. output_stream = open(filename, "w")
  112. if output_stream is None:
  113. try:
  114. output_stream = os.fdopen(8, "w")
  115. except Exception:
  116. debug("Unable to open fd 8 for writing, quitting")
  117. exit_method(1)
  118. assert output_stream is not None
  119. ifs = os.environ.get("_ARGCOMPLETE_IFS", "\013")
  120. if len(ifs) != 1:
  121. debug("Invalid value for IFS, quitting [{v}]".format(v=ifs))
  122. exit_method(1)
  123. dfs = os.environ.get("_ARGCOMPLETE_DFS")
  124. if dfs and len(dfs) != 1:
  125. debug("Invalid value for DFS, quitting [{v}]".format(v=dfs))
  126. exit_method(1)
  127. comp_line = os.environ["COMP_LINE"]
  128. comp_point = int(os.environ["COMP_POINT"])
  129. cword_prequote, cword_prefix, cword_suffix, comp_words, last_wordbreak_pos = split_line(comp_line, comp_point)
  130. # _ARGCOMPLETE is set by the shell script to tell us where comp_words
  131. # should start, based on what we're completing.
  132. # 1: <script> [args]
  133. # 2: python <script> [args]
  134. # 3: python -m <module> [args]
  135. start = int(os.environ["_ARGCOMPLETE"]) - 1
  136. comp_words = comp_words[start:]
  137. if cword_prefix and cword_prefix[0] in self._parser.prefix_chars and "=" in cword_prefix:
  138. # Special case for when the current word is "--optional=PARTIAL_VALUE". Give the optional to the parser.
  139. comp_words.append(cword_prefix.split("=", 1)[0])
  140. debug(
  141. "\nLINE: {!r}".format(comp_line),
  142. "\nPOINT: {!r}".format(comp_point),
  143. "\nPREQUOTE: {!r}".format(cword_prequote),
  144. "\nPREFIX: {!r}".format(cword_prefix),
  145. "\nSUFFIX: {!r}".format(cword_suffix),
  146. "\nWORDS:",
  147. comp_words,
  148. )
  149. completions = self._get_completions(comp_words, cword_prefix, cword_prequote, last_wordbreak_pos)
  150. if dfs:
  151. display_completions = {
  152. key: value.replace(ifs, " ") if value else "" for key, value in self._display_completions.items()
  153. }
  154. completions = [dfs.join((key, display_completions.get(key) or "")) for key in completions]
  155. if os.environ.get("_ARGCOMPLETE_SHELL") == "zsh":
  156. completions = [f"{c}:{self._display_completions.get(c)}" for c in completions]
  157. debug("\nReturning completions:", completions)
  158. output_stream.write(ifs.join(completions))
  159. output_stream.flush()
  160. _io.debug_stream.flush()
  161. exit_method(0)
  162. def _init_debug_stream(self):
  163. """Initialize debug output stream
  164. By default, writes to file descriptor 9, or stderr if that fails.
  165. This can be overridden by derived classes, for example to avoid
  166. clashes with file descriptors being used elsewhere (such as in pytest).
  167. """
  168. try:
  169. _io.debug_stream = os.fdopen(9, "w")
  170. except Exception:
  171. _io.debug_stream = sys.stderr
  172. debug()
  173. def _get_completions(self, comp_words, cword_prefix, cword_prequote, last_wordbreak_pos):
  174. active_parsers = self._patch_argument_parser()
  175. parsed_args = argparse.Namespace()
  176. self.completing = True
  177. try:
  178. debug("invoking parser with", comp_words[1:])
  179. with mute_stderr():
  180. a = self._parser.parse_known_args(comp_words[1:], namespace=parsed_args)
  181. debug("parsed args:", a)
  182. except BaseException as e:
  183. debug("\nexception", type(e), str(e), "while parsing args")
  184. self.completing = False
  185. if "--" in comp_words:
  186. self.always_complete_options = False
  187. completions = self.collect_completions(active_parsers, parsed_args, cword_prefix)
  188. completions = self.filter_completions(completions)
  189. completions = self.quote_completions(completions, cword_prequote, last_wordbreak_pos)
  190. return completions
  191. def _patch_argument_parser(self):
  192. """
  193. Since argparse doesn't support much introspection, we monkey-patch it to replace the parse_known_args method and
  194. all actions with hooks that tell us which action was last taken or about to be taken, and let us have the parser
  195. figure out which subparsers need to be activated (then recursively monkey-patch those).
  196. We save all active ArgumentParsers to extract all their possible option names later.
  197. """
  198. self.active_parsers: List[argparse.ArgumentParser] = []
  199. self.visited_positionals: List[argparse.Action] = []
  200. completer = self
  201. def patch(parser):
  202. completer.visited_positionals.append(parser)
  203. completer.active_parsers.append(parser)
  204. if isinstance(parser, IntrospectiveArgumentParser):
  205. return
  206. classname = "MonkeyPatchedIntrospectiveArgumentParser"
  207. parser.__class__ = type(classname, (IntrospectiveArgumentParser, parser.__class__), {})
  208. for action in parser._actions:
  209. if hasattr(action, "_orig_class"):
  210. continue
  211. # TODO: accomplish this with super
  212. class IntrospectAction(action.__class__): # type: ignore
  213. def __call__(self, parser, namespace, values, option_string=None):
  214. debug("Action stub called on", self)
  215. debug("\targs:", parser, namespace, values, option_string)
  216. debug("\torig class:", self._orig_class)
  217. debug("\torig callable:", self._orig_callable)
  218. if not completer.completing:
  219. self._orig_callable(parser, namespace, values, option_string=option_string)
  220. elif issubclass(self._orig_class, argparse._SubParsersAction):
  221. debug("orig class is a subparsers action: patching and running it")
  222. patch(self._name_parser_map[values[0]])
  223. self._orig_callable(parser, namespace, values, option_string=option_string)
  224. elif self._orig_class in safe_actions:
  225. if not self.option_strings:
  226. completer.visited_positionals.append(self)
  227. self._orig_callable(parser, namespace, values, option_string=option_string)
  228. action._orig_class = action.__class__
  229. action._orig_callable = action.__call__
  230. action.__class__ = IntrospectAction
  231. patch(self._parser)
  232. debug("Active parsers:", self.active_parsers)
  233. debug("Visited positionals:", self.visited_positionals)
  234. return self.active_parsers
  235. def _get_subparser_completions(self, parser, cword_prefix):
  236. aliases_by_parser: Dict[argparse.ArgumentParser, List[str]] = {}
  237. for key in parser.choices.keys():
  238. p = parser.choices[key]
  239. aliases_by_parser.setdefault(p, []).append(key)
  240. for action in parser._get_subactions():
  241. for alias in aliases_by_parser[parser.choices[action.dest]]:
  242. if alias.startswith(cword_prefix):
  243. self._display_completions[alias] = action.help or ""
  244. completions = [subcmd for subcmd in parser.choices.keys() if subcmd.startswith(cword_prefix)]
  245. return completions
  246. def _include_options(self, action, cword_prefix):
  247. if len(cword_prefix) > 0 or self.always_complete_options is True:
  248. return [opt for opt in action.option_strings if opt.startswith(cword_prefix)]
  249. long_opts = [opt for opt in action.option_strings if len(opt) > 2]
  250. short_opts = [opt for opt in action.option_strings if len(opt) <= 2]
  251. if self.always_complete_options == "long":
  252. return long_opts if long_opts else short_opts
  253. elif self.always_complete_options == "short":
  254. return short_opts if short_opts else long_opts
  255. return []
  256. def _get_option_completions(self, parser, cword_prefix):
  257. for action in parser._actions:
  258. if action.option_strings:
  259. for option_string in action.option_strings:
  260. if option_string.startswith(cword_prefix):
  261. self._display_completions[option_string] = action.help or ""
  262. option_completions = []
  263. for action in parser._actions:
  264. if not self.print_suppressed:
  265. completer = getattr(action, "completer", None)
  266. if isinstance(completer, SuppressCompleter) and completer.suppress():
  267. continue
  268. if action.help == argparse.SUPPRESS:
  269. continue
  270. if not self._action_allowed(action, parser):
  271. continue
  272. if not isinstance(action, argparse._SubParsersAction):
  273. option_completions += self._include_options(action, cword_prefix)
  274. return option_completions
  275. @staticmethod
  276. def _action_allowed(action, parser):
  277. # Logic adapted from take_action in ArgumentParser._parse_known_args
  278. # (members are saved by vendor._argparse.IntrospectiveArgumentParser)
  279. for conflict_action in parser._action_conflicts.get(action, []):
  280. if conflict_action in parser._seen_non_default_actions:
  281. return False
  282. return True
  283. def _complete_active_option(self, parser, next_positional, cword_prefix, parsed_args, completions):
  284. debug("Active actions (L={l}): {a}".format(l=len(parser.active_actions), a=parser.active_actions))
  285. isoptional = cword_prefix and cword_prefix[0] in parser.prefix_chars
  286. optional_prefix = ""
  287. greedy_actions = [x for x in parser.active_actions if action_is_greedy(x, isoptional)]
  288. if greedy_actions:
  289. assert len(greedy_actions) == 1, "expect at most 1 greedy action"
  290. # This means the action will fail to parse if the word under the cursor is not given
  291. # to it, so give it exclusive control over completions (flush previous completions)
  292. debug("Resetting completions because", greedy_actions[0], "must consume the next argument")
  293. self._display_completions = {}
  294. completions = []
  295. elif isoptional:
  296. if "=" in cword_prefix:
  297. # Special case for when the current word is "--optional=PARTIAL_VALUE".
  298. # The completer runs on PARTIAL_VALUE. The prefix is added back to the completions
  299. # (and chopped back off later in quote_completions() by the COMP_WORDBREAKS logic).
  300. optional_prefix, _, cword_prefix = cword_prefix.partition("=")
  301. else:
  302. # Only run completers if current word does not start with - (is not an optional)
  303. return completions
  304. complete_remaining_positionals = False
  305. # Use the single greedy action (if there is one) or all active actions.
  306. for active_action in greedy_actions or parser.active_actions:
  307. if not active_action.option_strings: # action is a positional
  308. if action_is_open(active_action):
  309. # Any positional arguments after this may slide down into this action
  310. # if more arguments are added (since the user may not be done yet),
  311. # so it is extremely difficult to tell which completers to run.
  312. # Running all remaining completers will probably show more than the user wants
  313. # but it also guarantees we won't miss anything.
  314. complete_remaining_positionals = True
  315. if not complete_remaining_positionals:
  316. if action_is_satisfied(active_action) and not action_is_open(active_action):
  317. debug("Skipping", active_action)
  318. continue
  319. debug("Activating completion for", active_action, active_action._orig_class)
  320. # completer = getattr(active_action, "completer", DefaultCompleter())
  321. completer = getattr(active_action, "completer", None)
  322. if completer is None:
  323. if active_action.choices is not None and not isinstance(active_action, argparse._SubParsersAction):
  324. completer = ChoicesCompleter(active_action.choices)
  325. elif not isinstance(active_action, argparse._SubParsersAction):
  326. completer = self.default_completer
  327. if completer:
  328. if isinstance(completer, SuppressCompleter) and completer.suppress():
  329. continue
  330. if callable(completer):
  331. completer_output = completer(
  332. prefix=cword_prefix, action=active_action, parser=parser, parsed_args=parsed_args
  333. )
  334. if isinstance(completer_output, Mapping):
  335. for completion, description in completer_output.items():
  336. if self.validator(completion, cword_prefix):
  337. completions.append(completion)
  338. self._display_completions[completion] = description
  339. else:
  340. for completion in completer_output:
  341. if self.validator(completion, cword_prefix):
  342. completions.append(completion)
  343. if isinstance(completer, ChoicesCompleter):
  344. self._display_completions[completion] = active_action.help or ""
  345. else:
  346. self._display_completions[completion] = ""
  347. else:
  348. debug("Completer is not callable, trying the readline completer protocol instead")
  349. for i in range(9999):
  350. next_completion = completer.complete(cword_prefix, i) # type: ignore
  351. if next_completion is None:
  352. break
  353. if self.validator(next_completion, cword_prefix):
  354. self._display_completions[next_completion] = ""
  355. completions.append(next_completion)
  356. if optional_prefix:
  357. completions = [optional_prefix + "=" + completion for completion in completions]
  358. debug("Completions:", completions)
  359. return completions
  360. def collect_completions(
  361. self, active_parsers: List[argparse.ArgumentParser], parsed_args: argparse.Namespace, cword_prefix: str
  362. ) -> List[str]:
  363. """
  364. Visits the active parsers and their actions, executes their completers or introspects them to collect their
  365. option strings. Returns the resulting completions as a list of strings.
  366. This method is exposed for overriding in subclasses; there is no need to use it directly.
  367. """
  368. completions: List[str] = []
  369. debug("all active parsers:", active_parsers)
  370. active_parser = active_parsers[-1]
  371. debug("active_parser:", active_parser)
  372. if self.always_complete_options or (len(cword_prefix) > 0 and cword_prefix[0] in active_parser.prefix_chars):
  373. completions += self._get_option_completions(active_parser, cword_prefix)
  374. debug("optional options:", completions)
  375. next_positional = self._get_next_positional()
  376. debug("next_positional:", next_positional)
  377. if isinstance(next_positional, argparse._SubParsersAction):
  378. completions += self._get_subparser_completions(next_positional, cword_prefix)
  379. completions = self._complete_active_option(
  380. active_parser, next_positional, cword_prefix, parsed_args, completions
  381. )
  382. debug("active options:", completions)
  383. debug("display completions:", self._display_completions)
  384. return completions
  385. def _get_next_positional(self):
  386. """
  387. Get the next positional action if it exists.
  388. """
  389. active_parser = self.active_parsers[-1]
  390. last_positional = self.visited_positionals[-1]
  391. all_positionals = active_parser._get_positional_actions()
  392. if not all_positionals:
  393. return None
  394. if active_parser == last_positional:
  395. return all_positionals[0]
  396. i = 0
  397. for i in range(len(all_positionals)):
  398. if all_positionals[i] == last_positional:
  399. break
  400. if i + 1 < len(all_positionals):
  401. return all_positionals[i + 1]
  402. return None
  403. def filter_completions(self, completions: List[str]) -> List[str]:
  404. """
  405. De-duplicates completions and excludes those specified by ``exclude``.
  406. Returns the filtered completions as a list.
  407. This method is exposed for overriding in subclasses; there is no need to use it directly.
  408. """
  409. filtered_completions = []
  410. for completion in completions:
  411. if self.exclude is not None:
  412. if completion in self.exclude:
  413. continue
  414. if completion not in filtered_completions:
  415. filtered_completions.append(completion)
  416. return filtered_completions
  417. def quote_completions(
  418. self, completions: List[str], cword_prequote: str, last_wordbreak_pos: Optional[int]
  419. ) -> List[str]:
  420. """
  421. If the word under the cursor started with a quote (as indicated by a nonempty ``cword_prequote``), escapes
  422. occurrences of that quote character in the completions, and adds the quote to the beginning of each completion.
  423. Otherwise, escapes all characters that bash splits words on (``COMP_WORDBREAKS``), and removes portions of
  424. completions before the first colon if (``COMP_WORDBREAKS``) contains a colon.
  425. If there is only one completion, and it doesn't end with a **continuation character** (``/``, ``:``, or ``=``),
  426. adds a space after the completion.
  427. This method is exposed for overriding in subclasses; there is no need to use it directly.
  428. """
  429. special_chars = "\\"
  430. # If the word under the cursor was quoted, escape the quote char.
  431. # Otherwise, escape all special characters and specially handle all COMP_WORDBREAKS chars.
  432. if cword_prequote == "":
  433. # Bash mangles completions which contain characters in COMP_WORDBREAKS.
  434. # This workaround has the same effect as __ltrim_colon_completions in bash_completion
  435. # (extended to characters other than the colon).
  436. if last_wordbreak_pos:
  437. completions = [c[last_wordbreak_pos + 1 :] for c in completions]
  438. special_chars += "();<>|&!`$* \t\n\"'"
  439. elif cword_prequote == '"':
  440. special_chars += '"`$!'
  441. if os.environ.get("_ARGCOMPLETE_SHELL") in ("tcsh", "fish"):
  442. # tcsh and fish escapes special characters itself.
  443. special_chars = ""
  444. elif cword_prequote == "'":
  445. # Nothing can be escaped in single quotes, so we need to close
  446. # the string, escape the single quote, then open a new string.
  447. special_chars = ""
  448. completions = [c.replace("'", r"'\''") for c in completions]
  449. # PowerShell uses ` as escape character.
  450. if os.environ.get("_ARGCOMPLETE_SHELL") == "powershell":
  451. escape_char = '`'
  452. special_chars = special_chars.replace('`', '')
  453. else:
  454. escape_char = "\\"
  455. if os.environ.get("_ARGCOMPLETE_SHELL") == "zsh":
  456. # zsh uses colon as a separator between a completion and its description.
  457. special_chars += ":"
  458. escaped_completions = []
  459. for completion in completions:
  460. escaped_completion = completion
  461. for char in special_chars:
  462. escaped_completion = escaped_completion.replace(char, escape_char + char)
  463. escaped_completions.append(escaped_completion)
  464. if completion in self._display_completions:
  465. self._display_completions[escaped_completion] = self._display_completions[completion]
  466. if self.append_space:
  467. # Similar functionality in bash was previously turned off by supplying the "-o nospace" option to complete.
  468. # Now it is conditionally disabled using "compopt -o nospace" if the match ends in a continuation character.
  469. # This code is retained for environments where this isn't done natively.
  470. continuation_chars = "=/:"
  471. if len(escaped_completions) == 1 and escaped_completions[0][-1] not in continuation_chars:
  472. if cword_prequote == "":
  473. escaped_completions[0] += " "
  474. return escaped_completions
  475. def rl_complete(self, text, state):
  476. """
  477. Alternate entry point for using the argcomplete completer in a readline-based REPL. See also
  478. `rlcompleter <https://docs.python.org/3/library/rlcompleter.html#completer-objects>`_.
  479. Usage:
  480. .. code-block:: python
  481. import argcomplete, argparse, readline
  482. parser = argparse.ArgumentParser()
  483. ...
  484. completer = argcomplete.CompletionFinder(parser)
  485. readline.set_completer_delims("")
  486. readline.set_completer(completer.rl_complete)
  487. readline.parse_and_bind("tab: complete")
  488. result = input("prompt> ")
  489. """
  490. if state == 0:
  491. cword_prequote, cword_prefix, cword_suffix, comp_words, first_colon_pos = split_line(text)
  492. comp_words.insert(0, sys.argv[0])
  493. matches = self._get_completions(comp_words, cword_prefix, cword_prequote, first_colon_pos)
  494. self._rl_matches = [text + match[len(cword_prefix) :] for match in matches]
  495. if state < len(self._rl_matches):
  496. return self._rl_matches[state]
  497. else:
  498. return None
  499. def get_display_completions(self):
  500. """
  501. This function returns a mapping of completions to their help strings for displaying to the user.
  502. """
  503. return self._display_completions
  504. class ExclusiveCompletionFinder(CompletionFinder):
  505. @staticmethod
  506. def _action_allowed(action, parser):
  507. if not CompletionFinder._action_allowed(action, parser):
  508. return False
  509. append_classes = (argparse._AppendAction, argparse._AppendConstAction)
  510. if action._orig_class in append_classes:
  511. return True
  512. if action not in parser._seen_non_default_actions:
  513. return True
  514. return False