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
Provenance
- Commit
3c4cacb- Tree
e7effeb- Author
Amy <leiamy12@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
47ecf34
4 files changed+702 added−390 removed
deleted:src/click/_bashcomplete.py-371 removed
1-import copy2-import os3-import re4-from collections import abc5-6-from .core import Argument7-from .core import MultiCommand8-from .core import Option9-from .parser import split_arg_string10-from .types import Choice11-from .utils import echo12-13-WORDBREAK = "="14-15-# Note, only BASH version 4.4 and later have the nosort option.16-COMPLETION_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-}24-25-%(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- fi33-34- complete $COMPLETION_OPTIONS -F %(complete_func)s %(script_names)s35-}36-37-%(complete_func)s_setup38-"""39-40-COMPLETION_SCRIPT_ZSH = """41-#compdef %(script_names)s42-43-%(complete_func)s() {44- local -a completions45- local -a completions_with_descriptions46- local -a response47- (( ! $+commands[%(script_names)s] )) && return 148-49- response=("${(@f)$( env COMP_WORDS=\"${words[*]}\" \\50- COMP_CWORD=$((CURRENT-1)) \\51- %(autocomplete_var)s=\"complete_zsh\" \\52- %(script_names)s )}")53-54- for key descr in ${(kv)response}; do55- if [[ "$descr" == "_" ]]; then56- completions+=("$key")57- else58- completions_with_descriptions+=("$key":"$descr")59- fi60- done61-62- if [ -n "$completions_with_descriptions" ]; then63- _describe -V unsorted completions_with_descriptions -U64- fi65-66- if [ -n "$completions" ]; then67- compadd -U -V unsorted -a completions68- fi69- compstate[insert]="automenu"70-}71-72-compdef %(complete_func)s %(script_names)s73-"""74-75-COMPLETION_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-)81-82-_completion_scripts = {83- "bash": COMPLETION_SCRIPT_BASH,84- "zsh": COMPLETION_SCRIPT_ZSH,85- "fish": COMPLETION_SCRIPT_FISH,86-}87-88-_invalid_ident_char_re = re.compile(r"[^a-zA-Z0-9_]")89-90-91-def 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() + ";"102-103-104-def resolve_ctx(cli, prog_name, args):105- """Parse into a hierarchy of contexts. Contexts are connected106- through the parent variable.107-108- :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 ctx145-146-147-def 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] == "-"154-155-156-def 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_str177-178- return True if last_option and last_option in cmd_param.opts else False179-180-181-def 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 False204-205-206-def 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 results228-229-230-def 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 command241-242-243-def 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- )252-253- # 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- )266-267-268-def 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)277-278- ctx = resolve_ctx(cli, prog_name, args)279- if ctx is None:280- return []281-282- has_double_dash = "--" in all_args283-284- # 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 = ""292-293- 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)315-316- add_subcommand_completions(ctx, incomplete, completions)317- # Sort before returning so that proper ordering can be enforced in custom types.318- return sorted(completions)319-320-321-def 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 = ""329-330- 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 "_")337-338- return True339-340-341-def 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:]345-346- 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])351-352- return True353-354-355-def 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"361-362- 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")370-371- return Falsemodified:src/click/core.py+142 added-19 removed
45 unmodified lines46 if cmd.deprecated:47 echo(style(DEPRECATED_INVOKE_NOTICE.format(name=cmd.name), fg="red"), err=True)48 49 50-def fast_exit(code):51- """Exit without garbage collection, this speeds up exit by about 10ms for52- things like bash completion.50+def _fast_exit(code):51+ """Low-level exit that skips Python's cleanup but speeds up exit by52+ about 10ms for things like shell completion.53+54+ :param code: Exit code.55 """56 sys.stdout.flush()57 sys.stderr.flush()58 os._exit(code)59 60 59-def _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- return61+def _complete_visible_commands(ctx, incomplete):62+ """List all the subcommands of a group that start with the63+ incomplete value and aren't hidden.64 67- 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)71 69- if bashcomplete(cmd, prog_name, complete_var, complete_instr):70- fast_exit(1)72+ if not command.hidden:73+ yield command74 75 76 def _check_multicommand(base_command, cmd_name, cmd, register=False):77 if not base_command.chain or not isinstance(cmd, MultiCommand):785 unmodified lines863 implementation is raising a not implemented error.864 """865 raise NotImplementedError("Base commands are not invokable by default")866 867+ 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.870+871+ 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.874+875+ :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.878+879+ .. versionadded:: 8.0880+ """881+ results = []882+883+ while ctx.parent is not None:884+ ctx = ctx.parent885+886+ 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+ )892+893+ return results894+895 def main(896 self,897 args=None,898 prog_name=None,44 unmodified lines943 944 if prog_name is None:945 prog_name = _detect_program_name()946 916- # 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)949 950 try:951 try:952 with self.make_context(prog_name, args, **extra) as ctx:41 unmodified lines994 raise995 echo("Aborted!", file=sys.stderr)996 sys.exit(1)997 998+ 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.1002+1003+ :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()1010+1011+ instruction = os.environ.get(complete_var)1012+1013+ if not instruction:1014+ return1015+1016+ from .shell_completion import shell_complete1017+1018+ rv = shell_complete(self, prog_name, complete_var, instruction)1019+ _fast_exit(rv)1020+1021 def __call__(self, *args, **kwargs):1022 """Alias for :meth:`main`."""1023 return self.main(*args, **kwargs)1024 250 unmodified lines1275 _maybe_show_deprecated_notice(self)1276 if self.callback is not None:1277 return ctx.invoke(self.callback, **ctx.params)1278 1279+ 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.1282 1283+ :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.1286+1287+ .. versionadded:: 8.01288+ """1289+ results = []1290+1291+ 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+ continue1295+1296+ 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+ )1306+1307+ results.extend(super().shell_complete(ctx, args, incomplete))1308+ return results1309+1310+1311 class 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 lines1563 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:]1568 1485- return cmd.name, cmd, args[1:]1486-1569 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 lines1577 appear.1578 """1579 return []1580 1581+ 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.1585 1586+ :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.1589+1590+ .. 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 results1598+1599+1600 class 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 lines1776 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.1783 1784 .. versionchanged:: 7.11785 Empty environment variables are ignored rather than taking the1786 empty string value. This makes it possible for scripts to clear232 unmodified lines2019 """2020 hint_list = self.opts or [self.human_readable_name]2021 return " / ".join(repr(x) for x in hint_list)2022 2023+ 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.2028 2029+ :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.2032+2033+ .. 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+ ]2040+2041+ return self.type.shell_complete(ctx, args, incomplete)2042+2043+2044 class 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 linesadded:src/click/shell_completion.py+507 added
1+import os2+import re3+4+from .core import Argument5+from .core import MultiCommand6+from .core import Option7+from .parser import split_arg_string8+from .utils import echo9+10+11+def shell_complete(cli, prog_name, complete_var, instruction):12+ """Perform shell completion for the given CLI program.13+14+ :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)24+25+ if comp_cls is None:26+ return 127+28+ comp = comp_cls(cli, prog_name, complete_var)29+30+ if instruction == "source":31+ echo(comp.source())32+ return 033+34+ if instruction == "complete":35+ echo(comp.complete())36+ return 037+38+ return 139+40+41+# Only Bash >= 4.4 has the nosort option.42+_SOURCE_BASH = """\43+%(complete_func)s() {44+ local IFS=$'\\n'45+ local response46+47+ response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \48+%(complete_var)s=complete_bash $1)49+50+ for completion in $response; do51+ IFS=',' read type value <<< "$completion"52+53+ 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+ done63+64+ return 065+}66+67+%(complete_func)s_setup() {68+ complete -o nosort -F %(complete_func)s %(prog_name)s69+}70+71+%(complete_func)s_setup;72+"""73+74+_SOURCE_ZSH = """\75+#compdef %(prog_name)s76+77+%(complete_func)s() {78+ local -a completions79+ local -a completions_with_descriptions80+ local -a response81+ (( ! $+commands[%(prog_name)s] )) && return 182+83+ response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) \84+%(complete_var)s=complete_zsh %(prog_name)s)}")85+86+ 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+ done99+100+ if [ -n "$completions_with_descriptions" ]; then101+ _describe -V unsorted completions_with_descriptions -U102+ fi103+104+ if [ -n "$completions" ]; then105+ compadd -U -V unsorted -a completions106+ fi107+}108+109+compdef %(complete_func)s %(prog_name)s;110+"""111+112+_SOURCE_FISH = """\113+function %(complete_func)s;114+ set -l response;115+116+ for value in (env %(complete_var)s=complete_fish COMP_WORDS=(commandline -cp) \117+COMP_CWORD=(commandline -t) %(prog_name)s);118+ set response $response $value;119+ end;120+121+ for completion in $response;122+ set -l metadata (string split "," $completion);123+124+ 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;132+end;133+134+complete --no-files --command %(prog_name)s --arguments \135+"(%(complete_func)s)";136+"""137+138+139+class 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``).143+144+ :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.148+149+ .. versionadded:: 8.0150+ """151+152+ 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+ """161+162+ def __init__(self, cli, prog_name, complete_var):163+ self.cli = cli164+ self.prog_name = prog_name165+ self.complete_var = complete_var166+167+ @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"174+175+ def source_vars(self):176+ """Vars for formatting :attr:`source_template`.177+178+ 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+ }186+187+ 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()194+195+ 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 NotImplementedError201+202+ 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.206+207+ :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)211+212+ if ctx is None:213+ return []214+215+ obj, incomplete = _resolve_incomplete(ctx, args, incomplete)216+ return obj.shell_complete(ctx, args, incomplete)217+218+ def format_completion(self, item):219+ """Format a completion item into the form recognized by the220+ shell script. This must be implemented by subclasses.221+222+ :param item: Completion item to format.223+ """224+ raise NotImplementedError225+226+ def complete(self):227+ """Produce the completion data to send back to the shell.228+229+ 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)237+238+239+class BashComplete(ShellComplete):240+ """Shell completion for Bash."""241+242+ name = "bash"243+ source_template = _SOURCE_BASH244+245+ def source(self):246+ import subprocess247+248+ output = subprocess.run(["bash", "--version"], stdout=subprocess.PIPE)249+ match = re.search(r"version (\d)\.(\d)\.\d", output.stdout.decode())250+251+ if match is not None:252+ major, minor = match.groups()253+254+ 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+ )263+264+ return super().source()265+266+ 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]270+271+ try:272+ incomplete = cwords[cword]273+ except IndexError:274+ incomplete = ""275+276+ return args, incomplete277+278+ def format_completion(self, item):279+ type, value, _ = item280+ return f"{type},{value}"281+282+283+class ZshComplete(ShellComplete):284+ """Shell completion for Zsh."""285+286+ name = "zsh"287+ source_template = _SOURCE_ZSH288+289+ 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]293+294+ try:295+ incomplete = cwords[cword]296+ except IndexError:297+ incomplete = ""298+299+ return args, incomplete300+301+ def format_completion(self, item):302+ type, value, desc = item303+ return f"{type}\n{value}\n{desc if desc else '_'}"304+305+306+class FishComplete(ShellComplete):307+ """Shell completion for Fish."""308+309+ name = "fish"310+ source_template = _SOURCE_FISH311+312+ def get_completion_args(self):313+ cwords = split_arg_string(os.environ["COMP_WORDS"])314+ incomplete = os.environ["COMP_CWORD"]315+ args = cwords[1:]316+317+ # 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()321+322+ return args, incomplete323+324+ def format_completion(self, item):325+ type, value, desc = item326+327+ if desc:328+ return f"{type},{value}\t{desc}"329+330+ return f"{type},{value}"331+332+333+_available_shells = {334+ "bash": BashComplete,335+ "fish": FishComplete,336+ "zsh": ZshComplete,337+}338+339+340+def 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.344+345+ :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.name352+353+ _available_shells[name] = cls354+355+356+def 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``.360+361+ :param shell: Name the class is registered under.362+ """363+ return _available_shells.get(shell)364+365+366+def _is_incomplete_argument(values, param):367+ """Determine if the given parameter is an argument that can still368+ accept values.369+370+ :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 False376+377+ value = values[param.name]378+379+ if value is None:380+ return True381+382+ if param.nargs == -1:383+ return True384+385+ if isinstance(value, list) and param.nargs > 1 and len(value) < param.nargs:386+ return True387+388+ return False389+390+391+def _start_of_option(value):392+ """Check if the value looks like the start of an option."""393+ return value and not value[0].isalnum()394+395+396+def _is_incomplete_option(args, param):397+ """Determine if the given parameter is an option that needs a value.398+399+ :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 False404+405+ if param.is_flag:406+ return False407+408+ last_option = None409+410+ for index, arg in enumerate(reversed(args)):411+ if index + 1 > param.nargs:412+ break413+414+ if _start_of_option(arg):415+ last_option = arg416+417+ return bool(last_option and last_option in param.opts)418+419+420+def _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.424+425+ :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.args431+432+ while args:433+ if isinstance(ctx.command, MultiCommand):434+ if not ctx.command.chain:435+ name, cmd, args = ctx.command.resolve_command(ctx, args)436+437+ if cmd is None:438+ return ctx439+440+ 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)445+446+ if cmd is None:447+ return ctx448+449+ 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.args458+459+ ctx = sub_ctx460+ args = sub_ctx.protected_args + sub_ctx.args461+ else:462+ break463+464+ return ctx465+466+467+def _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.470+471+ :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)485+486+ # 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, incomplete492+493+ # 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, incomplete498+499+ # 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, incomplete504+505+ # There were no unparsed arguments, the command may be a group that506+ # will provide command name completions.507+ return ctx.command, incompletemodified:src/click/types.py+53 added
105 unmodified lines106 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)109 110+ 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.114 115+ :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.118+119+ .. versionadded:: 8.0120+ """121+ return []122+123+124 class CompositeParamType(ParamType):125 is_composite = True126 127 @property133 unmodified lines261 262 def __repr__(self):263 return f"Choice({list(self.choices)})"264 265+ def shell_complete(self, ctx, args, incomplete):266+ """Return a list of completions for the incomplete value based267+ on the choices.268 269+ :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.272+273+ .. versionadded:: 8.0274+ """275+ return [276+ ("plain", c, None) for c in self.choices if str(c).startswith(incomplete)277+ ]278+279+280 class DateTime(ParamType):281 """The DateTime type converts date strings into `datetime` objects.282 283 The format strings which are checked are configurable, but default to some325 unmodified lines609 param,610 ctx,611 )612 613+ 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.616 617+ :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.620+621+ .. versionadded:: 8.0622+ """623+ return [("file", incomplete, None)]624+625+626 class 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 various122 unmodified lines752 )753 754 return self.coerce_path_result(rv)755 756+ 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.760 761+ :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.764+765+ .. versionadded:: 8.0766+ """767+ completion_type = "dir" if self.dir_okay and not self.file_okay else "file"768+ return [(completion_type, incomplete, None)]769+770+771 class 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 this109 unmodified lines