shell_completion.py
This file
Path
src/click/shell_completion.py
574 lines · 17.5 KiB · Python
Last changed by
Merge pull request #1856 from pallets/typingDavid Lordbefore adoptionffeddba
History of this fileTake it
1import os2import re3import typing as t4from gettext import gettext as _56from .core import Argument7from .core import BaseCommand8from .core import Context9from .core import MultiCommand10from .core import Option11from .core import Parameter12from .core import ParameterSource13from .parser import split_arg_string14from .utils import echo151617def shell_complete(18 cli: BaseCommand,19 ctx_args: t.Dict[str, t.Any],20 prog_name: str,21 complete_var: str,22 instruction: str,23) -> int:24 """Perform shell completion for the given CLI program.2526 :param cli: Command being called.27 :param ctx_args: Extra arguments to pass to28 ``cli.make_context``.29 :param prog_name: Name of the executable in the shell.30 :param complete_var: Name of the environment variable that holds31 the completion instruction.32 :param instruction: Value of ``complete_var`` with the completion33 instruction and shell, in the form ``instruction_shell``.34 :return: Status code to exit with.35 """36 shell, _, instruction = instruction.partition("_")37 comp_cls = get_completion_class(shell)3839 if comp_cls is None:40 return 14142 comp = comp_cls(cli, ctx_args, prog_name, complete_var)4344 if instruction == "source":45 echo(comp.source())46 return 04748 if instruction == "complete":49 echo(comp.complete())50 return 05152 return 1535455class CompletionItem:56 """Represents a completion value and metadata about the value. The57 default metadata is ``type`` to indicate special shell handling,58 and ``help`` if a shell supports showing a help string next to the59 value.6061 Arbitrary parameters can be passed when creating the object, and62 accessed using ``item.attr``. If an attribute wasn't passed,63 accessing it returns ``None``.6465 :param value: The completion suggestion.66 :param type: Tells the shell script to provide special completion67 support for the type. Click uses ``"dir"`` and ``"file"``.68 :param help: String shown next to the value if supported.69 :param kwargs: Arbitrary metadata. The built-in implementations70 don't use this, but custom type completions paired with custom71 shell support could use it.72 """7374 __slots__ = ("value", "type", "help", "_info")7576 def __init__(77 self,78 value: t.Any,79 type: str = "plain",80 help: t.Optional[str] = None,81 **kwargs: t.Any,82 ) -> None:83 self.value = value84 self.type = type85 self.help = help86 self._info = kwargs8788 def __getattr__(self, name: str) -> t.Any:89 return self._info.get(name)909192# Only Bash >= 4.4 has the nosort option.93_SOURCE_BASH = """\94%(complete_func)s() {95 local IFS=$'\\n'96 local response9798 response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \99%(complete_var)s=bash_complete $1)100101 for completion in $response; do102 IFS=',' read type value <<< "$completion"103104 if [[ $type == 'dir' ]]; then105 COMREPLY=()106 compopt -o dirnames107 elif [[ $type == 'file' ]]; then108 COMREPLY=()109 compopt -o default110 elif [[ $type == 'plain' ]]; then111 COMPREPLY+=($value)112 fi113 done114115 return 0116}117118%(complete_func)s_setup() {119 complete -o nosort -F %(complete_func)s %(prog_name)s120}121122%(complete_func)s_setup;123"""124125_SOURCE_ZSH = """\126#compdef %(prog_name)s127128%(complete_func)s() {129 local -a completions130 local -a completions_with_descriptions131 local -a response132 (( ! $+commands[%(prog_name)s] )) && return 1133134 response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) \135%(complete_var)s=zsh_complete %(prog_name)s)}")136137 for type key descr in ${response}; do138 if [[ "$type" == "plain" ]]; then139 if [[ "$descr" == "_" ]]; then140 completions+=("$key")141 else142 completions_with_descriptions+=("$key":"$descr")143 fi144 elif [[ "$type" == "dir" ]]; then145 _path_files -/146 elif [[ "$type" == "file" ]]; then147 _path_files -f148 fi149 done150151 if [ -n "$completions_with_descriptions" ]; then152 _describe -V unsorted completions_with_descriptions -U153 fi154155 if [ -n "$completions" ]; then156 compadd -U -V unsorted -a completions157 fi158}159160compdef %(complete_func)s %(prog_name)s;161"""162163_SOURCE_FISH = """\164function %(complete_func)s;165 set -l response;166167 for value in (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \168COMP_CWORD=(commandline -t) %(prog_name)s);169 set response $response $value;170 end;171172 for completion in $response;173 set -l metadata (string split "," $completion);174175 if test $metadata[1] = "dir";176 __fish_complete_directories $metadata[2];177 else if test $metadata[1] = "file";178 __fish_complete_path $metadata[2];179 else if test $metadata[1] = "plain";180 echo $metadata[2];181 end;182 end;183end;184185complete --no-files --command %(prog_name)s --arguments \186"(%(complete_func)s)";187"""188189190class ShellComplete:191 """Base class for providing shell completion support. A subclass for192 a given shell will override attributes and methods to implement the193 completion instructions (``source`` and ``complete``).194195 :param cli: Command being called.196 :param prog_name: Name of the executable in the shell.197 :param complete_var: Name of the environment variable that holds198 the completion instruction.199200 .. versionadded:: 8.0201 """202203 name: t.ClassVar[str]204 """Name to register the shell as with :func:`add_completion_class`.205 This is used in completion instructions (``{name}_source`` and206 ``{name}_complete``).207 """208209 source_template: t.ClassVar[str]210 """Completion script template formatted by :meth:`source`. This must211 be provided by subclasses.212 """213214 def __init__(215 self,216 cli: BaseCommand,217 ctx_args: t.Dict[str, t.Any],218 prog_name: str,219 complete_var: str,220 ) -> None:221 self.cli = cli222 self.ctx_args = ctx_args223 self.prog_name = prog_name224 self.complete_var = complete_var225226 @property227 def func_name(self) -> str:228 """The name of the shell function defined by the completion229 script.230 """231 safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), re.ASCII)232 return f"_{safe_name}_completion"233234 def source_vars(self) -> t.Dict[str, t.Any]:235 """Vars for formatting :attr:`source_template`.236237 By default this provides ``complete_func``, ``complete_var``,238 and ``prog_name``.239 """240 return {241 "complete_func": self.func_name,242 "complete_var": self.complete_var,243 "prog_name": self.prog_name,244 }245246 def source(self) -> str:247 """Produce the shell script that defines the completion248 function. By default this ``%``-style formats249 :attr:`source_template` with the dict returned by250 :meth:`source_vars`.251 """252 return self.source_template % self.source_vars()253254 def get_completion_args(self) -> t.Tuple[t.List[str], str]:255 """Use the env vars defined by the shell script to return a256 tuple of ``args, incomplete``. This must be implemented by257 subclasses.258 """259 raise NotImplementedError260261 def get_completions(262 self, args: t.List[str], incomplete: str263 ) -> t.List[CompletionItem]:264 """Determine the context and last complete command or parameter265 from the complete args. Call that object's ``shell_complete``266 method to get the completions for the incomplete value.267268 :param args: List of complete args before the incomplete value.269 :param incomplete: Value being completed. May be empty.270 """271 ctx = _resolve_context(self.cli, self.ctx_args, self.prog_name, args)272 obj, incomplete = _resolve_incomplete(ctx, args, incomplete)273 return obj.shell_complete(ctx, incomplete)274275 def format_completion(self, item: CompletionItem) -> str:276 """Format a completion item into the form recognized by the277 shell script. This must be implemented by subclasses.278279 :param item: Completion item to format.280 """281 raise NotImplementedError282283 def complete(self) -> str:284 """Produce the completion data to send back to the shell.285286 By default this calls :meth:`get_completion_args`, gets the287 completions, then calls :meth:`format_completion` for each288 completion.289 """290 args, incomplete = self.get_completion_args()291 completions = self.get_completions(args, incomplete)292 out = [self.format_completion(item) for item in completions]293 return "\n".join(out)294295296class BashComplete(ShellComplete):297 """Shell completion for Bash."""298299 name = "bash"300 source_template = _SOURCE_BASH301302 def _check_version(self) -> None:303 import subprocess304305 output = subprocess.run(["bash", "--version"], stdout=subprocess.PIPE)306 match = re.search(r"version (\d)\.(\d)\.\d", output.stdout.decode())307308 if match is not None:309 major, minor = match.groups()310311 if major < "4" or major == "4" and minor < "4":312 raise RuntimeError(313 _(314 "Shell completion is not supported for Bash"315 " versions older than 4.4."316 )317 )318 else:319 raise RuntimeError(320 _("Couldn't detect Bash version, shell completion is not supported.")321 )322323 def source(self) -> str:324 self._check_version()325 return super().source()326327 def get_completion_args(self) -> t.Tuple[t.List[str], str]:328 cwords = split_arg_string(os.environ["COMP_WORDS"])329 cword = int(os.environ["COMP_CWORD"])330 args = cwords[1:cword]331332 try:333 incomplete = cwords[cword]334 except IndexError:335 incomplete = ""336337 return args, incomplete338339 def format_completion(self, item: CompletionItem) -> str:340 return f"{item.type},{item.value}"341342343class ZshComplete(ShellComplete):344 """Shell completion for Zsh."""345346 name = "zsh"347 source_template = _SOURCE_ZSH348349 def get_completion_args(self) -> t.Tuple[t.List[str], str]:350 cwords = split_arg_string(os.environ["COMP_WORDS"])351 cword = int(os.environ["COMP_CWORD"])352 args = cwords[1:cword]353354 try:355 incomplete = cwords[cword]356 except IndexError:357 incomplete = ""358359 return args, incomplete360361 def format_completion(self, item: CompletionItem) -> str:362 return f"{item.type}\n{item.value}\n{item.help if item.help else '_'}"363364365class FishComplete(ShellComplete):366 """Shell completion for Fish."""367368 name = "fish"369 source_template = _SOURCE_FISH370371 def get_completion_args(self) -> t.Tuple[t.List[str], str]:372 cwords = split_arg_string(os.environ["COMP_WORDS"])373 incomplete = os.environ["COMP_CWORD"]374 args = cwords[1:]375376 # Fish stores the partial word in both COMP_WORDS and377 # COMP_CWORD, remove it from complete args.378 if incomplete and args and args[-1] == incomplete:379 args.pop()380381 return args, incomplete382383 def format_completion(self, item: CompletionItem) -> str:384 if item.help:385 return f"{item.type},{item.value}\t{item.help}"386387 return f"{item.type},{item.value}"388389390_available_shells: t.Dict[str, t.Type[ShellComplete]] = {391 "bash": BashComplete,392 "fish": FishComplete,393 "zsh": ZshComplete,394}395396397def add_completion_class(398 cls: t.Type[ShellComplete], name: t.Optional[str] = None399) -> None:400 """Register a :class:`ShellComplete` subclass under the given name.401 The name will be provided by the completion instruction environment402 variable during completion.403404 :param cls: The completion class that will handle completion for the405 shell.406 :param name: Name to register the class under. Defaults to the407 class's ``name`` attribute.408 """409 if name is None:410 name = cls.name411412 _available_shells[name] = cls413414415def get_completion_class(shell: str) -> t.Optional[t.Type[ShellComplete]]:416 """Look up a registered :class:`ShellComplete` subclass by the name417 provided by the completion instruction environment variable. If the418 name isn't registered, returns ``None``.419420 :param shell: Name the class is registered under.421 """422 return _available_shells.get(shell)423424425def _is_incomplete_argument(ctx: Context, param: Parameter) -> bool:426 """Determine if the given parameter is an argument that can still427 accept values.428429 :param ctx: Invocation context for the command represented by the430 parsed complete args.431 :param param: Argument object being checked.432 """433 if not isinstance(param, Argument):434 return False435436 assert param.name is not None437 value = ctx.params[param.name]438 return (439 param.nargs == -1440 or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE441 or (442 param.nargs > 1443 and isinstance(value, (tuple, list))444 and len(value) < param.nargs445 )446 )447448449def _start_of_option(value: str) -> bool:450 """Check if the value looks like the start of an option."""451 return not value[0].isalnum() if value else False452453454def _is_incomplete_option(args: t.List[str], param: Parameter) -> bool:455 """Determine if the given parameter is an option that needs a value.456457 :param args: List of complete args before the incomplete value.458 :param param: Option object being checked.459 """460 if not isinstance(param, Option):461 return False462463 if param.is_flag:464 return False465466 last_option = None467468 for index, arg in enumerate(reversed(args)):469 if index + 1 > param.nargs:470 break471472 if _start_of_option(arg):473 last_option = arg474475 return last_option is not None and last_option in param.opts476477478def _resolve_context(479 cli: BaseCommand, ctx_args: t.Dict[str, t.Any], prog_name: str, args: t.List[str]480) -> Context:481 """Produce the context hierarchy starting with the command and482 traversing the complete arguments. This only follows the commands,483 it doesn't trigger input prompts or callbacks.484485 :param cli: Command being called.486 :param prog_name: Name of the executable in the shell.487 :param args: List of complete args before the incomplete value.488 """489 ctx_args["resilient_parsing"] = True490 ctx = cli.make_context(prog_name, args.copy(), **ctx_args)491 args = ctx.protected_args + ctx.args492493 while args:494 command = ctx.command495496 if isinstance(command, MultiCommand):497 if not command.chain:498 name, cmd, args = command.resolve_command(ctx, args)499500 if cmd is None:501 return ctx502503 ctx = cmd.make_context(name, args, parent=ctx, resilient_parsing=True)504 args = ctx.protected_args + ctx.args505 else:506 while args:507 name, cmd, args = command.resolve_command(ctx, args)508509 if cmd is None:510 return ctx511512 sub_ctx = cmd.make_context(513 name,514 args,515 parent=ctx,516 allow_extra_args=True,517 allow_interspersed_args=False,518 resilient_parsing=True,519 )520 args = sub_ctx.args521522 ctx = sub_ctx523 args = [*sub_ctx.protected_args, *sub_ctx.args]524 else:525 break526527 return ctx528529530def _resolve_incomplete(531 ctx: Context, args: t.List[str], incomplete: str532) -> t.Tuple[t.Union[BaseCommand, Parameter], str]:533 """Find the Click object that will handle the completion of the534 incomplete value. Return the object and the incomplete value.535536 :param ctx: Invocation context for the command represented by537 the parsed complete args.538 :param args: List of complete args before the incomplete value.539 :param incomplete: Value being completed. May be empty.540 """541 # Different shells treat an "=" between a long option name and542 # value differently. Might keep the value joined, return the "="543 # as a separate item, or return the split name and value. Always544 # split and discard the "=" to make completion easier.545 if incomplete == "=":546 incomplete = ""547 elif "=" in incomplete and _start_of_option(incomplete):548 name, _, incomplete = incomplete.partition("=")549 args.append(name)550551 # The "--" marker tells Click to stop treating values as options552 # even if they start with the option character. If it hasn't been553 # given and the incomplete arg looks like an option, the current554 # command will provide option name completions.555 if "--" not in args and _start_of_option(incomplete):556 return ctx.command, incomplete557558 params = ctx.command.get_params(ctx)559560 # If the last complete arg is an option name with an incomplete561 # value, the option will provide value completions.562 for param in params:563 if _is_incomplete_option(args, param):564 return param, incomplete565566 # It's not an option name or value. The first argument without a567 # parsed value will provide value completions.568 for param in params:569 if _is_incomplete_argument(ctx, param):570 return param, incomplete571572 # There were no unparsed arguments, the command may be a group that573 # will provide command name completions.574 return ctx.command, incomplete