don't pass all args to shell_complete methods
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent 3faede8 · Browse files · 7 files·+61 added−49 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+61 added−49 removed
- tests:+15 added−3 removed
- other:+46 added−46 removed
Provenance
- Commit
1b9a657- Tree
1631f0e- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
3faede8
7 files changed+61 added−49 removed
modified:docs/shell-completion.rst+2 added-3 removed
130 unmodified lines131 132 .. code-block:: python133 134 class EnvVarType(ParamType):135- def shell_complete(self, ctx, args, incomplete):135+ def shell_complete(self, ctx, param, incomplete):136 return [137 CompletionItem(name)138 for name in os.environ if name.startswith(incomplete)139 ]13 unmodified lines153 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.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 a3 unmodified lines164 start with the incomplete value.165 166 .. code-block:: python167 169- def complete_env_vars(ctx, param, args, incomplete):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)117 unmodified linesmodified:examples/completion/completion.py+3 added-3 removed
13 unmodified lines14 def ls(dir):15 click.echo("\n".join(os.listdir(dir)))16 17 18-def get_env_vars(ctx, param, args, incomplete):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 9 unmodified lines32 def group():33 pass34 35 36-def list_users(ctx, args, incomplete):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")]3 unmodified lines44 yield CompletionItem(value, help=help)45 46 47 @group.command(help="Choose a user")48-@click.argument("user", type=click.STRING, autocompletion=list_users)48+@click.argument("user", shell_complete=list_users)49 def select_user(user):50 click.echo(f"Chosen user is {user}")51 52 1 unmodified linemodified:src/click/core.py+30 added-25 removed
282 unmodified lines283 #: the :class:`Command` for this context.284 self.command = command285 #: the descriptive information name286 self.info_name = info_name287- #: the parsed parameters except if the value is hidden in which288- #: 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 867- def shell_complete(self, ctx, args, incomplete):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.876- :param args: List of complete args before the incomplete value.880 :param incomplete: Value being completed. May be empty.881 882 .. versionadded:: 8.0883 """396 unmodified lines1280 _maybe_show_deprecated_notice(self)1281 if self.callback is not None:1282 return ctx.invoke(self.callback, **ctx.params)1283 1281- def shell_complete(self, ctx, args, incomplete):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.1286- :param args: List of complete args before the incomplete value.1289 :param incomplete: Value being completed. May be empty.1290 1291 .. versionadded:: 8.01292 """2 unmodified lines1295 results = []1296 1297 if incomplete and not incomplete[0].isalnum():1298 for param in self.get_params(ctx):1297- if not isinstance(param, Option) or param.hidden: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_opts1303- if (1304- (name not in args or param.multiple)1305- and name.startswith(incomplete)1309+ if name.startswith(incomplete)1306- )1310 )1311 1309- results.extend(super().shell_complete(ctx, args, incomplete))1312+ results.extend(super().shell_complete(ctx, incomplete))1313 return results1314 1315 1316 class MultiCommand(Command):265 unmodified lines1582 appear.1583 """1584 return []1585 1583- def shell_complete(self, ctx, args, incomplete):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.1589- :param args: List of complete args before the incomplete value.1592 :param incomplete: Value being completed. May be empty.1593 1594 .. versionadded:: 8.01595 """2 unmodified lines1598 results = [1599 CompletionItem(name, help=command.get_short_help_str())1600 for name, command in _complete_visible_commands(ctx, incomplete)1601 ]1600- results.extend(super().shell_complete(ctx, args, incomplete))1602+ results.extend(super().shell_complete(ctx, incomplete))1603 return results1604 1605 1606 class Group(MultiCommand):177 unmodified lines1784 :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 if1786- given. Takes ``ctx, param, args, incomplete`` and returns a list1788+ 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 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.1794+ 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 clear56 unmodified lines1857 DeprecationWarning,1858 stacklevel=2,1859 )1860 1859- def shell_complete(ctx, param, args, incomplete):1861+ def shell_complete(ctx, param, incomplete):1862 from click.shell_completion import CompletionItem1863 1864 out = []1865 1864- for c in autocompletion(ctx, args, incomplete):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)177 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 2065- def shell_complete(self, ctx, args, incomplete):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.2072- :param args: List of complete args before the incomplete value.2078 :param incomplete: Value being completed. May be empty.2079 2080 .. versionadded:: 8.02081 """2082 if self._custom_shell_complete is not None:2078- results = self._custom_shell_complete(ctx, self, args, incomplete)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 2087- return self.type.shell_complete(ctx, self, args, incomplete)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 and409 unmodified linesmodified:src/click/shell_completion.py+2 added-2 removed
242 unmodified lines243 if ctx is None:244 return []245 246 obj, incomplete = _resolve_incomplete(ctx, args, incomplete)247- return obj.shell_complete(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.190 unmodified lines442 443 if _start_of_option(arg):444 last_option = arg445 446- return bool(last_option and last_option in param.opts)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 and86 unmodified linesmodified:src/click/types.py+4 added-8 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, param, args, incomplete):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 args: List of complete args before the incomplete value.119 :param incomplete: Value being completed. May be empty.120 121 .. versionadded:: 8.0122 """140 unmodified lines263 264 def __repr__(self):265 return f"Choice({list(self.choices)})"266 268- def shell_complete(self, ctx, param, args, incomplete):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.273- :param args: List of complete args before the incomplete value.272 :param incomplete: Value being completed. May be empty.273 274 .. versionadded:: 8.0275 """335 unmodified lines611 param,612 ctx,613 )614 617- def shell_complete(self, ctx, param, args, incomplete):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.623- :param args: List of complete args before the incomplete value.621 :param incomplete: Value being completed. May be empty.622 623 .. versionadded:: 8.0624 """131 unmodified lines756 )757 758 return self.coerce_path_result(rv)759 763- def shell_complete(self, ctx, param, args, incomplete):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.770- :param args: List of complete args before the incomplete value.767 :param incomplete: Value being completed. May be empty.768 769 .. versionadded:: 8.0770 """119 unmodified linesmodified:tests/test_shell_completion.py+15 added-3 removed
26 unmodified lines27 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 suggested31- assert _get_words(cli, ["-t", "a"], "-") == ["--test", "--help"]32+ 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,69 unmodified lines124 assert _get_words(cli, ["x", "--on"], "a") == ["a1", "a2"]125 126 127 def test_option_custom():117- def custom(ctx, param, args, incomplete):128+ def custom(ctx, param, incomplete):129 return [incomplete.upper()]130 131 cli = Command(132 "cli",7 unmodified lines140 assert _get_words(cli, ["a", "b"], "c") == ["C"]141 142 143 def test_autocompletion_deprecated():133- # old function takes three params, returns all values, can mix144+ # 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)])126 unmodified linesmodified:CHANGES.rst+5 added-5 removed
97 unmodified lines98 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.102+ 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 -------------635 unmodified lines