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
Provenance
- Commit
cb5c21e- Tree
6acb930- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
00d5dcc
6 files changed+114 added−58 removed
modified:docs/api.rst+2 added
176 unmodified lines177 customizing Click's shell completion system.178 179 .. currentmodule:: click.shell_completion180 181+.. autoclass:: CompletionItem182+183 .. autoclass:: ShellComplete184 :members:185 :member-order: bysource186 13 unmodified linesmodified:docs/shell-completion.rst+10 added-7 removed
119 unmodified lines120 121 When creating a custom :class:`~click.ParamType`, override its122 :meth:`~click.ParamType.shell_complete` method to provide shell123 completion for parameters with the type. The method must return a list124-of ``(type, value, help)`` tuples. ``type`` will usually be ``"plain"``125-unless you've implemented a custom shell script. Some shells know how to126-display a ``help`` string next to each suggestion.124+of :class:`~CompletionItem` objects. Besides the value, these objects125+hold metadata that shell support might use. The built-in implementations126+use ``type`` to indicate special handling for paths, and ``help`` for127+shells that support showing a help string next to a suggestion.128 129 In this example, the type will suggest environment variables that start130 with the incomplete value.131 1 unmodified line133 134 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 ]140 141 @click.command()142 @click.option("--ev", type=EnvVarType())6 unmodified lines149 150 Value completions for a parameter can be customized without a custom151 type by providing an ``autocompletion`` function. The function is used152 instead of any completion provided by the type. It is passed 3 keyword153-arguments, and returns a list of strings to be shown.153+arguments:154 155 - ``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.159 160+It must return a list of :class:`CompletionItem` objects, or as a161+shortcut it can return a list of strings.162+163 In this example, the command will suggest environment variables that164 start with the incomplete value.165 166 .. code-block:: python123 unmodified linesmodified:src/click/core.py+27 added-14 removed
876 unmodified lines877 :param incomplete: Value being completed. May be empty.878 879 .. versionadded:: 8.0880 """881+ from click.shell_completion import CompletionItem882+883 results = []884 885 while ctx.parent is not None:886 ctx = ctx.parent887 888 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 lines1287 :param incomplete: Value being completed. May be empty.1288 1289 .. versionadded:: 8.01290 """1291+ from click.shell_completion import CompletionItem1292+1293 results = []1294 1295 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 continue1299 1296- 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- )1308 1309 results.extend(super().shell_complete(ctx, args, incomplete))1310 return results1311 278 unmodified lines1590 :param incomplete: Value being completed. May be empty.1591 1592 .. versionadded:: 8.01593 """1594+ from click.shell_completion import CompletionItem1595+1596 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 results433 unmodified lines2035 :param incomplete: Value being completed. May be empty.2036 2037 .. versionadded:: 8.02038 """2039+ from click.shell_completion import CompletionItem2040+2041 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 = []2043 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))2051+2052+ return results2053+2054 return self.type.shell_complete(ctx, args, incomplete)2055 2056 2057 class Option(Parameter):410 unmodified linesmodified:src/click/shell_completion.py+39 added-12 removed
36 unmodified lines37 38 return 139 40 41+class 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.46+47+ 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``.50+51+ :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+ """59+60+ __slots__ = ("value", "type", "help", "_info")61+62+ def __init__(self, value, type="plain", help=None, **kwargs):63+ self.value = value64+ self.type = type65+ self.help = help66+ self._info = kwargs67+68+ def __getattr__(self, name):69+ return self._info.get(name)70+71+72 # Only Bash >= 4.4 has the nosort option.73 _SOURCE_BASH = """\74 %(complete_func)s() {75 local IFS=$'\\n'231 unmodified lines307 incomplete = ""308 309 return args, incomplete310 280- 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}"313 314 315 class ZshComplete(ShellComplete):316 """Shell completion for Zsh."""12 unmodified lines329 incomplete = ""330 331 return args, incomplete332 303- 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 '_'}"335 336 337 class FishComplete(ShellComplete):338 """Shell completion for Fish."""12 unmodified lines351 args.pop()352 353 return args, incomplete354 326- 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}"358 329- if desc:330- return f"{type},{value}\t{desc}"359+ return f"{item.type},{item.value}"360 332- return f"{type},{value}"361 334-362 _available_shells = {363 "bash": BashComplete,364 "fish": FishComplete,365 "zsh": ZshComplete,171 unmodified linesmodified:src/click/types.py+17 added-11 removed
106 unmodified lines107 """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):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.116 117 :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 lines264 def __repr__(self):265 return f"Choice({list(self.choices)})"266 267 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.269 270 :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.273 274 .. 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 CompletionItem277 278+ str_choices = map(str, self.choices)279+ return [CompletionItem(c) for c in str_choices if c.startswith(incomplete)]280 281+282 class DateTime(ParamType):283 """The DateTime type converts date strings into `datetime` objects.284 285 The format strings which are checked are configurable, but default to some335 unmodified lines621 :param incomplete: Value being completed. May be empty.622 623 .. versionadded:: 8.0624 """623- return [("file", incomplete, None)]625+ from click.shell_completion import CompletionItem626 627+ return [CompletionItem(incomplete, type="file")]628 629+630 class 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 various133 unmodified lines767 :param incomplete: Value being completed. May be empty.768 769 .. 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 CompletionItem772 773+ type = "dir" if self.dir_okay and not self.file_okay else "file"774+ return [CompletionItem(incomplete, type=type)]775 776+777 class 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 this109 unmodified linesmodified:tests/test_shell_completion.py+19 added-14 removed
4 unmodified lines5 from click.core import Argument6 from click.core import Command7 from click.core import Group8 from click.core import Option9+from click.shell_completion import CompletionItem10 from click.shell_completion import ShellComplete11 from click.types import Choice12 from click.types import File13 from click.types import Path4 unmodified lines18 return comp.get_completions(args, incomplete)19 20 21 def _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)]23 24 25 def test_command():26 cli = Command("cli", params=[Option(["-t", "--test"])])58 unmodified lines85 assert _get_words(cli, ["-c"], "a") == ["a1", "a2"]86 assert _get_words(cli, ["-c"], "a2") == ["a2"]87 88 88-def 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+)93+def 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 == expect100 101 93-def test_type_path_file():94- cli = Command("cli", params=[Option(["-p"], type=Path())])95- assert _get_completions(cli, ["-p"], "ab") == [("file", "ab", None)]96-97-98-def 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)]101-102-102 def test_option_flag():103 cli = Command(104 "cli",105 add_help_option=False,102 unmodified lines208 assert "renamed" in words209 assert "original" not in words210 211 212+def test_completion_item_data():213+ c = CompletionItem("test", a=1)214+ assert c.a == 1215+ assert c.b is None216+217+218 @pytest.fixture()219 def _patch_for_completion(monkeypatch):220 monkeypatch.setattr("click.core._fast_exit", sys.exit)221 monkeypatch.setattr(31 unmodified lines