Implemented defaults for args with nargs > 1.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This fixes #463
authored by Armin Ronacher · committed by Armin Ronacher · parent 0a2919f · Browse files · 6 files·+107 added−78 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+107 added−78 removed
- tests:+18 added−0 removed
- other:+89 added−78 removed
Provenance
- Commit
5f98f57- Tree
20f813d- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
0a2919f
6 files changed+107 added−78 removed
modified:click/__init__.py+4 added-2 removed
39 unmodified lines40 pause41 42 # Exceptions43 from .exceptions import ClickException, UsageError, BadParameter, \44- FileError, Abort, NoSuchOption, BadOptionUsage, MissingParameter44+ FileError, Abort, NoSuchOption, BadOptionUsage, BadArgumentUsage, \45+ MissingParameter46 47 # Formatting48 from .formatting import HelpFormatter, wrap_text49 28 unmodified lines78 'getchar', 'pause',79 80 # Exceptions81 'ClickException', 'UsageError', 'BadParameter', 'FileError',81- 'Abort', 'NoSuchOption', 'BadOptionUsage', 'MissingParameter',82+ 'Abort', 'NoSuchOption', 'BadOptionUsage', 'BadArgumentUsage',83+ 'MissingParameter',84 85 # Formatting86 'HelpFormatter', 'wrap_text',87 11 unmodified linesmodified:click/exceptions.py+13 added-1 removed
163 unmodified lines164 165 .. versionadded:: 4.0166 """167 168- def __init__(self, option_name, message, ctx=None):168+ def __init__(self, message, ctx=None):169 UsageError.__init__(self, message, ctx)170 171 172+class BadArgumentUsage(UsageError):173+ """Raised if an argument is generally supplied but the use of the argument174+ was incorrect. This is for instance raised if the number of values175+ for an argument is not correct.176+177+ .. versionadded:: 6.0178+ """179+180+ def __init__(self, message, ctx=None):181+ UsageError.__init__(self, message, ctx)182+183+184 class FileError(ClickException):185 """Raised if a file cannot be opened."""186 187 def __init__(self, filename, hint=None):13 unmodified linesmodified:click/parser.py+69 added-10 removed
14 unmodified lines15 generated and optparse in the stdlib uses gettext for no good reason16 and might cause us issues.17 """18 import re19-from .exceptions import UsageError, NoSuchOption, BadOptionUsage20-from .utils import unpack_args19+from collections import deque20+from .exceptions import UsageError, NoSuchOption, BadOptionUsage, \21+ BadArgumentUsage22 23 24+def _unpack_args(args, nargs_spec):25+ """Given an iterable of arguments and an iterable of nargs specifications,26+ it returns a tuple with all the unpacked arguments at the first index27+ and all remaining arguments as the second.28+29+ The nargs specification is the number of arguments that should be consumed30+ or `-1` to indicate that this position should eat up all the remainders.31+32+ Missing items are filled with `None`.33+ """34+ args = deque(args)35+ nargs_spec = deque(nargs_spec)36+ rv = []37+ spos = None38+39+ def _fetch(c):40+ try:41+ if spos is None:42+ return c.popleft()43+ else:44+ return c.pop()45+ except IndexError:46+ return None47+48+ while nargs_spec:49+ nargs = _fetch(nargs_spec)50+ if nargs == 1:51+ rv.append(_fetch(args))52+ elif nargs > 1:53+ x = [_fetch(args) for _ in range(nargs)]54+ # If we're reversed, we're pulling in the arguments in reverse,55+ # so we need to turn them around.56+ if spos is not None:57+ x.reverse()58+ rv.append(tuple(x))59+ elif nargs < 0:60+ if spos is not None:61+ raise TypeError('Cannot have two nargs < 0')62+ spos = len(rv)63+ rv.append(None)64+65+ # spos is the position of the wildcard (star). If it's not `None`,66+ # we fill it with the remainder.67+ if spos is not None:68+ rv[spos] = tuple(args)69+ args = []70+ rv[spos + 1:] = reversed(rv[spos + 1:])71+72+ return tuple(rv), list(args)73+74+23-def _error_args(nargs, opt):75+def _error_opt_args(nargs, opt):76 if nargs == 1:25- raise BadOptionUsage(opt, '%s option requires an argument' % opt)26- raise BadOptionUsage(opt, '%s option requires %d arguments' % (opt, nargs))77+ raise BadOptionUsage('%s option requires an argument' % opt)78+ raise BadOptionUsage('%s option requires %d arguments' % (opt, nargs))79 80 81 def split_opt(opt):82 first = opt[:1]84 unmodified lines167 self.nargs = nargs168 self.obj = obj169 170 def process(self, value, state):171+ if self.nargs > 1:172+ holes = sum(1 for x in value if x is None)173+ if holes == len(value):174+ value = None175+ elif holes != 0:176+ raise BadArgumentUsage('argument %s takes %d values'177+ % (self.dest, self.nargs))178 state.opts[self.dest] = value179 state.order.append(self.obj)180 181 89 unmodified lines271 raise272 return state.opts, state.largs, state.order273 274 def _process_args_for_args(self, state):216- pargs, args = unpack_args(state.largs + state.rargs,217- [x.nargs for x in self._args])275+ pargs, args = _unpack_args(state.largs + state.rargs,276+ [x.nargs for x in self._args])277 278 for idx, arg in enumerate(self._args):279 arg.process(pargs[idx], state)280 52 unmodified lines333 state.rargs.insert(0, explicit_value)334 335 nargs = option.nargs336 if len(state.rargs) < nargs:278- _error_args(nargs, opt)337+ _error_opt_args(nargs, opt)338 elif nargs == 1:339 value = state.rargs.pop(0)340 else:341 value = tuple(state.rargs[:nargs])342 del state.rargs[:nargs]343 344 elif explicit_value is not None:286- raise BadOptionUsage(opt, '%s option does not take a value' % opt)345+ raise BadOptionUsage('%s option does not take a value' % opt)346 347 else:348 value = None349 23 unmodified lines373 stop = True374 375 nargs = option.nargs376 if len(state.rargs) < nargs:318- _error_args(nargs, opt)377+ _error_opt_args(nargs, opt)378 elif nargs == 1:379 value = state.rargs.pop(0)380 else:381 value = tuple(state.rargs[:nargs])45 unmodified linesmodified:click/utils.py-65 removed
1 import os2 import sys3-from collections import deque3 4 from .globals import resolve_color_default5 6 from ._compat import text_type, open_stream, get_filesystem_encoding, \14 unmodified lines21 def _posixify(name):22 return '-'.join(name.split()).lower()23 24 26-def unpack_args(args, nargs_spec):27- """Given an iterable of arguments and an iterable of nargs specifications,28- it returns a tuple with all the unpacked arguments at the first index29- and all remaining arguments as the second.30-31- The nargs specification is the number of arguments that should be consumed32- or `-1` to indicate that this position should eat up all the remainders.33-34- Missing items are filled with `None`.35-36- Examples:37-38- >>> unpack_args(range(6), [1, 2, 1, -1])39- ((0, (1, 2), 3, (4, 5)), [])40- >>> unpack_args(range(6), [1, 2, 1])41- ((0, (1, 2), 3), [4, 5])42- >>> unpack_args(range(6), [-1])43- (((0, 1, 2, 3, 4, 5),), [])44- >>> unpack_args(range(6), [1, 1])45- ((0, 1), [2, 3, 4, 5])46- >>> unpack_args(range(6), [-1,1,1,1,1])47- (((0, 1), 2, 3, 4, 5), [])48- """49- args = deque(args)50- nargs_spec = deque(nargs_spec)51- rv = []52- spos = None53-54- def _fetch(c):55- try:56- if spos is None:57- return c.popleft()58- else:59- return c.pop()60- except IndexError:61- return None62-63- while nargs_spec:64- nargs = _fetch(nargs_spec)65- if nargs == 1:66- rv.append(_fetch(args))67- elif nargs > 1:68- x = [_fetch(args) for _ in range(nargs)]69- # If we're reversed, we're pulling in the arguments in reverse,70- # so we need to turn them around.71- if spos is not None:72- x.reverse()73- rv.append(tuple(x))74- elif nargs < 0:75- if spos is not None:76- raise TypeError('Cannot have two nargs < 0')77- spos = len(rv)78- rv.append(None)79-80- # spos is the position of the wildcard (star). If it's not `None`,81- # we fill it with the remainder.82- if spos is not None:83- rv[spos] = tuple(args)84- args = []85- rv[spos + 1:] = reversed(rv[spos + 1:])86-87- return tuple(rv), list(args)88-89-25 def safecall(func):26 """Wraps a function so that it swallows exceptions."""27 def wrapper(*args, **kwargs):28 try:387 unmodified linesmodified:tests/test_arguments.py+18 added
256 unmodified lines257 PY2 and "(u'a', u'b', u'c')" or "('a', 'b', 'c')",258 'd',259 PY2 and "(u'e', u'f')" or "('e', 'f')",260 ]261+262+263+def test_defaults_for_nargs(runner):264+ @click.command()265+ @click.argument('a', nargs=2, type=int, default=(1, 2))266+ def cmd(a):267+ x, y = a268+ click.echo(x + y)269+270+ result = runner.invoke(cmd, [])271+ assert result.output.strip() == '3'272+273+ result = runner.invoke(cmd, ['3', '4'])274+ assert result.output.strip() == '7'275+276+ result = runner.invoke(cmd, ['3'])277+ assert result.exception is not None278+ assert 'argument a takes 2 values' in result.outputmodified:CHANGES+3 added
37 unmodified lines38 exception when optional arguments are attached to multi commands if chain39 mode is enabled.40 - Relaxed restriction that disallowed chained commands to have other41 chained commands as child commands.42+- Arguments with positive nargs can now have defaults implemented.43+ Previously this configuration would often result in slightly unexpected44+ values be returned.45 46 Version 5.147 -----------48 251 unmodified lines