Skip to content
Myr

redesign shell completion system

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Amy · committed by David Lord · parent 47ecf34 · Browse files · 4 files+702 added−390 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Kai Chen <kaichen120@gmail.com>
  • Co-authored-by: David Lord <davidism@gmail.com>

Diff stats

4 files+702 added−390 removed

  • other:+702 added−390 removed

4 files+702 added−390 removed

deleted:src/click/_bashcomplete.py-371 removed
1import copy2import os3import re4from collections import abc56from .core import Argument7from .core import MultiCommand8from .core import Option9from .parser import split_arg_string10from .types import Choice11from .utils import echo1213WORDBREAK = "="1415# Note, only BASH version 4.4 and later have the nosort option.16COMPLETION_SCRIPT_BASH = """17%(complete_func)s() {18 local IFS=$'\n'19 COMPREPLY=( $( env COMP_WORDS="${COMP_WORDS[*]}" \\20 COMP_CWORD=$COMP_CWORD \\21 %(autocomplete_var)s=complete $1 ) )22 return 023}2425%(complete_func)s_setup() {26 local COMPLETION_OPTIONS=""27 local BASH_VERSION_ARR=(${BASH_VERSION//./ })28 # Only BASH version 4.4 and later have the nosort option.29 if [ ${BASH_VERSION_ARR[0]} -gt 4 ] || ([ ${BASH_VERSION_ARR[0]} -eq 4 ] \30&& [ ${BASH_VERSION_ARR[1]} -ge 4 ]); then31 COMPLETION_OPTIONS="-o nosort"32 fi3334 complete $COMPLETION_OPTIONS -F %(complete_func)s %(script_names)s35}3637%(complete_func)s_setup38"""3940COMPLETION_SCRIPT_ZSH = """41#compdef %(script_names)s4243%(complete_func)s() {44 local -a completions45 local -a completions_with_descriptions46 local -a response47 (( ! $+commands[%(script_names)s] )) && return 14849 response=("${(@f)$( env COMP_WORDS=\"${words[*]}\" \\50 COMP_CWORD=$((CURRENT-1)) \\51 %(autocomplete_var)s=\"complete_zsh\" \\52 %(script_names)s )}")5354 for key descr in ${(kv)response}; do55 if [[ "$descr" == "_" ]]; then56 completions+=("$key")57 else58 completions_with_descriptions+=("$key":"$descr")59 fi60 done6162 if [ -n "$completions_with_descriptions" ]; then63 _describe -V unsorted completions_with_descriptions -U64 fi6566 if [ -n "$completions" ]; then67 compadd -U -V unsorted -a completions68 fi69 compstate[insert]="automenu"70}7172compdef %(complete_func)s %(script_names)s73"""7475COMPLETION_SCRIPT_FISH = (76 "complete --no-files --command %(script_names)s --arguments"77 ' "(env %(autocomplete_var)s=complete_fish'78 " COMP_WORDS=(commandline -cp) COMP_CWORD=(commandline -t)"79 ' %(script_names)s)"'80)8182_completion_scripts = {83 "bash": COMPLETION_SCRIPT_BASH,84 "zsh": COMPLETION_SCRIPT_ZSH,85 "fish": COMPLETION_SCRIPT_FISH,86}8788_invalid_ident_char_re = re.compile(r"[^a-zA-Z0-9_]")899091def get_completion_script(prog_name, complete_var, shell):92 cf_name = _invalid_ident_char_re.sub("", prog_name.replace("-", "_"))93 script = _completion_scripts.get(shell, COMPLETION_SCRIPT_BASH)94 return (95 script96 % {97 "complete_func": f"_{cf_name}_completion",98 "script_names": prog_name,99 "autocomplete_var": complete_var,100 }101 ).strip() + ";"102103104def resolve_ctx(cli, prog_name, args):105 """Parse into a hierarchy of contexts. Contexts are connected106 through the parent variable.107108 :param cli: command definition109 :param prog_name: the program that is running110 :param args: full list of args111 :return: the final context/command parsed112 """113 ctx = cli.make_context(prog_name, args, resilient_parsing=True)114 args = ctx.protected_args + ctx.args115 while args:116 if isinstance(ctx.command, MultiCommand):117 if not ctx.command.chain:118 cmd_name, cmd, args = ctx.command.resolve_command(ctx, args)119 if cmd is None:120 return ctx121 ctx = cmd.make_context(122 cmd_name, args, parent=ctx, resilient_parsing=True123 )124 args = ctx.protected_args + ctx.args125 else:126 # Walk chained subcommand contexts saving the last one.127 while args:128 cmd_name, cmd, args = ctx.command.resolve_command(ctx, args)129 if cmd is None:130 return ctx131 sub_ctx = cmd.make_context(132 cmd_name,133 args,134 parent=ctx,135 allow_extra_args=True,136 allow_interspersed_args=False,137 resilient_parsing=True,138 )139 args = sub_ctx.args140 ctx = sub_ctx141 args = sub_ctx.protected_args + sub_ctx.args142 else:143 break144 return ctx145146147def start_of_option(param_str):148 """149 :param param_str: param_str to check150 :return: whether or not this is the start of an option declaration151 (i.e. starts "-" or "--")152 """153 return param_str and param_str[:1] == "-"154155156def is_incomplete_option(all_args, cmd_param):157 """158 :param all_args: the full original list of args supplied159 :param cmd_param: the current command parameter160 :return: whether or not the last option declaration (i.e. starts161 "-" or "--") is incomplete and corresponds to this cmd_param. In162 other words whether this cmd_param option can still accept163 values164 """165 if not isinstance(cmd_param, Option):166 return False167 if cmd_param.is_flag:168 return False169 last_option = None170 for index, arg_str in enumerate(171 reversed([arg for arg in all_args if arg != WORDBREAK])172 ):173 if index + 1 > cmd_param.nargs:174 break175 if start_of_option(arg_str):176 last_option = arg_str177178 return True if last_option and last_option in cmd_param.opts else False179180181def is_incomplete_argument(current_params, cmd_param):182 """183 :param current_params: the current params and values for this184 argument as already entered185 :param cmd_param: the current command parameter186 :return: whether or not the last argument is incomplete and187 corresponds to this cmd_param. In other words whether or not the188 this cmd_param argument can still accept values189 """190 if not isinstance(cmd_param, Argument):191 return False192 current_param_values = current_params[cmd_param.name]193 if current_param_values is None:194 return True195 if cmd_param.nargs == -1:196 return True197 if (198 isinstance(current_param_values, abc.Iterable)199 and cmd_param.nargs > 1200 and len(current_param_values) < cmd_param.nargs201 ):202 return True203 return False204205206def get_user_autocompletions(ctx, args, incomplete, cmd_param):207 """208 :param ctx: context associated with the parsed command209 :param args: full list of args210 :param incomplete: the incomplete text to autocomplete211 :param cmd_param: command definition212 :return: all the possible user-specified completions for the param213 """214 results = []215 if isinstance(cmd_param.type, Choice):216 # Choices don't support descriptions.217 results = [218 (c, None) for c in cmd_param.type.choices if str(c).startswith(incomplete)219 ]220 elif cmd_param.autocompletion is not None:221 dynamic_completions = cmd_param.autocompletion(222 ctx=ctx, args=args, incomplete=incomplete223 )224 results = [225 c if isinstance(c, tuple) else (c, None) for c in dynamic_completions226 ]227 return results228229230def get_visible_commands_starting_with(ctx, starts_with):231 """232 :param ctx: context associated with the parsed command233 :starts_with: string that visible commands must start with.234 :return: all visible (not hidden) commands that start with starts_with.235 """236 for c in ctx.command.list_commands(ctx):237 if c.startswith(starts_with):238 command = ctx.command.get_command(ctx, c)239 if not command.hidden:240 yield command241242243def add_subcommand_completions(ctx, incomplete, completions_out):244 # Add subcommand completions.245 if isinstance(ctx.command, MultiCommand):246 completions_out.extend(247 [248 (c.name, c.get_short_help_str())249 for c in get_visible_commands_starting_with(ctx, incomplete)250 ]251 )252253 # Walk up the context list and add any other completion254 # possibilities from chained commands255 while ctx.parent is not None:256 ctx = ctx.parent257 if isinstance(ctx.command, MultiCommand) and ctx.command.chain:258 remaining_commands = [259 c260 for c in get_visible_commands_starting_with(ctx, incomplete)261 if c.name not in ctx.protected_args262 ]263 completions_out.extend(264 [(c.name, c.get_short_help_str()) for c in remaining_commands]265 )266267268def get_choices(cli, prog_name, args, incomplete):269 """270 :param cli: command definition271 :param prog_name: the program that is running272 :param args: full list of args273 :param incomplete: the incomplete text to autocomplete274 :return: all the possible completions for the incomplete275 """276 all_args = copy.deepcopy(args)277278 ctx = resolve_ctx(cli, prog_name, args)279 if ctx is None:280 return []281282 has_double_dash = "--" in all_args283284 # In newer versions of bash long opts with '='s are partitioned, but285 # it's easier to parse without the '='286 if start_of_option(incomplete) and WORDBREAK in incomplete:287 partition_incomplete = incomplete.partition(WORDBREAK)288 all_args.append(partition_incomplete[0])289 incomplete = partition_incomplete[2]290 elif incomplete == WORDBREAK:291 incomplete = ""292293 completions = []294 if not has_double_dash and start_of_option(incomplete):295 # completions for partial options296 for param in ctx.command.get_params(ctx):297 if isinstance(param, Option) and not param.hidden:298 param_opts = [299 param_opt300 for param_opt in param.opts + param.secondary_opts301 if param_opt not in all_args or param.multiple302 ]303 completions.extend(304 [(o, param.help) for o in param_opts if o.startswith(incomplete)]305 )306 return completions307 # completion for option values from user supplied values308 for param in ctx.command.get_params(ctx):309 if is_incomplete_option(all_args, param):310 return get_user_autocompletions(ctx, all_args, incomplete, param)311 # completion for argument values from user supplied values312 for param in ctx.command.get_params(ctx):313 if is_incomplete_argument(ctx.params, param):314 return get_user_autocompletions(ctx, all_args, incomplete, param)315316 add_subcommand_completions(ctx, incomplete, completions)317 # Sort before returning so that proper ordering can be enforced in custom types.318 return sorted(completions)319320321def do_complete(cli, prog_name, include_descriptions):322 cwords = split_arg_string(os.environ["COMP_WORDS"])323 cword = int(os.environ["COMP_CWORD"])324 args = cwords[1:cword]325 try:326 incomplete = cwords[cword]327 except IndexError:328 incomplete = ""329330 for item in get_choices(cli, prog_name, args, incomplete):331 echo(item[0])332 if include_descriptions:333 # ZSH has trouble dealing with empty array parameters when334 # returned from commands, use '_' to indicate no description335 # is present.336 echo(item[1] if item[1] else "_")337338 return True339340341def do_complete_fish(cli, prog_name):342 cwords = split_arg_string(os.environ["COMP_WORDS"])343 incomplete = os.environ["COMP_CWORD"]344 args = cwords[1:]345346 for item in get_choices(cli, prog_name, args, incomplete):347 if item[1]:348 echo(f"{item[0]}\t{item[1]}")349 else:350 echo(item[0])351352 return True353354355def bashcomplete(cli, prog_name, complete_var, complete_instr):356 if "_" in complete_instr:357 command, shell = complete_instr.split("_", 1)358 else:359 command = complete_instr360 shell = "bash"361362 if command == "source":363 echo(get_completion_script(prog_name, complete_var, shell))364 return True365 elif command == "complete":366 if shell == "fish":367 return do_complete_fish(cli, prog_name)368 elif shell in {"bash", "zsh"}:369 return do_complete(cli, prog_name, shell == "zsh")370371 return False
modified:src/click/core.py+142 added-19 removed
45 unmodified lines
46 if cmd.deprecated:47 echo(style(DEPRECATED_INVOKE_NOTICE.format(name=cmd.name), fg="red"), err=True)484950def fast_exit(code):51 """Exit without garbage collection, this speeds up exit by about 10ms for52 things like bash completion.50def _fast_exit(code):51 """Low-level exit that skips Python's cleanup but speeds up exit by52 about 10ms for things like shell completion.5354 :param code: Exit code.55 """56 sys.stdout.flush()57 sys.stderr.flush()58 os._exit(code)596059def _bashcomplete(cmd, prog_name, complete_var=None):60 """Internal handler for the bash completion support."""61 if complete_var is None:62 complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper()63 complete_instr = os.environ.get(complete_var)64 if not complete_instr:65 return61def _complete_visible_commands(ctx, incomplete):62 """List all the subcommands of a group that start with the63 incomplete value and aren't hidden.6467 from ._bashcomplete import bashcomplete65 :param ctx: Invocation context for the group.66 :param incomplete: Value being completed. May be empty.67 """68 for name in ctx.command.list_commands(ctx):69 if name.startswith(incomplete):70 command = ctx.command.get_command(ctx, name)7169 if bashcomplete(cmd, prog_name, complete_var, complete_instr):70 fast_exit(1)72 if not command.hidden:73 yield command747576def _check_multicommand(base_command, cmd_name, cmd, register=False):77 if not base_command.chain or not isinstance(cmd, MultiCommand):
785 unmodified lines
863 implementation is raising a not implemented error.864 """865 raise NotImplementedError("Base commands are not invokable by default")866867 def shell_complete(self, ctx, args, incomplete):868 """Return a list of completions for the incomplete value. Looks869 at the names of chained multi-commands.870871 Any command could be part of a chained multi-command, so sibling872 commands are valid at any point during command completion. Other873 command classes will return more completions.874875 :param ctx: Invocation context for this command.876 :param args: List of complete args before the incomplete value.877 :param incomplete: Value being completed. May be empty.878879 .. versionadded:: 8.0880 """881 results = []882883 while ctx.parent is not None:884 ctx = ctx.parent885886 if isinstance(ctx.command, MultiCommand) and ctx.command.chain:887 results.extend(888 ("plain", command.name, command.get_short_help_str())889 for command in _complete_visible_commands(ctx, incomplete)890 if command.name not in ctx.protected_args891 )892893 return results894895 def main(896 self,897 args=None,898 prog_name=None,
44 unmodified lines
943944 if prog_name is None:945 prog_name = _detect_program_name()946916 # Hook for the Bash completion. This only activates if the Bash917 # completion is actually enabled, otherwise this is quite a fast918 # noop.919 _bashcomplete(self, prog_name, complete_var)947 # Process shell completion requests and exit early.948 self._main_shell_completion(prog_name, complete_var)949950 try:951 try:952 with self.make_context(prog_name, args, **extra) as ctx:
41 unmodified lines
994 raise995 echo("Aborted!", file=sys.stderr)996 sys.exit(1)997998 def _main_shell_completion(self, prog_name, complete_var=None):999 """Check if the shell is asking for tab completion, process1000 that, then exit early. Called from :meth:`main` before the1001 program is invoked.10021003 :param prog_name: Name of the executable in the shell.1004 :param complete_var: Name of the environment variable that holds1005 the completion instruction. Defaults to1006 ``_{PROG_NAME}_COMPLETE``.1007 """1008 if complete_var is None:1009 complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper()10101011 instruction = os.environ.get(complete_var)10121013 if not instruction:1014 return10151016 from .shell_completion import shell_complete10171018 rv = shell_complete(self, prog_name, complete_var, instruction)1019 _fast_exit(rv)10201021 def __call__(self, *args, **kwargs):1022 """Alias for :meth:`main`."""1023 return self.main(*args, **kwargs)1024
250 unmodified lines
1275 _maybe_show_deprecated_notice(self)1276 if self.callback is not None:1277 return ctx.invoke(self.callback, **ctx.params)12781279 def shell_complete(self, ctx, args, incomplete):1280 """Return a list of completions for the incomplete value. Looks1281 at the names of options and chained multi-commands.12821283 :param ctx: Invocation context for this command.1284 :param args: List of complete args before the incomplete value.1285 :param incomplete: Value being completed. May be empty.12861287 .. versionadded:: 8.01288 """1289 results = []12901291 if incomplete and not incomplete[0].isalnum():1292 for param in self.get_params(ctx):1293 if not isinstance(param, Option) or param.hidden:1294 continue12951296 names = (1297 name1298 for name in param.opts + param.secondary_opts1299 if name not in args or param.multiple1300 )1301 results.extend(1302 ("plain", name, param.help)1303 for name in names1304 if name.startswith(incomplete)1305 )13061307 results.extend(super().shell_complete(ctx, args, incomplete))1308 return results130913101311class MultiCommand(Command):1312 """A multi command is the basic implementation of a command that1313 dispatches to subcommands. The most common version is the1314 :class:`Group`.
248 unmodified lines
1563 if cmd is None and not ctx.resilient_parsing:1564 if split_opt(cmd_name)[0]:1565 self.parse_args(ctx, ctx.args)1566 ctx.fail(f"No such command '{original_cmd_name}'.")1567 return cmd.name if cmd else None, cmd, args[1:]15681485 return cmd.name, cmd, args[1:]14861569 def get_command(self, ctx, cmd_name):1570 """Given a context and a command name, this returns a1571 :class:`Command` object if it exists or returns `None`.1572 """
4 unmodified lines
1577 appear.1578 """1579 return []15801581 def shell_complete(self, ctx, args, incomplete):1582 """Return a list of completions for the incomplete value. Looks1583 at the names of options, subcommands, and chained1584 multi-commands.15851586 :param ctx: Invocation context for this command.1587 :param args: List of complete args before the incomplete value.1588 :param incomplete: Value being completed. May be empty.15891590 .. versionadded:: 8.01591 """1592 results = [1593 ("plain", command.name, command.get_short_help_str())1594 for command in _complete_visible_commands(ctx, incomplete)1595 ]1596 results.extend(super().shell_complete(ctx, args, incomplete))1597 return results159815991600class Group(MultiCommand):1601 """A group allows a command to have subcommands attached. This is1602 the most common way to implement nesting in Click.1603
172 unmodified lines
1776 should not be set for arguments or it will inverse the1777 order of processing.1778 :param envvar: a string or list of strings that are environment variables1779 that should be checked.1780 :param autocompletion: A function that returns custom shell1781 completions. Used instead of the param's type completion if1782 given.17831784 .. versionchanged:: 7.11785 Empty environment variables are ignored rather than taking the1786 empty string value. This makes it possible for scripts to clear
232 unmodified lines
2019 """2020 hint_list = self.opts or [self.human_readable_name]2021 return " / ".join(repr(x) for x in hint_list)20222023 def shell_complete(self, ctx, args, incomplete):2024 """Return a list of completions for the incomplete value. If an2025 :attr:`autocompletion` function was given, it is used.2026 Otherwise, the :attr:`type`2027 :meth:`~click.types.ParamType.shell_complete` function is used.20282029 :param ctx: Invocation context for this command.2030 :param args: List of complete args before the incomplete value.2031 :param incomplete: Value being completed. May be empty.20322033 .. versionadded:: 8.02034 """2035 if self.autocompletion is not None:2036 return [2037 ("plain",) + c if isinstance(c, tuple) else ("plain", c, None)2038 for c in self.autocompletion(ctx=ctx, args=args, incomplete=incomplete)2039 ]20402041 return self.type.shell_complete(ctx, args, incomplete)204220432044class Option(Parameter):2045 """Options are usually optional values on the command line and2046 have some extra features that arguments don't have.2047
407 unmodified lines
added:src/click/shell_completion.py+507 added
1import os2import re34from .core import Argument5from .core import MultiCommand6from .core import Option7from .parser import split_arg_string8from .utils import echo91011def shell_complete(cli, prog_name, complete_var, instruction):12 """Perform shell completion for the given CLI program.1314 :param cli: Command being called.15 :param prog_name: Name of the executable in the shell.16 :param complete_var: Name of the environment variable that holds17 the completion instruction.18 :param instruction: Value of ``complete_var`` with the completion19 instruction and shell, in the form ``instruction_shell``.20 :return: Status code to exit with.21 """22 instruction, _, shell = instruction.partition("_")23 comp_cls = get_completion_class(shell)2425 if comp_cls is None:26 return 12728 comp = comp_cls(cli, prog_name, complete_var)2930 if instruction == "source":31 echo(comp.source())32 return 03334 if instruction == "complete":35 echo(comp.complete())36 return 03738 return 1394041# Only Bash >= 4.4 has the nosort option.42_SOURCE_BASH = """\43%(complete_func)s() {44 local IFS=$'\\n'45 local response4647 response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \48%(complete_var)s=complete_bash $1)4950 for completion in $response; do51 IFS=',' read type value <<< "$completion"5253 if [[ $type == 'dir' ]]; then54 COMREPLY=()55 compopt -o dirnames56 elif [[ $type == 'file' ]]; then57 COMREPLY=()58 compopt -o default59 elif [[ $type == 'plain' ]]; then60 COMPREPLY+=($value)61 fi62 done6364 return 065}6667%(complete_func)s_setup() {68 complete -o nosort -F %(complete_func)s %(prog_name)s69}7071%(complete_func)s_setup;72"""7374_SOURCE_ZSH = """\75#compdef %(prog_name)s7677%(complete_func)s() {78 local -a completions79 local -a completions_with_descriptions80 local -a response81 (( ! $+commands[%(prog_name)s] )) && return 18283 response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) \84%(complete_var)s=complete_zsh %(prog_name)s)}")8586 for type key descr in ${response}; do87 if [[ "$type" == "plain" ]]; then88 if [[ "$descr" == "_" ]]; then89 completions+=("$key")90 else91 completions_with_descriptions+=("$key":"$descr")92 fi93 elif [[ "$type" == "dir" ]]; then94 _path_files -/95 elif [[ "$type" == "file" ]]; then96 _path_files -f97 fi98 done99100 if [ -n "$completions_with_descriptions" ]; then101 _describe -V unsorted completions_with_descriptions -U102 fi103104 if [ -n "$completions" ]; then105 compadd -U -V unsorted -a completions106 fi107}108109compdef %(complete_func)s %(prog_name)s;110"""111112_SOURCE_FISH = """\113function %(complete_func)s;114 set -l response;115116 for value in (env %(complete_var)s=complete_fish COMP_WORDS=(commandline -cp) \117COMP_CWORD=(commandline -t) %(prog_name)s);118 set response $response $value;119 end;120121 for completion in $response;122 set -l metadata (string split "," $completion);123124 if test $metadata[1] = "dir";125 __fish_complete_directories $metadata[2];126 else if test $metadata[1] = "file";127 __fish_complete_path $metadata[2];128 else if test $metadata[1] = "plain";129 echo $metadata[2];130 end;131 end;132end;133134complete --no-files --command %(prog_name)s --arguments \135"(%(complete_func)s)";136"""137138139class ShellComplete:140 """Base class for providing shell completion support. A subclass for141 a given shell will override attributes and methods to implement the142 completion instructions (``source`` and ``complete``).143144 :param cli: Command being called.145 :param prog_name: Name of the executable in the shell.146 :param complete_var: Name of the environment variable that holds147 the completion instruction.148149 .. versionadded:: 8.0150 """151152 name = None153 """Name to register the shell as with :func:`add_completion_class`.154 This is used in completion instructions (``source_{name}`` and155 ``complete_{name}``).156 """157 source_template = None158 """Completion script template formatted by :meth:`source`. This must159 be provided by subclasses.160 """161162 def __init__(self, cli, prog_name, complete_var):163 self.cli = cli164 self.prog_name = prog_name165 self.complete_var = complete_var166167 @property168 def func_name(self):169 """The name of the shell function defined by the completion170 script.171 """172 safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), re.ASCII)173 return f"_{safe_name}_completion"174175 def source_vars(self):176 """Vars for formatting :attr:`source_template`.177178 By default this provides ``complete_func``, ``complete_var``,179 and ``prog_name``.180 """181 return {182 "complete_func": self.func_name,183 "complete_var": self.complete_var,184 "prog_name": self.prog_name,185 }186187 def source(self):188 """Produce the shell script that defines the completion189 function. By default this ``%``-style formats190 :attr:`source_template` with the dict returned by191 :meth:`source_vars`.192 """193 return self.source_template % self.source_vars()194195 def get_completion_args(self):196 """Use the env vars defined by the shell script to return a197 tuple of ``args, incomplete``. This must be implemented by198 subclasses.199 """200 raise NotImplementedError201202 def get_completions(self, args, incomplete):203 """Determine the context and last complete command or parameter204 from the complete args. Call that object's ``shell_complete``205 method to get the completions for the incomplete value.206207 :param args: List of complete args before the incomplete value.208 :param incomplete: Value being completed. May be empty.209 """210 ctx = _resolve_context(self.cli, self.prog_name, args)211212 if ctx is None:213 return []214215 obj, incomplete = _resolve_incomplete(ctx, args, incomplete)216 return obj.shell_complete(ctx, args, incomplete)217218 def format_completion(self, item):219 """Format a completion item into the form recognized by the220 shell script. This must be implemented by subclasses.221222 :param item: Completion item to format.223 """224 raise NotImplementedError225226 def complete(self):227 """Produce the completion data to send back to the shell.228229 By default this calls :meth:`get_completion_args`, gets the230 completions, then calls `:meth:`format_completion` for each231 completion.232 """233 args, incomplete = self.get_completion_args()234 completions = self.get_completions(args, incomplete)235 out = [self.format_completion(item) for item in completions]236 return "\n".join(out)237238239class BashComplete(ShellComplete):240 """Shell completion for Bash."""241242 name = "bash"243 source_template = _SOURCE_BASH244245 def source(self):246 import subprocess247248 output = subprocess.run(["bash", "--version"], stdout=subprocess.PIPE)249 match = re.search(r"version (\d)\.(\d)\.\d", output.stdout.decode())250251 if match is not None:252 major, minor = match.groups()253254 if major < "4" or major == "4" and minor < "4":255 raise RuntimeError(256 "Shell completion is not supported for Bash"257 " versions older than 4.4."258 )259 else:260 raise RuntimeError(261 "Couldn't detect Bash version, shell completion is not supported."262 )263264 return super().source()265266 def get_completion_args(self):267 cwords = split_arg_string(os.environ["COMP_WORDS"])268 cword = int(os.environ["COMP_CWORD"])269 args = cwords[1:cword]270271 try:272 incomplete = cwords[cword]273 except IndexError:274 incomplete = ""275276 return args, incomplete277278 def format_completion(self, item):279 type, value, _ = item280 return f"{type},{value}"281282283class ZshComplete(ShellComplete):284 """Shell completion for Zsh."""285286 name = "zsh"287 source_template = _SOURCE_ZSH288289 def get_completion_args(self):290 cwords = split_arg_string(os.environ["COMP_WORDS"])291 cword = int(os.environ["COMP_CWORD"])292 args = cwords[1:cword]293294 try:295 incomplete = cwords[cword]296 except IndexError:297 incomplete = ""298299 return args, incomplete300301 def format_completion(self, item):302 type, value, desc = item303 return f"{type}\n{value}\n{desc if desc else '_'}"304305306class FishComplete(ShellComplete):307 """Shell completion for Fish."""308309 name = "fish"310 source_template = _SOURCE_FISH311312 def get_completion_args(self):313 cwords = split_arg_string(os.environ["COMP_WORDS"])314 incomplete = os.environ["COMP_CWORD"]315 args = cwords[1:]316317 # Fish stores the partial word in both COMP_WORDS and318 # COMP_CWORD, remove it from complete args.319 if incomplete and args and args[-1] == incomplete:320 args.pop()321322 return args, incomplete323324 def format_completion(self, item):325 type, value, desc = item326327 if desc:328 return f"{type},{value}\t{desc}"329330 return f"{type},{value}"331332333_available_shells = {334 "bash": BashComplete,335 "fish": FishComplete,336 "zsh": ZshComplete,337}338339340def add_completion_class(cls, name=None):341 """Register a :class:`ShellComplete` subclass under the given name.342 The name will be provided by the completion instruction environment343 variable during completion.344345 :param cls: The completion class that will handle completion for the346 shell.347 :param name: Name to register the class under. Defaults to the348 class's ``name`` attribute.349 """350 if name is None:351 name = cls.name352353 _available_shells[name] = cls354355356def get_completion_class(shell):357 """Look up a registered :class:`ShellComplete` subclass by the name358 provided by the completion instruction environment variable. If the359 name isn't registered, returns ``None``.360361 :param shell: Name the class is registered under.362 """363 return _available_shells.get(shell)364365366def _is_incomplete_argument(values, param):367 """Determine if the given parameter is an argument that can still368 accept values.369370 :param values: Dict of param names and values parsed from the371 command line args.372 :param param: Argument object being checked.373 """374 if not isinstance(param, Argument):375 return False376377 value = values[param.name]378379 if value is None:380 return True381382 if param.nargs == -1:383 return True384385 if isinstance(value, list) and param.nargs > 1 and len(value) < param.nargs:386 return True387388 return False389390391def _start_of_option(value):392 """Check if the value looks like the start of an option."""393 return value and not value[0].isalnum()394395396def _is_incomplete_option(args, param):397 """Determine if the given parameter is an option that needs a value.398399 :param args: List of complete args before the incomplete value.400 :param param: Option object being checked.401 """402 if not isinstance(param, Option):403 return False404405 if param.is_flag:406 return False407408 last_option = None409410 for index, arg in enumerate(reversed(args)):411 if index + 1 > param.nargs:412 break413414 if _start_of_option(arg):415 last_option = arg416417 return bool(last_option and last_option in param.opts)418419420def _resolve_context(cli, prog_name, args):421 """Produce the context hierarchy starting with the command and422 traversing the complete arguments. This only follows the commands,423 it doesn't trigger input prompts or callbacks.424425 :param cli: Command being called.426 :param prog_name: Name of the executable in the shell.427 :param args: List of complete args before the incomplete value.428 """429 ctx = cli.make_context(prog_name, args.copy(), resilient_parsing=True)430 args = ctx.protected_args + ctx.args431432 while args:433 if isinstance(ctx.command, MultiCommand):434 if not ctx.command.chain:435 name, cmd, args = ctx.command.resolve_command(ctx, args)436437 if cmd is None:438 return ctx439440 ctx = cmd.make_context(name, args, parent=ctx, resilient_parsing=True)441 args = ctx.protected_args + ctx.args442 else:443 while args:444 name, cmd, args = ctx.command.resolve_command(ctx, args)445446 if cmd is None:447 return ctx448449 sub_ctx = cmd.make_context(450 name,451 args,452 parent=ctx,453 allow_extra_args=True,454 allow_interspersed_args=False,455 resilient_parsing=True,456 )457 args = sub_ctx.args458459 ctx = sub_ctx460 args = sub_ctx.protected_args + sub_ctx.args461 else:462 break463464 return ctx465466467def _resolve_incomplete(ctx, args, incomplete):468 """Find the Click object that will handle the completion of the469 incomplete value. Return the object and the incomplete value.470471 :param ctx: Invocation context for the command represented by472 the parsed complete args.473 :param args: List of complete args before the incomplete value.474 :param incomplete: Value being completed. May be empty.475 """476 # Different shells treat an "=" between a long option name and477 # value differently. Might keep the value joined, return the "="478 # as a separate item, or return the split name and value. Always479 # split and discard the "=" to make completion easier.480 if incomplete == "=":481 incomplete = ""482 elif "=" in incomplete and _start_of_option(incomplete):483 name, _, incomplete = incomplete.partition("=")484 args.append(name)485486 # The "--" marker tells Click to stop treating values as options487 # even if they start with the option character. If it hasn't been488 # given and the incomplete arg looks like an option, the current489 # command will provide option name completions.490 if "--" not in args and _start_of_option(incomplete):491 return ctx.command, incomplete492493 # If the last complete arg is an option name with an incomplete494 # value, the option will provide value completions.495 for param in ctx.command.get_params(ctx):496 if _is_incomplete_option(args, param):497 return param, incomplete498499 # It's not an option name or value. The first argument without a500 # parsed value will provide value completions.501 for param in ctx.command.get_params(ctx):502 if _is_incomplete_argument(ctx.params, param):503 return param, incomplete504505 # There were no unparsed arguments, the command may be a group that506 # will provide command name completions.507 return ctx.command, incomplete
modified:src/click/types.py+53 added
105 unmodified lines
106 def fail(self, message, param=None, ctx=None):107 """Helper method to fail with an invalid value message."""108 raise BadParameter(message, ctx=ctx, param=param)109110 def shell_complete(self, ctx, args, incomplete):111 """Return a list of completions for the incomplete value. Most112 types do not provide completions, but some do, and this allows113 custom types to provide custom completions as well.114115 :param ctx: Invocation context for this command.116 :param args: List of complete args before the incomplete value.117 :param incomplete: Value being completed. May be empty.118119 .. versionadded:: 8.0120 """121 return []122123124class CompositeParamType(ParamType):125 is_composite = True126127 @property
133 unmodified lines
261262 def __repr__(self):263 return f"Choice({list(self.choices)})"264265 def shell_complete(self, ctx, args, incomplete):266 """Return a list of completions for the incomplete value based267 on the choices.268269 :param ctx: Invocation context for this command.270 :param args: List of complete args before the incomplete value.271 :param incomplete: Value being completed. May be empty.272273 .. versionadded:: 8.0274 """275 return [276 ("plain", c, None) for c in self.choices if str(c).startswith(incomplete)277 ]278279280class DateTime(ParamType):281 """The DateTime type converts date strings into `datetime` objects.282283 The format strings which are checked are configurable, but default to some
325 unmodified lines
609 param,610 ctx,611 )612613 def shell_complete(self, ctx, args, incomplete):614 """Return a special completion marker that tells the completion615 system to use the shell to provide file path completions.616617 :param ctx: Invocation context for this command.618 :param args: List of complete args before the incomplete value.619 :param incomplete: Value being completed. May be empty.620621 .. versionadded:: 8.0622 """623 return [("file", incomplete, None)]624625626class Path(ParamType):627 """The path type is similar to the :class:`File` type but it performs628 different checks. First of all, instead of returning an open file629 handle it returns just the filename. Secondly, it can perform various
122 unmodified lines
752 )753754 return self.coerce_path_result(rv)755756 def shell_complete(self, ctx, args, incomplete):757 """Return a special completion marker that tells the completion758 system to use the shell to provide path completions for only759 directories or any paths.760761 :param ctx: Invocation context for this command.762 :param args: List of complete args before the incomplete value.763 :param incomplete: Value being completed. May be empty.764765 .. versionadded:: 8.0766 """767 completion_type = "dir" if self.dir_okay and not self.file_okay else "file"768 return [(completion_type, incomplete, None)]769770771class Tuple(CompositeParamType):772 """The default behavior of Click is to apply a type on a value directly.773 This works well in most cases, except for when `nargs` is set to a fixed774 count and different types should be used for different items. In this
109 unmodified lines