shell_completion.py
This file
Path
src/click/shell_completion.py
801 lines · 25.6 KiB · Python
Last changed by
Merge main into stable (#3800)Rowlando13before adoption420c8fb
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) -> t.Literal[0, 1]: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 # Write bytes, otherwise Windows text stdout translates LF to CRLF and breaks.47 if instruction == "source":48 echo(comp.source().encode(), nl=False)49 return 05051 if instruction == "complete":52 echo(comp.complete().encode())53 return 05455 return 1565758if t.TYPE_CHECKING:59 from typing_extensions import TypeVar6061 # `Any` is used as default for backwards compatibility (instead of e.g. `str`)62 _ValueT_co = TypeVar("_ValueT_co", covariant=True, default=t.Any)63else:64 _ValueT_co = t.TypeVar("_ValueT_co", covariant=True)656667class CompletionItem(t.Generic[_ValueT_co]):68 """Represents a completion value and metadata about the value. The69 default metadata is ``type`` to indicate special shell handling,70 and ``help`` if a shell supports showing a help string next to the71 value.7273 Arbitrary parameters can be passed when creating the object, and74 accessed using ``item.attr``. If an attribute wasn't passed,75 accessing it returns ``None``.7677 :param value: The completion suggestion.78 :param type: Tells the shell script to provide special completion79 support for the type. Click uses ``"dir"`` and ``"file"``.80 :param help: String shown next to the value if supported.81 :param kwargs: Arbitrary metadata. The built-in implementations82 don't use this, but custom type completions paired with custom83 shell support could use it.84 """8586 __slots__ = ("value", "type", "help", "_info")8788 def __init__(89 self,90 value: _ValueT_co,91 type: str = "plain",92 help: str | None = None,93 **kwargs: t.Any,94 ) -> None:95 self.value: _ValueT_co = value96 self.type: str = type97 self.help: str | None = help98 self._info = kwargs99100 def __getattr__(self, name: str) -> t.Any:101 return self._info.get(name)102103104# Only Bash >= 4.4 has the nosort option.105_SOURCE_BASH = """\106%(complete_func)s() {107 local IFS=$'\\n'108 local response109110 response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \111%(complete_var)s=bash_complete $1)112113 for completion in $response; do114 IFS=',' read type value <<< "$completion"115116 if [[ $type == 'dir' ]]; then117 COMPREPLY=()118 compopt -o dirnames119 elif [[ $type == 'file' ]]; then120 COMPREPLY=()121 compopt -o default122 elif [[ $type == 'plain' ]]; then123 COMPREPLY+=($value)124 fi125 done126127 return 0128}129130%(complete_func)s_setup() {131 complete -o nosort -F %(complete_func)s %(prog_name)s132}133134%(complete_func)s_setup;135"""136137# See ZshComplete.format_completion below, and issue #2703, before138# changing this script.139#140# (TL;DR: _describe is picky about the format, but this Zsh script snippet141# is already widely deployed. So freeze this script, and use clever-ish142# handling of colons in ZshComplet.format_completion.)143_SOURCE_ZSH = """\144#compdef %(prog_name)s145146%(complete_func)s() {147 local -a completions148 local -a completions_with_descriptions149 local -a response150 (( ! $+commands[%(prog_name)s] )) && return 1151152 response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) \153%(complete_var)s=zsh_complete %(prog_name)s)}")154155 for type key descr in ${response}; do156 if [[ "$type" == "plain" ]]; then157 if [[ "$descr" == "_" ]]; then158 completions+=("$key")159 else160 completions_with_descriptions+=("$key":"$descr")161 fi162 elif [[ "$type" == "dir" ]]; then163 _path_files -/164 elif [[ "$type" == "file" ]]; then165 _path_files -f166 fi167 done168169 if [ -n "$completions_with_descriptions" ]; then170 _describe -V unsorted completions_with_descriptions -U171 fi172173 if [ -n "$completions" ]; then174 compadd -U -V unsorted -a completions175 fi176}177178if [[ $zsh_eval_context[-1] == loadautofunc ]]; then179 # autoload from fpath, call function directly180 %(complete_func)s "$@"181else182 # eval/source/. command, register function for later183 compdef %(complete_func)s %(prog_name)s184fi185"""186187_SOURCE_FISH = """\188function %(complete_func)s;189 set -l response (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \190COMP_CWORD=(commandline -t) %(prog_name)s);191192 for completion in $response;193 set -l metadata (string split "," $completion);194195 if test $metadata[1] = "dir";196 __fish_complete_directories $metadata[2];197 else if test $metadata[1] = "file";198 __fish_complete_path $metadata[2];199 else if test $metadata[1] = "plain";200 echo $metadata[2];201 end;202 end;203end;204205complete --no-files --command %(prog_name)s --arguments \206"(%(complete_func)s)";207"""208209# Compatible with Windows PowerShell 5.1+ and PowerShell (pwsh) 7+.210# Uses Register-ArgumentCompleter -Native, which receives the command AST211# as parsed by PowerShell. The command text is forwarded verbatim through212# COMP_WORDS so the Python side can reuse the same shlex-based splitting213# used by the bash/zsh completers.214_SOURCE_POWERSHELL = """\215Register-ArgumentCompleter -Native -CommandName %(prog_name)s -ScriptBlock {216 param($wordToComplete, $commandAst, $cursorPosition)217218 $prev_complete = $env:%(complete_var)s219 $prev_words = $env:COMP_WORDS220 $prev_cword = $env:COMP_CWORD221222 $env:%(complete_var)s = 'powershell_complete'223 $env:COMP_WORDS = $commandAst.ToString()224 if ($wordToComplete) {225 $env:COMP_CWORD = $commandAst.CommandElements.Count - 1226 } else {227 $env:COMP_CWORD = $commandAst.CommandElements.Count228 }229230 try {231 $response = & %(prog_name)s 2>$null232 } finally {233 $env:%(complete_var)s = $prev_complete234 $env:COMP_WORDS = $prev_words235 $env:COMP_CWORD = $prev_cword236 }237238 if (-not $response) { return }239240 $prefix = "$wordToComplete*"241 $lines = $response -split "`n"242 for ($i = 0; $i + 2 -lt $lines.Count; $i += 3) {243 $type = $lines[$i]244 $value = $lines[$i + 1]245 $descr = $lines[$i + 2]246 if (-not $type) { continue }247248 if ($type -eq 'plain') {249 $tip = if ($descr -and $descr -ne '_') { $descr } else { $value }250 [System.Management.Automation.CompletionResult]::new(251 $value, $value, 'ParameterValue', $tip)252 } elseif ($type -eq 'dir') {253 Get-ChildItem -Directory -Path $prefix -ErrorAction SilentlyContinue |254 ForEach-Object {255 [System.Management.Automation.CompletionResult]::new(256 $_.FullName, $_.Name, 'ProviderContainer', $_.FullName)257 }258 } elseif ($type -eq 'file') {259 Get-ChildItem -Path $prefix -ErrorAction SilentlyContinue |260 ForEach-Object {261 $kind = 'ProviderItem'262 if ($_.PSIsContainer) { $kind = 'ProviderContainer' }263 [System.Management.Automation.CompletionResult]::new(264 $_.FullName, $_.Name, $kind, $_.FullName)265 }266 }267 }268}269"""270271272class _SourceVarsDict(t.TypedDict):273 complete_func: str274 complete_var: str275 prog_name: str276277278class ShellComplete:279 """Base class for providing shell completion support. A subclass for280 a given shell will override attributes and methods to implement the281 completion instructions (``source`` and ``complete``).282283 :param cli: Command being called.284 :param prog_name: Name of the executable in the shell.285 :param complete_var: Name of the environment variable that holds286 the completion instruction.287288 .. versionadded:: 8.0289 """290291 name: t.ClassVar[str]292 """Name to register the shell as with :func:`add_completion_class`.293 This is used in completion instructions (``{name}_source`` and294 ``{name}_complete``).295 """296297 source_template: t.ClassVar[str]298 """Completion script template formatted by :meth:`source`. This must299 be provided by subclasses.300 """301302 cli: Command303 ctx_args: cabc.MutableMapping[str, t.Any]304 prog_name: str305 complete_var: str306307 def __init__(308 self,309 cli: Command,310 ctx_args: cabc.MutableMapping[str, t.Any],311 prog_name: str,312 complete_var: str,313 ) -> None:314 self.cli = cli315 self.ctx_args = ctx_args316 self.prog_name = prog_name317 self.complete_var = complete_var318319 @property320 def func_name(self) -> str:321 """The name of the shell function defined by the completion322 script.323 """324 safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), flags=re.ASCII)325 return f"_{safe_name}_completion"326327 def source_vars(self) -> _SourceVarsDict:328 """Vars for formatting :attr:`source_template`.329330 By default this provides ``complete_func``, ``complete_var``,331 and ``prog_name``.332 """333 return {334 "complete_func": self.func_name,335 "complete_var": self.complete_var,336 "prog_name": self.prog_name,337 }338339 def source(self) -> str:340 """Produce the shell script that defines the completion341 function. By default this ``%``-style formats342 :attr:`source_template` with the dict returned by343 :meth:`source_vars`.344 """345 return self.source_template % self.source_vars()346347 def get_completion_args(self) -> tuple[list[str], str]:348 """Use the env vars defined by the shell script to return a349 tuple of ``args, incomplete``. This must be implemented by350 subclasses.351 """352 raise NotImplementedError353354 def get_completions(355 self, args: list[str], incomplete: str356 ) -> list[CompletionItem[str]]:357 """Determine the context and last complete command or parameter358 from the complete args. Call that object's ``shell_complete``359 method to get the completions for the incomplete value.360361 :param args: List of complete args before the incomplete value.362 :param incomplete: Value being completed. May be empty.363 """364 ctx = _resolve_context(self.cli, self.ctx_args, self.prog_name, args)365 obj, incomplete = _resolve_incomplete(ctx, args, incomplete)366 return obj.shell_complete(ctx, incomplete)367368 def format_completion(self, item: CompletionItem[str]) -> str:369 """Format a completion item into the form recognized by the370 shell script. This must be implemented by subclasses.371372 :param item: Completion item to format.373 """374 raise NotImplementedError375376 def complete(self) -> str:377 """Produce the completion data to send back to the shell.378379 By default this calls :meth:`get_completion_args`, gets the380 completions, then calls :meth:`format_completion` for each381 completion.382 """383 args, incomplete = self.get_completion_args()384 completions = self.get_completions(args, incomplete)385 out = [self.format_completion(item) for item in completions]386 return "\n".join(out)387388389class BashComplete(ShellComplete):390 """Shell completion for Bash."""391392 name: t.ClassVar[str] = "bash"393 source_template: t.ClassVar[str] = _SOURCE_BASH394395 @staticmethod396 def _check_version() -> None:397 import shutil398 import subprocess399400 bash_exe = shutil.which("bash")401402 if bash_exe is None:403 match = None404 else:405 output = subprocess.run(406 [bash_exe, "--norc", "-c", 'echo "${BASH_VERSION}"'],407 stdout=subprocess.PIPE,408 )409 match = re.search(r"^(\d+)\.(\d+)\.\d+", output.stdout.decode())410411 if match is not None:412 major, minor = match.groups()413414 if major < "4" or major == "4" and minor < "4":415 echo(416 _(417 "Shell completion is not supported for Bash"418 " versions older than 4.4."419 ),420 err=True,421 )422 else:423 echo(424 _("Couldn't detect Bash version, shell completion is not supported."),425 err=True,426 )427428 def source(self) -> str:429 self._check_version()430 return super().source()431432 def get_completion_args(self) -> tuple[list[str], str]:433 cwords = split_arg_string(os.environ["COMP_WORDS"])434 cword = int(os.environ["COMP_CWORD"])435 args = cwords[1:cword]436437 try:438 incomplete = cwords[cword]439 except IndexError:440 incomplete = ""441442 return args, incomplete443444 def format_completion(self, item: CompletionItem[t.Any]) -> str:445 return f"{item.type},{item.value}"446447448class ZshComplete(ShellComplete):449 """Shell completion for Zsh."""450451 name: t.ClassVar[str] = "zsh"452 source_template: t.ClassVar[str] = _SOURCE_ZSH453454 def get_completion_args(self) -> tuple[list[str], str]:455 cwords = split_arg_string(os.environ["COMP_WORDS"])456 cword = int(os.environ["COMP_CWORD"])457 args = cwords[1:cword]458459 try:460 incomplete = cwords[cword]461 except IndexError:462 incomplete = ""463464 return args, incomplete465466 def format_completion(self, item: CompletionItem[str]) -> str:467 help_ = item.help or "_"468 # The zsh completion script uses `_describe` on items with help469 # texts (which splits the item help from the item value at the470 # first unescaped colon) and `compadd` on items without help471 # text (which uses the item value as-is and does not support472 # colon escaping). So escape colons in the item value if and473 # only if the item help is not the sentinel "_" value, as used474 # by the completion script.475 #476 # (The zsh completion script is potentially widely deployed, and477 # thus harder to fix than this method.)478 #479 # See issue #1812 and issue #2703 for further context.480 value = item.value.replace(":", r"\:") if help_ != "_" else item.value481 return f"{item.type}\n{value}\n{help_}"482483484class FishComplete(ShellComplete):485 """Shell completion for Fish."""486487 name: t.ClassVar[str] = "fish"488 source_template: t.ClassVar[str] = _SOURCE_FISH489490 def get_completion_args(self) -> tuple[list[str], str]:491 cwords = split_arg_string(os.environ["COMP_WORDS"])492 incomplete = os.environ["COMP_CWORD"]493 if incomplete:494 incomplete = split_arg_string(incomplete)[0]495 args = cwords[1:]496497 # Fish stores the partial word in both COMP_WORDS and498 # COMP_CWORD, remove it from complete args.499 if incomplete and args and args[-1] == incomplete:500 args.pop()501502 return args, incomplete503504 def format_completion(self, item: CompletionItem[str]) -> str:505 """506 .. versionchanged:: 8.4.2507 Escape newlines and replace tabs with spaces in the help text to508 fix completion errors with multi-line help strings.509 """510 # According to https://fishshell.com/docs/current/cmds/complete.html511 # Command substitutions found in ARGUMENTS should return a newline-512 # separated list of arguments, and each argument may optionally have a tab513 # character followed by the argument description.514 if item.help:515 help_ = item.help.replace("\n", "\\n").replace("\t", " ")516 return f"{item.type},{item.value}\t{help_}"517518 return f"{item.type},{item.value}"519520521class PowerShellComplete(ShellComplete):522 """Shell completion for PowerShell (Windows PowerShell 5.1+ and pwsh 7+).523524 .. versionadded:: 8.5.0525 """526527 name: t.ClassVar[str] = "powershell"528 source_template: t.ClassVar[str] = _SOURCE_POWERSHELL529530 def get_completion_args(self) -> tuple[list[str], str]:531 cwords = split_arg_string(os.environ["COMP_WORDS"])532 cword = int(os.environ["COMP_CWORD"])533 args = cwords[1:cword]534535 try:536 incomplete = cwords[cword]537 except IndexError:538 incomplete = ""539540 return args, incomplete541542 def format_completion(self, item: CompletionItem[str]) -> str:543 # PowerShell parses the response by splitting on newlines and544 # consuming three lines per completion (type, value, help).545 # Multi-line help text would break that framing, so collapse546 # newlines and carriage returns to spaces. The literal "_"547 # sentinel matches what ZshComplete uses for "no help text".548 if item.help:549 help_ = item.help.replace("\r", " ").replace("\n", " ")550 else:551 help_ = "_"552 return f"{item.type}\n{item.value}\n{help_}"553554555_available_shells: t.Final[dict[str, type[ShellComplete]]] = {556 "bash": BashComplete,557 "fish": FishComplete,558 "powershell": PowerShellComplete,559 "zsh": ZshComplete,560}561562_ShellCompleteT = t.TypeVar("_ShellCompleteT", bound="ShellComplete")563564565def add_completion_class(566 cls: type[_ShellCompleteT], name: str | None = None567) -> type[_ShellCompleteT]:568 """Register a :class:`ShellComplete` subclass under the given name.569 The name will be provided by the completion instruction environment570 variable during completion.571572 :param cls: The completion class that will handle completion for the573 shell.574 :param name: Name to register the class under. Defaults to the575 class's ``name`` attribute.576 """577 if name is None:578 name = cls.name579580 _available_shells[name] = cls581582 return cls583584585@t.overload586def get_completion_class(shell: t.Literal["bash"]) -> type[BashComplete]: ...587@t.overload588def get_completion_class(shell: t.Literal["fish"]) -> type[FishComplete]: ...589@t.overload590def get_completion_class(shell: t.Literal["zsh"]) -> type[ZshComplete]: ...591@t.overload592def get_completion_class(shell: str) -> type[ShellComplete] | None: ...593def get_completion_class(shell: str) -> type[ShellComplete] | None:594 """Look up a registered :class:`ShellComplete` subclass by the name595 provided by the completion instruction environment variable. If the596 name isn't registered, returns ``None``.597598 :param shell: Name the class is registered under.599 """600 return _available_shells.get(shell)601602603def split_arg_string(string: str) -> list[str]:604 """Split an argument string as with :func:`shlex.split`, but don't605 fail if the string is incomplete. Ignores a missing closing quote or606 incomplete escape sequence and uses the partial token as-is.607608 .. code-block:: python609610 split_arg_string("example 'my file")611 ["example", "my file"]612613 split_arg_string("example my\\")614 ["example", "my"]615616 :param string: String to split.617618 .. versionchanged:: 8.2619 Moved to ``shell_completion`` from ``parser``.620 """621 import shlex622623 lex = shlex.shlex(string, posix=True)624 lex.whitespace_split = True625 lex.commenters = ""626 out: list[str] = []627628 try:629 out.extend(lex)630 except ValueError:631 # Raised when end-of-string is reached in an invalid state. Use632 # the partial token as-is. The quote or escape character is in633 # lex.state, not lex.token.634 out.append(lex.token)635636 return out637638639def _is_incomplete_argument(ctx: Context, param: Parameter) -> bool:640 """Determine if the given parameter is an argument that can still641 accept values.642643 :param ctx: Invocation context for the command represented by the644 parsed complete args.645 :param param: Argument object being checked.646 """647 if not isinstance(param, Argument):648 return False649650 value = ctx.params.get(param.name)651 return (652 param.nargs == -1653 or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE654 or (655 param.nargs > 1656 and isinstance(value, (tuple, list))657 and len(value) < param.nargs658 )659 )660661662def _start_of_option(ctx: Context, value: str) -> bool:663 """Check if the value looks like the start of an option."""664 if not value:665 return False666667 c = value[0]668 return c in ctx._opt_prefixes669670671def _is_incomplete_option(ctx: Context, args: list[str], param: Parameter) -> bool:672 """Determine if the given parameter is an option that needs a value.673674 :param args: List of complete args before the incomplete value.675 :param param: Option object being checked.676 """677 if not isinstance(param, Option):678 return False679680 if param.is_flag or param.count:681 return False682683 last_option = None684685 for index, arg in enumerate(reversed(args)):686 if index + 1 > param.nargs:687 break688689 if _start_of_option(ctx, arg):690 last_option = arg691 break692693 return last_option is not None and last_option in param.opts694695696def _resolve_context(697 cli: Command,698 ctx_args: cabc.MutableMapping[str, t.Any],699 prog_name: str,700 args: list[str],701) -> Context:702 """Produce the context hierarchy starting with the command and703 traversing the complete arguments. This only follows the commands,704 it doesn't trigger input prompts or callbacks.705706 :param cli: Command being called.707 :param prog_name: Name of the executable in the shell.708 :param args: List of complete args before the incomplete value.709 """710 ctx_args["resilient_parsing"] = True711 with cli.make_context(prog_name, args.copy(), **ctx_args) as ctx:712 args = ctx._protected_args + ctx.args713714 while args:715 command = ctx.command716717 if isinstance(command, Group):718 if not command.chain:719 name, cmd, args = command.resolve_command(ctx, args)720721 if cmd is None:722 return ctx723724 with cmd.make_context(725 name, args, parent=ctx, resilient_parsing=True726 ) as sub_ctx:727 ctx = sub_ctx728 args = ctx._protected_args + ctx.args729 else:730 sub_ctx = ctx731732 while args:733 name, cmd, args = command.resolve_command(ctx, args)734735 if cmd is None:736 return ctx737738 with cmd.make_context(739 name,740 args,741 parent=ctx,742 allow_extra_args=True,743 allow_interspersed_args=False,744 resilient_parsing=True,745 ) as sub_sub_ctx:746 sub_ctx = sub_sub_ctx747 args = sub_ctx.args748749 ctx = sub_ctx750 args = [*sub_ctx._protected_args, *sub_ctx.args]751 else:752 break753754 return ctx755756757def _resolve_incomplete(758 ctx: Context, args: list[str], incomplete: str759) -> tuple[Command | Parameter, str]:760 """Find the Click object that will handle the completion of the761 incomplete value. Return the object and the incomplete value.762763 :param ctx: Invocation context for the command represented by764 the parsed complete args.765 :param args: List of complete args before the incomplete value.766 :param incomplete: Value being completed. May be empty.767 """768 # Different shells treat an "=" between a long option name and769 # value differently. Might keep the value joined, return the "="770 # as a separate item, or return the split name and value. Always771 # split and discard the "=" to make completion easier.772 if incomplete == "=":773 incomplete = ""774 elif "=" in incomplete and _start_of_option(ctx, incomplete):775 name, _, incomplete = incomplete.partition("=")776 args.append(name)777778 # The "--" marker tells Click to stop treating values as options779 # even if they start with the option character. If it hasn't been780 # given and the incomplete arg looks like an option, the current781 # command will provide option name completions.782 if "--" not in args and _start_of_option(ctx, incomplete):783 return ctx.command, incomplete784785 params = ctx.command.get_params(ctx)786787 # If the last complete arg is an option name with an incomplete788 # value, the option will provide value completions.789 for param in params:790 if _is_incomplete_option(ctx, args, param):791 return param, incomplete792793 # It's not an option name or value. The first argument without a794 # parsed value will provide value completions.795 for param in params:796 if _is_incomplete_argument(ctx, param):797 return param, incomplete798799 # There were no unparsed arguments, the command may be a group that800 # will provide command name completions.801 return ctx.command, incomplete