Merge branch 'master' into feature/bash_autocompletion_6.6
Before adoption: this commit came in with the history the project adopted, so no landing records it.
# Conflicts: # click/_bashcomplete.py # docs/bashcomplete.rst # tests/test_bashcomplete.py
authored by Nicholas Wiles · committed by Nicholas Wiles · parents 8ac004f, 430c50a · Browse files · 6 files·+323 added−65 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+323 added−65 removed
- tests:+167 added−0 removed
- other:+156 added−65 removed
Provenance
- Commit
014ce7c- Tree
822a5c1- Author
Nicholas Wiles <nwiles@google.com>- Committer
Nicholas Wiles <nwiles@google.com>- Parent 1
8ac004f- Parent 2
430c50a
6 files changed+323 added−65 removed
modified:click/_bashcomplete.py+114 added-25 removed
1+import collections2+import copy3 import os4 import re5+6 from .utils import echo7 from .parser import split_arg_string8 from .core import MultiCommand, Option, Argument9 from .types import Choice10 11+WORDBREAK = '='12+13 COMPLETION_SCRIPT = '''14 %(complete_func)s() {15 COMPREPLY=( $( env COMP_WORDS="${COMP_WORDS[*]}" \\16 COMP_CWORD=$COMP_CWORD \\16 unmodified lines33 }).strip() + ';'34 35 36 def resolve_ctx(cli, prog_name, args):37+ """38+ Parse into a hierarchy of contexts. Contexts are connected through the parent variable.39+ :param cli: command definition40+ :param prog_name: the program that is running41+ :param args: full list of args42+ :return: the final context/command parsed43+ """44 ctx = cli.make_context(prog_name, args, resilient_parsing=True)45 while ctx.protected_args + ctx.args and isinstance(ctx.command, MultiCommand):46 a = ctx.protected_args + ctx.args47 cmd = ctx.command.get_command(ctx, a[0])2 unmodified lines50 ctx = cmd.make_context(a[0], a[1:], parent=ctx, resilient_parsing=True)51 return ctx52 53 54+def start_of_option(param_str):55+ """56+ :param param_str: param_str to check57+ :return: whether or not this is the start of an option declaration (i.e. starts "-" or "--")58+ """59+ return param_str and param_str[:1] == '-'60+61+62+def is_incomplete_option(all_args, cmd_param):63+ """64+ :param all_args: the full original list of args supplied65+ :param cmd_param: the current command paramter66+ :return: whether or not the last option declaration (i.e. starts "-" or "--") is incomplete and67+ corresponds to this cmd_param. In other words whether this cmd_param option can still accept68+ values69+ """70+ if cmd_param.is_flag:71+ return False72+ last_option = None73+ for index, arg_str in enumerate(reversed([arg for arg in all_args if arg != WORDBREAK])):74+ if index + 1 > cmd_param.nargs:75+ break76+ if start_of_option(arg_str):77+ last_option = arg_str78+79+ return True if last_option and last_option in cmd_param.opts else False80+81+82+def is_incomplete_argument(current_params, cmd_param):83+ """84+ :param current_params: the current params and values for this argument as already entered85+ :param cmd_param: the current command parameter86+ :return: whether or not the last argument is incomplete and corresponds to this cmd_param. In87+ other words whether or not the this cmd_param argument can still accept values88+ """89+ current_param_values = current_params[cmd_param.name]90+ if current_param_values is None:91+ return True92+ if cmd_param.nargs == -1:93+ return True94+ if isinstance(current_param_values, collections.Iterable) \95+ and cmd_param.nargs > 1 and len(current_param_values) < cmd_param.nargs:96+ return True97+ return False98+99+def get_user_autocompletions(ctx, args, incomplete, cmd_param):100+ """101+ :param cmd_param: command definition102+ :return: all the possible user-specified completions for the param103+ """104+ choices = []105+ if isinstance(cmd_param.type, Choice):106+ choices.extend(cmd_param.type.choices)107+ elif hasattr(cmd_param, 'autocompletion'):108+ choices.extend(cmd_param.autocompletion(ctx=ctx,109+ args=args,110+ incomplete=incomplete))111+ return choices112+113 def get_choices(cli, prog_name, args, incomplete):114+ """115+ :param cli: command definition116+ :param prog_name: the program that is running117+ :param args: full list of args118+ :param incomplete: the incomplete text to autocomplete119+ :return: all the possible completions for the incomplete120+ """121+ all_args = copy.deepcopy(args)122+123 ctx = resolve_ctx(cli, prog_name, args)124 if ctx is None:125 return126 127+ # In newer versions of bash long opts with '='s are partitioned, but it's easier to parse128+ # without the '='129+ if start_of_option(incomplete) and WORDBREAK in incomplete:130+ partition_incomplete = incomplete.partition(WORDBREAK)131+ all_args.append(partition_incomplete[0])132+ incomplete = partition_incomplete[2]133+ elif incomplete == WORDBREAK:134+ incomplete = ''135+136 choices = []48- if incomplete and not incomplete[:1].isalnum():137+ found_param = False138+ if start_of_option(incomplete):139+ # completions for options140 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):141+ if isinstance(param, Option):142+ choices.extend([param_opt for param_opt in param.opts + param.secondary_opts143+ if param_opt not in all_args or param.multiple])144+ found_param = True145+146+ if not found_param:147+ # completion for option values by choices148+ for cmd_param in ctx.command.params:149+ if isinstance(cmd_param, Option) and is_incomplete_option(all_args, cmd_param):150+ choices.extend(get_user_autocompletions(ctx, all_args, incomplete, cmd_param))151+ found_param = True152+ break153+ if not found_param:154+ # completion for argument values by choices155+ for cmd_param in ctx.command.params:156+ if isinstance(cmd_param, Argument) and is_incomplete_argument(ctx.params, cmd_param):157+ choices.extend(get_user_autocompletions(ctx, all_args, incomplete, cmd_param))158+ found_param = True159+ break160+161+ if not found_param and isinstance(ctx.command, MultiCommand):162+ # completion for any subcommands163 choices.extend(ctx.command.list_commands(ctx))56- else:57- for param in ctx.command.params:58- if isinstance(param, Option) and isinstance(param.type, Choice):59- if args[-1] in param.opts:60- choices.extend(param.type.choices)61- break62- elif hasattr(param, 'autocompletion'):63- value = ctx.params[param.name]64- if (value is None) or (isinstance(value, tuple) and (len(value) < param.nargs or param.nargs == -1)):65- try:66- if callable(param.autocompletion):67- choices.extend(param.autocompletion(ctx=ctx,68- args=args,69- incomplete=incomplete))70- else:71- choices.extend(param.autocompletion)72- except AttributeError:73- pass74- break164 165 for item in choices:166 if item.startswith(incomplete):167 yield item24 unmodified linesmodified:docs/bashcomplete.rst+24 added-25 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 18-Currently, Bash completion is an internal feature that is not customizable.19-This might be relaxed in future versions.20-19 What it Completes20 -----------------21 24-By default, the Bash completion support will complete subcommands and25-parameters. Subcommands are always listed whereas parameters only if at22+Generally, the Bash completion support will complete subcommands, options23+and any option or argument values where the type is click.Choice.24+Subcommands and choices are always listed whereas options only if at25 least a dash has been provided. Example::26 27 $ repo <TAB><TAB>28 clone commit copy delete setuser29 $ repo clone -<TAB><TAB>30 --deep --help --rev --shallow -r32- 31+32 Additionally, custom suggestions can be provided for arguments with the34-``autocompletion`` parameter. ``autocompletion`` may be a list of strings, as35-in the following example:33+``autocompletion`` parameter. ``autocompletion`` should a callback function34+that returns a list of strings. This is useful when the suggestions need to be35+dynamically generated at bash completion time. The callback function will be36+passed 3 keyword arguments:37 37-.. click:example::38-39- @click.command()40- @click.argument("name", type=click.STRING, autocompletion=["John", "Simon", "Doe"])41- def cmd1(name):42- click.echo('Name: %s' % name)43- 44-Alternatively, ``autocompletion`` may be a callback function that returns a list45-of strings. This is useful when the suggestions need to be dynamically generated46-at bash completion time. The callback function will be passed 4 keyword47-arguments:48-38 - ``ctx`` - The current click context.39+- ``args`` - The list of arguments passed in.40 - ``incomplete`` - The partial word that is being completed, as a string. May41 be an empty string ``''`` if no characters have been entered yet.52-- ``cwords`` - The bash `COMP_WORDS <https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion.html#Programmable-Completion>`_ array, as a list of strings.53-- ``cword`` - The bash `COMP_CWORD <https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion.html#Programmable-Completion>`_ variable, as an integer.42 43 Here is an example of using a callback function to generate dynamic suggestions:44 45 .. click:example::46 47 import os60- 48+49 def get_env_vars(ctx, incomplete, cwords, cword):50 return os.environ.keys()51 52 @click.command()53 @click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)54 def cmd1(envvar):55 click.echo('Environment variable: %s' % envvar)56 click.echo('Value: %s' % os.environ[envvar])69- 57 58+59 Activation60 ----------61 62 In order to activate Bash completion, you need to inform Bash that29 unmodified lines92 93 And then you would put this into your bashrc instead::94 95 . /path/to/foo-bar-complete.sh96+97+Zsh Compatibility98+----------------99+100+To enable Bash completion in Zsh, add the following lines to your .zshrc:101+102+ autoload bashcompinit103+ bashcompinit104+105+See https://github.com/pallets/click/issues/323 for more information on106+this issue.modified:examples/bashcompletion/bashcompletion.py+12 added-13 removed
1 import click2 import os3+from netifaces import interfaces, ifaddresses, AF_INET4 5 @click.group()6 def cli():7 pass8 8-9-@cli.command()10-@click.option('-c', '--count', type=click.INT, default=1)11-@click.argument("first", type=click.STRING, autocompletion=["John", "Bob", "Fred"])12-@click.argument("last", type=click.STRING, autocompletion=["Smith", "Simon", "Doe"])13-def cmd1(count, first, last):14- for c in range(count):15- click.echo('Name: %s %s' % (first, last))16-9 def get_env_vars(ctx, args, incomplete):10 return os.environ.keys()11 12 @cli.command()13 @click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)22-def cmd2(envvar):14+def cmd1(envvar):15 click.echo('Environment variable: %s' % envvar)16 click.echo('Value: %s' % os.environ[envvar])17 18 @cli.command()3 unmodified lines22 @click.group()23 def group():24 pass25 26+def ip4_addresses():27+ ip_list = []28+ for interface in interfaces():29+ for link in ifaddresses(interface)[AF_INET]:30+ ip_list.append(link['addr'])31+ return ip_list32+33 @group.command()35-@click.argument("color", type=click.STRING, autocompletion=['red', 'green', 'blue'])36-def subcmd(color):37- click.echo('Color is: %s' % color)34+@click.argument("ip", type=click.STRING, autocompletion=ip4_addresses)35+def subcmd(ip):36+ click.echo('Chosen IP is %s' % color)37 38 cli.add_command(group)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):51 unmodified lines108 assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub', '--csub'], '')) == CSUB_CHOICES109 assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub', '--csub-opt'], 'f')) == ['foo']110 assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], '')) == COLORS111 assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], 'b')) == ['blue']112+113+114+def test_argument_choice():115+ @click.command()116+ @click.argument('arg1', required=False, type=click.Choice(['arg11', 'arg12']))117+ @click.argument('arg2', required=False, type=click.Choice(['arg21', 'arg22']))118+ @click.argument('arg3', required=False, type=click.Choice(['arg', 'argument']))119+ def cli():120+ pass121+122+ assert list(get_choices(cli, 'lol', [], '')) == ['arg11', 'arg12']123+ assert list(get_choices(cli, 'lol', [], 'arg')) == ['arg11', 'arg12']124+ assert list(get_choices(cli, 'lol', ['arg11'], '')) == ['arg21', 'arg22']125+ assert list(get_choices(cli, 'lol', ['arg12', 'arg21'], '')) == ['arg', 'argument']126+ assert list(get_choices(cli, 'lol', ['arg12', 'arg21'], 'argu')) == ['argument']127+128+129+def test_option_choice():130+ @click.command()131+ @click.option('--opt1', type=click.Choice(['opt11', 'opt12']))132+ @click.option('--opt2', type=click.Choice(['opt21', 'opt22']))133+ @click.option('--opt3', type=click.Choice(['opt', 'option']))134+ def cli():135+ pass136+137+ assert list(get_choices(cli, 'lol', [], '-')) == ['--opt1', '--opt2', '--opt3']138+ assert list(get_choices(cli, 'lol', [], '--opt')) == ['--opt1', '--opt2', '--opt3']139+ assert list(get_choices(cli, 'lol', [], '--opt1=')) == ['opt11', 'opt12']140+ assert list(get_choices(cli, 'lol', [], '--opt2=')) == ['opt21', 'opt22']141+ assert list(get_choices(cli, 'lol', ['--opt2'], '=')) == ['opt21', 'opt22']142+ assert list(get_choices(cli, 'lol', ['--opt2', '='], 'opt')) == ['opt21', 'opt22']143+ assert list(get_choices(cli, 'lol', ['--opt1'], '')) == ['opt11', 'opt12']144+ assert list(get_choices(cli, 'lol', ['--opt2'], '')) == ['opt21', 'opt22']145+ assert list(get_choices(cli, 'lol', ['--opt1', 'opt11', '--opt2'], '')) == ['opt21', 'opt22']146+ assert list(get_choices(cli, 'lol', ['--opt2', 'opt21'], '-')) == ['--opt1', '--opt3']147+ assert list(get_choices(cli, 'lol', ['--opt1', 'opt11'], '-')) == ['--opt2', '--opt3']148+ assert list(get_choices(cli, 'lol', ['--opt1'], 'opt')) == ['opt11', 'opt12']149+ assert list(get_choices(cli, 'lol', ['--opt3'], 'opti')) == ['option']150+151+ assert list(get_choices(cli, 'lol', ['--opt1', 'invalid_opt'], '-')) == ['--opt2', '--opt3']152+153+154+def test_option_and_arg_choice():155+ @click.command()156+ @click.option('--opt1', type=click.Choice(['opt11', 'opt12']))157+ @click.argument('arg1', required=False, type=click.Choice(['arg11', 'arg12']))158+ @click.option('--opt2', type=click.Choice(['opt21', 'opt22']))159+ def cli():160+ pass161+162+ assert list(get_choices(cli, 'lol', ['--opt1'], '')) == ['opt11', 'opt12']163+ assert list(get_choices(cli, 'lol', [''], '--opt1=')) == ['opt11', 'opt12']164+ assert list(get_choices(cli, 'lol', [], '')) == ['arg11', 'arg12']165+ assert list(get_choices(cli, 'lol', ['--opt2'], '')) == ['opt21', 'opt22']166+167+168+def test_boolean_flag_choice():169+ @click.command()170+ @click.option('--shout/--no-shout', default=False)171+ @click.argument('arg', required=False, type=click.Choice(['arg1', 'arg2']))172+ def cli(local_opt):173+ pass174+175+ assert list(get_choices(cli, 'lol', [], '-')) == ['--shout', '--no-shout']176+ assert list(get_choices(cli, 'lol', ['--shout'], '')) == ['arg1', 'arg2']177+178+179+def test_multi_value_option_choice():180+ @click.command()181+ @click.option('--pos', nargs=2, type=click.Choice(['pos1', 'pos2']))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', ['--pos'], '')) == ['pos1', 'pos2']187+ assert list(get_choices(cli, 'lol', ['--pos', 'pos1'], '')) == ['pos1', 'pos2']188+ assert list(get_choices(cli, 'lol', ['--pos', 'pos1', 'pos2'], '')) == ['arg1', 'arg2']189+ assert list(get_choices(cli, 'lol', ['--pos', 'pos1', 'pos2', 'arg1'], '')) == []190+191+192+def test_multi_option_choice():193+ @click.command()194+ @click.option('--message', '-m', multiple=True, type=click.Choice(['m1', 'm2']))195+ @click.argument('arg', required=False, type=click.Choice(['arg1', 'arg2']))196+ def cli(local_opt):197+ pass198+199+ assert list(get_choices(cli, 'lol', ['-m'], '')) == ['m1', 'm2']200+ assert list(get_choices(cli, 'lol', ['-m', 'm1', '-m'], '')) == ['m1', 'm2']201+ assert list(get_choices(cli, 'lol', ['-m', 'm1'], '')) == ['arg1', 'arg2']202+203+204+def test_variadic_argument_choice():205+ @click.command()206+ @click.argument('src', nargs=-1, type=click.Choice(['src1', 'src2']))207+ def cli(local_opt):208+ pass209+210+ assert list(get_choices(cli, 'lol', ['src1', 'src2'], '')) == ['src1', 'src2']211+212+213+def test_long_chain_choice():214+ @click.group()215+ def cli():216+ pass217+218+ @cli.group('sub')219+ @click.option('--sub-opt', type=click.Choice(['subopt1', 'subopt2']))220+ @click.argument('sub-arg', required=False, type=click.Choice(['subarg1', 'subarg2']))221+ def sub(sub_opt):222+ pass223+224+ @sub.command('bsub')225+ @click.option('--bsub-opt', type=click.Choice(['bsubopt1', 'bsubopt2']))226+ @click.argument('bsub-arg1', required=False, type=click.Choice(['bsubarg1', 'bsubarg2']))227+ @click.argument('bbsub-arg2', required=False, type=click.Choice(['bbsubarg1', 'bbsubarg2']))228+ def bsub(bsub_opt):229+ pass230+231+ assert list(get_choices(cli, 'lol', ['sub'], '')) == ['subarg1', 'subarg2']232+ assert list(get_choices(cli, 'lol', ['sub', '--sub-opt'], '')) == ['subopt1', 'subopt2']233+ assert list(get_choices(cli, 'lol', ['sub', '--sub-opt', 'subopt1'], '')) == \234+ ['subarg1', 'subarg2']235+ assert list(get_choices(cli, 'lol',236+ ['sub', '--sub-opt', 'subopt1', 'subarg1', 'bsub'], '-')) == ['--bsub-opt']237+ assert list(get_choices(cli, 'lol',238+ ['sub', '--sub-opt', 'subopt1', 'subarg1', 'bsub', '--bsub-opt'], '')) == \239+ ['bsubopt1', 'bsubopt2']240+ assert list(get_choices(cli, 'lol',241+ ['sub', '--sub-opt', 'subopt1', 'subarg1', 'bsub', '--bsub-opt', 'bsubopt1', 'bsubarg1'],242+ '')) == ['bbsubarg1', 'bbsubarg2']modified:.gitignore+1 added
8 unmodified lines9 click.egg-info10 .tox11 .cache12 .ropeproject13+.ideamodified:CHANGES+5 added-2 removed
5 unmodified lines6 Version 7.07 -----------8 9 (upcoming release with new features, release date to be decided)10-10+- Added support for dynamic bash completion from a user-supplied callback.11+ See #75512+- Added support for bash completion of type=click.Choice for Options and13+ Arguments. See #535.14 - The user is now presented with the available choices if prompt=True and15 type=click.Choice in a click.option. The choices are listed within13- parentthesis like 'Choose fruit (apple, orange): '.16+ parenthesis like 'Choose fruit (apple, orange): '.17 - The exception objects now store unicode properly.18 - Added the ability to hide commands and options from help.19 - Added Float Range in Types.20 - `secho`'s first argument can now be `None`, like in `echo`.360 unmodified lines