Added support for alternative prefix chars
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 8c184c6 · Browse files · 4 files·+59 added−16 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+59 added−16 removed
- tests:+19 added−0 removed
- other:+40 added−16 removed
Provenance
- Commit
38b3b41- Tree
2c03b98- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
8c184c6
4 files changed+59 added−16 removed
modified:click/_compat.py+7 added
1 import sys2+import re3 import codecs4 5 6 def _wrap_stream_for_codec(f, encoding=None, errors='strict'):13 unmodified lines20 bytes = str21 raw_input = raw_input22 string_types = (str, unicode)23 24+ _identifier_re = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*$')25+26+ def isidentifier(x):27+ return _identifier_re.search(x) is not None28+29 def open_stream(filename, mode='r', encoding=None, errors='strict'):30 if filename != '-':31 if encoding is not None:32 return codecs.open(filename, mode, encoding, errors), True13 unmodified lines46 import io47 text_type = str48 raw_input = input49 string_types = (str,)50+ isidentifier = lambda x: x.isidentifier()51 52 def _make_binary_stream(f, stream_name):53 buf = getattr(f, 'buffer', None)54 if buf is not None and isinstance(buf, io.BufferedReader):27 unmodified linesmodified:click/core.py+15 added-7 removed
8 unmodified lines9 from .helpers import prompt, confirm, echo10 from .formatting import HelpFormatter11 from .parser import OptionParser12 13-from ._compat import PY213+from ._compat import PY2, isidentifier14 15 _missing = object()16 17 18+def _cleanup_name(name):19+ prefix = name[:1]20+ if not prefix.isalnum():21+ return name.lstrip(prefix)22+ return name23+24+25 class Context(object):26 """The context is a special internal object that holds state relevant27 for the script execution at every single level. It's normally invisible28 to commands unless they opt-in to getting access to it.829 unmodified lines858 name = None859 possible_names = []860 861 for decl in decls:855- if not decl.startswith('-'):862+ if isidentifier(decl):863 if name is not None:864 raise TypeError('Name defined twice')865 name = decl866 else:867 if '/' in decl:868 first, second = decl.split('/', 1)862- possible_names.append(first.lstrip('-'))869+ possible_names.append(_cleanup_name(first))870 opts.append(first)871 secondary_opts.append(second)872 else:866- possible_names.append(decl.lstrip('-'))873+ possible_names.append(_cleanup_name(decl))874 opts.append(decl)875 876 if name is None and possible_names:877 possible_names.sort(key=len)871- name = possible_names[-1]878+ name = possible_names[-1].replace('-', '_')879 880 if name is None:881 raise TypeError('Could not determine name for option')882 876- return name.replace('-', '_'), opts, secondary_opts883+ return name, opts, secondary_opts884 885 def add_to_parser(self, parser, ctx):886 kwargs = {887 'dest': self.name,114 unmodified lines1002 if not decls:1003 raise TypeError('Could not determine name for argument')1004 if len(decls) == 1:1005 name = arg = decls[0]1006+ name = name.replace('-', '_')1007 elif len(decls) == 2:1008 name, arg = decls1009 else:1010 raise TypeError('Arguments take exactly one or two '1011 'parameter declarations, got %d' % len(decls))1004- return name.replace('-', '_'), [arg], []1012+ return name, [arg], []1013 1014 def get_usage_pieces(self, ctx):1015 return [self.make_metavar()]1016 6 unmodified linesmodified:click/parser.py+18 added-9 removed
22 unmodified lines23 24 def __init__(self, opts, dest, action=None, nargs=1, const=None):25 self._short_opts = []26 self._long_opts = []27+ self.prefixes = set()28 29 for opt in opts:29- if opt[:2] == '--':30- self._long_opts.append(opt)31- elif opt[:1] == '-':30+ first = opt[:1]31+ if first.isalnum():32+ raise ValueError('Invalid start character for option (%s)'33+ % first)34+ self.prefixes.add(first)35+ if opt[1:2] != first:36 self._short_opts.append(opt)37+ else:38+ self._long_opts.append(opt)39+ self.prefixes.add(opt[:2])40 41 if action is None:42 action = 'store'43 27 unmodified lines71 self._short_opt = {}72 self._long_opt = {}73 self._arg_dest = []74 self._nargs = []75+ self._opt_prefixes = set(['-', '--'])76 77 def add_option(self, opts, **kwargs):78 option = Option(opts, **kwargs)79+ self._opt_prefixes.update(option.prefixes)80 for opt in option._short_opts:81 self._short_opt[opt] = option82 for opt in option._long_opts:83 self._long_opt[opt] = option20 unmodified lines104 105 def _process_args_for_options(self, largs, rargs, opts):106 while rargs:107 arg = rargs[0]99- # We handle bare '--' explicitly, and bare '-' is handled by the100- # standard arg handler since the short arg case ensures that the101- # len of the opt string is greater than 1.108+ # Double dash es always handled explicitly regardless of what109+ # prefixes are valid.110 if arg == '--':111 del rargs[0]112 return105- elif arg[0:2] == '--':113+ elif arg[0:2] in self._opt_prefixes:114 # process a single long option (possibly with value(s))115 self._process_long_opt(rargs, opts)108- elif arg[:1] == '-' and len(arg) > 1:116+ elif arg[:1] in self._opt_prefixes and len(arg) > 1:117 # process a cluster of short options (possibly with118 # value(s) for the last one only)119 self._process_short_opts(rargs, opts)120 elif self.allow_interspersed_args:83 unmodified lines204 def _process_short_opts(self, rargs, opts):205 arg = rargs.pop(0)206 stop = False207 i = 1208+ prefix = arg[0]209 for ch in arg[1:]:201- opt = '-' + ch210+ opt = prefix + ch211 option = self._short_opt.get(opt)212 i += 1213 214 if not option:31 unmodified linesadded:tests/test_options.py+19 added
1+# -*- coding: utf-8 -*-2+import re3+import click4+5+6+def test_prefixes(runner):7+ @click.command()8+ @click.option('++foo', is_flag=True, help='das foo')9+ @click.option('--bar', is_flag=True, help='das bar')10+ def cli(foo, bar):11+ click.echo('foo=%s bar=%s' % (foo, bar))12+13+ result = runner.invoke(cli, ['++foo', '--bar'])14+ assert not result.exception15+ assert result.output == 'foo=True bar=True\n'16+17+ result = runner.invoke(cli, ['--help'])18+ assert re.search(r'\+\+foo\s+das foo', result.output) is not None19+ assert re.search(r'--bar\s+das bar', result.output) is not None