Skip to content
Myr

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

11 files+176 added−95 removed

modified:docs/shell-completion.rst+4 added-3 removed
146 unmodified lines
147Overriding Value Completion148---------------------------149150Value completions for a parameter can be customized without a custom151type by providing an ``autocompletion`` function. The function is used151type by providing a ``shell_complete`` function. The function is used152instead of any completion provided by the type. It is passed 3 keyword153arguments:154155- ``ctx`` - The current command context.156- ``param`` - The current parameter requesting completion.157- ``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 lines
165start with the incomplete value.166167.. code-block:: python168168 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)]171172 @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 lines
deleted:examples/bashcompletion/bashcompletion.py-45 removed
1import os23import click456@click.group()7def cli():8 pass91011def get_env_vars(ctx, args, incomplete):12 # Completions returned as strings do not have a description displayed.13 for key in os.environ.keys():14 if incomplete in key:15 yield key161718@cli.command(help="A command to print environment variables")19@click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)20def cmd1(envvar):21 click.echo(f"Environment variable: {envvar}")22 click.echo(f"Value: {os.environ[envvar]}")232425@click.group(help="A group that holds a subcommand")26def group():27 pass282930def list_users(ctx, args, incomplete):31 # You can generate completions with descriptions by returning32 # tuples in the form (completion, description).33 users = [("bob", "butcher"), ("alice", "baker"), ("jerry", "candlestick maker")]34 # Ths will allow completion matches based on matches within the35 # description string too!36 return [user for user in users if incomplete in user[0] or incomplete in user[1]]373839@group.command(help="Choose a user")40@click.argument("user", type=click.STRING, autocompletion=list_users)41def subcmd(user):42 click.echo(f"Chosen user is {user}")434445cli.add_command(group)
deleted:examples/bashcompletion/README-12 removed
1$ bashcompletion23 bashcompletion is a simple example of an application that4 tries to autocomplete commands, arguments and options.56 This example requires Click 2.0 or higher.78Usage:910 $ pip install --editable .11 $ eval "$(_BASHCOMPLETION_COMPLETE=source bashcompletion)"12 $ bashcompletion --help
deleted:examples/bashcompletion/setup.py-13 removed
1from setuptools import setup23setup(4 name="click-example-bashcompletion",5 version="1.0",6 py_modules=["bashcompletion"],7 include_package_data=True,8 install_requires=["click"],9 entry_points="""10 [console_scripts]11 bashcompletion=bashcompletion:cli12 """,13)
added:examples/completion/completion.py+53 added
1import os23import click4from click.shell_completion import CompletionItem567@click.group()8def cli():9 pass101112@cli.command()13@click.option("--dir", type=click.Path(file_okay=False))14def ls(dir):15 click.echo("\n".join(os.listdir(dir)))161718def get_env_vars(ctx, param, 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]222324@cli.command(help="A command to print environment variables")25@click.argument("envvar", shell_complete=get_env_vars)26def show_env(envvar):27 click.echo(f"Environment variable: {envvar}")28 click.echo(f"Value: {os.environ[envvar]}")293031@cli.group(help="A group that holds a subcommand")32def group():33 pass343536def list_users(ctx, 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")]4142 for value, help in items:43 if incomplete in value or incomplete in help:44 yield CompletionItem(value, help=help)454647@group.command(help="Choose a user")48@click.argument("user", type=click.STRING, autocompletion=list_users)49def select_user(user):50 click.echo(f"Chosen user is {user}")515253cli.add_command(group)
added:examples/completion/README+28 added
1$ completion2============34Demonstrates Click's shell completion support.56.. code-block:: bash78 pip install --editable .910For Bash:1112.. code-block:: bash1314 eval "$(_COMPLETION_COMPLETE=source_bash completion)"1516For Zsh:1718.. code-block:: zsh1920 eval "$(_COMPLETION_COMPLETE=source_zsh completion)"2122For Fish:2324.. code-block:: fish2526 eval (env _COMPLETION_COMPLETE=source_fish completion)2728Now press tab (maybe twice) after typing something to see completions.
added:examples/completion/setup.py+13 added
1from setuptools import setup23setup(4 name="click-example-completion",5 version="1.0",6 py_modules=["completion"],7 include_package_data=True,8 install_requires=["click"],9 entry_points="""10 [console_scripts]11 completion=completion:cli12 """,13)
modified:src/click/core.py+49 added-16 removed
1779 unmodified lines
1780 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.17891790 .. 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.17951796 .. 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 lines
1802 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 """18061807 param_type_name = "parameter"18081809 def __init__(1810 self,
6 unmodified lines
1817 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_value
17 unmodified lines
1843 self.default = default1844 self.is_eager = is_eager1845 self.metavar = metavar1846 self.envvar = envvar1837 self.autocompletion = autocompletion18471848 if autocompletion is not None:1849 import warnings18501851 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 )18581859 def shell_complete(ctx, param, args, incomplete):1860 from click.shell_completion import CompletionItem18611862 out = []18631864 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)18691870 if c.value.startswith(incomplete):1871 out.append(c)18721873 return out18741875 self._custom_shell_complete = shell_complete18761877 def to_info_dict(self):1878 """Gather information that could be useful for a tool generating1879 user-facing documentation.1880
181 unmodified lines
2062 hint_list = self.opts or [self.human_readable_name]2063 return " / ".join(repr(x) for x in hint_list)20642065 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.20702071 :param ctx: Invocation context for this command.
1 unmodified line
2073 :param incomplete: Value being completed. May be empty.20742075 .. 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)20792041 if self.autocompletion is not None:2042 results = []2080 if results and isinstance(results[0], str):2081 from click.shell_completion import CompletionItem20822044 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]20842085 return results20862054 return self.type.shell_complete(ctx, args, incomplete)2087 return self.type.shell_complete(ctx, self, args, incomplete)208820892090class Option(Parameter):2091 """Options are usually optional values on the command line and
409 unmodified lines
modified:src/click/types.py+8 added-4 removed
105 unmodified lines
106 def fail(self, message, param=None, ctx=None):107 """Helper method to fail with an invalid value message."""108 raise BadParameter(message, ctx=ctx, param=param)109110 def shell_complete(self, ctx, args, incomplete):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.116117 :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.121122 .. versionadded:: 8.0
141 unmodified lines
264265 def __repr__(self):266 return f"Choice({list(self.choices)})"267267 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.270271 :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.275276 .. versionadded:: 8.0
336 unmodified lines
613 param,614 ctx,615 )616615 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.620621 :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.625626 .. versionadded:: 8.0
132 unmodified lines
759 )760761 return self.coerce_path_result(rv)762760 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.767768 :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.772773 .. versionadded:: 8.0
120 unmodified lines
modified:tests/test_shell_completion.py+15 added-2 removed
112 unmodified lines
113 assert _get_words(cli, ["x", "--on"], "a") == ["a1", "a2"]114115116def test_option_custom():117 def custom(ctx, args, incomplete):117 def custom(ctx, param, args, incomplete):118 return [incomplete.upper()]119120 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"]130131132def 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"]137138 with pytest.deprecated_call():139 cli = Command("cli", params=[Argument(["x"], autocompletion=custom)])140141 assert _get_words(cli, [], "") == ["art", "bat", "cat"]142 assert _get_words(cli, [], "c") == ["cat"]143144145def test_option_multiple():146 cli = Command(147 "type",148 params=[Option(["-m"], type=Choice(["a", "b"]), multiple=True), Option(["-f"])],
117 unmodified lines
modified:CHANGES.rst+6 added
96 unmodified lines
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 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.107108109Version 7.1.2110-------------
635 unmodified lines