rename autocompletion to shell_complete
Before adoption: this commit came in with the history the project adopted, so no landing records it.
new function takes additional param arg, must return a homogeneous list of strings or CompletionItem, and must perform matching on results
authored by David Lord · committed by David Lord · parent cb5c21e · Browse files · 11 files·+176 added−95 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+176 added−95 removed
- tests:+15 added−2 removed
- other:+161 added−93 removed
Provenance
- Commit
3faede8- Tree
65e9b97- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
cb5c21e
11 files changed+176 added−95 removed
modified:docs/shell-completion.rst+4 added-3 removed
146 unmodified lines147 Overriding Value Completion148 ---------------------------149 150 Value completions for a parameter can be customized without a custom151-type by providing an ``autocompletion`` function. The function is used151+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 - ``args`` - The list of complete args before the incomplete value.158 - ``incomplete`` - The partial word that is being completed. May159 be an empty string if no characters have been entered yet.160 4 unmodified lines165 start with the incomplete value.166 167 .. code-block:: python168 168- def complete_env_vars(ctx, args, incomplete):169+ def complete_env_vars(ctx, param, args, incomplete):170 return [k for k in os.environ if k.startswith(incomplete)]171 172 @click.command()172- @click.argument("name", autocompletion=complete_env_vars)173+ @click.argument("name", shell_complete=complete_env_vars)174 def cli(name):175 click.echo(f"Name: {name}")176 click.echo(f"Value: {os.environ[name]}")177 113 unmodified linesdeleted: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, args, 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, args, 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", type=click.STRING, autocompletion=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:src/click/core.py+49 added-16 removed
1779 unmodified lines1780 should not be set for arguments or it will inverse the1781 order of processing.1782 :param envvar: a string or list of strings that are environment variables1783 that should be checked.1784- :param autocompletion: A function that returns custom shell1784+ :param shell_complete: A function that returns custom shell1785 completions. Used instead of the param's type completion if1786- given.1786+ given. Takes ``ctx, param, args, incomplete`` and returns a list1787+ of :class:`~click.shell_completion.CompletionItem` or a list of1788+ strings.1789 1790+ .. versionchanged:: 8.01791+ ``autocompletion`` is renamed to ``shell_complete`` and has new1792+ semantics described in the docs above. The old name is1793+ deprecated and will be removed in 8.1, until then it will be1794+ wrapped to match the new requirements.1795+1796 .. versionchanged:: 7.11797 Empty environment variables are ignored rather than taking the1798 empty string value. This makes it possible for scripts to clear1799 variables if they can't unset them.2 unmodified lines1802 Changed signature for parameter callback to also be passed the1803 parameter. The old callback format will still work, but it will1804 raise a warning to give you a chance to migrate the code easier.1805 """1806+1807 param_type_name = "parameter"1808 1809 def __init__(1810 self,6 unmodified lines1817 metavar=None,1818 expose_value=True,1819 is_eager=False,1820 envvar=None,1821+ shell_complete=None,1822 autocompletion=None,1823 ):1824 self.name, self.opts, self.secondary_opts = self._parse_decls(1825 param_decls or (), expose_value17 unmodified lines1843 self.default = default1844 self.is_eager = is_eager1845 self.metavar = metavar1846 self.envvar = envvar1837- self.autocompletion = autocompletion1847 1848+ if autocompletion is not None:1849+ import warnings1850+1851+ warnings.warn(1852+ "'autocompletion' is renamed to 'shell_complete'. The old name is"1853+ " deprecated and will be removed in Click 8.1. See the docs about"1854+ " 'Parameter' for information about new behavior.",1855+ DeprecationWarning,1856+ stacklevel=2,1857+ )1858+1859+ def shell_complete(ctx, param, args, incomplete):1860+ from click.shell_completion import CompletionItem1861+1862+ out = []1863+1864+ for c in autocompletion(ctx, args, incomplete):1865+ if isinstance(c, tuple):1866+ c = CompletionItem(c[0], help=c[1])1867+ elif isinstance(c, str):1868+ c = CompletionItem(c)1869+1870+ if c.value.startswith(incomplete):1871+ out.append(c)1872+1873+ return out1874+1875+ self._custom_shell_complete = shell_complete1876+1877 def to_info_dict(self):1878 """Gather information that could be useful for a tool generating1879 user-facing documentation.1880 181 unmodified lines2062 hint_list = self.opts or [self.human_readable_name]2063 return " / ".join(repr(x) for x in hint_list)2064 2065 def shell_complete(self, ctx, args, incomplete):2028- """Return a list of completions for the incomplete value. If an2029- :attr:`autocompletion` function was given, it is used.2066+ """Return a list of completions for the incomplete value. If a2067+ ``shell_complete`` function was given during init, it is used.2068 Otherwise, the :attr:`type`2069 :meth:`~click.types.ParamType.shell_complete` function is used.2070 2071 :param ctx: Invocation context for this command.1 unmodified line2073 :param incomplete: Value being completed. May be empty.2074 2075 .. versionadded:: 8.02076 """2039- from click.shell_completion import CompletionItem2077+ if self._custom_shell_complete is not None:2078+ results = self._custom_shell_complete(ctx, self, args, incomplete)2079 2041- if self.autocompletion is not None:2042- results = []2080+ if results and isinstance(results[0], str):2081+ from click.shell_completion import CompletionItem2082 2044- for c in self.autocompletion(ctx=ctx, args=args, incomplete=incomplete):2045- if isinstance(c, CompletionItem):2046- results.append(c)2047- elif isinstance(c, tuple):2048- results.append(CompletionItem(c[0], help=c[1]))2049- else:2050- results.append(CompletionItem(c))2083+ results = [CompletionItem(c) for c in results]2084 2085 return results2086 2054- return self.type.shell_complete(ctx, args, incomplete)2087+ return self.type.shell_complete(ctx, self, args, incomplete)2088 2089 2090 class Option(Parameter):2091 """Options are usually optional values on the command line and409 unmodified linesmodified:src/click/types.py+8 added-4 removed
105 unmodified lines106 def fail(self, message, param=None, ctx=None):107 """Helper method to fail with an invalid value message."""108 raise BadParameter(message, ctx=ctx, param=param)109 110- def shell_complete(self, ctx, args, incomplete):110+ def shell_complete(self, ctx, param, args, 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 args: List of complete args before the incomplete value.120 :param incomplete: Value being completed. May be empty.121 122 .. versionadded:: 8.0141 unmodified lines264 265 def __repr__(self):266 return f"Choice({list(self.choices)})"267 267- def shell_complete(self, ctx, args, incomplete):268+ def shell_complete(self, ctx, param, args, incomplete):269 """Complete choices that start with the incomplete value.270 271 :param ctx: Invocation context for this command.272+ :param param: The parameter that is requesting completion.273 :param args: List of complete args before the incomplete value.274 :param incomplete: Value being completed. May be empty.275 276 .. versionadded:: 8.0336 unmodified lines613 param,614 ctx,615 )616 615- def shell_complete(self, ctx, args, incomplete):617+ def shell_complete(self, ctx, param, args, incomplete):618 """Return a special completion marker that tells the completion619 system to use the shell to provide file path completions.620 621 :param ctx: Invocation context for this command.622+ :param param: The parameter that is requesting completion.623 :param args: List of complete args before the incomplete value.624 :param incomplete: Value being completed. May be empty.625 626 .. versionadded:: 8.0132 unmodified lines759 )760 761 return self.coerce_path_result(rv)762 760- def shell_complete(self, ctx, args, incomplete):763+ def shell_complete(self, ctx, param, args, incomplete):764 """Return a special completion marker that tells the completion765 system to use the shell to provide path completions for only766 directories or any paths.767 768 :param ctx: Invocation context for this command.769+ :param param: The parameter that is requesting completion.770 :param args: List of complete args before the incomplete value.771 :param incomplete: Value being completed. May be empty.772 773 .. versionadded:: 8.0120 unmodified linesmodified:tests/test_shell_completion.py+15 added-2 removed
112 unmodified lines113 assert _get_words(cli, ["x", "--on"], "a") == ["a1", "a2"]114 115 116 def test_option_custom():117- def custom(ctx, args, incomplete):117+ def custom(ctx, param, args, incomplete):118 return [incomplete.upper()]119 120 cli = Command(121 "cli",122 params=[123 Argument(["x"]),124 Argument(["y"]),125- Argument(["z"], autocompletion=custom),125+ Argument(["z"], shell_complete=custom),126 ],127 )128 assert _get_words(cli, ["a", "b"], "") == [""]129 assert _get_words(cli, ["a", "b"], "c") == ["C"]130 131 132+def test_autocompletion_deprecated():133+ # old function takes three params, returns all values, can mix134+ # strings and tuples135+ def custom(ctx, args, incomplete):136+ return [("art", "x"), "bat", "cat"]137+138+ with pytest.deprecated_call():139+ cli = Command("cli", params=[Argument(["x"], autocompletion=custom)])140+141+ assert _get_words(cli, [], "") == ["art", "bat", "cat"]142+ assert _get_words(cli, [], "c") == ["cat"]143+144+145 def test_option_multiple():146 cli = Command(147 "type",148 params=[Option(["-m"], type=Choice(["a", "b"]), multiple=True), Option(["-f"])],117 unmodified linesmodified:CHANGES.rst+6 added
96 unmodified lines97 - 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 take four103+ parameters ``ctx, param, args, incomplete``, must do matching104+ rather than return all values, and must return a list of strings105+ or a list of ``ShellComplete``. The old name and behavior is106+ deprecated and will be removed in 8.1.107 108 109 Version 7.1.2110 -------------635 unmodified lines