Skip to content
Myr

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

7 files+61 added−49 removed

modified:docs/shell-completion.rst+2 added-3 removed
130 unmodified lines
131132.. code-block:: python133134 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 lines
153arguments:154155- ``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.159160It must return a list of :class:`CompletionItem` objects, or as a
3 unmodified lines
164start with the incomplete value.165166.. code-block:: python167169 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)]170171 @click.command()172 @click.argument("name", shell_complete=complete_env_vars)
117 unmodified lines
modified:examples/completion/completion.py+3 added-3 removed
13 unmodified lines
14def ls(dir):15 click.echo("\n".join(os.listdir(dir)))161718def get_env_vars(ctx, param, args, incomplete):18def 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 lines
32def group():33 pass343536def list_users(ctx, args, incomplete):36def 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 lines
44 yield CompletionItem(value, help=help)454647@group.command(help="Choose a user")48@click.argument("user", type=click.STRING, autocompletion=list_users)48@click.argument("user", shell_complete=list_users)49def select_user(user):50 click.echo(f"Chosen user is {user}")5152
1 unmodified line
modified:src/click/core.py+30 added-25 removed
282 unmodified lines
283 #: 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 but
569 unmodified lines
867 implementation is raising a not implemented error.868 """869 raise NotImplementedError("Base commands are not invokable by default")870867 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.874875 Any command could be part of a chained multi-command, so sibling876 commands are valid at any point during command completion. Other877 command classes will return more completions.878879 :param ctx: Invocation context for this command.876 :param args: List of complete args before the incomplete value.880 :param incomplete: Value being completed. May be empty.881882 .. versionadded:: 8.0883 """
396 unmodified lines
1280 _maybe_show_deprecated_notice(self)1281 if self.callback is not None:1282 return ctx.invoke(self.callback, **ctx.params)12831281 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.12871288 :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.12901291 .. versionadded:: 8.01292 """
2 unmodified lines
1295 results = []12961297 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 continue13051306 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 )13111309 results.extend(super().shell_complete(ctx, args, incomplete))1312 results.extend(super().shell_complete(ctx, incomplete))1313 return results131413151316class MultiCommand(Command):
265 unmodified lines
1582 appear.1583 """1584 return []15851583 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.15901591 :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.15931594 .. versionadded:: 8.01595 """
2 unmodified lines
1598 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 results160416051606class Group(MultiCommand):
177 unmodified lines
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 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.17911792 .. 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.17971798 .. versionchanged:: 7.11799 Empty environment variables are ignored rather than taking the1800 empty string value. This makes it possible for scripts to clear
56 unmodified lines
1857 DeprecationWarning,1858 stacklevel=2,1859 )18601859 def shell_complete(ctx, param, args, incomplete):1861 def shell_complete(ctx, param, incomplete):1862 from click.shell_completion import CompletionItem18631864 out = []18651864 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 lines
2048 raise20492050 if self.expose_value:2051 ctx.params[self.name] = value20522053 if value is not None:2054 ctx._seen_params.add(self)20552056 return value, args20572058 def get_help_record(self, ctx):2059 pass
7 unmodified lines
2067 """2068 hint_list = self.opts or [self.human_readable_name]2069 return " / ".join(repr(x) for x in hint_list)20702065 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.20762077 :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.20792080 .. 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)20842085 if results and isinstance(results[0], str):2086 from click.shell_completion import CompletionItem20872088 results = [CompletionItem(c) for c in results]20892090 return results20912087 return self.type.shell_complete(ctx, self, args, incomplete)2092 return self.type.shell_complete(ctx, self, incomplete)209320942095class Option(Parameter):2096 """Options are usually optional values on the command line and
409 unmodified lines
modified:src/click/shell_completion.py+2 added-2 removed
242 unmodified lines
243 if ctx is None:244 return []245246 obj, incomplete = _resolve_incomplete(ctx, args, incomplete)247 return obj.shell_complete(ctx, args, incomplete)247 return obj.shell_complete(ctx, incomplete)248249 def format_completion(self, item):250 """Format a completion item into the form recognized by the251 shell script. This must be implemented by subclasses.
190 unmodified lines
442443 if _start_of_option(arg):444 last_option = arg445446 return bool(last_option and last_option in param.opts)446 return last_option is not None and last_option in param.opts447448449def _resolve_context(cli, prog_name, args):450 """Produce the context hierarchy starting with the command and
86 unmodified lines
modified:src/click/types.py+4 added-8 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, 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.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.119 :param incomplete: Value being completed. May be empty.120121 .. versionadded:: 8.0122 """
140 unmodified lines
263264 def __repr__(self):265 return f"Choice({list(self.choices)})"266268 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.269270 :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.273274 .. versionadded:: 8.0275 """
335 unmodified lines
611 param,612 ctx,613 )614617 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.618619 :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.622623 .. versionadded:: 8.0624 """
131 unmodified lines
756 )757758 return self.coerce_path_result(rv)759763 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.764765 :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.768769 .. versionadded:: 8.0770 """
119 unmodified lines
modified:tests/test_shell_completion.py+15 added-3 removed
26 unmodified lines
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 suggested31 assert _get_words(cli, ["-t", "a"], "-") == ["--test", "--help"]32 assert _get_words(cli, ["-t", "a"], "-") == ["--help"]333435def test_group():36 cli = Group("cli", params=[Option(["-a"])], commands=[Command("x"), Command("y")])37 assert _get_words(cli, [], "") == ["x", "y"]38 assert _get_words(cli, [], "-") == ["-a", "--help"]394041def test_group_command_same_option():42 cli = Group(43 "cli", params=[Option(["-a"])], commands=[Command("x", params=[Option(["-a"])])]44 )45 assert _get_words(cli, [], "-") == ["-a", "--help"]46 assert _get_words(cli, ["-a", "a"], "-") == ["--help"]47 assert _get_words(cli, ["-a", "a", "x"], "-") == ["-a", "--help"]48 assert _get_words(cli, ["-a", "a", "x", "-a", "a"], "-") == ["--help"]495051def test_chained():52 cli = Group(53 "cli",54 chain=True,
69 unmodified lines
124 assert _get_words(cli, ["x", "--on"], "a") == ["a1", "a2"]125126127def test_option_custom():117 def custom(ctx, param, args, incomplete):128 def custom(ctx, param, incomplete):129 return [incomplete.upper()]130131 cli = Command(132 "cli",
7 unmodified lines
140 assert _get_words(cli, ["a", "b"], "c") == ["C"]141142143def 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"]149150 with pytest.deprecated_call():151 cli = Command("cli", params=[Argument(["x"], autocompletion=custom)])
126 unmodified lines
modified:CHANGES.rst+5 added-5 removed
97 unmodified lines
98 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.107108109Version 7.1.2110-------------
635 unmodified lines