Skip to content
Myr

return list of CompletionItem objects

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 00d5dcc · Browse files · 6 files+114 added−58 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+114 added−58 removed

  • tests:+19 added−14 removed
  • other:+95 added−44 removed

6 files+114 added−58 removed

modified:docs/api.rst+2 added
176 unmodified lines
177customizing Click's shell completion system.178179.. currentmodule:: click.shell_completion180181.. autoclass:: CompletionItem182183.. autoclass:: ShellComplete184 :members:185 :member-order: bysource186
13 unmodified lines
modified:docs/shell-completion.rst+10 added-7 removed
119 unmodified lines
120121When creating a custom :class:`~click.ParamType`, override its122:meth:`~click.ParamType.shell_complete` method to provide shell123completion for parameters with the type. The method must return a list124of ``(type, value, help)`` tuples. ``type`` will usually be ``"plain"``125unless you've implemented a custom shell script. Some shells know how to126display a ``help`` string next to each suggestion.124of :class:`~CompletionItem` objects. Besides the value, these objects125hold metadata that shell support might use. The built-in implementations126use ``type`` to indicate special handling for paths, and ``help`` for127shells that support showing a help string next to a suggestion.128129In this example, the type will suggest environment variables that start130with the incomplete value.131
1 unmodified line
133134 class EnvVarType(ParamType):135 def shell_complete(self, ctx, args, incomplete):136 return [136 ("plain", k, None)137 for k in os.environ138 if k.startswith(incomplete)137 CompletionItem(name)138 for name in os.environ if name.startswith(incomplete)139 ]140141 @click.command()142 @click.option("--ev", type=EnvVarType())
6 unmodified lines
149150Value completions for a parameter can be customized without a custom151type by providing an ``autocompletion`` function. The function is used152instead of any completion provided by the type. It is passed 3 keyword153arguments, and returns a list of strings to be shown.153arguments:154155- ``ctx`` - The current command context.156- ``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 a161shortcut it can return a list of strings.162163In this example, the command will suggest environment variables that164start with the incomplete value.165166.. code-block:: python
123 unmodified lines
modified:src/click/core.py+27 added-14 removed
876 unmodified lines
877 :param incomplete: Value being completed. May be empty.878879 .. versionadded:: 8.0880 """881 from click.shell_completion import CompletionItem882883 results = []884885 while ctx.parent is not None:886 ctx = ctx.parent887888 if isinstance(ctx.command, MultiCommand) and ctx.command.chain:889 results.extend(888 ("plain", name, command.get_short_help_str())890 CompletionItem(name, help=command.get_short_help_str())891 for name, command in _complete_visible_commands(ctx, incomplete)892 if name not in ctx.protected_args893 )894
392 unmodified lines
1287 :param incomplete: Value being completed. May be empty.12881289 .. versionadded:: 8.01290 """1291 from click.shell_completion import CompletionItem12921293 results = []12941295 if incomplete and not incomplete[0].isalnum():1296 for param in self.get_params(ctx):1297 if not isinstance(param, Option) or param.hidden:1298 continue12991296 names = (1297 name1300 results.extend(1301 CompletionItem(name, help=param.help)1302 for name in param.opts + param.secondary_opts1299 if name not in args or param.multiple1303 if (1304 (name not in args or param.multiple)1305 and name.startswith(incomplete)1306 )1307 )1301 results.extend(1302 ("plain", name, param.help)1303 for name in names1304 if name.startswith(incomplete)1305 )13081309 results.extend(super().shell_complete(ctx, args, incomplete))1310 return results1311
278 unmodified lines
1590 :param incomplete: Value being completed. May be empty.15911592 .. versionadded:: 8.01593 """1594 from click.shell_completion import CompletionItem15951596 results = [1593 ("plain", name, command.get_short_help_str())1597 CompletionItem(name, help=command.get_short_help_str())1598 for name, command in _complete_visible_commands(ctx, incomplete)1599 ]1600 results.extend(super().shell_complete(ctx, args, incomplete))1601 return results
433 unmodified lines
2035 :param incomplete: Value being completed. May be empty.20362037 .. versionadded:: 8.02038 """2039 from click.shell_completion import CompletionItem20402041 if self.autocompletion is not None:2036 return [2037 ("plain",) + c if isinstance(c, tuple) else ("plain", c, None)2038 for c in self.autocompletion(ctx=ctx, args=args, incomplete=incomplete)2039 ]2042 results = []20432044 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))20512052 return results20532054 return self.type.shell_complete(ctx, args, incomplete)205520562057class Option(Parameter):
410 unmodified lines
modified:src/click/shell_completion.py+39 added-12 removed
36 unmodified lines
3738 return 1394041class 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.4647 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``.5051 :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 """5960 __slots__ = ("value", "type", "help", "_info")6162 def __init__(self, value, type="plain", help=None, **kwargs):63 self.value = value64 self.type = type65 self.help = help66 self._info = kwargs6768 def __getattr__(self, name):69 return self._info.get(name)707172# Only Bash >= 4.4 has the nosort option.73_SOURCE_BASH = """\74%(complete_func)s() {75 local IFS=$'\\n'
231 unmodified lines
307 incomplete = ""308309 return args, incomplete310280 def format_completion(self, item):281 type, value, _ = item282 return f"{type},{value}"311 def format_completion(self, item: CompletionItem):312 return f"{item.type},{item.value}"313314315class ZshComplete(ShellComplete):316 """Shell completion for Zsh."""
12 unmodified lines
329 incomplete = ""330331 return args, incomplete332303 def format_completion(self, item):304 type, value, desc = item305 return f"{type}\n{value}\n{desc if desc else '_'}"333 def format_completion(self, item: CompletionItem):334 return f"{item.type}\n{item.value}\n{item.help if item.help else '_'}"335336337class FishComplete(ShellComplete):338 """Shell completion for Fish."""
12 unmodified lines
351 args.pop()352353 return args, incomplete354326 def format_completion(self, item):327 type, value, desc = item355 def format_completion(self, item: CompletionItem):356 if item.help:357 return f"{item.type},{item.value}\t{item.help}"358329 if desc:330 return f"{type},{value}\t{desc}"359 return f"{item.type},{item.value}"360332 return f"{type},{value}"361334362_available_shells = {363 "bash": BashComplete,364 "fish": FishComplete,365 "zsh": ZshComplete,
171 unmodified lines
modified:src/click/types.py+17 added-11 removed
106 unmodified lines
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):111 """Return a list of completions for the incomplete value. Most112 types do not provide completions, but some do, and this allows113 custom types to provide custom completions as well.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 args: List of complete args before the incomplete value.119 :param incomplete: Value being completed. May be empty.
144 unmodified lines
264 def __repr__(self):265 return f"Choice({list(self.choices)})"266267 def shell_complete(self, ctx, args, incomplete):266 """Return a list of completions for the incomplete value based267 on the choices.268 """Complete choices that start with the incomplete value.269270 :param ctx: Invocation context for this command.271 :param args: List of complete args before the incomplete value.272 :param incomplete: Value being completed. May be empty.273274 .. versionadded:: 8.0275 """275 return [276 ("plain", c, None) for c in self.choices if str(c).startswith(incomplete)277 ]276 from click.shell_completion import CompletionItem277278 str_choices = map(str, self.choices)279 return [CompletionItem(c) for c in str_choices if c.startswith(incomplete)]280281282class DateTime(ParamType):283 """The DateTime type converts date strings into `datetime` objects.284285 The format strings which are checked are configurable, but default to some
335 unmodified lines
621 :param incomplete: Value being completed. May be empty.622623 .. versionadded:: 8.0624 """623 return [("file", incomplete, None)]625 from click.shell_completion import CompletionItem626627 return [CompletionItem(incomplete, type="file")]628629630class 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 various
133 unmodified lines
767 :param incomplete: Value being completed. May be empty.768769 .. versionadded:: 8.0770 """767 completion_type = "dir" if self.dir_okay and not self.file_okay else "file"768 return [(completion_type, incomplete, None)]771 from click.shell_completion import CompletionItem772773 type = "dir" if self.dir_okay and not self.file_okay else "file"774 return [CompletionItem(incomplete, type=type)]775776777class 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 this
109 unmodified lines
modified:tests/test_shell_completion.py+19 added-14 removed
4 unmodified lines
5from click.core import Argument6from click.core import Command7from click.core import Group8from click.core import Option9from click.shell_completion import CompletionItem10from click.shell_completion import ShellComplete11from click.types import Choice12from click.types import File13from click.types import Path
4 unmodified lines
18 return comp.get_completions(args, incomplete)192021def _get_words(cli, args, incomplete):21 return [c[1] for c in _get_completions(cli, args, incomplete)]22 return [c.value for c in _get_completions(cli, args, incomplete)]232425def test_command():26 cli = Command("cli", params=[Option(["-t", "--test"])])
58 unmodified lines
85 assert _get_words(cli, ["-c"], "a") == ["a1", "a2"]86 assert _get_words(cli, ["-c"], "a2") == ["a2"]878888def test_type_file():89 cli = Command("cli", params=[Option(["-f"], type=File())])90 assert _get_completions(cli, ["-f"], "ab") == [("file", "ab", None)]89@pytest.mark.parametrize(90 ("type", "expect"),91 [(File(), "file"), (Path(), "file"), (Path(file_okay=False), "dir")],92)93def test_path_types(type, expect):94 cli = Command("cli", params=[Option(["-f"], type=type)])95 out = _get_completions(cli, ["-f"], "ab")96 assert len(out) == 197 c = out[0]98 assert c.value == "ab"99 assert c.type == expect10010193def test_type_path_file():94 cli = Command("cli", params=[Option(["-p"], type=Path())])95 assert _get_completions(cli, ["-p"], "ab") == [("file", "ab", None)]969798def test_type_path_dir():99 cli = Command("cli", params=[Option(["-d"], type=Path(file_okay=False))])100 assert _get_completions(cli, ["-d"], "ab") == [("dir", "ab", None)]101102102def test_option_flag():103 cli = Command(104 "cli",105 add_help_option=False,
102 unmodified lines
208 assert "renamed" in words209 assert "original" not in words210211212def test_completion_item_data():213 c = CompletionItem("test", a=1)214 assert c.a == 1215 assert c.b is None216217218@pytest.fixture()219def _patch_for_completion(monkeypatch):220 monkeypatch.setattr("click.core._fast_exit", sys.exit)221 monkeypatch.setattr(
31 unmodified lines