Skip to content
Myr

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

4 files+59 added−16 removed

modified:click/_compat.py+7 added
1import sys2import re3import codecs456def _wrap_stream_for_codec(f, encoding=None, errors='strict'):
13 unmodified lines
20 bytes = str21 raw_input = raw_input22 string_types = (str, unicode)2324 _identifier_re = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*$')2526 def isidentifier(x):27 return _identifier_re.search(x) is not None2829 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), True
13 unmodified lines
46 import io47 text_type = str48 raw_input = input49 string_types = (str,)50 isidentifier = lambda x: x.isidentifier()5152 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 lines
modified:click/core.py+15 added-7 removed
8 unmodified lines
9from .helpers import prompt, confirm, echo10from .formatting import HelpFormatter11from .parser import OptionParser1213from ._compat import PY213from ._compat import PY2, isidentifier1415_missing = object()161718def _cleanup_name(name):19 prefix = name[:1]20 if not prefix.isalnum():21 return name.lstrip(prefix)22 return name232425class 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 lines
858 name = None859 possible_names = []860861 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)875876 if name is None and possible_names:877 possible_names.sort(key=len)871 name = possible_names[-1]878 name = possible_names[-1].replace('-', '_')879880 if name is None:881 raise TypeError('Could not determine name for option')882876 return name.replace('-', '_'), opts, secondary_opts883 return name, opts, secondary_opts884885 def add_to_parser(self, parser, ctx):886 kwargs = {887 'dest': self.name,
114 unmodified lines
1002 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], []10131014 def get_usage_pieces(self, ctx):1015 return [self.make_metavar()]1016
6 unmodified lines
modified:click/parser.py+18 added-9 removed
22 unmodified lines
2324 def __init__(self, opts, dest, action=None, nargs=1, const=None):25 self._short_opts = []26 self._long_opts = []27 self.prefixes = set()2829 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])4041 if action is None:42 action = 'store'43
27 unmodified lines
71 self._short_opt = {}72 self._long_opt = {}73 self._arg_dest = []74 self._nargs = []75 self._opt_prefixes = set(['-', '--'])7677 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] = option
20 unmodified lines
104105 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 lines
204 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 += 1213214 if not option:
31 unmodified lines
added:tests/test_options.py+19 added
1# -*- coding: utf-8 -*-2import re3import click456def 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))1213 result = runner.invoke(cli, ['++foo', '--bar'])14 assert not result.exception15 assert result.output == 'foo=True bar=True\n'1617 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