Skip to content
Myr

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

6 files+323 added−65 removed

modified:click/_bashcomplete.py+114 added-25 removed
1import collections2import copy3import os4import re56from .utils import echo7from .parser import split_arg_string8from .core import MultiCommand, Option, Argument9from .types import Choice1011WORDBREAK = '='1213COMPLETION_SCRIPT = '''14%(complete_func)s() {15 COMPREPLY=( $( env COMP_WORDS="${COMP_WORDS[*]}" \\16 COMP_CWORD=$COMP_CWORD \\
16 unmodified lines
33 }).strip() + ';'343536def 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 lines
50 ctx = cmd.make_context(a[0], a[1:], parent=ctx, resilient_parsing=True)51 return ctx525354def 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] == '-'606162def 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_str7879 return True if last_option and last_option in cmd_param.opts else False808182def 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 False9899def 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 choices112113def 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)122123 ctx = resolve_ctx(cli, prog_name, args)124 if ctx is None:125 return126127 # 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 = ''135136 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 = True145146 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 break160161 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 break164165 for item in choices:166 if item.startswith(incomplete):167 yield item
24 unmodified lines
modified:docs/bashcomplete.rst+24 added-25 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.1818Currently, Bash completion is an internal feature that is not customizable.19This might be relaxed in future versions.2019What it Completes20-----------------2124By default, the Bash completion support will complete subcommands and25parameters. Subcommands are always listed whereas parameters only if at22Generally, the Bash completion support will complete subcommands, options23and any option or argument values where the type is click.Choice.24Subcommands and choices are always listed whereas options only if at25least a dash has been provided. Example::2627 $ repo <TAB><TAB>28 clone commit copy delete setuser29 $ repo clone -<TAB><TAB>30 --deep --help --rev --shallow -r32 3132Additionally, custom suggestions can be provided for arguments with the34``autocompletion`` parameter. ``autocompletion`` may be a list of strings, as35in the following example:33``autocompletion`` parameter. ``autocompletion`` should a callback function34that returns a list of strings. This is useful when the suggestions need to be35dynamically generated at bash completion time. The callback function will be36passed 3 keyword arguments:3737.. click:example::3839 @click.command()40 @click.argument("name", type=click.STRING, autocompletion=["John", "Simon", "Doe"])41 def cmd1(name):42 click.echo('Name: %s' % name)43 44Alternatively, ``autocompletion`` may be a callback function that returns a list45of strings. This is useful when the suggestions need to be dynamically generated46at bash completion time. The callback function will be passed 4 keyword47arguments:4838- ``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.4243Here is an example of using a callback function to generate dynamic suggestions:4445.. click:example::4647 import os60 4849 def get_env_vars(ctx, incomplete, cwords, cword):50 return os.environ.keys()5152 @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 575859Activation60----------6162In order to activate Bash completion, you need to inform Bash that
29 unmodified lines
9293And then you would put this into your bashrc instead::9495 . /path/to/foo-bar-complete.sh9697Zsh Compatibility98----------------99100To enable Bash completion in Zsh, add the following lines to your .zshrc:101102 autoload bashcompinit103 bashcompinit104105See https://github.com/pallets/click/issues/323 for more information on106this issue.
modified:examples/bashcompletion/bashcompletion.py+12 added-13 removed
1import click2import os3from netifaces import interfaces, ifaddresses, AF_INET45@click.group()6def cli():7 pass889@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"])13def cmd1(count, first, last):14 for c in range(count):15 click.echo('Name: %s %s' % (first, last))169def get_env_vars(ctx, args, incomplete):10 return os.environ.keys()1112@cli.command()13@click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)22def cmd2(envvar):14def cmd1(envvar):15 click.echo('Environment variable: %s' % envvar)16 click.echo('Value: %s' % os.environ[envvar])1718@cli.command()
3 unmodified lines
22@click.group()23def group():24 pass2526def 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_list3233@group.command()35@click.argument("color", type=click.STRING, autocompletion=['red', 'green', 'blue'])36def subcmd(color):37 click.echo('Color is: %s' % color)34@click.argument("ip", type=click.STRING, autocompletion=ip4_addresses)35def subcmd(ip):36 click.echo('Chosen IP is %s' % color)3738cli.add_command(group)
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):
51 unmodified lines
108 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']112113114def 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 pass121122 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']127128129def 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 pass136137 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']150151 assert list(get_choices(cli, 'lol', ['--opt1', 'invalid_opt'], '-')) == ['--opt2', '--opt3']152153154def 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 pass161162 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']166167168def 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 pass174175 assert list(get_choices(cli, 'lol', [], '-')) == ['--shout', '--no-shout']176 assert list(get_choices(cli, 'lol', ['--shout'], '')) == ['arg1', 'arg2']177178179def 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 pass185186 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'], '')) == []190191192def 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 pass198199 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']202203204def test_variadic_argument_choice():205 @click.command()206 @click.argument('src', nargs=-1, type=click.Choice(['src1', 'src2']))207 def cli(local_opt):208 pass209210 assert list(get_choices(cli, 'lol', ['src1', 'src2'], '')) == ['src1', 'src2']211212213def test_long_chain_choice():214 @click.group()215 def cli():216 pass217218 @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 pass223224 @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 pass230231 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 lines
9click.egg-info10.tox11.cache12.ropeproject13.idea
modified:CHANGES+5 added-2 removed
5 unmodified lines
6Version 7.07-----------89(upcoming release with new features, release date to be decided)1010- 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