Skip to content
Myr

Issue #535: Bash completion for click.Choice()

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

Added support for bash completion of type=click.Choice Options and Arguments. Added comprehensive tests for bash completion. There are many scenarios present for arguments.

authored by Peter Kelley · committed by Peter Kelley · parent c3da861 · Browse files · 5 files+290 added−10 removed
This commit

State

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

Diff stats

5 files+290 added−10 removed

  • tests:+167 added−0 removed
  • other:+123 added−10 removed

5 files+290 added−10 removed

modified:click/_bashcomplete.py+104 added-7 removed
1import collections2import copy3import os4import re56from .utils import echo7from .parser import split_arg_string5from .core import MultiCommand, Option8from .core import MultiCommand, Option, Argument9from .types import Choice101112WORDBREAK = '='1314COMPLETION_SCRIPT = '''15%(complete_func)s() {16 COMPREPLY=( $( env COMP_WORDS="${COMP_WORDS[*]}" \\17 COMP_CWORD=$COMP_CWORD \\
16 unmodified lines
34 }).strip() + ';'353637def resolve_ctx(cli, prog_name, args):38 """39 Parse into a hierarchy of contexts. Contexts are connected through the parent variable.40 :param cli: command definition41 :param prog_name: the program that is running42 :param args: full list of args43 :return: the final context/command parsed44 """45 ctx = cli.make_context(prog_name, args, resilient_parsing=True)46 while ctx.protected_args + ctx.args and isinstance(ctx.command, MultiCommand):47 a = ctx.protected_args + ctx.args48 cmd = ctx.command.get_command(ctx, a[0])
2 unmodified lines
51 ctx = cmd.make_context(a[0], a[1:], parent=ctx, resilient_parsing=True)52 return ctx535455def start_of_option(param_str):56 """57 :param param_str: param_str to check58 :return: whether or not this is the start of an option declaration (i.e. starts "-" or "--")59 """60 return param_str and param_str[:1] == '-'616263def is_incomplete_option(all_args, cmd_param):64 """65 :param all_args: the full original list of args supplied66 :param cmd_param: the current command paramter67 :return: whether or not the last option declaration (i.e. starts "-" or "--") is incomplete and68 corresponds to this cmd_param. In other words whether this cmd_param option can still accept69 values70 """71 if cmd_param.is_flag:72 return False73 last_option = None74 for index, arg_str in enumerate(reversed([arg for arg in all_args if arg != WORDBREAK])):75 if index + 1 > cmd_param.nargs:76 break77 if start_of_option(arg_str):78 last_option = arg_str7980 return True if last_option and last_option in cmd_param.opts else False818283def is_incomplete_argument(current_params, cmd_param):84 """85 :param current_params: the current params and values for this argument as already entered86 :param cmd_param: the current command parameter87 :return: whether or not the last argument is incomplete and corresponds to this cmd_param. In88 other words whether or not the this cmd_param argument can still accept values89 """90 current_param_values = current_params[cmd_param.name]91 if current_param_values is None:92 return True93 if cmd_param.nargs == -1:94 return True95 if isinstance(current_param_values, collections.Iterable) \96 and cmd_param.nargs > 1 and len(current_param_values) < cmd_param.nargs:97 return True98 return False99100101def get_choices(cli, prog_name, args, incomplete):102 """103 :param cli: command definition104 :param prog_name: the program that is running105 :param args: full list of args106 :param incomplete: the incomplete text to autocomplete107 :return: all the possible completions for the incomplete108 """109 all_args = copy.deepcopy(args)110111 ctx = resolve_ctx(cli, prog_name, args)112 if ctx is None:113 return114115 # In newer versions of bash long opts with '='s are partitioned, but it's easier to parse116 # without the '='117 if start_of_option(incomplete) and WORDBREAK in incomplete:118 partition_incomplete = incomplete.partition(WORDBREAK)119 all_args.append(partition_incomplete[0])120 incomplete = partition_incomplete[2]121 elif incomplete == WORDBREAK:122 incomplete = ''123124 choices = []48 if incomplete and not incomplete[:1].isalnum():125 found_param = False126 if start_of_option(incomplete):127 # completions for options128 for param in ctx.command.params:50 if not isinstance(param, Option):51 continue52 choices.extend(param.opts)53 choices.extend(param.secondary_opts)54 elif isinstance(ctx.command, MultiCommand):129 if isinstance(param, Option):130 choices.extend([param_opt for param_opt in param.opts + param.secondary_opts131 if param_opt not in all_args or param.multiple])132 found_param = True133 if not found_param:134 # completion for option values by choices135 for cmd_param in ctx.command.params:136 if isinstance(cmd_param, Option) and is_incomplete_option(all_args, cmd_param):137 if isinstance(cmd_param.type, Choice):138 choices.extend(cmd_param.type.choices)139 found_param = True140 break141 if not found_param:142 # completion for argument values by choices143 for cmd_param in ctx.command.params:144 if isinstance(cmd_param, Argument) and is_incomplete_argument(ctx.params, cmd_param):145 if isinstance(cmd_param.type, Choice):146 choices.extend(cmd_param.type.choices)147 found_param = True148 break149150 if not found_param and isinstance(ctx.command, MultiCommand):151 # completion for any subcommands152 choices.extend(ctx.command.list_commands(ctx))153154 for item in choices:155 if item.startswith(incomplete):
25 unmodified lines
modified:docs/bashcomplete.rst+16 added-3 removed
11 unmodified lines
1213Bash completion is only available if a script has been installed properly,14and not executed through the ``python`` command. For information about15how to do that, see :ref:`setuptools-integration`. Also, Click currently16only supports completion for Bash.16only supports completion for Bash. Zsh support is available through Zsh's17bash completion compatibility mode.1819Currently, Bash completion is an internal feature that is not customizable.20This might be relaxed in future versions.2122What it Completes23-----------------2424Generally, the Bash completion support will complete subcommands and25parameters. Subcommands are always listed whereas parameters only if at25Generally, the Bash completion support will complete subcommands, options26and any option or argument values where the type is click.Choice.27Subcommands and choices are always listed whereas options only if at28least a dash has been provided. Example::2930 $ repo <TAB><TAB>31 clone commit copy delete setuser
36 unmodified lines
6869And then you would put this into your bashrc instead::7071 . /path/to/foo-bar-complete.sh7273Zsh Compatibility74----------------7576To enable Bash completion in Zsh, add the following lines to your .zshrc:7778 autoload bashcompinit79 bashcompinit8081See https://github.com/pallets/click/issues/323 for more information on82this issue.
modified:tests/test_bashcomplete.py+167 added
12 unmodified lines
13 assert list(get_choices(cli, 'lol', [], '-')) == ['--local-opt']14 assert list(get_choices(cli, 'lol', [], '')) == []151617def test_boolean_flag():18 @click.command()19 @click.option('--shout/--no-shout', default=False)20 def cli(local_opt):21 pass2223 assert list(get_choices(cli, 'lol', [], '-')) == ['--shout', '--no-shout']242526def test_multi_value_option():27 @click.group()28 @click.option('--pos', nargs=2, type=float)29 def cli(local_opt):30 pass3132 @cli.command()33 @click.option('--local-opt')34 def sub(local_opt):35 pass3637 assert list(get_choices(cli, 'lol', [], '-')) == ['--pos']38 assert list(get_choices(cli, 'lol', ['--pos'], '')) == []39 assert list(get_choices(cli, 'lol', ['--pos', '1.0'], '')) == []40 assert list(get_choices(cli, 'lol', ['--pos', '1.0', '1.0'], '')) == ['sub']414243def test_multi_option():44 @click.command()45 @click.option('--message', '-m', multiple=True)46 def cli(local_opt):47 pass4849 assert list(get_choices(cli, 'lol', [], '-')) == ['--message', '-m']50 assert list(get_choices(cli, 'lol', ['-m'], '')) == []515253def test_small_chain():54 @click.group()55 @click.option('--global-opt')56 def cli(global_opt):
38 unmodified lines
95 assert list(get_choices(cli, 'lol', ['asub', 'bsub'], '-')) == ['--bsub-opt']96 assert list(get_choices(cli, 'lol', ['asub', 'bsub'], '')) == ['csub']97 assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], '-')) == ['--csub-opt']98 assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], '')) == []99100101def test_argument_choice():102 @click.command()103 @click.argument('arg1', required=False, type=click.Choice(['arg11', 'arg12']))104 @click.argument('arg2', required=False, type=click.Choice(['arg21', 'arg22']))105 @click.argument('arg3', required=False, type=click.Choice(['arg', 'argument']))106 def cli():107 pass108109 assert list(get_choices(cli, 'lol', [], '')) == ['arg11', 'arg12']110 assert list(get_choices(cli, 'lol', [], 'arg')) == ['arg11', 'arg12']111 assert list(get_choices(cli, 'lol', ['arg11'], '')) == ['arg21', 'arg22']112 assert list(get_choices(cli, 'lol', ['arg12', 'arg21'], '')) == ['arg', 'argument']113 assert list(get_choices(cli, 'lol', ['arg12', 'arg21'], 'argu')) == ['argument']114115116def test_option_choice():117 @click.command()118 @click.option('--opt1', type=click.Choice(['opt11', 'opt12']))119 @click.option('--opt2', type=click.Choice(['opt21', 'opt22']))120 @click.option('--opt3', type=click.Choice(['opt', 'option']))121 def cli():122 pass123124 assert list(get_choices(cli, 'lol', [], '-')) == ['--opt1', '--opt2', '--opt3']125 assert list(get_choices(cli, 'lol', [], '--opt')) == ['--opt1', '--opt2', '--opt3']126 assert list(get_choices(cli, 'lol', [], '--opt1=')) == ['opt11', 'opt12']127 assert list(get_choices(cli, 'lol', [], '--opt2=')) == ['opt21', 'opt22']128 assert list(get_choices(cli, 'lol', ['--opt2'], '=')) == ['opt21', 'opt22']129 assert list(get_choices(cli, 'lol', ['--opt2', '='], 'opt')) == ['opt21', 'opt22']130 assert list(get_choices(cli, 'lol', ['--opt1'], '')) == ['opt11', 'opt12']131 assert list(get_choices(cli, 'lol', ['--opt2'], '')) == ['opt21', 'opt22']132 assert list(get_choices(cli, 'lol', ['--opt1', 'opt11', '--opt2'], '')) == ['opt21', 'opt22']133 assert list(get_choices(cli, 'lol', ['--opt2', 'opt21'], '-')) == ['--opt1', '--opt3']134 assert list(get_choices(cli, 'lol', ['--opt1', 'opt11'], '-')) == ['--opt2', '--opt3']135 assert list(get_choices(cli, 'lol', ['--opt1'], 'opt')) == ['opt11', 'opt12']136 assert list(get_choices(cli, 'lol', ['--opt3'], 'opti')) == ['option']137138 assert list(get_choices(cli, 'lol', ['--opt1', 'invalid_opt'], '-')) == ['--opt2', '--opt3']139140141def test_option_and_arg_choice():142 @click.command()143 @click.option('--opt1', type=click.Choice(['opt11', 'opt12']))144 @click.argument('arg1', required=False, type=click.Choice(['arg11', 'arg12']))145 @click.option('--opt2', type=click.Choice(['opt21', 'opt22']))146 def cli():147 pass148149 assert list(get_choices(cli, 'lol', ['--opt1'], '')) == ['opt11', 'opt12']150 assert list(get_choices(cli, 'lol', [''], '--opt1=')) == ['opt11', 'opt12']151 assert list(get_choices(cli, 'lol', [], '')) == ['arg11', 'arg12']152 assert list(get_choices(cli, 'lol', ['--opt2'], '')) == ['opt21', 'opt22']153154155def test_boolean_flag_choice():156 @click.command()157 @click.option('--shout/--no-shout', default=False)158 @click.argument('arg', required=False, type=click.Choice(['arg1', 'arg2']))159 def cli(local_opt):160 pass161162 assert list(get_choices(cli, 'lol', [], '-')) == ['--shout', '--no-shout']163 assert list(get_choices(cli, 'lol', ['--shout'], '')) == ['arg1', 'arg2']164165166def test_multi_value_option_choice():167 @click.command()168 @click.option('--pos', nargs=2, type=click.Choice(['pos1', 'pos2']))169 @click.argument('arg', required=False, type=click.Choice(['arg1', 'arg2']))170 def cli(local_opt):171 pass172173 assert list(get_choices(cli, 'lol', ['--pos'], '')) == ['pos1', 'pos2']174 assert list(get_choices(cli, 'lol', ['--pos', 'pos1'], '')) == ['pos1', 'pos2']175 assert list(get_choices(cli, 'lol', ['--pos', 'pos1', 'pos2'], '')) == ['arg1', 'arg2']176 assert list(get_choices(cli, 'lol', ['--pos', 'pos1', 'pos2', 'arg1'], '')) == []177178179def test_multi_option_choice():180 @click.command()181 @click.option('--message', '-m', multiple=True, type=click.Choice(['m1', 'm2']))182 @click.argument('arg', required=False, type=click.Choice(['arg1', 'arg2']))183 def cli(local_opt):184 pass185186 assert list(get_choices(cli, 'lol', ['-m'], '')) == ['m1', 'm2']187 assert list(get_choices(cli, 'lol', ['-m', 'm1', '-m'], '')) == ['m1', 'm2']188 assert list(get_choices(cli, 'lol', ['-m', 'm1'], '')) == ['arg1', 'arg2']189190191def test_variadic_argument_choice():192 @click.command()193 @click.argument('src', nargs=-1, type=click.Choice(['src1', 'src2']))194 def cli(local_opt):195 pass196197 assert list(get_choices(cli, 'lol', ['src1', 'src2'], '')) == ['src1', 'src2']198199200def test_long_chain_choice():201 @click.group()202 def cli():203 pass204205 @cli.group('sub')206 @click.option('--sub-opt', type=click.Choice(['subopt1', 'subopt2']))207 @click.argument('sub-arg', required=False, type=click.Choice(['subarg1', 'subarg2']))208 def sub(sub_opt):209 pass210211 @sub.command('bsub')212 @click.option('--bsub-opt', type=click.Choice(['bsubopt1', 'bsubopt2']))213 @click.argument('bsub-arg1', required=False, type=click.Choice(['bsubarg1', 'bsubarg2']))214 @click.argument('bbsub-arg2', required=False, type=click.Choice(['bbsubarg1', 'bbsubarg2']))215 def bsub(bsub_opt):216 pass217218 assert list(get_choices(cli, 'lol', ['sub'], '')) == ['subarg1', 'subarg2']219 assert list(get_choices(cli, 'lol', ['sub', '--sub-opt'], '')) == ['subopt1', 'subopt2']220 assert list(get_choices(cli, 'lol', ['sub', '--sub-opt', 'subopt1'], '')) == \221 ['subarg1', 'subarg2']222 assert list(get_choices(cli, 'lol',223 ['sub', '--sub-opt', 'subopt1', 'subarg1', 'bsub'], '-')) == ['--bsub-opt']224 assert list(get_choices(cli, 'lol',225 ['sub', '--sub-opt', 'subopt1', 'subarg1', 'bsub', '--bsub-opt'], '')) == \226 ['bsubopt1', 'bsubopt2']227 assert list(get_choices(cli, 'lol',228 ['sub', '--sub-opt', 'subopt1', 'subarg1', 'bsub', '--bsub-opt', 'bsubopt1', 'bsubarg1'],229 '')) == ['bbsubarg1', 'bbsubarg2']
modified:.gitignore+1 added
8 unmodified lines
9click.egg-info10.tox11.cache12.ropeproject13.idea
modified:CHANGES+2 added
6 unmodified lines
7-----------89(upcoming release with new features, release date to be decided)1011- Added support for bash completion of type=click.Choice for Options and12 Arguments. See #535.13- The user is now presented with the available choices if prompt=True and14 type=click.Choice in a click.option. The choices are listed within15 parentthesis like 'Choose fruit (apple, orange): '.16- The exception objects now store unicode properly.
363 unmodified lines