Skip to content
Myr

shell_completion.py

This file

Path

src/click/shell_completion.py

603 lines · 18.2 KiB · Python

Last changed by

More robust check of bash version (#2639)Nils Hjeltebefore adoption273fb90

History of this file

Take 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.MutableMapping[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: t.Any = value84        self.type: str = type85        self.help: t.Optional[str] = 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            COMPREPLY=()106            compopt -o dirnames107        elif [[ $type == 'file' ]]; then108            COMPREPLY=()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}159160if [[ $zsh_eval_context[-1] == loadautofunc ]]; then161    # autoload from fpath, call function directly162    %(complete_func)s "$@"163else164    # eval/source/. command, register function for later165    compdef %(complete_func)s %(prog_name)s166fi167"""168169_SOURCE_FISH = """\170function %(complete_func)s;171    set -l response (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \172COMP_CWORD=(commandline -t) %(prog_name)s);173174    for completion in $response;175        set -l metadata (string split "," $completion);176177        if test $metadata[1] = "dir";178            __fish_complete_directories $metadata[2];179        else if test $metadata[1] = "file";180            __fish_complete_path $metadata[2];181        else if test $metadata[1] = "plain";182            echo $metadata[2];183        end;184    end;185end;186187complete --no-files --command %(prog_name)s --arguments \188"(%(complete_func)s)";189"""190191192class ShellComplete:193    """Base class for providing shell completion support. A subclass for194    a given shell will override attributes and methods to implement the195    completion instructions (``source`` and ``complete``).196197    :param cli: Command being called.198    :param prog_name: Name of the executable in the shell.199    :param complete_var: Name of the environment variable that holds200        the completion instruction.201202    .. versionadded:: 8.0203    """204205    name: t.ClassVar[str]206    """Name to register the shell as with :func:`add_completion_class`.207    This is used in completion instructions (``{name}_source`` and208    ``{name}_complete``).209    """210211    source_template: t.ClassVar[str]212    """Completion script template formatted by :meth:`source`. This must213    be provided by subclasses.214    """215216    def __init__(217        self,218        cli: BaseCommand,219        ctx_args: t.MutableMapping[str, t.Any],220        prog_name: str,221        complete_var: str,222    ) -> None:223        self.cli = cli224        self.ctx_args = ctx_args225        self.prog_name = prog_name226        self.complete_var = complete_var227228    @property229    def func_name(self) -> str:230        """The name of the shell function defined by the completion231        script.232        """233        safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), flags=re.ASCII)234        return f"_{safe_name}_completion"235236    def source_vars(self) -> t.Dict[str, t.Any]:237        """Vars for formatting :attr:`source_template`.238239        By default this provides ``complete_func``, ``complete_var``,240        and ``prog_name``.241        """242        return {243            "complete_func": self.func_name,244            "complete_var": self.complete_var,245            "prog_name": self.prog_name,246        }247248    def source(self) -> str:249        """Produce the shell script that defines the completion250        function. By default this ``%``-style formats251        :attr:`source_template` with the dict returned by252        :meth:`source_vars`.253        """254        return self.source_template % self.source_vars()255256    def get_completion_args(self) -> t.Tuple[t.List[str], str]:257        """Use the env vars defined by the shell script to return a258        tuple of ``args, incomplete``. This must be implemented by259        subclasses.260        """261        raise NotImplementedError262263    def get_completions(264        self, args: t.List[str], incomplete: str265    ) -> t.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) -> t.Tuple[t.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) -> t.Tuple[t.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) -> t.Tuple[t.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=t.Type[ShellComplete])405406407_available_shells: t.Dict[str, t.Type[ShellComplete]] = {408    "bash": BashComplete,409    "fish": FishComplete,410    "zsh": ZshComplete,411}412413414def add_completion_class(415    cls: ShellCompleteType, name: t.Optional[str] = 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) -> t.Optional[t.Type[ShellComplete]]: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 _is_incomplete_argument(ctx: Context, param: Parameter) -> bool:445    """Determine if the given parameter is an argument that can still446    accept values.447448    :param ctx: Invocation context for the command represented by the449        parsed complete args.450    :param param: Argument object being checked.451    """452    if not isinstance(param, Argument):453        return False454455    assert param.name is not None456    # Will be None if expose_value is False.457    value = ctx.params.get(param.name)458    return (459        param.nargs == -1460        or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE461        or (462            param.nargs > 1463            and isinstance(value, (tuple, list))464            and len(value) < param.nargs465        )466    )467468469def _start_of_option(ctx: Context, value: str) -> bool:470    """Check if the value looks like the start of an option."""471    if not value:472        return False473474    c = value[0]475    return c in ctx._opt_prefixes476477478def _is_incomplete_option(ctx: Context, args: t.List[str], param: Parameter) -> bool:479    """Determine if the given parameter is an option that needs a value.480481    :param args: List of complete args before the incomplete value.482    :param param: Option object being checked.483    """484    if not isinstance(param, Option):485        return False486487    if param.is_flag or param.count:488        return False489490    last_option = None491492    for index, arg in enumerate(reversed(args)):493        if index + 1 > param.nargs:494            break495496        if _start_of_option(ctx, arg):497            last_option = arg498499    return last_option is not None and last_option in param.opts500501502def _resolve_context(503    cli: BaseCommand,504    ctx_args: t.MutableMapping[str, t.Any],505    prog_name: str,506    args: t.List[str],507) -> Context:508    """Produce the context hierarchy starting with the command and509    traversing the complete arguments. This only follows the commands,510    it doesn't trigger input prompts or callbacks.511512    :param cli: Command being called.513    :param prog_name: Name of the executable in the shell.514    :param args: List of complete args before the incomplete value.515    """516    ctx_args["resilient_parsing"] = True517    ctx = cli.make_context(prog_name, args.copy(), **ctx_args)518    args = ctx.protected_args + ctx.args519520    while args:521        command = ctx.command522523        if isinstance(command, MultiCommand):524            if not command.chain:525                name, cmd, args = command.resolve_command(ctx, args)526527                if cmd is None:528                    return ctx529530                ctx = cmd.make_context(name, args, parent=ctx, resilient_parsing=True)531                args = ctx.protected_args + ctx.args532            else:533                sub_ctx = ctx534535                while args:536                    name, cmd, args = command.resolve_command(ctx, args)537538                    if cmd is None:539                        return ctx540541                    sub_ctx = cmd.make_context(542                        name,543                        args,544                        parent=ctx,545                        allow_extra_args=True,546                        allow_interspersed_args=False,547                        resilient_parsing=True,548                    )549                    args = sub_ctx.args550551                ctx = sub_ctx552                args = [*sub_ctx.protected_args, *sub_ctx.args]553        else:554            break555556    return ctx557558559def _resolve_incomplete(560    ctx: Context, args: t.List[str], incomplete: str561) -> t.Tuple[t.Union[BaseCommand, Parameter], str]:562    """Find the Click object that will handle the completion of the563    incomplete value. Return the object and the incomplete value.564565    :param ctx: Invocation context for the command represented by566        the parsed complete args.567    :param args: List of complete args before the incomplete value.568    :param incomplete: Value being completed. May be empty.569    """570    # Different shells treat an "=" between a long option name and571    # value differently. Might keep the value joined, return the "="572    # as a separate item, or return the split name and value. Always573    # split and discard the "=" to make completion easier.574    if incomplete == "=":575        incomplete = ""576    elif "=" in incomplete and _start_of_option(ctx, incomplete):577        name, _, incomplete = incomplete.partition("=")578        args.append(name)579580    # The "--" marker tells Click to stop treating values as options581    # even if they start with the option character. If it hasn't been582    # given and the incomplete arg looks like an option, the current583    # command will provide option name completions.584    if "--" not in args and _start_of_option(ctx, incomplete):585        return ctx.command, incomplete586587    params = ctx.command.get_params(ctx)588589    # If the last complete arg is an option name with an incomplete590    # value, the option will provide value completions.591    for param in params:592        if _is_incomplete_option(ctx, args, param):593            return param, incomplete594595    # It's not an option name or value. The first argument without a596    # parsed value will provide value completions.597    for param in params:598        if _is_incomplete_argument(ctx, param):599            return param, incomplete600601    # There were no unparsed arguments, the command may be a group that602    # will provide command name completions.603    return ctx.command, incomplete