Merge pull request #755 from stopthatcow/feature/bash_autocompletion_6.6
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Dynamic bash autocompletion
authored by Markus Unterwaditzer · committed by GitHub · parents 430c50a, 32fb787 · Browse files · 8 files·+127 added−15 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+127 added−15 removed
- tests:+18 added−4 removed
- other:+109 added−11 removed
Provenance
- Commit
5f2ff4f- Tree
dfefda6- Author
Markus Unterwaditzer <markus@unterwaditzer.net>- Committer
GitHub <noreply@github.com>- Parent 1
430c50a- Parent 2
32fb787
8 files changed+127 added−15 removed
modified:click/_bashcomplete.py+18 added-5 removed
6 unmodified lines7 from .parser import split_arg_string8 from .core import MultiCommand, Option, Argument9 from .types import Choice10 11-11 WORDBREAK = '='12 13 COMPLETION_SCRIPT = '''14 %(complete_func)s() {80 unmodified lines95 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 ctx: context associated with the parsed command102+ :param args: full list of args103+ :param incomplete: the incomplete text to autocomplete104+ :param cmd_param: command definition105+ :return: all the possible user-specified completions for the param106+ """107+ if isinstance(cmd_param.type, Choice):108+ return cmd_param.type.choices109+ elif cmd_param.autocompletion is not None:110+ return cmd_param.autocompletion(ctx=ctx,111+ args=args,112+ incomplete=incomplete)113+ else:114+ return []115 116 def get_choices(cli, prog_name, args, incomplete):117 """118 :param cli: command definition29 unmodified lines148 if not found_param:149 # completion for option values by choices150 for cmd_param in ctx.command.params:151 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)152+ choices.extend(get_user_autocompletions(ctx, all_args, incomplete, cmd_param))153 found_param = True154 break155 if not found_param:156 # completion for argument values by choices157 for cmd_param in ctx.command.params:158 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)159+ choices.extend(get_user_autocompletions(ctx, all_args, incomplete, cmd_param))160 found_param = True161 break162 163 if not found_param and isinstance(ctx.command, MultiCommand):30 unmodified linesmodified:click/core.py+3 added-1 removed
1264 unmodified lines1265 param_type_name = 'parameter'1266 1267 def __init__(self, param_decls=None, type=None, required=False,1268 default=None, callback=None, nargs=None, metavar=None,1269- expose_value=True, is_eager=False, envvar=None):1269+ expose_value=True, is_eager=False, envvar=None,1270+ autocompletion=None):1271 self.name, self.opts, self.secondary_opts = \1272 self._parse_decls(param_decls or (), expose_value)1273 1274 self.type = convert_type(type, default)14 unmodified lines1289 self.default = default1290 self.is_eager = is_eager1291 self.metavar = metavar1292 self.envvar = envvar1293+ self.autocompletion = autocompletion1294 1295 @property1296 def human_readable_name(self):1297 """Returns the human readable name of this parameter. This is the459 unmodified linesmodified:docs/bashcomplete.rst+27 added-3 removed
14 unmodified lines15 how to do that, see :ref:`setuptools-integration`. Also, Click currently16 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-19 What it Completes20 -----------------21 22 Generally, the Bash completion support will complete subcommands, options5 unmodified lines28 clone commit copy delete setuser29 $ repo clone -<TAB><TAB>30 --deep --help --rev --shallow -r31 32+Additionally, custom suggestions can be provided for arguments and options with33+the ``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+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.42+43+Here is an example of using a callback function to generate dynamic suggestions:44+45+.. click:example::46+47+ import os48+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])57+58+59 Activation60 ----------61 62 In order to activate Bash completion, you need to inform Bash that44 unmodified linesadded:examples/bashcompletion/bashcompletion.py+31 added
1+import click2+import os3+4+@click.group()5+def cli():6+ pass7+8+def get_env_vars(ctx, args, incomplete):9+ return os.environ.keys()10+11+@cli.command()12+@click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)13+def cmd1(envvar):14+ click.echo('Environment variable: %s' % envvar)15+ click.echo('Value: %s' % os.environ[envvar])16+17+@click.group()18+def group():19+ pass20+21+def list_users(ctx, args, incomplete):22+ # Here you can generate completions dynamically23+ users = ['bob', 'alice']24+ return users25+26+@group.command()27+@click.argument("user", type=click.STRING, autocompletion=list_users)28+def subcmd(user):29+ click.echo('Chosen user is %s' % user)30+31+cli.add_command(group)added:examples/bashcompletion/README+12 added
1+$ bashcompletion2+3+ bashcompletion is a simple example of an application that4+ tries to autocomplete commands, arguments and options.5+6+ This example requires Click 2.0 or higher.7+8+Usage:9+10+ $ pip install --editable .11+ $ eval "$(_BASHCOMPLETION_COMPLETE=source bashcompletion)"12+ $ bashcompletion --helpadded:examples/bashcompletion/setup.py+15 added
1+from setuptools import setup2+3+setup(4+ name='click-example-bashcompletion',5+ version='1.0',6+ py_modules=['bashcompletion'],7+ include_package_data=True,8+ install_requires=[9+ 'click',10+ ],11+ entry_points='''12+ [console_scripts]13+ bashcompletion=bashcompletion:cli14+ ''',15+)modified:tests/test_bashcomplete.py+18 added-4 removed
81 unmodified lines82 @click.option('--bsub-opt')83 def bsub(bsub_opt):84 pass85 86+ COLORS = ['red', 'green', 'blue']87+ def get_colors(ctx, args, incomplete):88+ for c in COLORS:89+ yield c90+91+ CSUB_OPT_CHOICES = ['foo', 'bar']92+ CSUB_CHOICES = ['bar', 'baz']93 @bsub.command('csub')87- @click.option('--csub-opt')88- def csub(csub_opt):94+ @click.option('--csub-opt', type=click.Choice(CSUB_OPT_CHOICES))95+ @click.option('--csub', type=click.Choice(CSUB_CHOICES))96+ @click.argument('color', autocompletion=get_colors)97+ def csub(csub_opt, color):98 pass99 100 assert list(get_choices(cli, 'lol', [], '-')) == ['--cli-opt']101 assert list(get_choices(cli, 'lol', [], '')) == ['asub']102 assert list(get_choices(cli, 'lol', ['asub'], '-')) == ['--asub-opt']103 assert list(get_choices(cli, 'lol', ['asub'], '')) == ['bsub']104 assert list(get_choices(cli, 'lol', ['asub', 'bsub'], '-')) == ['--bsub-opt']105 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'], '')) == []106+ assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], '-')) == ['--csub-opt', '--csub']107+ assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub', '--csub-opt'], '')) == CSUB_OPT_CHOICES108+ assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], '--csub')) == ['--csub-opt', '--csub']109+ assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub', '--csub'], '')) == CSUB_CHOICES110+ assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub', '--csub-opt'], 'f')) == ['foo']111+ assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], '')) == COLORS112+ assert list(get_choices(cli, 'lol', ['asub', 'bsub', 'csub'], 'b')) == ['blue']113 114 115 def test_argument_choice():116 @click.command()127 unmodified linesmodified:CHANGES+3 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 within15- 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