Skip to content
Myr

Merge pull request #806 from stopthatcow/feature/790

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

Fix overzealous completion when required options/arguments are being completed

authored by Markus Unterwaditzer · committed by GitHub · parents 752ff79, aae0ae2 · Browse files · 4 files+99 added−53 removed
This commit

State

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

Diff stats

4 files+99 added−53 removed

  • tests:+25 added−8 removed
  • other:+74 added−45 removed

4 files+99 added−53 removed

modified:click/_bashcomplete.py+56 added-42 removed
43 unmodified lines
44 """45 ctx = cli.make_context(prog_name, args, resilient_parsing=True)46 args_remaining = ctx.protected_args + ctx.args47 while ctx is not None and args_remaining:48 if isinstance(ctx.command, MultiCommand):49 cmd = ctx.command.get_command(ctx, args_remaining[0])50 if cmd is None:51 return None52 ctx = cmd.make_context(args_remaining[0], args_remaining[1:], parent=ctx, resilient_parsing=True)53 args_remaining = ctx.protected_args + ctx.args54 else:55 ctx = ctx.parent48 if isinstance(ctx.command, MultiCommand):49 cmd = ctx.command.get_command(ctx, args_remaining[0])50 if cmd is None:51 return None52 ctx = cmd.make_context(53 args_remaining[0], args_remaining[1:], parent=ctx, resilient_parsing=True)54 args_remaining = ctx.protected_args + ctx.args55 else:56 ctx = ctx.parent5758 return ctx596061def start_of_option(param_str):62 """63 :param param_str: param_str to check64 :return: whether or not this is the start of an option declaration (i.e. starts "-" or "--")
8 unmodified lines
73 :return: whether or not the last option declaration (i.e. starts "-" or "--") is incomplete and74 corresponds to this cmd_param. In other words whether this cmd_param option can still accept75 values76 """77 if not isinstance(cmd_param, Option):78 return False79 if cmd_param.is_flag:80 return False81 last_option = None82 for index, arg_str in enumerate(reversed([arg for arg in all_args if arg != WORDBREAK])):
11 unmodified lines
94 :param cmd_param: the current command parameter95 :return: whether or not the last argument is incomplete and corresponds to this cmd_param. In96 other words whether or not the this cmd_param argument can still accept values97 """98 if not isinstance(cmd_param, Argument):99 return False100 current_param_values = current_params[cmd_param.name]101 if current_param_values is None:102 return True103 if cmd_param.nargs == -1:
2 unmodified lines
106 and cmd_param.nargs > 1 and len(current_param_values) < cmd_param.nargs:107 return True108 return False109110111def get_user_autocompletions(ctx, args, incomplete, cmd_param):112 """113 :param ctx: context associated with the parsed command114 :param args: full list of args
1 unmodified line
116 :param cmd_param: command definition117 :return: all the possible user-specified completions for the param118 """119 if isinstance(cmd_param.type, Choice):113 return cmd_param.type.choices120 return [c for c in cmd_param.type.choices if c.startswith(incomplete)]121 elif cmd_param.autocompletion is not None:122 return cmd_param.autocompletion(ctx=ctx,123 args=args,124 incomplete=incomplete)125 else:126 return []127128129def add_subcommand_completions(ctx, incomplete, completions_out):130 # Add subcommand completions.131 if isinstance(ctx.command, MultiCommand):132 completions_out.extend(133 [c for c in ctx.command.list_commands(ctx) if c.startswith(incomplete)])134135 # Walk up the context list and add any other completion possibilities from chained commands136 while ctx.parent is not None:137 ctx = ctx.parent138 if isinstance(ctx.command, MultiCommand) and ctx.command.chain:139 remaining_commands = sorted(140 set(ctx.command.list_commands(ctx)) - set(ctx.protected_args))141 completions_out.extend(142 [c for c in remaining_commands if c.startswith(incomplete)])143144145def get_choices(cli, prog_name, args, incomplete):146 """147 :param cli: command definition148 :param prog_name: the program that is running
4 unmodified lines
153 all_args = copy.deepcopy(args)154155 ctx = resolve_ctx(cli, prog_name, args)156 if ctx is None:133 return157 return []158159 # In newer versions of bash long opts with '='s are partitioned, but it's easier to parse160 # without the '='161 if start_of_option(incomplete) and WORDBREAK in incomplete:
2 unmodified lines
164 incomplete = partition_incomplete[2]165 elif incomplete == WORDBREAK:166 incomplete = ''167144 choices = []145 found_param = False168 completions = []169 if start_of_option(incomplete):147 # completions for options170 # completions for partial options171 for param in ctx.command.params:172 if isinstance(param, Option):150 choices.extend([param_opt for param_opt in param.opts + param.secondary_opts151 if param_opt not in all_args or param.multiple])152 found_param = True153 if not found_param:154 # completion for option values by choices155 for cmd_param in ctx.command.params:156 if isinstance(cmd_param, Option) and is_incomplete_option(all_args, cmd_param):157 choices.extend(get_user_autocompletions(ctx, all_args, incomplete, cmd_param))158 found_param = True159 break160 if not found_param:161 # completion for argument values by choices162 for cmd_param in ctx.command.params:163 if isinstance(cmd_param, Argument) and is_incomplete_argument(ctx.params, cmd_param):164 choices.extend(get_user_autocompletions(ctx, all_args, incomplete, cmd_param))165 found_param = True166 break173 param_opts = [param_opt for param_opt in param.opts +174 param.secondary_opts if param_opt not in all_args or param.multiple]175 completions.extend(176 [c for c in param_opts if c.startswith(incomplete)])177 return completions178 # completion for option values from user supplied values179 for param in ctx.command.params:180 if is_incomplete_option(all_args, param):181 return get_user_autocompletions(ctx, all_args, incomplete, param)182 # completion for argument values from user supplied values183 for param in ctx.command.params:184 if is_incomplete_argument(ctx.params, param):185 completions.extend(get_user_autocompletions(186 ctx, all_args, incomplete, param))187 # Stop looking for other completions only if this argument is required.188 if param.required:189 return completions190 break191168 if not found_param and isinstance(ctx.command, MultiCommand):169 # completion for any subcommands170 choices.extend(ctx.command.list_commands(ctx))192 add_subcommand_completions(ctx, incomplete, completions)193 return completions194172 if not start_of_option(incomplete) and ctx.parent is not None and isinstance(ctx.parent.command, MultiCommand) and ctx.parent.command.chain:173 # completion for chained commands174 remaining_comands = set(ctx.parent.command.list_commands(ctx.parent))-set(ctx.parent.protected_args)175 choices.extend(remaining_comands)195177 for item in choices:178 if item.startswith(incomplete):179 yield item180181196def do_complete(cli, prog_name):197 cwords = split_arg_string(os.environ['COMP_WORDS'])198 cword = int(os.environ['COMP_CWORD'])199 args = cwords[1:cword]
18 unmodified lines
modified:examples/bashcompletion/bashcompletion.py+12 added-2 removed
1import click2import os345@click.group()6def cli():7 pass8910def get_env_vars(ctx, args, incomplete):9 return os.environ.keys()11 for key in os.environ.keys():12 if incomplete in key:13 yield key141516@cli.command()17@click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)18def cmd1(envvar):19 click.echo('Environment variable: %s' % envvar)20 click.echo('Value: %s' % os.environ[envvar])212223@click.group()24def group():25 pass262728def list_users(ctx, args, incomplete):29 # Here you can generate completions dynamically30 users = ['bob', 'alice']24 return users31 for user in users:32 if user.startswith(incomplete):33 yield user343536@group.command()37@click.argument("user", type=click.STRING, autocompletion=list_users)38def subcmd(user):39 click.echo('Chosen user is %s' % user)
2 unmodified lines
modified:tests/test_bashcomplete.py+25 added-8 removed
84 unmodified lines
8586 COLORS = ['red', 'green', 'blue']87 def get_colors(ctx, args, incomplete):88 for c in COLORS:89 if c.startswith(incomplete):89 yield c90 yield c9192 def search_colors(ctx, args, incomplete):93 for c in COLORS:94 if incomplete in c:95 yield c9697 CSUB_OPT_CHOICES = ['foo', 'bar']98 CSUB_CHOICES = ['bar', 'baz']99 @bsub.command('csub')100 @click.option('--csub-opt', type=click.Choice(CSUB_OPT_CHOICES))101 @click.option('--csub', type=click.Choice(CSUB_CHOICES))102 @click.option('--search-color', autocompletion=search_colors)103 @click.argument('color', autocompletion=get_colors)104 def csub(csub_opt, color):105 pass106
2 unmodified lines
109 assert list(get_choices(cli, 'lol', ['asub'], '-')) == ['--asub-opt']110 assert list(get_choices(cli, 'lol', ['asub'], '')) == ['bsub']111 assert list(get_choices(cli, 'lol', ['asub', 'bsub'], '-')) == ['--bsub-opt']112 assert list(get_choices(cli, 'lol', ['asub', 'bsub'], '')) == ['csub']106 assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], '-')) == ['--csub-opt', '--csub']113 assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], '-')) == ['--csub-opt', '--csub', '--search-color']114 assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub', '--csub-opt'], '')) == CSUB_OPT_CHOICES115 assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], '--csub')) == ['--csub-opt', '--csub']116 assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub', '--csub'], '')) == CSUB_CHOICES117 assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub', '--csub-opt'], 'f')) == ['foo']118 assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], '')) == COLORS119 assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], 'b')) == ['blue']120 assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub', '--search-color'], 'een')) == ['green']121122123def test_chaining():124 @click.group('cli', chain=True)
7 unmodified lines
132 pass133134 @cli.command('bsub')135 @click.option('--bsub-opt')128 @click.argument('arg', type=click.Choice(['arg1', 'arg2']))136 @click.argument('arg', type=click.Choice(['arg1', 'arg2']), required=True)137 def bsub(bsub_opt, arg):138 pass139140 @cli.command('csub')141 @click.option('--csub-opt')142 @click.argument('arg', type=click.Choice(['carg1', 'carg2']), required=False)143 def csub(csub_opt, arg):144 pass145146 assert list(get_choices(cli, 'lol', [], '-')) == ['--cli-opt']133 assert list(get_choices(cli, 'lol', [], '')) == ['asub', 'bsub']147 assert list(get_choices(cli, 'lol', [], '')) == ['asub', 'bsub', 'csub']148 assert list(get_choices(cli, 'lol', ['asub'], '-')) == ['--asub-opt']135 assert list(get_choices(cli, 'lol', ['asub'], '')) == ['bsub']136 assert list(get_choices(cli, 'lol', ['bsub'], '')) == ['arg1', 'arg2', 'asub']149 assert list(get_choices(cli, 'lol', ['asub'], '')) == ['bsub', 'csub']150 assert list(get_choices(cli, 'lol', ['bsub'], '')) == ['arg1', 'arg2']151 assert list(get_choices(cli, 'lol', ['asub', '--asub-opt'], '')) == []152 assert list(get_choices(cli, 'lol', ['asub', '--asub-opt', '5', 'bsub'], '-')) == ['--bsub-opt']153 assert list(get_choices(cli, 'lol', ['asub', 'bsub'], '-')) == ['--bsub-opt']154 assert list(get_choices(cli, 'lol', ['asub', 'csub'], '')) == ['carg1', 'carg2', 'bsub']155 assert list(get_choices(cli, 'lol', ['asub', 'csub'], '-')) == ['--csub-opt']156157158def test_argument_choice():159 @click.command()
111 unmodified lines
271 @click.argument('bbsub-arg2', required=False, type=click.Choice(['bbsubarg1', 'bbsubarg2']))272 def bsub(bsub_opt):273 pass274258 assert list(get_choices(cli, 'lol', ['sub'], '')) == ['subarg1', 'subarg2']275 assert list(get_choices(cli, 'lol', ['sub'], '')) == ['subarg1', 'subarg2', 'bsub']276 assert list(get_choices(cli, 'lol', ['sub', '--sub-opt'], '')) == ['subopt1', 'subopt2']277 assert list(get_choices(cli, 'lol', ['sub', '--sub-opt', 'subopt1'], '')) == \261 ['subarg1', 'subarg2']278 ['subarg1', 'subarg2', 'bsub']279 assert list(get_choices(cli, 'lol',280 ['sub', '--sub-opt', 'subopt1', 'subarg1', 'bsub'], '-')) == ['--bsub-opt']281 assert list(get_choices(cli, 'lol',282 ['sub', '--sub-opt', 'subopt1', 'subarg1', 'bsub', '--bsub-opt'], '')) == \
4 unmodified lines
modified:CHANGES+6 added-1 removed
21 unmodified lines
22- Usage errors now hint at the `--help` option.23- ``launch`` now works properly under Cygwin. See #650.24- `CliRunner.invoke` now may receive `args` as a string representing25 a Unix shell command. See #664.26- Fix bug that caused bashcompletion to give inproper completions on 26- Fix bug that caused bashcompletion to give improper completions on 27 chained commands. See #774.28- 't' and 'f' are now converted to True and False. 29- Fix bug that caused bashcompletion to give improper completions on30 chained commands when a required option/argument was being completed.31 See #790.32- Allow autocompletion function to determine whether or not to return33 completions that start with the incomplete argument.3435Version 6.836-----------37
354 unmodified lines