Merge pull request #2041 from spanglerco/shell-completion-option-values
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Make shell completion prioritize option values over new options
authored by David Lord · committed by GitHub · parents d251cb0, f2e579a · Browse files · 7 files·+134 added−9 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+134 added−9 removed
- tests:+121 added−0 removed
- other:+13 added−9 removed
Provenance
- Commit
ef11be6- Tree
69c832d- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
d251cb0- Parent 2
f2e579a
7 files changed+134 added−9 removed
modified:src/click/core.py+3 added
290 unmodified lines291 #: to `args` when certain parsing scenarios are encountered but292 #: must be never propagated to another arguments. This is used293 #: to implement nested parsing.294 self.protected_args: t.List[str] = []295+ #: the collected prefixes of the command's options.296+ self._opt_prefixes: t.Set[str] = set(parent._opt_prefixes) if parent else set()297 298 if obj is None and parent is not None:299 obj = parent.obj300 1085 unmodified lines1386 ).format(args=" ".join(map(str, args)))1387 )1388 1389 ctx.args = args1390+ ctx._opt_prefixes.update(parser._opt_prefixes)1391 return args1392 1393 def invoke(self, ctx: Context) -> t.Any:1394 """Given a context, this invokes the attached callback (if it exists)1572 unmodified linesmodified:src/click/shell_completion.py+8 added-9 removed
446 unmodified lines447 )448 )449 450 451-def _start_of_option(value: str) -> bool:451+def _start_of_option(ctx: Context, value: str) -> bool:452 """Check if the value looks like the start of an option."""453 if not value:454 return False455 456 c = value[0]457- # Allow "/" since that starts a path.458- return not c.isalnum() and c != "/"457+ return c in ctx._opt_prefixes458 459 461-def _is_incomplete_option(args: t.List[str], param: Parameter) -> bool:460+def _is_incomplete_option(ctx: Context, args: t.List[str], param: Parameter) -> bool:461 """Determine if the given parameter is an option that needs a value.462 463 :param args: List of complete args before the incomplete value.464 :param param: Option object being checked.465 """466 if not isinstance(param, Option):467 return False468 470- if param.is_flag:469+ if param.is_flag or param.count:470 return False471 472 last_option = None473 474 for index, arg in enumerate(reversed(args)):475 if index + 1 > param.nargs:476 break477 479- if _start_of_option(arg):478+ if _start_of_option(ctx, arg):479 last_option = arg480 481 return last_option is not None and last_option in param.opts482 66 unmodified lines549 # as a separate item, or return the split name and value. Always550 # split and discard the "=" to make completion easier.551 if incomplete == "=":552 incomplete = ""554- elif "=" in incomplete and _start_of_option(incomplete):553+ elif "=" in incomplete and _start_of_option(ctx, incomplete):554 name, _, incomplete = incomplete.partition("=")555 args.append(name)556 557 # The "--" marker tells Click to stop treating values as options558 # even if they start with the option character. If it hasn't been559 # given and the incomplete arg looks like an option, the current560 # command will provide option name completions.562- if "--" not in args and _start_of_option(incomplete):561+ if "--" not in args and _start_of_option(ctx, incomplete):562 return ctx.command, incomplete563 564 params = ctx.command.get_params(ctx)565 566 # If the last complete arg is an option name with an incomplete567 # value, the option will provide value completions.568 for param in params:570- if _is_incomplete_option(args, param):569+ if _is_incomplete_option(ctx, args, param):570 return param, incomplete571 572 # It's not an option name or value. The first argument without a573 # parsed value will provide value completions.7 unmodified linesmodified:tests/test_commands.py+59 added
350 unmodified lines351 pass352 353 result = runner.invoke(deprecated_cmd)354 assert "DeprecationWarning:" in result.output355+356+357+def test_command_parse_args_collects_option_prefixes():358+ @click.command()359+ @click.option("+p", is_flag=True)360+ @click.option("!e", is_flag=True)361+ def test(p, e):362+ pass363+364+ ctx = click.Context(test)365+ test.parse_args(ctx, [])366+367+ assert ctx._opt_prefixes == {"-", "--", "+", "!"}368+369+370+def test_group_parse_args_collects_base_option_prefixes():371+ @click.group()372+ @click.option("~t", is_flag=True)373+ def group(t):374+ pass375+376+ @group.command()377+ @click.option("+p", is_flag=True)378+ def command1(p):379+ pass380+381+ @group.command()382+ @click.option("!e", is_flag=True)383+ def command2(e):384+ pass385+386+ ctx = click.Context(group)387+ group.parse_args(ctx, ["command1", "+p"])388+389+ assert ctx._opt_prefixes == {"-", "--", "~"}390+391+392+def test_group_invoke_collects_used_option_prefixes(runner):393+ opt_prefixes = set()394+395+ @click.group()396+ @click.option("~t", is_flag=True)397+ def group(t):398+ pass399+400+ @group.command()401+ @click.option("+p", is_flag=True)402+ @click.pass_context403+ def command1(ctx, p):404+ nonlocal opt_prefixes405+ opt_prefixes = ctx._opt_prefixes406+407+ @group.command()408+ @click.option("!e", is_flag=True)409+ def command2(e):410+ pass411+412+ runner.invoke(group, ["command1"])413+ assert opt_prefixes == {"-", "--", "~", "+"}modified:tests/test_context.py+8 added
363 unmodified lines364 return ctx.get_parameter_source("option")365 366 rv = runner.invoke(cli, standalone_mode=False, **invoke_args)367 assert rv.return_value == expect368+369+370+def test_propagate_opt_prefixes():371+ parent = click.Context(click.Command("test"))372+ parent._opt_prefixes = {"-", "--", "!"}373+ ctx = click.Context(click.Command("test2"), parent=parent)374+375+ assert ctx._opt_prefixes == {"-", "--", "!"}modified:tests/test_parser.py+15 added
1 import pytest2 3+import click4+from click.parser import OptionParser5 from click.parser import split_arg_string6 7 8 @pytest.mark.parametrize(7 unmodified lines16 ],17 )18 def test_split_arg_string(value, expect):19 assert split_arg_string(value) == expect20+21+22+def test_parser_default_prefixes():23+ parser = OptionParser()24+ assert parser._opt_prefixes == {"-", "--"}25+26+27+def test_parser_collects_prefixes():28+ ctx = click.Context(click.Command("test"))29+ parser = OptionParser(ctx)30+ click.Option("+p", is_flag=True).add_to_parser(parser, ctx)31+ click.Option("!e", is_flag=True).add_to_parser(parser, ctx)32+ assert parser._opt_prefixes == {"-", "--", "+", "!"}modified:tests/test_shell_completion.py+39 added
108 unmodified lines109 assert _get_words(cli, ["-c"], "a") == ["a1", "a2"]110 assert _get_words(cli, ["-c"], "a2") == ["a2"]111 112 113+def test_choice_special_characters():114+ cli = Command("cli", params=[Option(["-c"], type=Choice(["!1", "!2", "+3"]))])115+ assert _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"]116+ assert _get_words(cli, ["-c"], "!") == ["!1", "!2"]117+ assert _get_words(cli, ["-c"], "!2") == ["!2"]118+119+120+def test_choice_conflicting_prefix():121+ cli = Command(122+ "cli",123+ params=[124+ Option(["-c"], type=Choice(["!1", "!2", "+3"])),125+ Option(["+p"], is_flag=True),126+ ],127+ )128+ assert _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"]129+ assert _get_words(cli, ["-c"], "+") == ["+p"]130+131+132+def test_option_count():133+ cli = Command("cli", params=[Option(["-c"], count=True)])134+ assert _get_words(cli, ["-c"], "") == []135+ assert _get_words(cli, ["-c"], "-") == ["--help"]136+137+138+def test_option_optional():139+ cli = Command(140+ "cli",141+ add_help_option=False,142+ params=[143+ Option(["--name"], is_flag=False, flag_value="value"),144+ Option(["--flag"], is_flag=True),145+ ],146+ )147+ assert _get_words(cli, ["--name"], "") == []148+ assert _get_words(cli, ["--name"], "-") == ["--flag"]149+ assert _get_words(cli, ["--name", "--flag"], "-") == []150+151+152 @pytest.mark.parametrize(153 ("type", "expect"),154 [(File(), "file"), (Path(), "file"), (Path(file_okay=False), "dir")],155 )189 unmodified linesmodified:CHANGES.rst+2 added
48 unmodified lines49 will invoke its result callback with the group function's return50 value. :issue:`2124`51 - ``to_info_dict`` will not fail if a ``ParamType`` doesn't define a52 ``name``. :issue:`2168`53+- Shell completion prioritizes option values with option prefixes over54+ new options. :issue:`2040`55 56 57 Version 8.0.458 -------------948 unmodified lines