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
Provenance
- Commit
6c8301e- Tree
1631f0e- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
47ecf34- Parent 2
1b9a657
22 files changed+1492 added−1167 removed
modified:docs/api.rst+18 added
167 unmodified lines168 169 .. autoclass:: OptionParser170 :members:171 172+173+Shell Completion174+----------------175+176+See :doc:`/shell-completion` for information about enabling and177+customizing Click's shell completion system.178+179+.. currentmodule:: click.shell_completion180+181+.. autoclass:: CompletionItem182+183+.. autoclass:: ShellComplete184+ :members:185+ :member-order: bysource186+187+.. autofunction:: add_completion_class188+189+190 Testing191 -------192 193 .. currentmodule:: click.testing6 unmodified linesdeleted:docs/bashcomplete.rst-163 removed
1-Shell Completion2-================3-4-.. versionadded:: 2.05-6-Click can provide tab completion for commands, options, and choice7-values. Bash, Zsh, and Fish are supported8-9-Completion is only available if a script is installed and invoked10-through an entry point, not through the ``python`` command. See11-:ref:`setuptools-integration`.12-13-14-What it Completes15------------------16-17-Generally, the shell completion support will complete commands,18-options, and any option or argument values where the type is19-:class:`click.Choice`. Options are only listed if at least a dash has20-been entered.21-22-.. code-block:: text23-24- $ repo <TAB><TAB>25- clone commit copy delete setuser26- $ repo clone -<TAB><TAB>27- --deep --help --rev --shallow -r28-29-Custom completions can be provided for argument and option values by30-providing an ``autocompletion`` function that returns a list of strings.31-This is useful when the suggestions need to be dynamically generated32-completion time. The callback function will be passed 3 keyword33-arguments:34-35-- ``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.39-40-Here is an example of using a callback function to generate dynamic41-suggestions:42-43-.. code-block:: python44-45- import os46-47- def get_env_vars(ctx, args, incomplete):48- return [k for k in os.environ.keys() if incomplete in k]49-50- @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]}")55-56-57-Completion help strings58------------------------59-60-ZSH and fish support showing documentation strings for completions.61-These are taken from the help parameters of options and subcommands. For62-dynamically generated completions a help string can be provided by63-returning a tuple instead of a string. The first element of the tuple is64-the completion and the second is the help string to display.65-66-Here is an example of using a callback function to generate dynamic67-suggestions with help strings:68-69-.. code-block:: python70-71- import os72-73- 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]]78-79- @click.command()80- @click.argument("color", type=click.STRING, autocompletion=get_colors)81- def cmd1(color):82- click.echo(f"Chosen color is {color}")83-84-85-Activation86-----------87-88-In order to activate shell completion, you need to inform your shell89-that completion is available for your script. Any Click application90-automatically provides support for that. If the program is executed with91-a special ``_<PROG_NAME>_COMPLETE`` variable, the completion mechanism92-is triggered instead of the normal command. ``<PROG_NAME>`` is the93-executable name in uppercase with dashes replaced by underscores.94-95-If your tool is called ``foo-bar``, then the variable is called96-``_FOO_BAR_COMPLETE``. By exporting it with the ``source_{shell}``97-value it will output the activation script to evaluate.98-99-Here are examples for a ``foo-bar`` script.100-101-For Bash, add this to ``~/.bashrc``:102-103-.. code-block:: text104-105- eval "$(_FOO_BAR_COMPLETE=source_bash foo-bar)"106-107-For Zsh, add this to ``~/.zshrc``:108-109-.. code-block:: text110-111- eval "$(_FOO_BAR_COMPLETE=source_zsh foo-bar)"112-113-For Fish, add this to ``~/.config/fish/completions/foo-bar.fish``:114-115-.. code-block:: text116-117- eval (env _FOO_BAR_COMPLETE=source_fish foo-bar)118-119-Open a new shell to enable completion. Or run the ``eval`` command120-directly in your current shell to enable it temporarily.121-122-123-Activation Script124------------------125-126-The above ``eval`` examples will invoke your application every time a127-shell is started. This may slow down shell startup time significantly.128-129-Alternatively, export the generated completion code as a static script130-to be executed. You can ship this file with your builds; tools like Git131-do this. At least Zsh will also cache the results of completion files,132-but not ``eval`` scripts.133-134-For Bash:135-136-.. code-block:: text137-138- _FOO_BAR_COMPLETE=source_bash foo-bar > foo-bar-complete.sh139-140-For Zsh:141-142-.. code-block:: text143-144- _FOO_BAR_COMPLETE=source_zsh foo-bar > foo-bar-complete.sh145-146-For Fish:147-148-.. code-block:: text149-150- _FOO_BAR_COMPLETE=source_fish foo-bar > foo-bar-complete.fish151-152-In ``.bashrc`` or ``.zshrc``, source the script instead of the ``eval``153-command:154-155-.. code-block:: text156-157- . /path/to/foo-bar-complete.sh158-159-For Fish, add the file to the completions directory:160-161-.. code-block:: text162-163- _FOO_BAR_COMPLETE=source_fish foo-bar > ~/.config/fish/completions/foo-bar-complete.fishmodified:docs/conf.py+1 added
20 unmodified lines21 "sphinx.ext.intersphinx",22 "sphinxcontrib.log_cabinet",23 "pallets_sphinx_themes",24 "sphinx_issues",25+ "sphinx_tabs.tabs",26 ]27 intersphinx_mapping = {"python": ("https://docs.python.org/3/", None)}28 issues_github_path = "pallets/click"29 27 unmodified linesmodified:docs/index.rst+1 added-1 removed
77 unmodified lines78 complex79 advanced80 testing81 utils82- bashcomplete82+ shell-completion83 exceptions84 unicode-support85 wincmd86 21 unmodified linesadded:docs/shell-completion.rst+289 added
1+.. currentmodule:: click.shell_completion2+3+Shell Completion4+================5+6+Click provides tab completion support for Bash (version 4.4 and up),7+Zsh, and Fish. It is possible to add support for other shells too, and8+suggestions can be customized at multiple levels.9+10+Shell completion suggests command names, option names, and values for11+choice, file, and path parameter types. Options are only listed if at12+least a dash has been entered. Hidden commands and options are not13+shown.14+15+.. code-block:: text16+17+ $ repo <TAB><TAB>18+ clone commit copy delete setuser19+ $ repo clone -<TAB><TAB>20+ --deep --help --rev --shallow -r21+22+23+Enabling Completion24+-------------------25+26+Completion is only available if a script is installed and invoked27+through an entry point, not through the ``python`` command. See28+:doc:`/setuptools`. Once the executable is installed, calling it with29+a special environment variable will put Click in completion mode.30+31+In order for completion to be used, the user needs to register a special32+function with their shell. The script is different for every shell, and33+Click will output it when called with ``_{PROG_NAME}_COMPLETE`` set to34+``source_{shell}``. ``{PROG_NAME}`` is the executable name in uppercase35+with dashes replaced by underscores. The built-in shells are ``bash``,36+``zsh``, and ``fish``.37+38+Provide your users with the following instructions customized to your39+program name. This uses ``foo-bar`` as an example.40+41+.. tabs::42+43+ .. group-tab:: Bash44+45+ Add this to ``~/.bashrc``:46+47+ .. code-block:: bash48+49+ eval "$(_FOO_BAR_COMPLETE=source_bash foo-bar)"50+51+ .. group-tab:: Zsh52+53+ Add this to ``~/.zshrc``:54+55+ .. code-block:: zsh56+57+ eval "$(_FOO_BAR_COMPLETE=source_zsh foo-bar)"58+59+ .. group-tab:: Fish60+61+ Add this to ``~/.config/fish/completions/foo-bar.fish``:62+63+ .. code-block:: fish64+65+ eval (env _FOO_BAR_COMPLETE=source_fish foo-bar)66+67+ This is the same file used for the activation script method68+ below. For Fish it's probably always easier to use that method.69+70+Using ``eval`` means that the command is invoked and evaluated every71+time a shell is started, which can delay shell responsiveness. To speed72+it up, write the generated script to a file, then source that. You can73+generate the files ahead of time and distribute them with your program74+to save your users a step.75+76+.. tabs::77+78+ .. group-tab:: Bash79+80+ Save the script somewhere.81+82+ .. code-block:: bash83+84+ _FOO_BAR_COMPLETE=source_bash foo-bar > ~/.foo-bar-complete.bash85+86+ Source the file in ``~/.bashrc``.87+88+ .. code-block:: bash89+90+ . ~/.foo-bar-complete.bash91+92+ .. group-tab:: Zsh93+94+ Save the script somewhere.95+96+ .. code-block:: bash97+98+ _FOO_BAR_COMPLETE=source_zsh foo-bar > ~/.foo-bar-complete.zsh99+100+ Source the file in ``~/.zshrc``.101+102+ .. code-block:: bash103+104+ . ~/.foo-bar-complete.zsh105+106+ .. group-tab:: Fish107+108+ Save the script to ``~/.config/fish/completions/foo-bar.fish``:109+110+ .. code-block:: fish111+112+ _FOO_BAR_COMPLETE=source_fish foo-bar > ~/.config/fish/completions/foo-bar.fish113+114+After modifying the shell config, you need to start a new shell in order115+for the changes to be loaded.116+117+118+Custom Type Completion119+----------------------120+121+When creating a custom :class:`~click.ParamType`, override its122+:meth:`~click.ParamType.shell_complete` method to provide shell123+completion for parameters with the type. The method must return a list124+of :class:`~CompletionItem` objects. Besides the value, these objects125+hold metadata that shell support might use. The built-in implementations126+use ``type`` to indicate special handling for paths, and ``help`` for127+shells that support showing a help string next to a suggestion.128+129+In this example, the type will suggest environment variables that start130+with the incomplete value.131+132+.. code-block:: python133+134+ 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+ ]140+141+ @click.command()142+ @click.option("--ev", type=EnvVarType())143+ def cli(ev):144+ click.echo(os.environ[ev])145+146+147+Overriding Value Completion148+---------------------------149+150+Value completions for a parameter can be customized without a custom151+type by providing a ``shell_complete`` function. The function is used152+instead of any completion provided by the type. It is passed 3 keyword153+arguments:154+155+- ``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.159+160+It must return a list of :class:`CompletionItem` objects, or as a161+shortcut it can return a list of strings.162+163+In this example, the command will suggest environment variables that164+start with the incomplete value.165+166+.. code-block:: python167+168+ def complete_env_vars(ctx, param, incomplete):169+ return [k for k in os.environ if k.startswith(incomplete)]170+171+ @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]}")176+177+178+Adding Support for a Shell179+--------------------------180+181+Support can be added for shells that do not come built in. Be sure to182+check PyPI to see if there's already a package that adds support for183+your shell. This topic is very technical, you'll want to look at Click's184+source to study the built-in implementations.185+186+Shell support is provided by subclasses of :class:`ShellComplete`187+registered with :func:`add_completion_class`. When Click is invoked in188+completion mode, it calls :meth:`~ShellComplete.source` to output the189+completion script, or :meth:`~ShellComplete.complete` to output190+completions. The base class provides default implementations that191+require implementing some smaller parts.192+193+First, you'll need to figure out how your shell's completion system194+works and write a script to integrate it with Click. It must invoke your195+program with the environment variable ``_{PROG_NAME}_COMPLETE`` set to196+``complete_{shell}`` and pass the complete args and incomplete value.197+How it passes those values, and the format of the completion response198+from Click is up to you.199+200+In your subclass, set :attr:`~ShellComplete.source_template` to the201+completion script. The default implementation will perform ``%``202+formatting with the following variables:203+204+- ``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.209+210+The example code is for a made up shell "My Shell" or "mysh" for short.211+212+.. code-block:: python213+214+ from click.shell_completion import add_completion_class215+ from click.shell_completion import ShellComplete216+217+ _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+ """224+225+ @add_completion_class226+ class MyshComplete(ShellComplete):227+ name = "mysh"228+ source_template = _mysh_source229+230+Next, implement :meth:`~ShellComplete.get_completion_args`. This must231+get, parse, and return the complete args and incomplete value from the232+completion script. For example, for the Bash implementation the233+``COMP_WORDS`` env var contains the command line args as a string, and234+the ``COMP_CWORD`` env var contains the index of the incomplete arg. The235+method must return a ``(args, incomplete)`` tuple.236+237+.. code-block:: python238+239+ import os240+ from click.parser import split_arg_string241+242+ class MyshComplete(ShellComplete):243+ ...244+245+ def get_completion_args(self):246+ args = split_arg_string(os.environ["COMP_WORDS"])247+248+ if os.environ["COMP_PARTIAL"] == "1":249+ incomplete = args.pop()250+ return args, incomplete251+252+ return args, ""253+254+Finally, implement :meth:`~ShellComplete.format_completion`. This is255+called to format each ``(type, value, help)`` tuples returned by Click256+into a string. For example, the Bash implementation returns257+``f"{type},{value}`` (it doesn't support help strings), and the Zsh258+implementation returns each part separated by a newline, replacing empty259+help with a ``_`` placeholder. This format is entirely up to what you260+parse with your completion script.261+262+The ``type`` value is usually ``plain``, but it can be another value263+that the completion script can switch on. For example, ``file`` or264+``dir`` can tell the shell to handle path completion, since the shell is265+better at that than Click.266+267+.. code-block:: python268+269+ import os270+ from click.parser import split_arg_string271+272+ class MyshComplete(ShellComplete):273+ ...274+275+ def format_completion(self, item):276+ type, value, _ = item277+ return f"{type}\t{value}"278+279+With those three things implemented, the new shell support is ready. In280+case those weren't sufficient, there are more parts that can be281+overridden, but that probably isn't necessary.282+283+The activation instructions will again depend on how your shell works.284+Use the following to generate the completion script, then load it into285+the shell somehow.286+287+.. code-block:: text288+289+ _FOO_BAR_COMPLETE=source_mysh foo-bardeleted:examples/bashcompletion/bashcompletion.py-45 removed
1-import os2-3-import click4-5-6-@click.group()7-def cli():8- pass9-10-11-def 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 key16-17-18-@cli.command(help="A command to print environment variables")19-@click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)20-def cmd1(envvar):21- click.echo(f"Environment variable: {envvar}")22- click.echo(f"Value: {os.environ[envvar]}")23-24-25-@click.group(help="A group that holds a subcommand")26-def group():27- pass28-29-30-def 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]]37-38-39-@group.command(help="Choose a user")40-@click.argument("user", type=click.STRING, autocompletion=list_users)41-def subcmd(user):42- click.echo(f"Chosen user is {user}")43-44-45-cli.add_command(group)deleted:examples/bashcompletion/README-12 removed
1-$ bashcompletion2-3- bashcompletion is a simple example of an application that4- tries to autocomplete commands, arguments and options.5-6- This example requires Click 2.0 or higher.7-8-Usage:9-10- $ pip install --editable .11- $ eval "$(_BASHCOMPLETION_COMPLETE=source bashcompletion)"12- $ bashcompletion --helpdeleted:examples/bashcompletion/setup.py-13 removed
1-from setuptools import setup2-3-setup(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
1+import os2+3+import click4+from click.shell_completion import CompletionItem5+6+7+@click.group()8+def cli():9+ pass10+11+12+@cli.command()13+@click.option("--dir", type=click.Path(file_okay=False))14+def ls(dir):15+ click.echo("\n".join(os.listdir(dir)))16+17+18+def 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]22+23+24+@cli.command(help="A command to print environment variables")25+@click.argument("envvar", shell_complete=get_env_vars)26+def show_env(envvar):27+ click.echo(f"Environment variable: {envvar}")28+ click.echo(f"Value: {os.environ[envvar]}")29+30+31+@cli.group(help="A group that holds a subcommand")32+def group():33+ pass34+35+36+def 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")]41+42+ for value, help in items:43+ if incomplete in value or incomplete in help:44+ yield CompletionItem(value, help=help)45+46+47+@group.command(help="Choose a user")48+@click.argument("user", shell_complete=list_users)49+def select_user(user):50+ click.echo(f"Chosen user is {user}")51+52+53+cli.add_command(group)added:examples/completion/README+28 added
1+$ completion2+============3+4+Demonstrates Click's shell completion support.5+6+.. code-block:: bash7+8+ pip install --editable .9+10+For Bash:11+12+.. code-block:: bash13+14+ eval "$(_COMPLETION_COMPLETE=source_bash completion)"15+16+For Zsh:17+18+.. code-block:: zsh19+20+ eval "$(_COMPLETION_COMPLETE=source_zsh completion)"21+22+For Fish:23+24+.. code-block:: fish25+26+ eval (env _COMPLETION_COMPLETE=source_fish completion)27+28+Now press tab (maybe twice) after typing something to see completions.added:examples/completion/setup.py+13 added
1+from setuptools import setup2+3+setup(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 lines29 pip-tools==5.3.1 # via -r requirements/dev.in30 pluggy==0.13.1 # via pytest, tox31 pre-commit==2.7.1 # via -r requirements/dev.in32 py==1.9.0 # via pytest, tox33-pygments==2.6.1 # via sphinx33+pygments==2.6.1 # via sphinx, sphinx-tabs34 pyparsing==2.4.7 # via packaging35 pytest==6.1.0 # via -r requirements/tests.in36 pytz==2020.1 # via babel37 pyyaml==5.3.1 # via pre-commit38 requests==2.23.0 # via sphinx39 six==1.15.0 # via packaging, pip-tools, tox, virtualenv40 snowballstemmer==2.0.0 # via sphinx41 sphinx-issues==1.2.0 # via -r requirements/docs.in42+sphinx-tabs==1.3.0 # via -r requirements/docs.in42-sphinx==3.2.1 # via -r requirements/docs.in, pallets-sphinx-themes, sphinx-issues, sphinxcontrib-log-cabinet43+sphinx==3.2.1 # via -r requirements/docs.in, pallets-sphinx-themes, sphinx-issues, sphinx-tabs, sphinxcontrib-log-cabinet44 sphinxcontrib-applehelp==1.0.2 # via sphinx45 sphinxcontrib-devhelp==1.0.2 # via sphinx46 sphinxcontrib-htmlhelp==1.0.3 # via sphinx47 sphinxcontrib-jsmath==1.0.1 # via sphinx12 unmodified linesmodified:requirements/docs.in+1 added
1 Pallets-Sphinx-Themes2 Sphinx3 sphinx-issues4 sphinxcontrib-log-cabinet5+sphinx-tabsmodified:requirements/docs.txt+3 added-2 removed
13 unmodified lines14 jinja2==2.11.2 # via sphinx15 markupsafe==1.1.1 # via jinja216 packaging==20.4 # via pallets-sphinx-themes, sphinx17 pallets-sphinx-themes==1.2.3 # via -r requirements/docs.in18-pygments==2.6.1 # via sphinx18+pygments==2.6.1 # via sphinx, sphinx-tabs19 pyparsing==2.4.7 # via packaging20 pytz==2020.1 # via babel21 requests==2.23.0 # via sphinx22 six==1.15.0 # via packaging23 snowballstemmer==2.0.0 # via sphinx24 sphinx-issues==1.2.0 # via -r requirements/docs.in25+sphinx-tabs==1.3.0 # via -r requirements/docs.in25-sphinx==3.2.1 # via -r requirements/docs.in, pallets-sphinx-themes, sphinx-issues, sphinxcontrib-log-cabinet26+sphinx==3.2.1 # via -r requirements/docs.in, pallets-sphinx-themes, sphinx-issues, sphinx-tabs, sphinxcontrib-log-cabinet27 sphinxcontrib-applehelp==1.0.2 # via sphinx28 sphinxcontrib-devhelp==1.0.2 # via sphinx29 sphinxcontrib-htmlhelp==1.0.3 # via sphinx30 sphinxcontrib-jsmath==1.0.1 # via sphinx7 unmodified linesdeleted: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+196 added-22 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 name, command74 75 76 def _check_multicommand(base_command, cmd_name, cmd, register=False):77 if not base_command.chain or not isinstance(cmd, MultiCommand):205 unmodified lines283 #: 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 but569 unmodified lines867 implementation is raising a not implemented error.868 """869 raise NotImplementedError("Base commands are not invokable by default")870 871+ def shell_complete(self, ctx, incomplete):872+ """Return a list of completions for the incomplete value. Looks873+ at the names of chained multi-commands.874+875+ 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.878+879+ :param ctx: Invocation context for this command.880+ :param incomplete: Value being completed. May be empty.881+882+ .. versionadded:: 8.0883+ """884+ from click.shell_completion import CompletionItem885+886+ results = []887+888+ while ctx.parent is not None:889+ ctx = ctx.parent890+891+ 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+ )897+898+ return results899+900 def main(901 self,902 args=None,903 prog_name=None,44 unmodified lines948 949 if prog_name is None:950 prog_name = _detect_program_name()951 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)952+ # Process shell completion requests and exit early.953+ self._main_shell_completion(prog_name, complete_var)954 955 try:956 try:957 with self.make_context(prog_name, args, **extra) as ctx:41 unmodified lines999 raise1000 echo("Aborted!", file=sys.stderr)1001 sys.exit(1)1002 1003+ 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.1007+1008+ :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()1015+1016+ instruction = os.environ.get(complete_var)1017+1018+ if not instruction:1019+ return1020+1021+ from .shell_completion import shell_complete1022+1023+ rv = shell_complete(self, prog_name, complete_var, instruction)1024+ _fast_exit(rv)1025+1026 def __call__(self, *args, **kwargs):1027 """Alias for :meth:`main`."""1028 return self.main(*args, **kwargs)1029 250 unmodified lines1280 _maybe_show_deprecated_notice(self)1281 if self.callback is not None:1282 return ctx.invoke(self.callback, **ctx.params)1283 1284+ 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.1287 1288+ :param ctx: Invocation context for this command.1289+ :param incomplete: Value being completed. May be empty.1290+1291+ .. versionadded:: 8.01292+ """1293+ from click.shell_completion import CompletionItem1294+1295+ results = []1296+1297+ 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+ continue1305+1306+ results.extend(1307+ CompletionItem(name, help=param.help)1308+ for name in param.opts + param.secondary_opts1309+ if name.startswith(incomplete)1310+ )1311+1312+ results.extend(super().shell_complete(ctx, incomplete))1313+ return results1314+1315+1316 class 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 lines1568 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:]1573 1485- return cmd.name, cmd, args[1:]1486-1574 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 lines1582 appear.1583 """1584 return []1585 1586+ 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.1590 1591+ :param ctx: Invocation context for this command.1592+ :param incomplete: Value being completed. May be empty.1593+1594+ .. versionadded:: 8.01595+ """1596+ from click.shell_completion import CompletionItem1597+1598+ 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 results1604+1605+1606 class 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 lines1782 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.1791 1792+ .. 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.1797+1798 .. 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 lines1804 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 """1808+1809 param_type_name = "parameter"1810 1811 def __init__(1812 self,6 unmodified lines1819 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_value17 unmodified lines1845 self.default = default1846 self.is_eager = is_eager1847 self.metavar = metavar1848 self.envvar = envvar1730- self.autocompletion = autocompletion1849 1850+ if autocompletion is not None:1851+ import warnings1852+1853+ 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+ )1860+1861+ def shell_complete(ctx, param, incomplete):1862+ from click.shell_completion import CompletionItem1863+1864+ out = []1865+1866+ 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)1871+1872+ if c.value.startswith(incomplete):1873+ out.append(c)1874+1875+ return out1876+1877+ self._custom_shell_complete = shell_complete1878+1879 def to_info_dict(self):1880 """Gather information that could be useful for a tool generating1881 user-facing documentation.1882 165 unmodified lines2048 raise2049 2050 if self.expose_value:2051 ctx.params[self.name] = value2052+2053+ if value is not None:2054+ ctx._seen_params.add(self)2055+2056 return value, args2057 2058 def get_help_record(self, ctx):2059 pass7 unmodified lines2067 """2068 hint_list = self.opts or [self.human_readable_name]2069 return " / ".join(repr(x) for x in hint_list)2070 2071+ 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.2076 2077+ :param ctx: Invocation context for this command.2078+ :param incomplete: Value being completed. May be empty.2079+2080+ .. versionadded:: 8.02081+ """2082+ if self._custom_shell_complete is not None:2083+ results = self._custom_shell_complete(ctx, self, incomplete)2084+2085+ if results and isinstance(results[0], str):2086+ from click.shell_completion import CompletionItem2087+2088+ results = [CompletionItem(c) for c in results]2089+2090+ return results2091+2092+ return self.type.shell_complete(ctx, self, incomplete)2093+2094+2095 class 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 linesadded:src/click/shell_completion.py+536 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+class 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.46+47+ 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``.50+51+ :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+ """59+60+ __slots__ = ("value", "type", "help", "_info")61+62+ def __init__(self, value, type="plain", help=None, **kwargs):63+ self.value = value64+ self.type = type65+ self.help = help66+ self._info = kwargs67+68+ def __getattr__(self, name):69+ return self._info.get(name)70+71+72+# Only Bash >= 4.4 has the nosort option.73+_SOURCE_BASH = """\74+%(complete_func)s() {75+ local IFS=$'\\n'76+ local response77+78+ response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \79+%(complete_var)s=complete_bash $1)80+81+ for completion in $response; do82+ IFS=',' read type value <<< "$completion"83+84+ 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+ done94+95+ return 096+}97+98+%(complete_func)s_setup() {99+ complete -o nosort -F %(complete_func)s %(prog_name)s100+}101+102+%(complete_func)s_setup;103+"""104+105+_SOURCE_ZSH = """\106+#compdef %(prog_name)s107+108+%(complete_func)s() {109+ local -a completions110+ local -a completions_with_descriptions111+ local -a response112+ (( ! $+commands[%(prog_name)s] )) && return 1113+114+ response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) \115+%(complete_var)s=complete_zsh %(prog_name)s)}")116+117+ 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+ done130+131+ if [ -n "$completions_with_descriptions" ]; then132+ _describe -V unsorted completions_with_descriptions -U133+ fi134+135+ if [ -n "$completions" ]; then136+ compadd -U -V unsorted -a completions137+ fi138+}139+140+compdef %(complete_func)s %(prog_name)s;141+"""142+143+_SOURCE_FISH = """\144+function %(complete_func)s;145+ set -l response;146+147+ for value in (env %(complete_var)s=complete_fish COMP_WORDS=(commandline -cp) \148+COMP_CWORD=(commandline -t) %(prog_name)s);149+ set response $response $value;150+ end;151+152+ for completion in $response;153+ set -l metadata (string split "," $completion);154+155+ 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;163+end;164+165+complete --no-files --command %(prog_name)s --arguments \166+"(%(complete_func)s)";167+"""168+169+170+class 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``).174+175+ :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.179+180+ .. versionadded:: 8.0181+ """182+183+ 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+ """192+193+ def __init__(self, cli, prog_name, complete_var):194+ self.cli = cli195+ self.prog_name = prog_name196+ self.complete_var = complete_var197+198+ @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"205+206+ def source_vars(self):207+ """Vars for formatting :attr:`source_template`.208+209+ 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+ }217+218+ 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()225+226+ 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 NotImplementedError232+233+ 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.237+238+ :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)242+243+ if ctx is None:244+ return []245+246+ obj, incomplete = _resolve_incomplete(ctx, args, incomplete)247+ return obj.shell_complete(ctx, incomplete)248+249+ def format_completion(self, item):250+ """Format a completion item into the form recognized by the251+ shell script. This must be implemented by subclasses.252+253+ :param item: Completion item to format.254+ """255+ raise NotImplementedError256+257+ def complete(self):258+ """Produce the completion data to send back to the shell.259+260+ 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)268+269+270+class BashComplete(ShellComplete):271+ """Shell completion for Bash."""272+273+ name = "bash"274+ source_template = _SOURCE_BASH275+276+ def _check_version(self):277+ import subprocess278+279+ output = subprocess.run(["bash", "--version"], stdout=subprocess.PIPE)280+ match = re.search(r"version (\d)\.(\d)\.\d", output.stdout.decode())281+282+ if match is not None:283+ major, minor = match.groups()284+285+ 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+ )294+295+ def source(self):296+ self._check_version()297+ return super().source()298+299+ 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]303+304+ try:305+ incomplete = cwords[cword]306+ except IndexError:307+ incomplete = ""308+309+ return args, incomplete310+311+ def format_completion(self, item: CompletionItem):312+ return f"{item.type},{item.value}"313+314+315+class ZshComplete(ShellComplete):316+ """Shell completion for Zsh."""317+318+ name = "zsh"319+ source_template = _SOURCE_ZSH320+321+ 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]325+326+ try:327+ incomplete = cwords[cword]328+ except IndexError:329+ incomplete = ""330+331+ return args, incomplete332+333+ def format_completion(self, item: CompletionItem):334+ return f"{item.type}\n{item.value}\n{item.help if item.help else '_'}"335+336+337+class FishComplete(ShellComplete):338+ """Shell completion for Fish."""339+340+ name = "fish"341+ source_template = _SOURCE_FISH342+343+ def get_completion_args(self):344+ cwords = split_arg_string(os.environ["COMP_WORDS"])345+ incomplete = os.environ["COMP_CWORD"]346+ args = cwords[1:]347+348+ # 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()352+353+ return args, incomplete354+355+ def format_completion(self, item: CompletionItem):356+ if item.help:357+ return f"{item.type},{item.value}\t{item.help}"358+359+ return f"{item.type},{item.value}"360+361+362+_available_shells = {363+ "bash": BashComplete,364+ "fish": FishComplete,365+ "zsh": ZshComplete,366+}367+368+369+def 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.373+374+ :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.name381+382+ _available_shells[name] = cls383+384+385+def 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``.389+390+ :param shell: Name the class is registered under.391+ """392+ return _available_shells.get(shell)393+394+395+def _is_incomplete_argument(values, param):396+ """Determine if the given parameter is an argument that can still397+ accept values.398+399+ :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 False405+406+ value = values[param.name]407+408+ if value is None:409+ return True410+411+ if param.nargs == -1:412+ return True413+414+ if isinstance(value, list) and param.nargs > 1 and len(value) < param.nargs:415+ return True416+417+ return False418+419+420+def _start_of_option(value):421+ """Check if the value looks like the start of an option."""422+ return value and not value[0].isalnum()423+424+425+def _is_incomplete_option(args, param):426+ """Determine if the given parameter is an option that needs a value.427+428+ :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 False433+434+ if param.is_flag:435+ return False436+437+ last_option = None438+439+ for index, arg in enumerate(reversed(args)):440+ if index + 1 > param.nargs:441+ break442+443+ if _start_of_option(arg):444+ last_option = arg445+446+ return last_option is not None and last_option in param.opts447+448+449+def _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.453+454+ :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.args460+461+ while args:462+ if isinstance(ctx.command, MultiCommand):463+ if not ctx.command.chain:464+ name, cmd, args = ctx.command.resolve_command(ctx, args)465+466+ if cmd is None:467+ return ctx468+469+ 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)474+475+ if cmd is None:476+ return ctx477+478+ 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.args487+488+ ctx = sub_ctx489+ args = sub_ctx.protected_args + sub_ctx.args490+ else:491+ break492+493+ return ctx494+495+496+def _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.499+500+ :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)514+515+ # 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, incomplete521+522+ # 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, incomplete527+528+ # 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, incomplete533+534+ # There were no unparsed arguments, the command may be a group that535+ # will provide command name completions.536+ return ctx.command, incompletemodified:src/click/types.py+59 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, 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.116 117+ :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.120+121+ .. versionadded:: 8.0122+ """123+ return []124+125+126 class CompositeParamType(ParamType):127 is_composite = True128 129 @property133 unmodified lines263 264 def __repr__(self):265 return f"Choice({list(self.choices)})"266 267+ def shell_complete(self, ctx, param, incomplete):268+ """Complete choices that start with the incomplete value.269 270+ :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.273+274+ .. versionadded:: 8.0275+ """276+ from click.shell_completion import CompletionItem277+278+ str_choices = map(str, self.choices)279+ return [CompletionItem(c) for c in str_choices if c.startswith(incomplete)]280+281+282 class DateTime(ParamType):283 """The DateTime type converts date strings into `datetime` objects.284 285 The format strings which are checked are configurable, but default to some325 unmodified lines611 param,612 ctx,613 )614 615+ 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.618 619+ :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.622+623+ .. versionadded:: 8.0624+ """625+ from click.shell_completion import CompletionItem626+627+ return [CompletionItem(incomplete, type="file")]628+629+630 class 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 various122 unmodified lines756 )757 758 return self.coerce_path_result(rv)759 760+ 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.764 765+ :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.768+769+ .. versionadded:: 8.0770+ """771+ from click.shell_completion import CompletionItem772+773+ type = "dir" if self.dir_okay and not self.file_okay else "file"774+ return [CompletionItem(incomplete, type=type)]775+776+777 class 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 this109 unmodified linesdeleted:tests/test_bashcomplete.py-519 removed
1-import pytest2-3-import click4-from click._bashcomplete import get_choices5-6-7-def choices_without_help(cli, args, incomplete):8- completions = get_choices(cli, "dummy", args, incomplete)9- return [c[0] for c in completions]10-11-12-def choices_with_help(cli, args, incomplete):13- return list(get_choices(cli, "dummy", args, incomplete))14-15-16-def test_single_command():17- @click.command()18- @click.option("--local-opt")19- def cli(local_opt):20- pass21-22- assert choices_without_help(cli, [], "-") == ["--local-opt", "--help"]23- assert choices_without_help(cli, [], "") == []24-25-26-def test_boolean_flag():27- @click.command()28- @click.option("--shout/--no-shout", default=False)29- def cli(local_opt):30- pass31-32- assert choices_without_help(cli, [], "-") == ["--shout", "--no-shout", "--help"]33-34-35-def test_multi_value_option():36- @click.group()37- @click.option("--pos", nargs=2, type=float)38- def cli(local_opt):39- pass40-41- @cli.command()42- @click.option("--local-opt")43- def sub(local_opt):44- pass45-46- 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"]50-51-52-def test_multi_option():53- @click.command()54- @click.option("--message", "-m", multiple=True)55- def cli(local_opt):56- pass57-58- assert choices_without_help(cli, [], "-") == ["--message", "-m", "--help"]59- assert choices_without_help(cli, ["-m"], "") == []60-61-62-def test_small_chain():63- @click.group()64- @click.option("--global-opt")65- def cli(global_opt):66- pass67-68- @cli.command()69- @click.option("--local-opt")70- def sub(local_opt):71- pass72-73- 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"]77-78-79-def test_long_chain():80- @click.group("cli")81- @click.option("--cli-opt")82- def cli(cli_opt):83- pass84-85- @cli.group("asub")86- @click.option("--asub-opt")87- def asub(asub_opt):88- pass89-90- @asub.group("bsub")91- @click.option("--bsub-opt")92- def bsub(bsub_opt):93- pass94-95- COLORS = ["red", "green", "blue"]96-97- def get_colors(ctx, args, incomplete):98- for c in COLORS:99- if c.startswith(incomplete):100- yield c101-102- def search_colors(ctx, args, incomplete):103- for c in COLORS:104- if incomplete in c:105- yield c106-107- CSUB_OPT_CHOICES = ["foo", "bar"]108- CSUB_CHOICES = ["bar", "baz"]109-110- @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- pass117-118- 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"]150-151-152-def 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- pass158-159- @cli.command()160- @click.option("--asub-opt")161- def asub(asub_opt):162- pass163-164- @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- pass169-170- @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- pass175-176- 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")]205-206-207-def 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- pass214-215- 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"]220-221-222-def 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- pass229-230- 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"]259-260- assert choices_without_help(cli, ["--opt1", "invalid_opt"], "-") == [261- "--opt2",262- "--opt3",263- "--help",264- ]265-266-267-def 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- pass274-275- 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"]281-282-283-def 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- pass289-290- assert choices_without_help(cli, [], "-") == ["--shout", "--no-shout", "--help"]291- assert choices_without_help(cli, ["--shout"], "") == ["arg1", "arg2"]292-293-294-def 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- pass300-301- 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"], "") == []305-306-307-def 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- pass313-314- 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"]317-318-319-def 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- pass325-326- 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"]330-331-332-def test_variadic_argument_complete():333- def _complete(ctx, args, incomplete):334- return ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "yz"]335-336- @click.group()337- def entrypoint():338- pass339-340- @click.command()341- @click.option("--opt", autocompletion=_complete)342- @click.argument("arg", nargs=-1)343- def subcommand(opt, arg):344- pass345-346- entrypoint.add_command(subcommand)347-348- 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- )358-359-360-def test_long_chain_choice():361- @click.group()362- def cli():363- pass364-365- @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- pass372-373- @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- pass383-384- @sub.group("csub")385- def csub():386- pass387-388- @csub.command()389- def dsub():390- pass391-392- 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"]428-429-430-def test_chained_multi():431- @click.group()432- def cli():433- pass434-435- @cli.group()436- def sub():437- pass438-439- @sub.group()440- def bsub():441- pass442-443- @sub.group(chain=True)444- def csub():445- pass446-447- @csub.command()448- def dsub():449- pass450-451- @csub.command()452- def esub():453- pass454-455- 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"]459-460-461-def 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- pass467-468- @cli.group(hidden=True)469- def hgroup():470- pass471-472- @hgroup.group()473- def hgroupsub():474- pass475-476- @cli.command()477- def asub():478- pass479-480- @cli.command(hidden=True)481- @click.option("--hname")482- def hsub():483- pass484-485- 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"]495-496-497-@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-)508-def 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)]512-513- @click.command()514- @click.option("--opt")515- @click.argument("args", nargs=-1, autocompletion=_complete)516- def cli(opt, args):517- pass518-519- assert choices_without_help(cli, args, part) == expectmodified:tests/test_compat.py-17 removed
2 unmodified lines3 from click._compat import should_strip_ansi4 from click._compat import WIN5 6 7-def test_bash_func_name():8- from click._bashcomplete import get_completion_script9-10- 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 script13-14-15-def test_zsh_func_name():16- from click._bashcomplete import get_completion_script17-18- 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 script22-23-7 @pytest.mark.xfail(WIN, reason="Jupyter not tested/supported on Windows")8 def test_is_jupyter_kernel_output():9 class JupyterKernelFakeStream:10 pass4 unmodified linesadded:tests/test_shell_completion.py+277 added
1+import sys2+3+import pytest4+5+from click.core import Argument6+from click.core import Command7+from click.core import Group8+from click.core import Option9+from click.shell_completion import CompletionItem10+from click.shell_completion import ShellComplete11+from click.types import Choice12+from click.types import File13+from click.types import Path14+15+16+def _get_completions(cli, args, incomplete):17+ comp = ShellComplete(cli, cli.name, "_CLICK_COMPLETE")18+ return comp.get_completions(args, incomplete)19+20+21+def _get_words(cli, args, incomplete):22+ return [c.value for c in _get_completions(cli, args, incomplete)]23+24+25+def 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"]33+34+35+def 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"]39+40+41+def 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"]49+50+51+def 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"]68+69+70+def 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"], "--") == []74+75+76+def 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"]91+92+93+def 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"]98+99+100+@pytest.mark.parametrize(101+ ("type", "expect"),102+ [(File(), "file"), (Path(), "file"), (Path(file_okay=False), "dir")],103+)104+def 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 == expect111+112+113+def 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"]125+126+127+def test_option_custom():128+ def custom(ctx, param, incomplete):129+ return [incomplete.upper()]130+131+ 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"]141+142+143+def 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"]149+150+ with pytest.deprecated_call():151+ cli = Command("cli", params=[Argument(["x"], autocompletion=custom)])152+153+ assert _get_words(cli, [], "") == ["art", "bat", "cat"]154+ assert _get_words(cli, [], "c") == ["cat"]155+156+157+def 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"], "-")167+168+169+def 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"], "") == []174+175+176+def 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"]192+193+194+def 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"]207+208+209+def 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"]228+229+230+def 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 words235+236+237+def test_completion_item_data():238+ c = CompletionItem("test", a=1)239+ assert c.a == 1240+ assert c.b is None241+242+243+@pytest.fixture()244+def _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+ )249+250+251+@pytest.mark.parametrize(252+ "shell", ["bash", "zsh", "fish"],253+)254+@pytest.mark.usefixtures("_patch_for_completion")255+def 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.output259+260+261+@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")273+def 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 == expectmodified:CHANGES.rst+14 added
88 unmodified lines89 - 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`94 95+ - 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.107 108+109 Version 7.1.2110 -------------111 112 Released 2020-04-27633 unmodified lines