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
Provenance
- Commit
6131e96- Tree
410e002- Author
Peter Kelley <peter@knewton.com>- Committer
Peter Kelley <peter@knewton.com>- Parent
c3da861
5 files changed+290 added−10 removed
modified:click/_bashcomplete.py+104 added-7 removed
1+import collections2+import copy3 import os4 import re5+6 from .utils import echo7 from .parser import split_arg_string5-from .core import MultiCommand, Option8+from .core import MultiCommand, Option, Argument9+from .types import Choice10 11 12+WORDBREAK = '='13+14 COMPLETION_SCRIPT = '''15 %(complete_func)s() {16 COMPREPLY=( $( env COMP_WORDS="${COMP_WORDS[*]}" \\17 COMP_CWORD=$COMP_CWORD \\16 unmodified lines34 }).strip() + ';'35 36 37 def 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 lines51 ctx = cmd.make_context(a[0], a[1:], parent=ctx, resilient_parsing=True)52 return ctx53 54 55+def 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] == '-'61+62+63+def 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_str79+80+ return True if last_option and last_option in cmd_param.opts else False81+82+83+def 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 False99+100+101 def 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)110+111 ctx = resolve_ctx(cli, prog_name, args)112 if ctx is None:113 return114 115+ # 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 = ''123+124 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+ break149+150+ if not found_param and isinstance(ctx.command, MultiCommand):151+ # completion for any subcommands152 choices.extend(ctx.command.list_commands(ctx))153 154 for item in choices:155 if item.startswith(incomplete):25 unmodified linesmodified:docs/bashcomplete.rst+16 added-3 removed
11 unmodified lines12 13 Bash completion is only available if a script has been installed properly,14 and not executed through the ``python`` command. For information about15 how to do that, see :ref:`setuptools-integration`. Also, Click currently16-only supports completion for Bash.16+only supports completion for Bash. Zsh support is available through Zsh's17+bash completion compatibility mode.18 19 Currently, Bash completion is an internal feature that is not customizable.20 This might be relaxed in future versions.21 22 What it Completes23 -----------------24 24-Generally, the Bash completion support will complete subcommands and25-parameters. Subcommands are always listed whereas parameters only if at25+Generally, the Bash completion support will complete subcommands, options26+and any option or argument values where the type is click.Choice.27+Subcommands and choices are always listed whereas options only if at28 least a dash has been provided. Example::29 30 $ repo <TAB><TAB>31 clone commit copy delete setuser36 unmodified lines68 69 And then you would put this into your bashrc instead::70 71 . /path/to/foo-bar-complete.sh72+73+Zsh Compatibility74+----------------75+76+To enable Bash completion in Zsh, add the following lines to your .zshrc:77+78+ autoload bashcompinit79+ bashcompinit80+81+See https://github.com/pallets/click/issues/323 for more information on82+this issue.modified:tests/test_bashcomplete.py+167 added
12 unmodified lines13 assert list(get_choices(cli, 'lol', [], '-')) == ['--local-opt']14 assert list(get_choices(cli, 'lol', [], '')) == []15 16 17+def test_boolean_flag():18+ @click.command()19+ @click.option('--shout/--no-shout', default=False)20+ def cli(local_opt):21+ pass22+23+ assert list(get_choices(cli, 'lol', [], '-')) == ['--shout', '--no-shout']24+25+26+def test_multi_value_option():27+ @click.group()28+ @click.option('--pos', nargs=2, type=float)29+ def cli(local_opt):30+ pass31+32+ @cli.command()33+ @click.option('--local-opt')34+ def sub(local_opt):35+ pass36+37+ 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']41+42+43+def test_multi_option():44+ @click.command()45+ @click.option('--message', '-m', multiple=True)46+ def cli(local_opt):47+ pass48+49+ assert list(get_choices(cli, 'lol', [], '-')) == ['--message', '-m']50+ assert list(get_choices(cli, 'lol', ['-m'], '')) == []51+52+53 def test_small_chain():54 @click.group()55 @click.option('--global-opt')56 def cli(global_opt):38 unmodified lines95 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'], '')) == []99+100+101+def 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+ pass108+109+ 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']114+115+116+def 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+ pass123+124+ 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']137+138+ assert list(get_choices(cli, 'lol', ['--opt1', 'invalid_opt'], '-')) == ['--opt2', '--opt3']139+140+141+def 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+ pass148+149+ 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']153+154+155+def 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+ pass161+162+ assert list(get_choices(cli, 'lol', [], '-')) == ['--shout', '--no-shout']163+ assert list(get_choices(cli, 'lol', ['--shout'], '')) == ['arg1', 'arg2']164+165+166+def 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+ pass172+173+ 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'], '')) == []177+178+179+def 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+ pass185+186+ 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']189+190+191+def test_variadic_argument_choice():192+ @click.command()193+ @click.argument('src', nargs=-1, type=click.Choice(['src1', 'src2']))194+ def cli(local_opt):195+ pass196+197+ assert list(get_choices(cli, 'lol', ['src1', 'src2'], '')) == ['src1', 'src2']198+199+200+def test_long_chain_choice():201+ @click.group()202+ def cli():203+ pass204+205+ @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+ pass210+211+ @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+ pass217+218+ 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 lines9 click.egg-info10 .tox11 .cache12 .ropeproject13+.ideamodified:CHANGES+2 added
6 unmodified lines7 -----------8 9 (upcoming release with new features, release date to be decided)10 11+- 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