Skip to content
Myr

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

8 files+127 added−15 removed

modified:click/_bashcomplete.py+18 added-5 removed
6 unmodified lines
7from .parser import split_arg_string8from .core import MultiCommand, Option, Argument9from .types import Choice101111WORDBREAK = '='1213COMPLETION_SCRIPT = '''14%(complete_func)s() {
80 unmodified lines
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 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 []115116def get_choices(cli, prog_name, args, incomplete):117 """118 :param cli: command definition
29 unmodified lines
148 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 break162163 if not found_param and isinstance(ctx.command, MultiCommand):
30 unmodified lines
modified:click/core.py+3 added-1 removed
1264 unmodified lines
1265 param_type_name = 'parameter'12661267 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)12731274 self.type = convert_type(type, default)
14 unmodified lines
1289 self.default = default1290 self.is_eager = is_eager1291 self.metavar = metavar1292 self.envvar = envvar1293 self.autocompletion = autocompletion12941295 @property1296 def human_readable_name(self):1297 """Returns the human readable name of this parameter. This is the
459 unmodified lines
modified:docs/bashcomplete.rst+27 added-3 removed
14 unmodified lines
15how to do that, see :ref:`setuptools-integration`. Also, Click currently16only 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.2119What it Completes20-----------------2122Generally, the Bash completion support will complete subcommands, options
5 unmodified lines
28 clone commit copy delete setuser29 $ repo clone -<TAB><TAB>30 --deep --help --rev --shallow -r3132Additionally, custom suggestions can be provided for arguments and options with33the ``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:3738- ``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.4243Here is an example of using a callback function to generate dynamic suggestions:4445.. click:example::4647 import os4849 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])575859Activation60----------6162In order to activate Bash completion, you need to inform Bash that
44 unmodified lines
added:examples/bashcompletion/bashcompletion.py+31 added
1import click2import os34@click.group()5def cli():6 pass78def get_env_vars(ctx, args, incomplete):9 return os.environ.keys()1011@cli.command()12@click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)13def cmd1(envvar):14 click.echo('Environment variable: %s' % envvar)15 click.echo('Value: %s' % os.environ[envvar])1617@click.group()18def group():19 pass2021def list_users(ctx, args, incomplete):22 # Here you can generate completions dynamically23 users = ['bob', 'alice']24 return users2526@group.command()27@click.argument("user", type=click.STRING, autocompletion=list_users)28def subcmd(user):29 click.echo('Chosen user is %s' % user)3031cli.add_command(group)
added:examples/bashcompletion/README+12 added
1$ bashcompletion23 bashcompletion is a simple example of an application that4 tries to autocomplete commands, arguments and options.56 This example requires Click 2.0 or higher.78Usage:910 $ pip install --editable .11 $ eval "$(_BASHCOMPLETION_COMPLETE=source bashcompletion)"12 $ bashcompletion --help
added:examples/bashcompletion/setup.py+15 added
1from setuptools import setup23setup(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 lines
82 @click.option('--bsub-opt')83 def bsub(bsub_opt):84 pass8586 COLORS = ['red', 'green', 'blue']87 def get_colors(ctx, args, incomplete):88 for c in COLORS:89 yield c9091 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 pass99100 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']113114115def test_argument_choice():116 @click.command()
127 unmodified lines
modified:CHANGES+3 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 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