Skip to content
Myr

Merge pull request #1622 from MLH-Fellowship/1484-redesign-completion

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

Redesign Completion System

authored by David Lord · committed by GitHub · parents 47ecf34, 1b9a657 · Browse files · 22 files+1492 added−1167 removed
This commit

State

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

Diff stats

22 files+1492 added−1167 removed

  • tests:+277 added−536 removed
  • other:+1215 added−631 removed

22 files+1492 added−1167 removed

modified:docs/api.rst+18 added
167 unmodified lines
168169.. autoclass:: OptionParser170 :members:171172173Shell Completion174----------------175176See :doc:`/shell-completion` for information about enabling and177customizing Click's shell completion system.178179.. currentmodule:: click.shell_completion180181.. autoclass:: CompletionItem182183.. autoclass:: ShellComplete184 :members:185 :member-order: bysource186187.. autofunction:: add_completion_class188189190Testing191-------192193.. currentmodule:: click.testing
6 unmodified lines
deleted:docs/bashcomplete.rst-163 removed
1Shell Completion2================34.. versionadded:: 2.056Click can provide tab completion for commands, options, and choice7values. Bash, Zsh, and Fish are supported89Completion is only available if a script is installed and invoked10through an entry point, not through the ``python`` command. See11:ref:`setuptools-integration`.121314What it Completes15-----------------1617Generally, the shell completion support will complete commands,18options, and any option or argument values where the type is19:class:`click.Choice`. Options are only listed if at least a dash has20been entered.2122.. code-block:: text2324 $ repo <TAB><TAB>25 clone commit copy delete setuser26 $ repo clone -<TAB><TAB>27 --deep --help --rev --shallow -r2829Custom completions can be provided for argument and option values by30providing an ``autocompletion`` function that returns a list of strings.31This is useful when the suggestions need to be dynamically generated32completion time. The callback function will be passed 3 keyword33arguments:3435- ``ctx`` - The current command context.36- ``args`` - The list of arguments passed in.37- ``incomplete`` - The partial word that is being completed. May38 be an empty string if no characters have been entered yet.3940Here is an example of using a callback function to generate dynamic41suggestions:4243.. code-block:: python4445 import os4647 def get_env_vars(ctx, args, incomplete):48 return [k for k in os.environ.keys() if incomplete in k]4950 @click.command()51 @click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)52 def cmd1(envvar):53 click.echo(f"Environment variable: {envvar}")54 click.echo(f"Value: {os.environ[envvar]}")555657Completion help strings58-----------------------5960ZSH and fish support showing documentation strings for completions.61These are taken from the help parameters of options and subcommands. For62dynamically generated completions a help string can be provided by63returning a tuple instead of a string. The first element of the tuple is64the completion and the second is the help string to display.6566Here is an example of using a callback function to generate dynamic67suggestions with help strings:6869.. code-block:: python7071 import os7273 def get_colors(ctx, args, incomplete):74 colors = [('red', 'a warm color'),75 ('blue', 'a cool color'),76 ('green', 'the other starter color')]77 return [c for c in colors if incomplete in c[0]]7879 @click.command()80 @click.argument("color", type=click.STRING, autocompletion=get_colors)81 def cmd1(color):82 click.echo(f"Chosen color is {color}")838485Activation86----------8788In order to activate shell completion, you need to inform your shell89that completion is available for your script. Any Click application90automatically provides support for that. If the program is executed with91a special ``_<PROG_NAME>_COMPLETE`` variable, the completion mechanism92is triggered instead of the normal command. ``<PROG_NAME>`` is the93executable name in uppercase with dashes replaced by underscores.9495If your tool is called ``foo-bar``, then the variable is called96``_FOO_BAR_COMPLETE``. By exporting it with the ``source_{shell}``97value it will output the activation script to evaluate.9899Here are examples for a ``foo-bar`` script.100101For Bash, add this to ``~/.bashrc``:102103.. code-block:: text104105 eval "$(_FOO_BAR_COMPLETE=source_bash foo-bar)"106107For Zsh, add this to ``~/.zshrc``:108109.. code-block:: text110111 eval "$(_FOO_BAR_COMPLETE=source_zsh foo-bar)"112113For Fish, add this to ``~/.config/fish/completions/foo-bar.fish``:114115.. code-block:: text116117 eval (env _FOO_BAR_COMPLETE=source_fish foo-bar)118119Open a new shell to enable completion. Or run the ``eval`` command120directly in your current shell to enable it temporarily.121122123Activation Script124-----------------125126The above ``eval`` examples will invoke your application every time a127shell is started. This may slow down shell startup time significantly.128129Alternatively, export the generated completion code as a static script130to be executed. You can ship this file with your builds; tools like Git131do this. At least Zsh will also cache the results of completion files,132but not ``eval`` scripts.133134For Bash:135136.. code-block:: text137138 _FOO_BAR_COMPLETE=source_bash foo-bar > foo-bar-complete.sh139140For Zsh:141142.. code-block:: text143144 _FOO_BAR_COMPLETE=source_zsh foo-bar > foo-bar-complete.sh145146For Fish:147148.. code-block:: text149150 _FOO_BAR_COMPLETE=source_fish foo-bar > foo-bar-complete.fish151152In ``.bashrc`` or ``.zshrc``, source the script instead of the ``eval``153command:154155.. code-block:: text156157 . /path/to/foo-bar-complete.sh158159For Fish, add the file to the completions directory:160161.. code-block:: text162163 _FOO_BAR_COMPLETE=source_fish foo-bar > ~/.config/fish/completions/foo-bar-complete.fish
modified:docs/conf.py+1 added
20 unmodified lines
21 "sphinx.ext.intersphinx",22 "sphinxcontrib.log_cabinet",23 "pallets_sphinx_themes",24 "sphinx_issues",25 "sphinx_tabs.tabs",26]27intersphinx_mapping = {"python": ("https://docs.python.org/3/", None)}28issues_github_path = "pallets/click"29
27 unmodified lines
modified:docs/index.rst+1 added-1 removed
77 unmodified lines
78 complex79 advanced80 testing81 utils82 bashcomplete82 shell-completion83 exceptions84 unicode-support85 wincmd86
21 unmodified lines
added:docs/shell-completion.rst+289 added
1.. currentmodule:: click.shell_completion23Shell Completion4================56Click provides tab completion support for Bash (version 4.4 and up),7Zsh, and Fish. It is possible to add support for other shells too, and8suggestions can be customized at multiple levels.910Shell completion suggests command names, option names, and values for11choice, file, and path parameter types. Options are only listed if at12least a dash has been entered. Hidden commands and options are not13shown.1415.. code-block:: text1617 $ repo <TAB><TAB>18 clone commit copy delete setuser19 $ repo clone -<TAB><TAB>20 --deep --help --rev --shallow -r212223Enabling Completion24-------------------2526Completion is only available if a script is installed and invoked27through an entry point, not through the ``python`` command. See28:doc:`/setuptools`. Once the executable is installed, calling it with29a special environment variable will put Click in completion mode.3031In order for completion to be used, the user needs to register a special32function with their shell. The script is different for every shell, and33Click will output it when called with ``_{PROG_NAME}_COMPLETE`` set to34``source_{shell}``. ``{PROG_NAME}`` is the executable name in uppercase35with dashes replaced by underscores. The built-in shells are ``bash``,36``zsh``, and ``fish``.3738Provide your users with the following instructions customized to your39program name. This uses ``foo-bar`` as an example.4041.. tabs::4243 .. group-tab:: Bash4445 Add this to ``~/.bashrc``:4647 .. code-block:: bash4849 eval "$(_FOO_BAR_COMPLETE=source_bash foo-bar)"5051 .. group-tab:: Zsh5253 Add this to ``~/.zshrc``:5455 .. code-block:: zsh5657 eval "$(_FOO_BAR_COMPLETE=source_zsh foo-bar)"5859 .. group-tab:: Fish6061 Add this to ``~/.config/fish/completions/foo-bar.fish``:6263 .. code-block:: fish6465 eval (env _FOO_BAR_COMPLETE=source_fish foo-bar)6667 This is the same file used for the activation script method68 below. For Fish it's probably always easier to use that method.6970Using ``eval`` means that the command is invoked and evaluated every71time a shell is started, which can delay shell responsiveness. To speed72it up, write the generated script to a file, then source that. You can73generate the files ahead of time and distribute them with your program74to save your users a step.7576.. tabs::7778 .. group-tab:: Bash7980 Save the script somewhere.8182 .. code-block:: bash8384 _FOO_BAR_COMPLETE=source_bash foo-bar > ~/.foo-bar-complete.bash8586 Source the file in ``~/.bashrc``.8788 .. code-block:: bash8990 . ~/.foo-bar-complete.bash9192 .. group-tab:: Zsh9394 Save the script somewhere.9596 .. code-block:: bash9798 _FOO_BAR_COMPLETE=source_zsh foo-bar > ~/.foo-bar-complete.zsh99100 Source the file in ``~/.zshrc``.101102 .. code-block:: bash103104 . ~/.foo-bar-complete.zsh105106 .. group-tab:: Fish107108 Save the script to ``~/.config/fish/completions/foo-bar.fish``:109110 .. code-block:: fish111112 _FOO_BAR_COMPLETE=source_fish foo-bar > ~/.config/fish/completions/foo-bar.fish113114After modifying the shell config, you need to start a new shell in order115for the changes to be loaded.116117118Custom Type Completion119----------------------120121When creating a custom :class:`~click.ParamType`, override its122:meth:`~click.ParamType.shell_complete` method to provide shell123completion for parameters with the type. The method must return a list124of :class:`~CompletionItem` objects. Besides the value, these objects125hold metadata that shell support might use. The built-in implementations126use ``type`` to indicate special handling for paths, and ``help`` for127shells that support showing a help string next to a suggestion.128129In this example, the type will suggest environment variables that start130with the incomplete value.131132.. code-block:: python133134 class EnvVarType(ParamType):135 def shell_complete(self, ctx, param, incomplete):136 return [137 CompletionItem(name)138 for name in os.environ if name.startswith(incomplete)139 ]140141 @click.command()142 @click.option("--ev", type=EnvVarType())143 def cli(ev):144 click.echo(os.environ[ev])145146147Overriding Value Completion148---------------------------149150Value completions for a parameter can be customized without a custom151type by providing a ``shell_complete`` function. The function is used152instead of any completion provided by the type. It is passed 3 keyword153arguments:154155- ``ctx`` - The current command context.156- ``param`` - The current parameter requesting completion.157- ``incomplete`` - The partial word that is being completed. May158 be an empty string if no characters have been entered yet.159160It must return a list of :class:`CompletionItem` objects, or as a161shortcut it can return a list of strings.162163In this example, the command will suggest environment variables that164start with the incomplete value.165166.. code-block:: python167168 def complete_env_vars(ctx, param, incomplete):169 return [k for k in os.environ if k.startswith(incomplete)]170171 @click.command()172 @click.argument("name", shell_complete=complete_env_vars)173 def cli(name):174 click.echo(f"Name: {name}")175 click.echo(f"Value: {os.environ[name]}")176177178Adding Support for a Shell179--------------------------180181Support can be added for shells that do not come built in. Be sure to182check PyPI to see if there's already a package that adds support for183your shell. This topic is very technical, you'll want to look at Click's184source to study the built-in implementations.185186Shell support is provided by subclasses of :class:`ShellComplete`187registered with :func:`add_completion_class`. When Click is invoked in188completion mode, it calls :meth:`~ShellComplete.source` to output the189completion script, or :meth:`~ShellComplete.complete` to output190completions. The base class provides default implementations that191require implementing some smaller parts.192193First, you'll need to figure out how your shell's completion system194works and write a script to integrate it with Click. It must invoke your195program with the environment variable ``_{PROG_NAME}_COMPLETE`` set to196``complete_{shell}`` and pass the complete args and incomplete value.197How it passes those values, and the format of the completion response198from Click is up to you.199200In your subclass, set :attr:`~ShellComplete.source_template` to the201completion script. The default implementation will perform ``%``202formatting with the following variables:203204- ``complete_func`` - A safe name for the completion function defined205 in the script.206- ``complete_var`` - The environment variable name for passing the207 ``complete_{shell}`` value.208- ``prog_name`` - The name of the executable being completed.209210The example code is for a made up shell "My Shell" or "mysh" for short.211212.. code-block:: python213214 from click.shell_completion import add_completion_class215 from click.shell_completion import ShellComplete216217 _mysh_source = """\218 %(complete_func)s {219 response=$(%(complete_var)s=complete_mysh %(prog_name)s)220 # parse response and set completions somehow221 }222 call-on-complete %(prog_name)s %(complete_func)s223 """224225 @add_completion_class226 class MyshComplete(ShellComplete):227 name = "mysh"228 source_template = _mysh_source229230Next, implement :meth:`~ShellComplete.get_completion_args`. This must231get, parse, and return the complete args and incomplete value from the232completion script. For example, for the Bash implementation the233``COMP_WORDS`` env var contains the command line args as a string, and234the ``COMP_CWORD`` env var contains the index of the incomplete arg. The235method must return a ``(args, incomplete)`` tuple.236237.. code-block:: python238239 import os240 from click.parser import split_arg_string241242 class MyshComplete(ShellComplete):243 ...244245 def get_completion_args(self):246 args = split_arg_string(os.environ["COMP_WORDS"])247248 if os.environ["COMP_PARTIAL"] == "1":249 incomplete = args.pop()250 return args, incomplete251252 return args, ""253254Finally, implement :meth:`~ShellComplete.format_completion`. This is255called to format each ``(type, value, help)`` tuples returned by Click256into a string. For example, the Bash implementation returns257``f"{type},{value}`` (it doesn't support help strings), and the Zsh258implementation returns each part separated by a newline, replacing empty259help with a ``_`` placeholder. This format is entirely up to what you260parse with your completion script.261262The ``type`` value is usually ``plain``, but it can be another value263that the completion script can switch on. For example, ``file`` or264``dir`` can tell the shell to handle path completion, since the shell is265better at that than Click.266267.. code-block:: python268269 import os270 from click.parser import split_arg_string271272 class MyshComplete(ShellComplete):273 ...274275 def format_completion(self, item):276 type, value, _ = item277 return f"{type}\t{value}"278279With those three things implemented, the new shell support is ready. In280case those weren't sufficient, there are more parts that can be281overridden, but that probably isn't necessary.282283The activation instructions will again depend on how your shell works.284Use the following to generate the completion script, then load it into285the shell somehow.286287.. code-block:: text288289 _FOO_BAR_COMPLETE=source_mysh foo-bar
deleted:examples/bashcompletion/bashcompletion.py-45 removed
1import os23import click456@click.group()7def cli():8 pass91011def get_env_vars(ctx, args, incomplete):12 # Completions returned as strings do not have a description displayed.13 for key in os.environ.keys():14 if incomplete in key:15 yield key161718@cli.command(help="A command to print environment variables")19@click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)20def cmd1(envvar):21 click.echo(f"Environment variable: {envvar}")22 click.echo(f"Value: {os.environ[envvar]}")232425@click.group(help="A group that holds a subcommand")26def group():27 pass282930def list_users(ctx, args, incomplete):31 # You can generate completions with descriptions by returning32 # tuples in the form (completion, description).33 users = [("bob", "butcher"), ("alice", "baker"), ("jerry", "candlestick maker")]34 # Ths will allow completion matches based on matches within the35 # description string too!36 return [user for user in users if incomplete in user[0] or incomplete in user[1]]373839@group.command(help="Choose a user")40@click.argument("user", type=click.STRING, autocompletion=list_users)41def subcmd(user):42 click.echo(f"Chosen user is {user}")434445cli.add_command(group)
deleted:examples/bashcompletion/README-12 removed
1$ bashcompletion23 bashcompletion is a simple example of an application that4 tries to autocomplete commands, arguments and options.56 This example requires Click 2.0 or higher.78Usage:910 $ pip install --editable .11 $ eval "$(_BASHCOMPLETION_COMPLETE=source bashcompletion)"12 $ bashcompletion --help
deleted:examples/bashcompletion/setup.py-13 removed
1from setuptools import setup23setup(4 name="click-example-bashcompletion",5 version="1.0",6 py_modules=["bashcompletion"],7 include_package_data=True,8 install_requires=["click"],9 entry_points="""10 [console_scripts]11 bashcompletion=bashcompletion:cli12 """,13)
added:examples/completion/completion.py+53 added
1import os23import click4from click.shell_completion import CompletionItem567@click.group()8def cli():9 pass101112@cli.command()13@click.option("--dir", type=click.Path(file_okay=False))14def ls(dir):15 click.echo("\n".join(os.listdir(dir)))161718def get_env_vars(ctx, param, incomplete):19 # Returning a list of values is a shortcut to returning a list of20 # CompletionItem(value).21 return [k for k in os.environ if incomplete in k]222324@cli.command(help="A command to print environment variables")25@click.argument("envvar", shell_complete=get_env_vars)26def show_env(envvar):27 click.echo(f"Environment variable: {envvar}")28 click.echo(f"Value: {os.environ[envvar]}")293031@cli.group(help="A group that holds a subcommand")32def group():33 pass343536def list_users(ctx, param, incomplete):37 # You can generate completions with help strings by returning a list38 # of CompletionItem. You can match on whatever you want, including39 # the help.40 items = [("bob", "butcher"), ("alice", "baker"), ("jerry", "candlestick maker")]4142 for value, help in items:43 if incomplete in value or incomplete in help:44 yield CompletionItem(value, help=help)454647@group.command(help="Choose a user")48@click.argument("user", shell_complete=list_users)49def select_user(user):50 click.echo(f"Chosen user is {user}")515253cli.add_command(group)
added:examples/completion/README+28 added
1$ completion2============34Demonstrates Click's shell completion support.56.. code-block:: bash78 pip install --editable .910For Bash:1112.. code-block:: bash1314 eval "$(_COMPLETION_COMPLETE=source_bash completion)"1516For Zsh:1718.. code-block:: zsh1920 eval "$(_COMPLETION_COMPLETE=source_zsh completion)"2122For Fish:2324.. code-block:: fish2526 eval (env _COMPLETION_COMPLETE=source_fish completion)2728Now press tab (maybe twice) after typing something to see completions.
added:examples/completion/setup.py+13 added
1from setuptools import setup23setup(4 name="click-example-completion",5 version="1.0",6 py_modules=["completion"],7 include_package_data=True,8 install_requires=["click"],9 entry_points="""10 [console_scripts]11 completion=completion:cli12 """,13)
modified:requirements/dev.txt+3 added-2 removed
28 unmodified lines
29pip-tools==5.3.1 # via -r requirements/dev.in30pluggy==0.13.1 # via pytest, tox31pre-commit==2.7.1 # via -r requirements/dev.in32py==1.9.0 # via pytest, tox33pygments==2.6.1 # via sphinx33pygments==2.6.1 # via sphinx, sphinx-tabs34pyparsing==2.4.7 # via packaging35pytest==6.1.0 # via -r requirements/tests.in36pytz==2020.1 # via babel37pyyaml==5.3.1 # via pre-commit38requests==2.23.0 # via sphinx39six==1.15.0 # via packaging, pip-tools, tox, virtualenv40snowballstemmer==2.0.0 # via sphinx41sphinx-issues==1.2.0 # via -r requirements/docs.in42sphinx-tabs==1.3.0 # via -r requirements/docs.in42sphinx==3.2.1 # via -r requirements/docs.in, pallets-sphinx-themes, sphinx-issues, sphinxcontrib-log-cabinet43sphinx==3.2.1 # via -r requirements/docs.in, pallets-sphinx-themes, sphinx-issues, sphinx-tabs, sphinxcontrib-log-cabinet44sphinxcontrib-applehelp==1.0.2 # via sphinx45sphinxcontrib-devhelp==1.0.2 # via sphinx46sphinxcontrib-htmlhelp==1.0.3 # via sphinx47sphinxcontrib-jsmath==1.0.1 # via sphinx
12 unmodified lines
modified:requirements/docs.in+1 added
1Pallets-Sphinx-Themes2Sphinx3sphinx-issues4sphinxcontrib-log-cabinet5sphinx-tabs
modified:requirements/docs.txt+3 added-2 removed
13 unmodified lines
14jinja2==2.11.2 # via sphinx15markupsafe==1.1.1 # via jinja216packaging==20.4 # via pallets-sphinx-themes, sphinx17pallets-sphinx-themes==1.2.3 # via -r requirements/docs.in18pygments==2.6.1 # via sphinx18pygments==2.6.1 # via sphinx, sphinx-tabs19pyparsing==2.4.7 # via packaging20pytz==2020.1 # via babel21requests==2.23.0 # via sphinx22six==1.15.0 # via packaging23snowballstemmer==2.0.0 # via sphinx24sphinx-issues==1.2.0 # via -r requirements/docs.in25sphinx-tabs==1.3.0 # via -r requirements/docs.in25sphinx==3.2.1 # via -r requirements/docs.in, pallets-sphinx-themes, sphinx-issues, sphinxcontrib-log-cabinet26sphinx==3.2.1 # via -r requirements/docs.in, pallets-sphinx-themes, sphinx-issues, sphinx-tabs, sphinxcontrib-log-cabinet27sphinxcontrib-applehelp==1.0.2 # via sphinx28sphinxcontrib-devhelp==1.0.2 # via sphinx29sphinxcontrib-htmlhelp==1.0.3 # via sphinx30sphinxcontrib-jsmath==1.0.1 # via sphinx
7 unmodified lines
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+196 added-22 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 name, command747576def _check_multicommand(base_command, cmd_name, cmd, register=False):77 if not base_command.chain or not isinstance(cmd, MultiCommand):
205 unmodified lines
283 #: the :class:`Command` for this context.284 self.command = command285 #: the descriptive information name286 self.info_name = info_name284 #: the parsed parameters except if the value is hidden in which285 #: case it's not remembered.287 #: Map of parameter names to their parsed values. Parameters288 #: with ``expose_value=False`` are not stored.289 self.params = {}290 # This tracks the actual param objects that were parsed, even if291 # they didn't expose a value. Used by completion system to know292 # what parameters to exclude.293 self._seen_params = set()294 #: the leftover arguments.295 self.args = []296 #: protected arguments. These are arguments that are prepended297 #: to `args` when certain parsing scenarios are encountered but
569 unmodified lines
867 implementation is raising a not implemented error.868 """869 raise NotImplementedError("Base commands are not invokable by default")870871 def shell_complete(self, ctx, incomplete):872 """Return a list of completions for the incomplete value. Looks873 at the names of chained multi-commands.874875 Any command could be part of a chained multi-command, so sibling876 commands are valid at any point during command completion. Other877 command classes will return more completions.878879 :param ctx: Invocation context for this command.880 :param incomplete: Value being completed. May be empty.881882 .. versionadded:: 8.0883 """884 from click.shell_completion import CompletionItem885886 results = []887888 while ctx.parent is not None:889 ctx = ctx.parent890891 if isinstance(ctx.command, MultiCommand) and ctx.command.chain:892 results.extend(893 CompletionItem(name, help=command.get_short_help_str())894 for name, command in _complete_visible_commands(ctx, incomplete)895 if name not in ctx.protected_args896 )897898 return results899900 def main(901 self,902 args=None,903 prog_name=None,
44 unmodified lines
948949 if prog_name is None:950 prog_name = _detect_program_name()951916 # 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)952 # Process shell completion requests and exit early.953 self._main_shell_completion(prog_name, complete_var)954955 try:956 try:957 with self.make_context(prog_name, args, **extra) as ctx:
41 unmodified lines
999 raise1000 echo("Aborted!", file=sys.stderr)1001 sys.exit(1)10021003 def _main_shell_completion(self, prog_name, complete_var=None):1004 """Check if the shell is asking for tab completion, process1005 that, then exit early. Called from :meth:`main` before the1006 program is invoked.10071008 :param prog_name: Name of the executable in the shell.1009 :param complete_var: Name of the environment variable that holds1010 the completion instruction. Defaults to1011 ``_{PROG_NAME}_COMPLETE``.1012 """1013 if complete_var is None:1014 complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper()10151016 instruction = os.environ.get(complete_var)10171018 if not instruction:1019 return10201021 from .shell_completion import shell_complete10221023 rv = shell_complete(self, prog_name, complete_var, instruction)1024 _fast_exit(rv)10251026 def __call__(self, *args, **kwargs):1027 """Alias for :meth:`main`."""1028 return self.main(*args, **kwargs)1029
250 unmodified lines
1280 _maybe_show_deprecated_notice(self)1281 if self.callback is not None:1282 return ctx.invoke(self.callback, **ctx.params)12831284 def shell_complete(self, ctx, incomplete):1285 """Return a list of completions for the incomplete value. Looks1286 at the names of options and chained multi-commands.12871288 :param ctx: Invocation context for this command.1289 :param incomplete: Value being completed. May be empty.12901291 .. versionadded:: 8.01292 """1293 from click.shell_completion import CompletionItem12941295 results = []12961297 if incomplete and not incomplete[0].isalnum():1298 for param in self.get_params(ctx):1299 if (1300 not isinstance(param, Option)1301 or param.hidden1302 or (not param.multiple and param in ctx._seen_params)1303 ):1304 continue13051306 results.extend(1307 CompletionItem(name, help=param.help)1308 for name in param.opts + param.secondary_opts1309 if name.startswith(incomplete)1310 )13111312 results.extend(super().shell_complete(ctx, incomplete))1313 return results131413151316class MultiCommand(Command):1317 """A multi command is the basic implementation of a command that1318 dispatches to subcommands. The most common version is the1319 :class:`Group`.
248 unmodified lines
1568 if cmd is None and not ctx.resilient_parsing:1569 if split_opt(cmd_name)[0]:1570 self.parse_args(ctx, ctx.args)1571 ctx.fail(f"No such command '{original_cmd_name}'.")1572 return cmd.name if cmd else None, cmd, args[1:]15731485 return cmd.name, cmd, args[1:]14861574 def get_command(self, ctx, cmd_name):1575 """Given a context and a command name, this returns a1576 :class:`Command` object if it exists or returns `None`.1577 """
4 unmodified lines
1582 appear.1583 """1584 return []15851586 def shell_complete(self, ctx, incomplete):1587 """Return a list of completions for the incomplete value. Looks1588 at the names of options, subcommands, and chained1589 multi-commands.15901591 :param ctx: Invocation context for this command.1592 :param incomplete: Value being completed. May be empty.15931594 .. versionadded:: 8.01595 """1596 from click.shell_completion import CompletionItem15971598 results = [1599 CompletionItem(name, help=command.get_short_help_str())1600 for name, command in _complete_visible_commands(ctx, incomplete)1601 ]1602 results.extend(super().shell_complete(ctx, incomplete))1603 return results160416051606class Group(MultiCommand):1607 """A group allows a command to have subcommands attached. This is1608 the most common way to implement nesting in Click.1609
172 unmodified lines
1782 should not be set for arguments or it will inverse the1783 order of processing.1784 :param envvar: a string or list of strings that are environment variables1785 that should be checked.1786 :param shell_complete: A function that returns custom shell1787 completions. Used instead of the param's type completion if1788 given. Takes ``ctx, param, incomplete`` and must return a list1789 of :class:`~click.shell_completion.CompletionItem` or a list of1790 strings.17911792 .. versionchanged:: 8.01793 ``autocompletion`` is renamed to ``shell_complete`` and has new1794 semantics described above. The old name is deprecated and will1795 be removed in 8.1, until then it will be wrapped to match the1796 new requirements.17971798 .. versionchanged:: 7.11799 Empty environment variables are ignored rather than taking the1800 empty string value. This makes it possible for scripts to clear1801 variables if they can't unset them.
2 unmodified lines
1804 Changed signature for parameter callback to also be passed the1805 parameter. The old callback format will still work, but it will1806 raise a warning to give you a chance to migrate the code easier.1807 """18081809 param_type_name = "parameter"18101811 def __init__(1812 self,
6 unmodified lines
1819 metavar=None,1820 expose_value=True,1821 is_eager=False,1822 envvar=None,1823 shell_complete=None,1824 autocompletion=None,1825 ):1826 self.name, self.opts, self.secondary_opts = self._parse_decls(1827 param_decls or (), expose_value
17 unmodified lines
1845 self.default = default1846 self.is_eager = is_eager1847 self.metavar = metavar1848 self.envvar = envvar1730 self.autocompletion = autocompletion18491850 if autocompletion is not None:1851 import warnings18521853 warnings.warn(1854 "'autocompletion' is renamed to 'shell_complete'. The old name is"1855 " deprecated and will be removed in Click 8.1. See the docs about"1856 " 'Parameter' for information about new behavior.",1857 DeprecationWarning,1858 stacklevel=2,1859 )18601861 def shell_complete(ctx, param, incomplete):1862 from click.shell_completion import CompletionItem18631864 out = []18651866 for c in autocompletion(ctx, [], incomplete):1867 if isinstance(c, tuple):1868 c = CompletionItem(c[0], help=c[1])1869 elif isinstance(c, str):1870 c = CompletionItem(c)18711872 if c.value.startswith(incomplete):1873 out.append(c)18741875 return out18761877 self._custom_shell_complete = shell_complete18781879 def to_info_dict(self):1880 """Gather information that could be useful for a tool generating1881 user-facing documentation.1882
165 unmodified lines
2048 raise20492050 if self.expose_value:2051 ctx.params[self.name] = value20522053 if value is not None:2054 ctx._seen_params.add(self)20552056 return value, args20572058 def get_help_record(self, ctx):2059 pass
7 unmodified lines
2067 """2068 hint_list = self.opts or [self.human_readable_name]2069 return " / ".join(repr(x) for x in hint_list)20702071 def shell_complete(self, ctx, incomplete):2072 """Return a list of completions for the incomplete value. If a2073 ``shell_complete`` function was given during init, it is used.2074 Otherwise, the :attr:`type`2075 :meth:`~click.types.ParamType.shell_complete` function is used.20762077 :param ctx: Invocation context for this command.2078 :param incomplete: Value being completed. May be empty.20792080 .. versionadded:: 8.02081 """2082 if self._custom_shell_complete is not None:2083 results = self._custom_shell_complete(ctx, self, incomplete)20842085 if results and isinstance(results[0], str):2086 from click.shell_completion import CompletionItem20872088 results = [CompletionItem(c) for c in results]20892090 return results20912092 return self.type.shell_complete(ctx, self, incomplete)209320942095class Option(Parameter):2096 """Options are usually optional values on the command line and2097 have some extra features that arguments don't have.2098
407 unmodified lines
added:src/click/shell_completion.py+536 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 1394041class CompletionItem:42 """Represents a completion value and metadata about the value. The43 default metadata is ``type`` to indicate special shell handling,44 and ``help`` if a shell supports showing a help string next to the45 value.4647 Arbitrary parameters can be passed when creating the object, and48 accessed using ``item.attr``. If an attribute wasn't passed,49 accessing it returns ``None``.5051 :param value: The completion suggestion.52 :param type: Tells the shell script to provide special completion53 support for the type. Click uses ``"dir"`` and ``"file"``.54 :param help: String shown next to the value if supported.55 :param kwargs: Arbitrary metadata. The built-in implementations56 don't use this, but custom type completions paired with custom57 shell support could use it.58 """5960 __slots__ = ("value", "type", "help", "_info")6162 def __init__(self, value, type="plain", help=None, **kwargs):63 self.value = value64 self.type = type65 self.help = help66 self._info = kwargs6768 def __getattr__(self, name):69 return self._info.get(name)707172# Only Bash >= 4.4 has the nosort option.73_SOURCE_BASH = """\74%(complete_func)s() {75 local IFS=$'\\n'76 local response7778 response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \79%(complete_var)s=complete_bash $1)8081 for completion in $response; do82 IFS=',' read type value <<< "$completion"8384 if [[ $type == 'dir' ]]; then85 COMREPLY=()86 compopt -o dirnames87 elif [[ $type == 'file' ]]; then88 COMREPLY=()89 compopt -o default90 elif [[ $type == 'plain' ]]; then91 COMPREPLY+=($value)92 fi93 done9495 return 096}9798%(complete_func)s_setup() {99 complete -o nosort -F %(complete_func)s %(prog_name)s100}101102%(complete_func)s_setup;103"""104105_SOURCE_ZSH = """\106#compdef %(prog_name)s107108%(complete_func)s() {109 local -a completions110 local -a completions_with_descriptions111 local -a response112 (( ! $+commands[%(prog_name)s] )) && return 1113114 response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) \115%(complete_var)s=complete_zsh %(prog_name)s)}")116117 for type key descr in ${response}; do118 if [[ "$type" == "plain" ]]; then119 if [[ "$descr" == "_" ]]; then120 completions+=("$key")121 else122 completions_with_descriptions+=("$key":"$descr")123 fi124 elif [[ "$type" == "dir" ]]; then125 _path_files -/126 elif [[ "$type" == "file" ]]; then127 _path_files -f128 fi129 done130131 if [ -n "$completions_with_descriptions" ]; then132 _describe -V unsorted completions_with_descriptions -U133 fi134135 if [ -n "$completions" ]; then136 compadd -U -V unsorted -a completions137 fi138}139140compdef %(complete_func)s %(prog_name)s;141"""142143_SOURCE_FISH = """\144function %(complete_func)s;145 set -l response;146147 for value in (env %(complete_var)s=complete_fish COMP_WORDS=(commandline -cp) \148COMP_CWORD=(commandline -t) %(prog_name)s);149 set response $response $value;150 end;151152 for completion in $response;153 set -l metadata (string split "," $completion);154155 if test $metadata[1] = "dir";156 __fish_complete_directories $metadata[2];157 else if test $metadata[1] = "file";158 __fish_complete_path $metadata[2];159 else if test $metadata[1] = "plain";160 echo $metadata[2];161 end;162 end;163end;164165complete --no-files --command %(prog_name)s --arguments \166"(%(complete_func)s)";167"""168169170class ShellComplete:171 """Base class for providing shell completion support. A subclass for172 a given shell will override attributes and methods to implement the173 completion instructions (``source`` and ``complete``).174175 :param cli: Command being called.176 :param prog_name: Name of the executable in the shell.177 :param complete_var: Name of the environment variable that holds178 the completion instruction.179180 .. versionadded:: 8.0181 """182183 name = None184 """Name to register the shell as with :func:`add_completion_class`.185 This is used in completion instructions (``source_{name}`` and186 ``complete_{name}``).187 """188 source_template = None189 """Completion script template formatted by :meth:`source`. This must190 be provided by subclasses.191 """192193 def __init__(self, cli, prog_name, complete_var):194 self.cli = cli195 self.prog_name = prog_name196 self.complete_var = complete_var197198 @property199 def func_name(self):200 """The name of the shell function defined by the completion201 script.202 """203 safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), re.ASCII)204 return f"_{safe_name}_completion"205206 def source_vars(self):207 """Vars for formatting :attr:`source_template`.208209 By default this provides ``complete_func``, ``complete_var``,210 and ``prog_name``.211 """212 return {213 "complete_func": self.func_name,214 "complete_var": self.complete_var,215 "prog_name": self.prog_name,216 }217218 def source(self):219 """Produce the shell script that defines the completion220 function. By default this ``%``-style formats221 :attr:`source_template` with the dict returned by222 :meth:`source_vars`.223 """224 return self.source_template % self.source_vars()225226 def get_completion_args(self):227 """Use the env vars defined by the shell script to return a228 tuple of ``args, incomplete``. This must be implemented by229 subclasses.230 """231 raise NotImplementedError232233 def get_completions(self, args, incomplete):234 """Determine the context and last complete command or parameter235 from the complete args. Call that object's ``shell_complete``236 method to get the completions for the incomplete value.237238 :param args: List of complete args before the incomplete value.239 :param incomplete: Value being completed. May be empty.240 """241 ctx = _resolve_context(self.cli, self.prog_name, args)242243 if ctx is None:244 return []245246 obj, incomplete = _resolve_incomplete(ctx, args, incomplete)247 return obj.shell_complete(ctx, incomplete)248249 def format_completion(self, item):250 """Format a completion item into the form recognized by the251 shell script. This must be implemented by subclasses.252253 :param item: Completion item to format.254 """255 raise NotImplementedError256257 def complete(self):258 """Produce the completion data to send back to the shell.259260 By default this calls :meth:`get_completion_args`, gets the261 completions, then calls :meth:`format_completion` for each262 completion.263 """264 args, incomplete = self.get_completion_args()265 completions = self.get_completions(args, incomplete)266 out = [self.format_completion(item) for item in completions]267 return "\n".join(out)268269270class BashComplete(ShellComplete):271 """Shell completion for Bash."""272273 name = "bash"274 source_template = _SOURCE_BASH275276 def _check_version(self):277 import subprocess278279 output = subprocess.run(["bash", "--version"], stdout=subprocess.PIPE)280 match = re.search(r"version (\d)\.(\d)\.\d", output.stdout.decode())281282 if match is not None:283 major, minor = match.groups()284285 if major < "4" or major == "4" and minor < "4":286 raise RuntimeError(287 "Shell completion is not supported for Bash"288 " versions older than 4.4."289 )290 else:291 raise RuntimeError(292 "Couldn't detect Bash version, shell completion is not supported."293 )294295 def source(self):296 self._check_version()297 return super().source()298299 def get_completion_args(self):300 cwords = split_arg_string(os.environ["COMP_WORDS"])301 cword = int(os.environ["COMP_CWORD"])302 args = cwords[1:cword]303304 try:305 incomplete = cwords[cword]306 except IndexError:307 incomplete = ""308309 return args, incomplete310311 def format_completion(self, item: CompletionItem):312 return f"{item.type},{item.value}"313314315class ZshComplete(ShellComplete):316 """Shell completion for Zsh."""317318 name = "zsh"319 source_template = _SOURCE_ZSH320321 def get_completion_args(self):322 cwords = split_arg_string(os.environ["COMP_WORDS"])323 cword = int(os.environ["COMP_CWORD"])324 args = cwords[1:cword]325326 try:327 incomplete = cwords[cword]328 except IndexError:329 incomplete = ""330331 return args, incomplete332333 def format_completion(self, item: CompletionItem):334 return f"{item.type}\n{item.value}\n{item.help if item.help else '_'}"335336337class FishComplete(ShellComplete):338 """Shell completion for Fish."""339340 name = "fish"341 source_template = _SOURCE_FISH342343 def get_completion_args(self):344 cwords = split_arg_string(os.environ["COMP_WORDS"])345 incomplete = os.environ["COMP_CWORD"]346 args = cwords[1:]347348 # Fish stores the partial word in both COMP_WORDS and349 # COMP_CWORD, remove it from complete args.350 if incomplete and args and args[-1] == incomplete:351 args.pop()352353 return args, incomplete354355 def format_completion(self, item: CompletionItem):356 if item.help:357 return f"{item.type},{item.value}\t{item.help}"358359 return f"{item.type},{item.value}"360361362_available_shells = {363 "bash": BashComplete,364 "fish": FishComplete,365 "zsh": ZshComplete,366}367368369def add_completion_class(cls, name=None):370 """Register a :class:`ShellComplete` subclass under the given name.371 The name will be provided by the completion instruction environment372 variable during completion.373374 :param cls: The completion class that will handle completion for the375 shell.376 :param name: Name to register the class under. Defaults to the377 class's ``name`` attribute.378 """379 if name is None:380 name = cls.name381382 _available_shells[name] = cls383384385def get_completion_class(shell):386 """Look up a registered :class:`ShellComplete` subclass by the name387 provided by the completion instruction environment variable. If the388 name isn't registered, returns ``None``.389390 :param shell: Name the class is registered under.391 """392 return _available_shells.get(shell)393394395def _is_incomplete_argument(values, param):396 """Determine if the given parameter is an argument that can still397 accept values.398399 :param values: Dict of param names and values parsed from the400 command line args.401 :param param: Argument object being checked.402 """403 if not isinstance(param, Argument):404 return False405406 value = values[param.name]407408 if value is None:409 return True410411 if param.nargs == -1:412 return True413414 if isinstance(value, list) and param.nargs > 1 and len(value) < param.nargs:415 return True416417 return False418419420def _start_of_option(value):421 """Check if the value looks like the start of an option."""422 return value and not value[0].isalnum()423424425def _is_incomplete_option(args, param):426 """Determine if the given parameter is an option that needs a value.427428 :param args: List of complete args before the incomplete value.429 :param param: Option object being checked.430 """431 if not isinstance(param, Option):432 return False433434 if param.is_flag:435 return False436437 last_option = None438439 for index, arg in enumerate(reversed(args)):440 if index + 1 > param.nargs:441 break442443 if _start_of_option(arg):444 last_option = arg445446 return last_option is not None and last_option in param.opts447448449def _resolve_context(cli, prog_name, args):450 """Produce the context hierarchy starting with the command and451 traversing the complete arguments. This only follows the commands,452 it doesn't trigger input prompts or callbacks.453454 :param cli: Command being called.455 :param prog_name: Name of the executable in the shell.456 :param args: List of complete args before the incomplete value.457 """458 ctx = cli.make_context(prog_name, args.copy(), resilient_parsing=True)459 args = ctx.protected_args + ctx.args460461 while args:462 if isinstance(ctx.command, MultiCommand):463 if not ctx.command.chain:464 name, cmd, args = ctx.command.resolve_command(ctx, args)465466 if cmd is None:467 return ctx468469 ctx = cmd.make_context(name, args, parent=ctx, resilient_parsing=True)470 args = ctx.protected_args + ctx.args471 else:472 while args:473 name, cmd, args = ctx.command.resolve_command(ctx, args)474475 if cmd is None:476 return ctx477478 sub_ctx = cmd.make_context(479 name,480 args,481 parent=ctx,482 allow_extra_args=True,483 allow_interspersed_args=False,484 resilient_parsing=True,485 )486 args = sub_ctx.args487488 ctx = sub_ctx489 args = sub_ctx.protected_args + sub_ctx.args490 else:491 break492493 return ctx494495496def _resolve_incomplete(ctx, args, incomplete):497 """Find the Click object that will handle the completion of the498 incomplete value. Return the object and the incomplete value.499500 :param ctx: Invocation context for the command represented by501 the parsed complete args.502 :param args: List of complete args before the incomplete value.503 :param incomplete: Value being completed. May be empty.504 """505 # Different shells treat an "=" between a long option name and506 # value differently. Might keep the value joined, return the "="507 # as a separate item, or return the split name and value. Always508 # split and discard the "=" to make completion easier.509 if incomplete == "=":510 incomplete = ""511 elif "=" in incomplete and _start_of_option(incomplete):512 name, _, incomplete = incomplete.partition("=")513 args.append(name)514515 # The "--" marker tells Click to stop treating values as options516 # even if they start with the option character. If it hasn't been517 # given and the incomplete arg looks like an option, the current518 # command will provide option name completions.519 if "--" not in args and _start_of_option(incomplete):520 return ctx.command, incomplete521522 # If the last complete arg is an option name with an incomplete523 # value, the option will provide value completions.524 for param in ctx.command.get_params(ctx):525 if _is_incomplete_option(args, param):526 return param, incomplete527528 # It's not an option name or value. The first argument without a529 # parsed value will provide value completions.530 for param in ctx.command.get_params(ctx):531 if _is_incomplete_argument(ctx.params, param):532 return param, incomplete533534 # There were no unparsed arguments, the command may be a group that535 # will provide command name completions.536 return ctx.command, incomplete
modified:src/click/types.py+59 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, param, incomplete):111 """Return a list of112 :class:`~click.shell_completion.CompletionItem` objects for the113 incomplete value. Most types do not provide completions, but114 some do, and this allows custom types to provide custom115 completions as well.116117 :param ctx: Invocation context for this command.118 :param param: The parameter that is requesting completion.119 :param incomplete: Value being completed. May be empty.120121 .. versionadded:: 8.0122 """123 return []124125126class CompositeParamType(ParamType):127 is_composite = True128129 @property
133 unmodified lines
263264 def __repr__(self):265 return f"Choice({list(self.choices)})"266267 def shell_complete(self, ctx, param, incomplete):268 """Complete choices that start with the incomplete value.269270 :param ctx: Invocation context for this command.271 :param param: The parameter that is requesting completion.272 :param incomplete: Value being completed. May be empty.273274 .. versionadded:: 8.0275 """276 from click.shell_completion import CompletionItem277278 str_choices = map(str, self.choices)279 return [CompletionItem(c) for c in str_choices if c.startswith(incomplete)]280281282class DateTime(ParamType):283 """The DateTime type converts date strings into `datetime` objects.284285 The format strings which are checked are configurable, but default to some
325 unmodified lines
611 param,612 ctx,613 )614615 def shell_complete(self, ctx, param, incomplete):616 """Return a special completion marker that tells the completion617 system to use the shell to provide file path completions.618619 :param ctx: Invocation context for this command.620 :param param: The parameter that is requesting completion.621 :param incomplete: Value being completed. May be empty.622623 .. versionadded:: 8.0624 """625 from click.shell_completion import CompletionItem626627 return [CompletionItem(incomplete, type="file")]628629630class Path(ParamType):631 """The path type is similar to the :class:`File` type but it performs632 different checks. First of all, instead of returning an open file633 handle it returns just the filename. Secondly, it can perform various
122 unmodified lines
756 )757758 return self.coerce_path_result(rv)759760 def shell_complete(self, ctx, param, incomplete):761 """Return a special completion marker that tells the completion762 system to use the shell to provide path completions for only763 directories or any paths.764765 :param ctx: Invocation context for this command.766 :param param: The parameter that is requesting completion.767 :param incomplete: Value being completed. May be empty.768769 .. versionadded:: 8.0770 """771 from click.shell_completion import CompletionItem772773 type = "dir" if self.dir_okay and not self.file_okay else "file"774 return [CompletionItem(incomplete, type=type)]775776777class Tuple(CompositeParamType):778 """The default behavior of Click is to apply a type on a value directly.779 This works well in most cases, except for when `nargs` is set to a fixed780 count and different types should be used for different items. In this
109 unmodified lines
deleted:tests/test_bashcomplete.py-519 removed
1import pytest23import click4from click._bashcomplete import get_choices567def choices_without_help(cli, args, incomplete):8 completions = get_choices(cli, "dummy", args, incomplete)9 return [c[0] for c in completions]101112def choices_with_help(cli, args, incomplete):13 return list(get_choices(cli, "dummy", args, incomplete))141516def test_single_command():17 @click.command()18 @click.option("--local-opt")19 def cli(local_opt):20 pass2122 assert choices_without_help(cli, [], "-") == ["--local-opt", "--help"]23 assert choices_without_help(cli, [], "") == []242526def test_boolean_flag():27 @click.command()28 @click.option("--shout/--no-shout", default=False)29 def cli(local_opt):30 pass3132 assert choices_without_help(cli, [], "-") == ["--shout", "--no-shout", "--help"]333435def test_multi_value_option():36 @click.group()37 @click.option("--pos", nargs=2, type=float)38 def cli(local_opt):39 pass4041 @cli.command()42 @click.option("--local-opt")43 def sub(local_opt):44 pass4546 assert choices_without_help(cli, [], "-") == ["--pos", "--help"]47 assert choices_without_help(cli, ["--pos"], "") == []48 assert choices_without_help(cli, ["--pos", "1.0"], "") == []49 assert choices_without_help(cli, ["--pos", "1.0", "1.0"], "") == ["sub"]505152def test_multi_option():53 @click.command()54 @click.option("--message", "-m", multiple=True)55 def cli(local_opt):56 pass5758 assert choices_without_help(cli, [], "-") == ["--message", "-m", "--help"]59 assert choices_without_help(cli, ["-m"], "") == []606162def test_small_chain():63 @click.group()64 @click.option("--global-opt")65 def cli(global_opt):66 pass6768 @cli.command()69 @click.option("--local-opt")70 def sub(local_opt):71 pass7273 assert choices_without_help(cli, [], "") == ["sub"]74 assert choices_without_help(cli, [], "-") == ["--global-opt", "--help"]75 assert choices_without_help(cli, ["sub"], "") == []76 assert choices_without_help(cli, ["sub"], "-") == ["--local-opt", "--help"]777879def test_long_chain():80 @click.group("cli")81 @click.option("--cli-opt")82 def cli(cli_opt):83 pass8485 @cli.group("asub")86 @click.option("--asub-opt")87 def asub(asub_opt):88 pass8990 @asub.group("bsub")91 @click.option("--bsub-opt")92 def bsub(bsub_opt):93 pass9495 COLORS = ["red", "green", "blue"]9697 def get_colors(ctx, args, incomplete):98 for c in COLORS:99 if c.startswith(incomplete):100 yield c101102 def search_colors(ctx, args, incomplete):103 for c in COLORS:104 if incomplete in c:105 yield c106107 CSUB_OPT_CHOICES = ["foo", "bar"]108 CSUB_CHOICES = ["bar", "baz"]109110 @bsub.command("csub")111 @click.option("--csub-opt", type=click.Choice(CSUB_OPT_CHOICES))112 @click.option("--csub", type=click.Choice(CSUB_CHOICES))113 @click.option("--search-color", autocompletion=search_colors)114 @click.argument("color", autocompletion=get_colors)115 def csub(csub_opt, color):116 pass117118 assert choices_without_help(cli, [], "-") == ["--cli-opt", "--help"]119 assert choices_without_help(cli, [], "") == ["asub"]120 assert choices_without_help(cli, ["asub"], "-") == ["--asub-opt", "--help"]121 assert choices_without_help(cli, ["asub"], "") == ["bsub"]122 assert choices_without_help(cli, ["asub", "bsub"], "-") == ["--bsub-opt", "--help"]123 assert choices_without_help(cli, ["asub", "bsub"], "") == ["csub"]124 assert choices_without_help(cli, ["asub", "bsub", "csub"], "-") == [125 "--csub-opt",126 "--csub",127 "--search-color",128 "--help",129 ]130 assert (131 choices_without_help(cli, ["asub", "bsub", "csub", "--csub-opt"], "")132 == CSUB_OPT_CHOICES133 )134 assert choices_without_help(cli, ["asub", "bsub", "csub"], "--csub") == [135 "--csub-opt",136 "--csub",137 ]138 assert (139 choices_without_help(cli, ["asub", "bsub", "csub", "--csub"], "")140 == CSUB_CHOICES141 )142 assert choices_without_help(cli, ["asub", "bsub", "csub", "--csub-opt"], "f") == [143 "foo"144 ]145 assert choices_without_help(cli, ["asub", "bsub", "csub"], "") == COLORS146 assert choices_without_help(cli, ["asub", "bsub", "csub"], "b") == ["blue"]147 assert choices_without_help(148 cli, ["asub", "bsub", "csub", "--search-color"], "een"149 ) == ["green"]150151152def test_chaining():153 @click.group("cli", chain=True)154 @click.option("--cli-opt")155 @click.argument("arg", type=click.Choice(["cliarg1", "cliarg2"]))156 def cli(cli_opt, arg):157 pass158159 @cli.command()160 @click.option("--asub-opt")161 def asub(asub_opt):162 pass163164 @cli.command(help="bsub help")165 @click.option("--bsub-opt")166 @click.argument("arg", type=click.Choice(["arg1", "arg2"]))167 def bsub(bsub_opt, arg):168 pass169170 @cli.command()171 @click.option("--csub-opt")172 @click.argument("arg", type=click.Choice(["carg1", "carg2"]), default="carg1")173 def csub(csub_opt, arg):174 pass175176 assert choices_without_help(cli, [], "-") == ["--cli-opt", "--help"]177 assert choices_without_help(cli, [], "") == ["cliarg1", "cliarg2"]178 assert choices_without_help(cli, ["cliarg1", "asub"], "-") == [179 "--asub-opt",180 "--help",181 ]182 assert choices_without_help(cli, ["cliarg1", "asub"], "") == ["bsub", "csub"]183 assert choices_without_help(cli, ["cliarg1", "bsub"], "") == ["arg1", "arg2"]184 assert choices_without_help(cli, ["cliarg1", "asub", "--asub-opt"], "") == []185 assert choices_without_help(186 cli, ["cliarg1", "asub", "--asub-opt", "5", "bsub"], "-"187 ) == ["--bsub-opt", "--help"]188 assert choices_without_help(cli, ["cliarg1", "asub", "bsub"], "-") == [189 "--bsub-opt",190 "--help",191 ]192 assert choices_without_help(cli, ["cliarg1", "asub", "csub"], "") == [193 "carg1",194 "carg2",195 ]196 assert choices_without_help(cli, ["cliarg1", "bsub", "arg1", "csub"], "") == [197 "carg1",198 "carg2",199 ]200 assert choices_without_help(cli, ["cliarg1", "asub", "csub"], "-") == [201 "--csub-opt",202 "--help",203 ]204 assert choices_with_help(cli, ["cliarg1", "asub"], "b") == [("bsub", "bsub help")]205206207def test_argument_choice():208 @click.command()209 @click.argument("arg1", required=True, type=click.Choice(["arg11", "arg12"]))210 @click.argument("arg2", type=click.Choice(["arg21", "arg22"]), default="arg21")211 @click.argument("arg3", type=click.Choice(["arg", "argument"]), default="arg")212 def cli():213 pass214215 assert choices_without_help(cli, [], "") == ["arg11", "arg12"]216 assert choices_without_help(cli, [], "arg") == ["arg11", "arg12"]217 assert choices_without_help(cli, ["arg11"], "") == ["arg21", "arg22"]218 assert choices_without_help(cli, ["arg12", "arg21"], "") == ["arg", "argument"]219 assert choices_without_help(cli, ["arg12", "arg21"], "argu") == ["argument"]220221222def test_option_choice():223 @click.command()224 @click.option("--opt1", type=click.Choice(["opt11", "opt12"]), help="opt1 help")225 @click.option("--opt2", type=click.Choice(["opt21", "opt22"]), default="opt21")226 @click.option("--opt3", type=click.Choice(["opt", "option"]))227 def cli():228 pass229230 assert choices_with_help(cli, [], "-") == [231 ("--opt1", "opt1 help"),232 ("--opt2", None),233 ("--opt3", None),234 ("--help", "Show this message and exit."),235 ]236 assert choices_without_help(cli, [], "--opt") == ["--opt1", "--opt2", "--opt3"]237 assert choices_without_help(cli, [], "--opt1=") == ["opt11", "opt12"]238 assert choices_without_help(cli, [], "--opt2=") == ["opt21", "opt22"]239 assert choices_without_help(cli, ["--opt2"], "=") == ["opt21", "opt22"]240 assert choices_without_help(cli, ["--opt2", "="], "opt") == ["opt21", "opt22"]241 assert choices_without_help(cli, ["--opt1"], "") == ["opt11", "opt12"]242 assert choices_without_help(cli, ["--opt2"], "") == ["opt21", "opt22"]243 assert choices_without_help(cli, ["--opt1", "opt11", "--opt2"], "") == [244 "opt21",245 "opt22",246 ]247 assert choices_without_help(cli, ["--opt2", "opt21"], "-") == [248 "--opt1",249 "--opt3",250 "--help",251 ]252 assert choices_without_help(cli, ["--opt1", "opt11"], "-") == [253 "--opt2",254 "--opt3",255 "--help",256 ]257 assert choices_without_help(cli, ["--opt1"], "opt") == ["opt11", "opt12"]258 assert choices_without_help(cli, ["--opt3"], "opti") == ["option"]259260 assert choices_without_help(cli, ["--opt1", "invalid_opt"], "-") == [261 "--opt2",262 "--opt3",263 "--help",264 ]265266267def test_option_and_arg_choice():268 @click.command()269 @click.option("--opt1", type=click.Choice(["opt11", "opt12"]))270 @click.argument("arg1", required=False, type=click.Choice(["arg11", "arg12"]))271 @click.option("--opt2", type=click.Choice(["opt21", "opt22"]))272 def cli():273 pass274275 assert choices_without_help(cli, ["--opt1"], "") == ["opt11", "opt12"]276 assert choices_without_help(cli, [""], "--opt1=") == ["opt11", "opt12"]277 assert choices_without_help(cli, [], "") == ["arg11", "arg12"]278 assert choices_without_help(cli, ["--opt2"], "") == ["opt21", "opt22"]279 assert choices_without_help(cli, ["arg11"], "--opt") == ["--opt1", "--opt2"]280 assert choices_without_help(cli, [], "--opt") == ["--opt1", "--opt2"]281282283def test_boolean_flag_choice():284 @click.command()285 @click.option("--shout/--no-shout", default=False)286 @click.argument("arg", required=False, type=click.Choice(["arg1", "arg2"]))287 def cli(local_opt):288 pass289290 assert choices_without_help(cli, [], "-") == ["--shout", "--no-shout", "--help"]291 assert choices_without_help(cli, ["--shout"], "") == ["arg1", "arg2"]292293294def test_multi_value_option_choice():295 @click.command()296 @click.option("--pos", nargs=2, type=click.Choice(["pos1", "pos2"]))297 @click.argument("arg", required=False, type=click.Choice(["arg1", "arg2"]))298 def cli(local_opt):299 pass300301 assert choices_without_help(cli, ["--pos"], "") == ["pos1", "pos2"]302 assert choices_without_help(cli, ["--pos", "pos1"], "") == ["pos1", "pos2"]303 assert choices_without_help(cli, ["--pos", "pos1", "pos2"], "") == ["arg1", "arg2"]304 assert choices_without_help(cli, ["--pos", "pos1", "pos2", "arg1"], "") == []305306307def test_multi_option_choice():308 @click.command()309 @click.option("--message", "-m", multiple=True, type=click.Choice(["m1", "m2"]))310 @click.argument("arg", required=False, type=click.Choice(["arg1", "arg2"]))311 def cli(local_opt):312 pass313314 assert choices_without_help(cli, ["-m"], "") == ["m1", "m2"]315 assert choices_without_help(cli, ["-m", "m1", "-m"], "") == ["m1", "m2"]316 assert choices_without_help(cli, ["-m", "m1"], "") == ["arg1", "arg2"]317318319def test_variadic_argument_choice():320 @click.command()321 @click.option("--opt", type=click.Choice(["opt1", "opt2"]))322 @click.argument("src", nargs=-1, type=click.Choice(["src1", "src2"]))323 def cli(local_opt):324 pass325326 assert choices_without_help(cli, ["src1", "src2"], "") == ["src1", "src2"]327 assert choices_without_help(cli, ["src1", "src2"], "--o") == ["--opt"]328 assert choices_without_help(cli, ["src1", "src2", "--opt"], "") == ["opt1", "opt2"]329 assert choices_without_help(cli, ["src1", "src2"], "") == ["src1", "src2"]330331332def test_variadic_argument_complete():333 def _complete(ctx, args, incomplete):334 return ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "yz"]335336 @click.group()337 def entrypoint():338 pass339340 @click.command()341 @click.option("--opt", autocompletion=_complete)342 @click.argument("arg", nargs=-1)343 def subcommand(opt, arg):344 pass345346 entrypoint.add_command(subcommand)347348 assert choices_without_help(entrypoint, ["subcommand", "--opt"], "") == _complete(349 0, 0, 0350 )351 assert choices_without_help(352 entrypoint, ["subcommand", "whatever", "--opt"], ""353 ) == _complete(0, 0, 0)354 assert (355 choices_without_help(entrypoint, ["subcommand", "whatever", "--opt", "abc"], "")356 == []357 )358359360def test_long_chain_choice():361 @click.group()362 def cli():363 pass364365 @cli.group()366 @click.option("--sub-opt", type=click.Choice(["subopt1", "subopt2"]))367 @click.argument(368 "sub-arg", required=False, type=click.Choice(["subarg1", "subarg2"])369 )370 def sub(sub_opt, sub_arg):371 pass372373 @sub.command(short_help="bsub help")374 @click.option("--bsub-opt", type=click.Choice(["bsubopt1", "bsubopt2"]))375 @click.argument(376 "bsub-arg1", required=False, type=click.Choice(["bsubarg1", "bsubarg2"])377 )378 @click.argument(379 "bbsub-arg2", required=False, type=click.Choice(["bbsubarg1", "bbsubarg2"])380 )381 def bsub(bsub_opt):382 pass383384 @sub.group("csub")385 def csub():386 pass387388 @csub.command()389 def dsub():390 pass391392 assert choices_with_help(cli, ["sub", "subarg1"], "") == [393 ("bsub", "bsub help"),394 ("csub", ""),395 ]396 assert choices_without_help(cli, ["sub"], "") == ["subarg1", "subarg2"]397 assert choices_without_help(cli, ["sub", "--sub-opt"], "") == ["subopt1", "subopt2"]398 assert choices_without_help(cli, ["sub", "--sub-opt", "subopt1"], "") == [399 "subarg1",400 "subarg2",401 ]402 assert choices_without_help(403 cli, ["sub", "--sub-opt", "subopt1", "subarg1", "bsub"], "-"404 ) == ["--bsub-opt", "--help"]405 assert choices_without_help(406 cli, ["sub", "--sub-opt", "subopt1", "subarg1", "bsub"], ""407 ) == ["bsubarg1", "bsubarg2"]408 assert choices_without_help(409 cli, ["sub", "--sub-opt", "subopt1", "subarg1", "bsub", "--bsub-opt"], ""410 ) == ["bsubopt1", "bsubopt2"]411 assert choices_without_help(412 cli,413 [414 "sub",415 "--sub-opt",416 "subopt1",417 "subarg1",418 "bsub",419 "--bsub-opt",420 "bsubopt1",421 "bsubarg1",422 ],423 "",424 ) == ["bbsubarg1", "bbsubarg2"]425 assert choices_without_help(426 cli, ["sub", "--sub-opt", "subopt1", "subarg1", "csub"], ""427 ) == ["dsub"]428429430def test_chained_multi():431 @click.group()432 def cli():433 pass434435 @cli.group()436 def sub():437 pass438439 @sub.group()440 def bsub():441 pass442443 @sub.group(chain=True)444 def csub():445 pass446447 @csub.command()448 def dsub():449 pass450451 @csub.command()452 def esub():453 pass454455 assert choices_without_help(cli, ["sub"], "") == ["bsub", "csub"]456 assert choices_without_help(cli, ["sub"], "c") == ["csub"]457 assert choices_without_help(cli, ["sub", "csub"], "") == ["dsub", "esub"]458 assert choices_without_help(cli, ["sub", "csub", "dsub"], "") == ["esub"]459460461def test_hidden():462 @click.group()463 @click.option("--name", hidden=True)464 @click.option("--choices", type=click.Choice([1, 2]), hidden=True)465 def cli(name):466 pass467468 @cli.group(hidden=True)469 def hgroup():470 pass471472 @hgroup.group()473 def hgroupsub():474 pass475476 @cli.command()477 def asub():478 pass479480 @cli.command(hidden=True)481 @click.option("--hname")482 def hsub():483 pass484485 assert choices_without_help(cli, [], "--n") == []486 assert choices_without_help(cli, [], "--c") == []487 # If the user exactly types out the hidden param, complete its options.488 assert choices_without_help(cli, ["--choices"], "") == [1, 2]489 assert choices_without_help(cli, [], "") == ["asub"]490 assert choices_without_help(cli, [], "") == ["asub"]491 assert choices_without_help(cli, [], "h") == []492 # If the user exactly types out the hidden command, complete its subcommands.493 assert choices_without_help(cli, ["hgroup"], "") == ["hgroupsub"]494 assert choices_without_help(cli, ["hsub"], "--h") == ["--hname", "--help"]495496497@pytest.mark.parametrize(498 ("args", "part", "expect"),499 [500 ([], "-", ["--opt", "--help"]),501 (["value"], "--", ["--opt", "--help"]),502 ([], "-o", []),503 (["--opt"], "-o", []),504 (["--"], "", ["name", "-o", "--opt", "--"]),505 (["--"], "--o", ["--opt"]),506 ],507)508def test_args_with_double_dash_complete(args, part, expect):509 def _complete(ctx, args, incomplete):510 values = ["name", "-o", "--opt", "--"]511 return [x for x in values if x.startswith(incomplete)]512513 @click.command()514 @click.option("--opt")515 @click.argument("args", nargs=-1, autocompletion=_complete)516 def cli(opt, args):517 pass518519 assert choices_without_help(cli, args, part) == expect
modified:tests/test_compat.py-17 removed
2 unmodified lines
3from click._compat import should_strip_ansi4from click._compat import WIN567def test_bash_func_name():8 from click._bashcomplete import get_completion_script910 script = get_completion_script("foo-bar baz_blah", "_COMPLETE_VAR", "bash").strip()11 assert script.startswith("_foo_barbaz_blah_completion()")12 assert "_COMPLETE_VAR=complete $1" in script131415def test_zsh_func_name():16 from click._bashcomplete import get_completion_script1718 script = get_completion_script("foo-bar", "_COMPLETE_VAR", "zsh").strip()19 assert script.startswith("#compdef foo-bar")20 assert "compdef _foo_bar_completion foo-bar;" in script21 assert "(( ! $+commands[foo-bar] )) && return 1" in script22237@pytest.mark.xfail(WIN, reason="Jupyter not tested/supported on Windows")8def test_is_jupyter_kernel_output():9 class JupyterKernelFakeStream:10 pass
4 unmodified lines
added:tests/test_shell_completion.py+277 added
1import sys23import pytest45from click.core import Argument6from click.core import Command7from click.core import Group8from click.core import Option9from click.shell_completion import CompletionItem10from click.shell_completion import ShellComplete11from click.types import Choice12from click.types import File13from click.types import Path141516def _get_completions(cli, args, incomplete):17 comp = ShellComplete(cli, cli.name, "_CLICK_COMPLETE")18 return comp.get_completions(args, incomplete)192021def _get_words(cli, args, incomplete):22 return [c.value for c in _get_completions(cli, args, incomplete)]232425def test_command():26 cli = Command("cli", params=[Option(["-t", "--test"])])27 assert _get_words(cli, [], "") == []28 assert _get_words(cli, [], "-") == ["-t", "--test", "--help"]29 assert _get_words(cli, [], "--") == ["--test", "--help"]30 assert _get_words(cli, [], "--t") == ["--test"]31 # -t has been seen, so --test isn't suggested32 assert _get_words(cli, ["-t", "a"], "-") == ["--help"]333435def test_group():36 cli = Group("cli", params=[Option(["-a"])], commands=[Command("x"), Command("y")])37 assert _get_words(cli, [], "") == ["x", "y"]38 assert _get_words(cli, [], "-") == ["-a", "--help"]394041def test_group_command_same_option():42 cli = Group(43 "cli", params=[Option(["-a"])], commands=[Command("x", params=[Option(["-a"])])]44 )45 assert _get_words(cli, [], "-") == ["-a", "--help"]46 assert _get_words(cli, ["-a", "a"], "-") == ["--help"]47 assert _get_words(cli, ["-a", "a", "x"], "-") == ["-a", "--help"]48 assert _get_words(cli, ["-a", "a", "x", "-a", "a"], "-") == ["--help"]495051def test_chained():52 cli = Group(53 "cli",54 chain=True,55 commands=[56 Command("set", params=[Option(["-y"])]),57 Command("start"),58 Group("get", commands=[Command("full")]),59 ],60 )61 assert _get_words(cli, [], "") == ["get", "set", "start"]62 assert _get_words(cli, [], "s") == ["set", "start"]63 assert _get_words(cli, ["set", "start"], "") == ["get"]64 # subcommands and parent subcommands65 assert _get_words(cli, ["get"], "") == ["full", "set", "start"]66 assert _get_words(cli, ["get", "full"], "") == ["set", "start"]67 assert _get_words(cli, ["get"], "s") == ["set", "start"]686970def test_help_option():71 cli = Group("cli", commands=[Command("with"), Command("no", add_help_option=False)])72 assert _get_words(cli, ["with"], "--") == ["--help"]73 assert _get_words(cli, ["no"], "--") == []747576def test_argument_order():77 cli = Command(78 "cli",79 params=[80 Argument(["plain"]),81 Argument(["c1"], type=Choice(["a1", "a2", "b"])),82 Argument(["c2"], type=Choice(["c1", "c2", "d"])),83 ],84 )85 # first argument has no completions86 assert _get_words(cli, [], "") == []87 assert _get_words(cli, [], "a") == []88 # first argument filled, now completion can happen89 assert _get_words(cli, ["x"], "a") == ["a1", "a2"]90 assert _get_words(cli, ["x", "b"], "d") == ["d"]919293def test_type_choice():94 cli = Command("cli", params=[Option(["-c"], type=Choice(["a1", "a2", "b"]))])95 assert _get_words(cli, ["-c"], "") == ["a1", "a2", "b"]96 assert _get_words(cli, ["-c"], "a") == ["a1", "a2"]97 assert _get_words(cli, ["-c"], "a2") == ["a2"]9899100@pytest.mark.parametrize(101 ("type", "expect"),102 [(File(), "file"), (Path(), "file"), (Path(file_okay=False), "dir")],103)104def test_path_types(type, expect):105 cli = Command("cli", params=[Option(["-f"], type=type)])106 out = _get_completions(cli, ["-f"], "ab")107 assert len(out) == 1108 c = out[0]109 assert c.value == "ab"110 assert c.type == expect111112113def test_option_flag():114 cli = Command(115 "cli",116 add_help_option=False,117 params=[118 Option(["--on/--off"]),119 Argument(["a"], type=Choice(["a1", "a2", "b"])),120 ],121 )122 assert _get_words(cli, ["type"], "--") == ["--on", "--off"]123 # flag option doesn't take value, use choice argument124 assert _get_words(cli, ["x", "--on"], "a") == ["a1", "a2"]125126127def test_option_custom():128 def custom(ctx, param, incomplete):129 return [incomplete.upper()]130131 cli = Command(132 "cli",133 params=[134 Argument(["x"]),135 Argument(["y"]),136 Argument(["z"], shell_complete=custom),137 ],138 )139 assert _get_words(cli, ["a", "b"], "") == [""]140 assert _get_words(cli, ["a", "b"], "c") == ["C"]141142143def test_autocompletion_deprecated():144 # old function takes args and not param, returns all values, can mix145 # strings and tuples146 def custom(ctx, args, incomplete):147 assert isinstance(args, list)148 return [("art", "x"), "bat", "cat"]149150 with pytest.deprecated_call():151 cli = Command("cli", params=[Argument(["x"], autocompletion=custom)])152153 assert _get_words(cli, [], "") == ["art", "bat", "cat"]154 assert _get_words(cli, [], "c") == ["cat"]155156157def test_option_multiple():158 cli = Command(159 "type",160 params=[Option(["-m"], type=Choice(["a", "b"]), multiple=True), Option(["-f"])],161 )162 assert _get_words(cli, ["-m"], "") == ["a", "b"]163 assert "-m" in _get_words(cli, ["-m", "a"], "-")164 assert _get_words(cli, ["-m", "a", "-m"], "") == ["a", "b"]165 # used single options aren't suggested again166 assert "-c" not in _get_words(cli, ["-c", "f"], "-")167168169def test_option_nargs():170 cli = Command("cli", params=[Option(["-c"], type=Choice(["a", "b"]), nargs=2)])171 assert _get_words(cli, ["-c"], "") == ["a", "b"]172 assert _get_words(cli, ["-c", "a"], "") == ["a", "b"]173 assert _get_words(cli, ["-c", "a", "b"], "") == []174175176def test_argument_nargs():177 cli = Command(178 "cli",179 params=[180 Argument(["x"], type=Choice(["a", "b"]), nargs=2),181 Argument(["y"], type=Choice(["c", "d"]), nargs=-1),182 Option(["-z"]),183 ],184 )185 assert _get_words(cli, [], "") == ["a", "b"]186 assert _get_words(cli, ["a"], "") == ["a", "b"]187 assert _get_words(cli, ["a", "b"], "") == ["c", "d"]188 assert _get_words(cli, ["a", "b", "c"], "") == ["c", "d"]189 assert _get_words(cli, ["a", "b", "c", "d"], "") == ["c", "d"]190 assert _get_words(cli, ["a", "-z", "1"], "") == ["a", "b"]191 assert _get_words(cli, ["a", "-z", "1", "b"], "") == ["c", "d"]192193194def test_double_dash():195 cli = Command(196 "cli",197 add_help_option=False,198 params=[199 Option(["--opt"]),200 Argument(["name"], type=Choice(["name", "--", "-o", "--opt"])),201 ],202 )203 assert _get_words(cli, [], "-") == ["--opt"]204 assert _get_words(cli, ["value"], "-") == ["--opt"]205 assert _get_words(cli, [], "") == ["name", "--", "-o", "--opt"]206 assert _get_words(cli, ["--"], "") == ["name", "--", "-o", "--opt"]207208209def test_hidden():210 cli = Group(211 "cli",212 commands=[213 Command(214 "hidden",215 add_help_option=False,216 hidden=True,217 params=[218 Option(["-a"]),219 Option(["-b"], type=Choice(["a", "b"]), hidden=True),220 ],221 )222 ],223 )224 assert "hidden" not in _get_words(cli, [], "")225 assert "hidden" not in _get_words(cli, [], "hidden")226 assert _get_words(cli, ["hidden"], "-") == ["-a"]227 assert _get_words(cli, ["hidden", "-b"], "") == ["a", "b"]228229230def test_add_different_name():231 cli = Group("cli", commands={"renamed": Command("original")})232 words = _get_words(cli, [], "")233 assert "renamed" in words234 assert "original" not in words235236237def test_completion_item_data():238 c = CompletionItem("test", a=1)239 assert c.a == 1240 assert c.b is None241242243@pytest.fixture()244def _patch_for_completion(monkeypatch):245 monkeypatch.setattr("click.core._fast_exit", sys.exit)246 monkeypatch.setattr(247 "click.shell_completion.BashComplete._check_version", lambda self: True248 )249250251@pytest.mark.parametrize(252 "shell", ["bash", "zsh", "fish"],253)254@pytest.mark.usefixtures("_patch_for_completion")255def test_full_source(runner, shell):256 cli = Group("cli", commands=[Command("a"), Command("b")])257 result = runner.invoke(cli, env={"_CLI_COMPLETE": f"source_{shell}"})258 assert f"_CLI_COMPLETE=complete_{shell}" in result.output259260261@pytest.mark.parametrize(262 ("shell", "env", "expect"),263 [264 ("bash", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain,a\nplain,b\n"),265 ("bash", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain,b\n"),266 ("zsh", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain\na\n_\nplain\nb\nbee\n"),267 ("zsh", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"),268 ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain,a\nplain,b\tbee\n"),269 ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain,b\tbee\n"),270 ],271)272@pytest.mark.usefixtures("_patch_for_completion")273def test_full_complete(runner, shell, env, expect):274 cli = Group("cli", commands=[Command("a"), Command("b", help="bee")])275 env["_CLI_COMPLETE"] = f"complete_{shell}"276 result = runner.invoke(cli, env=env)277 assert result.output == expect
modified:CHANGES.rst+14 added
88 unmodified lines
89- Core objects have a ``to_info_dict()`` method. This gathers90 information about the object's structure that could be useful for a91 tool generating user-facing documentation. To get the structure of92 an entire CLI, use ``Context(cli).to_info_dict()``. :issue:`461`93- Redesign the shell completion system. :issue:`1484`, :pr:`1622`9495 - Support Bash >= 4.4, Zsh, and Fish, with the ability for96 extensions to add support for other shells.97 - Allow commands, groups, parameters, and types to override their98 completions suggestions.99 - Groups complete the names commands were registered with, which100 can differ from the name they were created with.101 - The ``autocompletion`` parameter for options and arguments is102 renamed to ``shell_complete``. The function must take103 ``ctx, param, incomplete``, must do matching rather than return104 all values, and must return a list of strings or a list of105 ``ShellComplete``. The old name and behavior is deprecated and106 will be removed in 8.1.107108109Version 7.1.2110-------------111112Released 2020-04-27
633 unmodified lines