Skip to content
Myr

shell completion prioritizes option values over new options

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

Allow option values that start with an option prefix to complete rather than treating them like new options. Don't treat count options as needing a value to complete.

authored by Paul Spangler · committed by David Lord · parent d251cb0 · 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

7 files+134 added−9 removed

modified:src/click/core.py+3 added
290 unmodified lines
291 #: 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()297298 if obj is None and parent is not None:299 obj = parent.obj300
1085 unmodified lines
1386 ).format(args=" ".join(map(str, args)))1387 )13881389 ctx.args = args1390 ctx._opt_prefixes.update(parser._opt_prefixes)1391 return args13921393 def invoke(self, ctx: Context) -> t.Any:1394 """Given a context, this invokes the attached callback (if it exists)
1572 unmodified lines
modified:src/click/shell_completion.py+8 added-9 removed
446 unmodified lines
447 )448 )449450451def _start_of_option(value: str) -> bool:451def _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 False455456 c = value[0]457 # Allow "/" since that starts a path.458 return not c.isalnum() and c != "/"457 return c in ctx._opt_prefixes458459461def _is_incomplete_option(args: t.List[str], param: Parameter) -> bool:460def _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.462463 :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 False468470 if param.is_flag:469 if param.is_flag or param.count:470 return False471472 last_option = None473474 for index, arg in enumerate(reversed(args)):475 if index + 1 > param.nargs:476 break477479 if _start_of_option(arg):478 if _start_of_option(ctx, arg):479 last_option = arg480481 return last_option is not None and last_option in param.opts482
66 unmodified lines
549 # 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)556557 # 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, incomplete563564 params = ctx.command.get_params(ctx)565566 # 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, incomplete571572 # It's not an option name or value. The first argument without a573 # parsed value will provide value completions.
7 unmodified lines
modified:tests/test_commands.py+59 added
350 unmodified lines
351 pass352353 result = runner.invoke(deprecated_cmd)354 assert "DeprecationWarning:" in result.output355356357def 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 pass363364 ctx = click.Context(test)365 test.parse_args(ctx, [])366367 assert ctx._opt_prefixes == {"-", "--", "+", "!"}368369370def test_group_parse_args_collects_base_option_prefixes():371 @click.group()372 @click.option("~t", is_flag=True)373 def group(t):374 pass375376 @group.command()377 @click.option("+p", is_flag=True)378 def command1(p):379 pass380381 @group.command()382 @click.option("!e", is_flag=True)383 def command2(e):384 pass385386 ctx = click.Context(group)387 group.parse_args(ctx, ["command1", "+p"])388389 assert ctx._opt_prefixes == {"-", "--", "~"}390391392def test_group_invoke_collects_used_option_prefixes(runner):393 opt_prefixes = set()394395 @click.group()396 @click.option("~t", is_flag=True)397 def group(t):398 pass399400 @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_prefixes406407 @group.command()408 @click.option("!e", is_flag=True)409 def command2(e):410 pass411412 runner.invoke(group, ["command1"])413 assert opt_prefixes == {"-", "--", "~", "+"}
modified:tests/test_context.py+8 added
363 unmodified lines
364 return ctx.get_parameter_source("option")365366 rv = runner.invoke(cli, standalone_mode=False, **invoke_args)367 assert rv.return_value == expect368369370def test_propagate_opt_prefixes():371 parent = click.Context(click.Command("test"))372 parent._opt_prefixes = {"-", "--", "!"}373 ctx = click.Context(click.Command("test2"), parent=parent)374375 assert ctx._opt_prefixes == {"-", "--", "!"}
modified:tests/test_parser.py+15 added
1import pytest23import click4from click.parser import OptionParser5from click.parser import split_arg_string678@pytest.mark.parametrize(
7 unmodified lines
16 ],17)18def test_split_arg_string(value, expect):19 assert split_arg_string(value) == expect202122def test_parser_default_prefixes():23 parser = OptionParser()24 assert parser._opt_prefixes == {"-", "--"}252627def 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 lines
109 assert _get_words(cli, ["-c"], "a") == ["a1", "a2"]110 assert _get_words(cli, ["-c"], "a2") == ["a2"]111112113def 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"]118119120def 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"]130131132def 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"]136137138def 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"], "-") == []150151152@pytest.mark.parametrize(153 ("type", "expect"),154 [(File(), "file"), (Path(), "file"), (Path(file_okay=False), "dir")],155)
189 unmodified lines
modified:CHANGES.rst+2 added
48 unmodified lines
49 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`555657Version 8.0.458-------------
948 unmodified lines