shell_completion.py
This file
Path
src/click/shell_completion.py
644 lines · 19.4 KiB · Python
Last changed by
fix shell completion for nested groups (#2935)David Lordbefore adoptionb7cf069
History of this fileTake it
1from __future__ import annotations23import collections.abc as cabc4import os5import re6import typing as t7from gettext import gettext as _89from .core import Argument10from .core import Command11from .core import Context12from .core import Group13from .core import Option14from .core import Parameter15from .core import ParameterSource16from .utils import echo171819def shell_complete(20 cli: Command,21 ctx_args: cabc.MutableMapping[str, t.Any],22 prog_name: str,23 complete_var: str,24 instruction: str,25) -> int:26 """Perform shell completion for the given CLI program.2728 :param cli: Command being called.29 :param ctx_args: Extra arguments to pass to30 ``cli.make_context``.31 :param prog_name: Name of the executable in the shell.32 :param complete_var: Name of the environment variable that holds33 the completion instruction.34 :param instruction: Value of ``complete_var`` with the completion35 instruction and shell, in the form ``instruction_shell``.36 :return: Status code to exit with.37 """38 shell, _, instruction = instruction.partition("_")39 comp_cls = get_completion_class(shell)4041 if comp_cls is None:42 return 14344 comp = comp_cls(cli, ctx_args, prog_name, complete_var)4546 if instruction == "source":47 echo(comp.source())48 return 04950 if instruction == "complete":51 echo(comp.complete())52 return 05354 return 1555657class CompletionItem:58 """Represents a completion value and metadata about the value. The59 default metadata is ``type`` to indicate special shell handling,60 and ``help`` if a shell supports showing a help string next to the61 value.6263 Arbitrary parameters can be passed when creating the object, and64 accessed using ``item.attr``. If an attribute wasn't passed,65 accessing it returns ``None``.6667 :param value: The completion suggestion.68 :param type: Tells the shell script to provide special completion69 support for the type. Click uses ``"dir"`` and ``"file"``.70 :param help: String shown next to the value if supported.71 :param kwargs: Arbitrary metadata. The built-in implementations72 don't use this, but custom type completions paired with custom73 shell support could use it.74 """7576 __slots__ = ("value", "type", "help", "_info")7778 def __init__(79 self,80 value: t.Any,81 type: str = "plain",82 help: str | None = None,83 **kwargs: t.Any,84 ) -> None:85 self.value: t.Any = value86 self.type: str = type87 self.help: str | None = help88 self._info = kwargs8990 def __getattr__(self, name: str) -> t.Any:91 return self._info.get(name)929394# Only Bash >= 4.4 has the nosort option.95_SOURCE_BASH = """\96%(complete_func)s() {97 local IFS=$'\\n'98 local response99100 response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \101%(complete_var)s=bash_complete $1)102103 for completion in $response; do104 IFS=',' read type value <<< "$completion"105106 if [[ $type == 'dir' ]]; then107 COMPREPLY=()108 compopt -o dirnames109 elif [[ $type == 'file' ]]; then110 COMPREPLY=()111 compopt -o default112 elif [[ $type == 'plain' ]]; then113 COMPREPLY+=($value)114 fi115 done116117 return 0118}119120%(complete_func)s_setup() {121 complete -o nosort -F %(complete_func)s %(prog_name)s122}123124%(complete_func)s_setup;125"""126127_SOURCE_ZSH = """\128#compdef %(prog_name)s129130%(complete_func)s() {131 local -a completions132 local -a completions_with_descriptions133 local -a response134 (( ! $+commands[%(prog_name)s] )) && return 1135136 response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) \137%(complete_var)s=zsh_complete %(prog_name)s)}")138139 for type key descr in ${response}; do140 if [[ "$type" == "plain" ]]; then141 if [[ "$descr" == "_" ]]; then142 completions+=("$key")143 else144 completions_with_descriptions+=("$key":"$descr")145 fi146 elif [[ "$type" == "dir" ]]; then147 _path_files -/148 elif [[ "$type" == "file" ]]; then149 _path_files -f150 fi151 done152153 if [ -n "$completions_with_descriptions" ]; then154 _describe -V unsorted completions_with_descriptions -U155 fi156157 if [ -n "$completions" ]; then158 compadd -U -V unsorted -a completions159 fi160}161162if [[ $zsh_eval_context[-1] == loadautofunc ]]; then163 # autoload from fpath, call function directly164 %(complete_func)s "$@"165else166 # eval/source/. command, register function for later167 compdef %(complete_func)s %(prog_name)s168fi169"""170171_SOURCE_FISH = """\172function %(complete_func)s;173 set -l response (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \174COMP_CWORD=(commandline -t) %(prog_name)s);175176 for completion in $response;177 set -l metadata (string split "," $completion);178179 if test $metadata[1] = "dir";180 __fish_complete_directories $metadata[2];181 else if test $metadata[1] = "file";182 __fish_complete_path $metadata[2];183 else if test $metadata[1] = "plain";184 echo $metadata[2];185 end;186 end;187end;188189complete --no-files --command %(prog_name)s --arguments \190"(%(complete_func)s)";191"""192193194class ShellComplete:195 """Base class for providing shell completion support. A subclass for196 a given shell will override attributes and methods to implement the197 completion instructions (``source`` and ``complete``).198199 :param cli: Command being called.200 :param prog_name: Name of the executable in the shell.201 :param complete_var: Name of the environment variable that holds202 the completion instruction.203204 .. versionadded:: 8.0205 """206207 name: t.ClassVar[str]208 """Name to register the shell as with :func:`add_completion_class`.209 This is used in completion instructions (``{name}_source`` and210 ``{name}_complete``).211 """212213 source_template: t.ClassVar[str]214 """Completion script template formatted by :meth:`source`. This must215 be provided by subclasses.216 """217218 def __init__(219 self,220 cli: Command,221 ctx_args: cabc.MutableMapping[str, t.Any],222 prog_name: str,223 complete_var: str,224 ) -> None:225 self.cli = cli226 self.ctx_args = ctx_args227 self.prog_name = prog_name228 self.complete_var = complete_var229230 @property231 def func_name(self) -> str:232 """The name of the shell function defined by the completion233 script.234 """235 safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), flags=re.ASCII)236 return f"_{safe_name}_completion"237238 def source_vars(self) -> dict[str, t.Any]:239 """Vars for formatting :attr:`source_template`.240241 By default this provides ``complete_func``, ``complete_var``,242 and ``prog_name``.243 """244 return {245 "complete_func": self.func_name,246 "complete_var": self.complete_var,247 "prog_name": self.prog_name,248 }249250 def source(self) -> str:251 """Produce the shell script that defines the completion252 function. By default this ``%``-style formats253 :attr:`source_template` with the dict returned by254 :meth:`source_vars`.255 """256 return self.source_template % self.source_vars()257258 def get_completion_args(self) -> tuple[list[str], str]:259 """Use the env vars defined by the shell script to return a260 tuple of ``args, incomplete``. This must be implemented by261 subclasses.262 """263 raise NotImplementedError264265 def get_completions(self, args: list[str], incomplete: str) -> list[CompletionItem]:266 """Determine the context and last complete command or parameter267 from the complete args. Call that object's ``shell_complete``268 method to get the completions for the incomplete value.269270 :param args: List of complete args before the incomplete value.271 :param incomplete: Value being completed. May be empty.272 """273 ctx = _resolve_context(self.cli, self.ctx_args, self.prog_name, args)274 obj, incomplete = _resolve_incomplete(ctx, args, incomplete)275 return obj.shell_complete(ctx, incomplete)276277 def format_completion(self, item: CompletionItem) -> str:278 """Format a completion item into the form recognized by the279 shell script. This must be implemented by subclasses.280281 :param item: Completion item to format.282 """283 raise NotImplementedError284285 def complete(self) -> str:286 """Produce the completion data to send back to the shell.287288 By default this calls :meth:`get_completion_args`, gets the289 completions, then calls :meth:`format_completion` for each290 completion.291 """292 args, incomplete = self.get_completion_args()293 completions = self.get_completions(args, incomplete)294 out = [self.format_completion(item) for item in completions]295 return "\n".join(out)296297298class BashComplete(ShellComplete):299 """Shell completion for Bash."""300301 name = "bash"302 source_template = _SOURCE_BASH303304 @staticmethod305 def _check_version() -> None:306 import shutil307 import subprocess308309 bash_exe = shutil.which("bash")310311 if bash_exe is None:312 match = None313 else:314 output = subprocess.run(315 [bash_exe, "--norc", "-c", 'echo "${BASH_VERSION}"'],316 stdout=subprocess.PIPE,317 )318 match = re.search(r"^(\d+)\.(\d+)\.\d+", output.stdout.decode())319320 if match is not None:321 major, minor = match.groups()322323 if major < "4" or major == "4" and minor < "4":324 echo(325 _(326 "Shell completion is not supported for Bash"327 " versions older than 4.4."328 ),329 err=True,330 )331 else:332 echo(333 _("Couldn't detect Bash version, shell completion is not supported."),334 err=True,335 )336337 def source(self) -> str:338 self._check_version()339 return super().source()340341 def get_completion_args(self) -> tuple[list[str], str]:342 cwords = split_arg_string(os.environ["COMP_WORDS"])343 cword = int(os.environ["COMP_CWORD"])344 args = cwords[1:cword]345346 try:347 incomplete = cwords[cword]348 except IndexError:349 incomplete = ""350351 return args, incomplete352353 def format_completion(self, item: CompletionItem) -> str:354 return f"{item.type},{item.value}"355356357class ZshComplete(ShellComplete):358 """Shell completion for Zsh."""359360 name = "zsh"361 source_template = _SOURCE_ZSH362363 def get_completion_args(self) -> tuple[list[str], str]:364 cwords = split_arg_string(os.environ["COMP_WORDS"])365 cword = int(os.environ["COMP_CWORD"])366 args = cwords[1:cword]367368 try:369 incomplete = cwords[cword]370 except IndexError:371 incomplete = ""372373 return args, incomplete374375 def format_completion(self, item: CompletionItem) -> str:376 return f"{item.type}\n{item.value}\n{item.help if item.help else '_'}"377378379class FishComplete(ShellComplete):380 """Shell completion for Fish."""381382 name = "fish"383 source_template = _SOURCE_FISH384385 def get_completion_args(self) -> tuple[list[str], str]:386 cwords = split_arg_string(os.environ["COMP_WORDS"])387 incomplete = os.environ["COMP_CWORD"]388 args = cwords[1:]389390 # Fish stores the partial word in both COMP_WORDS and391 # COMP_CWORD, remove it from complete args.392 if incomplete and args and args[-1] == incomplete:393 args.pop()394395 return args, incomplete396397 def format_completion(self, item: CompletionItem) -> str:398 if item.help:399 return f"{item.type},{item.value}\t{item.help}"400401 return f"{item.type},{item.value}"402403404ShellCompleteType = t.TypeVar("ShellCompleteType", bound="type[ShellComplete]")405406407_available_shells: dict[str, type[ShellComplete]] = {408 "bash": BashComplete,409 "fish": FishComplete,410 "zsh": ZshComplete,411}412413414def add_completion_class(415 cls: ShellCompleteType, name: str | None = None416) -> ShellCompleteType:417 """Register a :class:`ShellComplete` subclass under the given name.418 The name will be provided by the completion instruction environment419 variable during completion.420421 :param cls: The completion class that will handle completion for the422 shell.423 :param name: Name to register the class under. Defaults to the424 class's ``name`` attribute.425 """426 if name is None:427 name = cls.name428429 _available_shells[name] = cls430431 return cls432433434def get_completion_class(shell: str) -> type[ShellComplete] | None:435 """Look up a registered :class:`ShellComplete` subclass by the name436 provided by the completion instruction environment variable. If the437 name isn't registered, returns ``None``.438439 :param shell: Name the class is registered under.440 """441 return _available_shells.get(shell)442443444def split_arg_string(string: str) -> list[str]:445 """Split an argument string as with :func:`shlex.split`, but don't446 fail if the string is incomplete. Ignores a missing closing quote or447 incomplete escape sequence and uses the partial token as-is.448449 .. code-block:: python450451 split_arg_string("example 'my file")452 ["example", "my file"]453454 split_arg_string("example my\\")455 ["example", "my"]456457 :param string: String to split.458459 .. versionchanged:: 8.2460 Moved to ``shell_completion`` from ``parser``.461 """462 import shlex463464 lex = shlex.shlex(string, posix=True)465 lex.whitespace_split = True466 lex.commenters = ""467 out = []468469 try:470 for token in lex:471 out.append(token)472 except ValueError:473 # Raised when end-of-string is reached in an invalid state. Use474 # the partial token as-is. The quote or escape character is in475 # lex.state, not lex.token.476 out.append(lex.token)477478 return out479480481def _is_incomplete_argument(ctx: Context, param: Parameter) -> bool:482 """Determine if the given parameter is an argument that can still483 accept values.484485 :param ctx: Invocation context for the command represented by the486 parsed complete args.487 :param param: Argument object being checked.488 """489 if not isinstance(param, Argument):490 return False491492 assert param.name is not None493 # Will be None if expose_value is False.494 value = ctx.params.get(param.name)495 return (496 param.nargs == -1497 or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE498 or (499 param.nargs > 1500 and isinstance(value, (tuple, list))501 and len(value) < param.nargs502 )503 )504505506def _start_of_option(ctx: Context, value: str) -> bool:507 """Check if the value looks like the start of an option."""508 if not value:509 return False510511 c = value[0]512 return c in ctx._opt_prefixes513514515def _is_incomplete_option(ctx: Context, args: list[str], param: Parameter) -> bool:516 """Determine if the given parameter is an option that needs a value.517518 :param args: List of complete args before the incomplete value.519 :param param: Option object being checked.520 """521 if not isinstance(param, Option):522 return False523524 if param.is_flag or param.count:525 return False526527 last_option = None528529 for index, arg in enumerate(reversed(args)):530 if index + 1 > param.nargs:531 break532533 if _start_of_option(ctx, arg):534 last_option = arg535536 return last_option is not None and last_option in param.opts537538539def _resolve_context(540 cli: Command,541 ctx_args: cabc.MutableMapping[str, t.Any],542 prog_name: str,543 args: list[str],544) -> Context:545 """Produce the context hierarchy starting with the command and546 traversing the complete arguments. This only follows the commands,547 it doesn't trigger input prompts or callbacks.548549 :param cli: Command being called.550 :param prog_name: Name of the executable in the shell.551 :param args: List of complete args before the incomplete value.552 """553 ctx_args["resilient_parsing"] = True554 with cli.make_context(prog_name, args.copy(), **ctx_args) as ctx:555 args = ctx._protected_args + ctx.args556557 while args:558 command = ctx.command559560 if isinstance(command, Group):561 if not command.chain:562 name, cmd, args = command.resolve_command(ctx, args)563564 if cmd is None:565 return ctx566567 with cmd.make_context(568 name, args, parent=ctx, resilient_parsing=True569 ) as sub_ctx:570 ctx = sub_ctx571 args = ctx._protected_args + ctx.args572 else:573 sub_ctx = ctx574575 while args:576 name, cmd, args = command.resolve_command(ctx, args)577578 if cmd is None:579 return ctx580581 with cmd.make_context(582 name,583 args,584 parent=ctx,585 allow_extra_args=True,586 allow_interspersed_args=False,587 resilient_parsing=True,588 ) as sub_sub_ctx:589 sub_ctx = sub_sub_ctx590 args = sub_ctx.args591592 ctx = sub_ctx593 args = [*sub_ctx._protected_args, *sub_ctx.args]594 else:595 break596597 return ctx598599600def _resolve_incomplete(601 ctx: Context, args: list[str], incomplete: str602) -> tuple[Command | Parameter, str]:603 """Find the Click object that will handle the completion of the604 incomplete value. Return the object and the incomplete value.605606 :param ctx: Invocation context for the command represented by607 the parsed complete args.608 :param args: List of complete args before the incomplete value.609 :param incomplete: Value being completed. May be empty.610 """611 # Different shells treat an "=" between a long option name and612 # value differently. Might keep the value joined, return the "="613 # as a separate item, or return the split name and value. Always614 # split and discard the "=" to make completion easier.615 if incomplete == "=":616 incomplete = ""617 elif "=" in incomplete and _start_of_option(ctx, incomplete):618 name, _, incomplete = incomplete.partition("=")619 args.append(name)620621 # The "--" marker tells Click to stop treating values as options622 # even if they start with the option character. If it hasn't been623 # given and the incomplete arg looks like an option, the current624 # command will provide option name completions.625 if "--" not in args and _start_of_option(ctx, incomplete):626 return ctx.command, incomplete627628 params = ctx.command.get_params(ctx)629630 # If the last complete arg is an option name with an incomplete631 # value, the option will provide value completions.632 for param in params:633 if _is_incomplete_option(ctx, args, param):634 return param, incomplete635636 # It's not an option name or value. The first argument without a637 # parsed value will provide value completions.638 for param in params:639 if _is_incomplete_argument(ctx, param):640 return param, incomplete641642 # There were no unparsed arguments, the command may be a group that643 # will provide command name completions.644 return ctx.command, incomplete