Added basic bash complete support.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 7b84866 · Browse files · 7 files·+217 added−9 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+217 added−9 removed
- other:+217 added−9 removed
Provenance
- Commit
4fa40cf- Tree
b577370- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
7b84866
7 files changed+217 added−9 removed
added:click/bashcomplete.py+74 added
1+import os2+from click.utils import echo3+from click.parser import split_arg_string4+from click.core import MultiCommand, Option5+6+7+COMPLETION_SCRIPT = '''8+%(complete_func)s() {9+ COMPREPLY=( $( COMP_WORDS="${COMP_WORDS[*]}" \\10+ COMP_CWORD=$COMP_CWORD \\11+ %(autocomplete_var)s=complete $1 ) )12+ return 013+}14+15+complete -F %(complete_func)s -o default %(script_names)s16+'''17+18+19+def get_completion_script(prog_name, complete_var):20+ return (COMPLETION_SCRIPT % {21+ 'complete_func': '_%s_completion' % prog_name,22+ 'script_names': prog_name,23+ 'autocomplete_var': complete_var,24+ }).strip() + ';'25+26+27+def resolve_ctx(cli, prog_name, args):28+ ctx = cli.make_context(prog_name, args, resilient_parsing=True)29+ while ctx.args and isinstance(ctx.command, MultiCommand):30+ cmd = ctx.command.get_command(ctx, ctx.args[0])31+ if cmd is None:32+ return None33+ ctx = cmd.make_context(ctx.args[0], ctx.args[1:], parent=ctx,34+ resilient_parsing=True)35+ return ctx36+37+38+def do_complete(cli, prog_name):39+ cwords = split_arg_string(os.environ['COMP_WORDS'])40+ cword = int(os.environ['COMP_CWORD'])41+ args = cwords[1:cword]42+ try:43+ incomplete = cwords[cword]44+ except IndexError:45+ incomplete = ''46+47+ ctx = resolve_ctx(cli, prog_name, args)48+ if ctx is None:49+ return True50+51+ choices = []52+ if incomplete and not incomplete[:1].isalnum():53+ for param in ctx.command.params:54+ if not isinstance(param, Option):55+ continue56+ choices.extend(param.opts)57+ choices.extend(param.secondary_opts)58+ elif isinstance(ctx.command, MultiCommand):59+ choices.extend(ctx.command.list_commands(ctx))60+61+ for item in choices:62+ if item.startswith(incomplete):63+ print item64+65+ return True66+67+68+def bashcomplete(cli, prog_name, complete_var, complete_instr):69+ if complete_instr == 'source':70+ echo(get_completion_script(prog_name, complete_var))71+ return True72+ elif complete_instr == 'complete':73+ return do_complete(cli, prog_name)74+ return Falsemodified:click/core.py+45 added-7 removed
14 unmodified lines15 16 _missing = object()17 18 19+def _bashcomplete(cmd, prog_name, complete_var=None):20+ """Internal handler for the bash completion support."""21+ if complete_var is None:22+ complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper()23+ complete_instr = os.environ.get(complete_var)24+ if not complete_instr:25+ return26+27+ from click.bashcomplete import bashcomplete28+ if bashcomplete(cmd, prog_name, complete_var, complete_instr):29+ sys.exit(1)30+31+32 def batch(iterable, batch_size):33 return list(zip(*repeat(iter(iterable), batch_size)))34 35 75 unmodified lines111 :param terminal_width: the width of the terminal. The default is112 inherit from parent context. If no context113 defines the terminal width then auto114 detection will be applied.115+ :param resilient_parsing: if this flag is enabled then the click will116+ parse without any interactivity or callback117+ invocation. This is useful for implementing118+ things such as completion support.119 """120 121 def __init__(self, command, parent=None, info_name=None, obj=None,122 auto_envvar_prefix=None, default_map=None,106- terminal_width=None):123+ terminal_width=None, resilient_parsing=False):124 #: the parent context or `None` if none exists.125 self.parent = parent126 #: the :class:`Command` for this context.127 self.command = command21 unmodified lines149 terminal_width = parent.terminal_width150 #: The width of the terminal (None is autodetection).151 self.terminal_width = terminal_width152 153+ #: Indicates if resilient parsing is enabled. In that case click154+ #: will do it's best to not cause any failures.155+ self.resilient_parsing = resilient_parsing156+157 # If there is no envvar prefix yet, but the parent has one and158 # the command on this level has a name, we can expand the envvar159 # prefix automatically.160 if auto_envvar_prefix is None:217 unmodified lines378 implementation is raising a not implemented error.379 """380 raise NotImplementedError('Base commands are not invokable by default')381 361- def main(self, args=None, prog_name=None, **extra):382+ def main(self, args=None, prog_name=None, complete_var=None, **extra):383 """This is the way to invoke a script with all the bells and384 whistles as a command line application. This will always terminate385 the application after a call. If this is not wanted, ``SystemExit``386 needs to be caught.5 unmodified lines392 provided, ``sys.argv[1:]`` is used.393 :param prog_name: the program name that should be used. By default394 the program name is constructed by taking the file395 name from ``sys.argv[0]``.396+ :param complete_var: the environment variable that controls the397+ bash completion support. The default is398+ ``"_<prog_name>_COMPLETE"`` with prog name in399+ uppercase.400 :param extra: extra keyword arguments are forwarded to the context401 constructor. See :class:`Context` for more information.402 """403 # If we are on python 3 we will verify that the environment is19 unmodified lines423 args = list(args)424 if prog_name is None:425 prog_name = make_str(os.path.basename(426 sys.argv and sys.argv[0] or __file__))427+428+ # Hook for the bash completion. This only activates if the bash429+ # completion is actually enabled, otherwise this is quite a fast430+ # noop.431+ _bashcomplete(self, prog_name, complete_var)432+433 try:434 try:435 with self.make_context(prog_name, args, **extra) as ctx:436 self.invoke(ctx)137 unmodified lines574 575 for param in iter_params_for_processing(param_order, self.params):576 value, args = param.handle_parse_result(ctx, opts, args)577 547- if args and not self.allow_extra_args:578+ if args and not self.allow_extra_args and not ctx.resilient_parsing:579 ctx.fail('Got unexpected extra argument%s (%s)'580 % (len(args) != 1 and 's' or '',581 ' '.join(map(make_str, args))))582 68 unmodified lines651 with formatter.section('Commands'):652 formatter.write_dl(rows)653 654 def parse_args(self, ctx, args):624- if not args and self.no_args_is_help:655+ if not args and self.no_args_is_help and not ctx.resilient_parsing:656 echo(ctx.get_help())657 ctx.exit()658 return Command.parse_args(self, ctx, args)659 264 unmodified lines924 925 def handle_parse_result(self, ctx, opts, args):926 with augment_usage_errors(ctx, param=self):927 value = self.consume_value(ctx, opts)928+ try:929+ value = self.full_process_value(ctx, value)930+ except Exception:931+ if not ctx.resilient_parsing:932+ raise897- value = self.full_process_value(ctx, value)898- if self.callback is not None:933+ value = None934+ if self.callback is not None \935+ and not ctx.resilient_parsing:936 value = invoke_param_callback(937 self.callback, ctx, self, value)938 939 if self.expose_value:250 unmodified lines1190 rv = batch(rv, self.nargs)1191 return rv1192 1193 def full_process_value(self, ctx, value):1157- if value is None and self.prompt is not None:1194+ if value is None and self.prompt is not None \1195+ and not ctx.resilient_parsing:1196 return self.prompt_for_value(ctx)1197 return Parameter.full_process_value(self, ctx, value)1198 1199 50 unmodified linesmodified:click/parser.py+25 added-2 removed
13 unmodified lines14 is that there are differences in 2.x and 3.x about the error messages15 generated and optparse in the stdlib uses gettext for no good reason16 and might cause us issues.17 """18+import re19 from .exceptions import UsageError20 from .utils import unpack_args21 22 5 unmodified lines28 return opt[:2], opt[2:]29 return first, opt[1:]30 31 32+def split_arg_string(string):33+ """Given an argument string this attempts to split it into small parts."""34+ rv = []35+ for match in re.finditer(r"('([^'\\]*(?:\\.[^'\\]*)*)'"36+ r'|"([^"\\]*(?:\\.[^"\\]*)*)"'37+ r'|\S+)\s*', string, re.S):38+ arg = match.group().strip()39+ if arg[:1] == arg[-1:] and arg[:1] in '"\'':40+ arg = arg[1:-1].encode('ascii', 'backslashreplace') \41+ .decode('unicode-escape')42+ try:43+ arg = type(string)(arg)44+ except UnicodeError:45+ pass46+ rv.append(arg)47+ return rv48+49+50 class Option(object):51 52 def __init__(self, opts, dest, action=None, nargs=1, const=None, obj=None):53 self._short_opts = []127 unmodified lines181 appear on the command line. If arguments appear multiple times they182 will be memorized multiple times as well.183 """184 state = ParsingState(args)185+ try:166- self._process_args_for_options(state)167- self._process_args_for_args(state)186+ self._process_args_for_options(state)187+ self._process_args_for_args(state)188+ except UsageError:189+ if not self.ctx.resilient_parsing:190+ raise191 return state.opts, state.largs, state.order192 193 def _process_args_for_args(self, state):194 pargs, args = unpack_args(state.largs + state.rargs,150 unmodified linesadded:docs/bashcomplete.rst+69 added
1+Bash Complete2+=============3+4+.. versionadded:: 2.05+6+Starting with click 2.0 there is built-in support for bash completion for7+any Click script. There are certain restrictions on when this completion8+is available but for the most part it should just work.9+10+Limitations11+-----------12+13+Bash completion is only available if a script has been installed properly14+and not executed through the ``python`` command. For information about15+how to do that see :ref:`setuptools-integration`. Currently click also16+only supports completion for bash.17+18+Currently bash completion is an internal feature that is not customizable.19+This might be relaxed in future versions.20+21+What it Completes22+-----------------23+24+Generally the bash completion support will complete subcommands and25+parameters. Subcommands are always listed whereas parameters only if at26+least a dash has been provided. Example::27+28+ $ repo <TAB><TAB>29+ clone commit copy delete setuser 30+ $ repo clone -<TAB><TAB>31+ --deep --help --rev --shallow -r 32+33+Activation34+----------35+36+In order to activate bash completion you need to inform bash that37+completion is available for your script and how. Any click application38+automatically provides support for that. The general way this works is39+through a magic environment variable called ``_<PROG_NAME>_COMPLETE``40+where ``<PROG_NAME>`` is your application executable name in uppercase41+with dashes replaced by underscores.42+43+So if your tool is called ``foo-bar`` then the magic variable is called44+``_FOO_BAR_COMPLETE``. By exporting it with the ``source`` value it will45+spit out the activation script which can be trivally be activated.46+47+For instance to enable bash completion for your ``foo-bar`` script, this48+is what you would need to put into your ``.bashrc``::49+50+ eval "$(_FOO_BAR_COMPLETE=source foo-bar)"51+52+From this point onwards your script will have bash completion enabled.53+54+Activation Script55+-----------------56+57+The above activation example will always invoke your application on58+startup. This might be slowing down the shell activation time59+significantly if you have many applications. Alternatively you could also60+ship a file with the contents of that which is what git and other systems61+are doing.62+63+This can be easily accomplished::64+65+ _FOO_BAR_COMPLETE=source foo-bar > foo-bar-complete.sh66+67+And then you would put this into your bashrc instead::68+69+ . /path/to/foo-bar-complete.shmodified:docs/index.rst+1 added
69 unmodified lines70 complex71 advanced72 testing73 utils74+ bashcomplete75 python376 77 API Reference78 -------------18 unmodified linesmodified:docs/setuptools.rst+2 added
1+.. _setuptools-integration:2+3 Usage with Setuptools4 =====================5 6 When writing command line utilities it's recommended to write them as75 unmodified linesmodified:CHANGES+1 added
29 unmodified lines30 - nargs of -1 for arguments can now be forced to be a single item through31 the required flag. It defaults to not required.32 - setting a default for arguments now implicitly makes it non required.33 - changed "yN" / "Yn" to "y/N" and "Y/n" in confirmation prompts.34+- added basic support for bash completion.35 36 Version 1.137 -----------38 11 unmodified lines