Skip to content
Myr

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

6 files+107 added−78 removed

modified:click/__init__.py+4 added-2 removed
39 unmodified lines
40 pause4142# Exceptions43from .exceptions import ClickException, UsageError, BadParameter, \44 FileError, Abort, NoSuchOption, BadOptionUsage, MissingParameter44 FileError, Abort, NoSuchOption, BadOptionUsage, BadArgumentUsage, \45 MissingParameter4647# Formatting48from .formatting import HelpFormatter, wrap_text49
28 unmodified lines
78 'getchar', 'pause',7980 # Exceptions81 'ClickException', 'UsageError', 'BadParameter', 'FileError',81 'Abort', 'NoSuchOption', 'BadOptionUsage', 'MissingParameter',82 'Abort', 'NoSuchOption', 'BadOptionUsage', 'BadArgumentUsage',83 'MissingParameter',8485 # Formatting86 'HelpFormatter', 'wrap_text',87
11 unmodified lines
modified:click/exceptions.py+13 added-1 removed
163 unmodified lines
164165 .. versionadded:: 4.0166 """167168 def __init__(self, option_name, message, ctx=None):168 def __init__(self, message, ctx=None):169 UsageError.__init__(self, message, ctx)170171172class 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.176177 .. versionadded:: 6.0178 """179180 def __init__(self, message, ctx=None):181 UsageError.__init__(self, message, ctx)182183184class FileError(ClickException):185 """Raised if a file cannot be opened."""186187 def __init__(self, filename, hint=None):
13 unmodified lines
modified:click/parser.py+69 added-10 removed
14 unmodified lines
15 generated and optparse in the stdlib uses gettext for no good reason16 and might cause us issues.17"""18import re19from .exceptions import UsageError, NoSuchOption, BadOptionUsage20from .utils import unpack_args19from collections import deque20from .exceptions import UsageError, NoSuchOption, BadOptionUsage, \21 BadArgumentUsage222324def _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.2829 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.3132 Missing items are filled with `None`.33 """34 args = deque(args)35 nargs_spec = deque(nargs_spec)36 rv = []37 spos = None3839 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 None4748 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)6465 # 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:])7172 return tuple(rv), list(args)737423def _error_args(nargs, opt):75def _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))798081def split_opt(opt):82 first = opt[:1]
84 unmodified lines
167 self.nargs = nargs168 self.obj = obj169170 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)180181
89 unmodified lines
271 raise272 return state.opts, state.largs, state.order273274 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])277278 for idx, arg in enumerate(self._args):279 arg.process(pargs[idx], state)280
52 unmodified lines
333 state.rargs.insert(0, explicit_value)334335 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]343344 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)346347 else:348 value = None349
23 unmodified lines
373 stop = True374375 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 lines
modified:click/utils.py-65 removed
1import os2import sys3from collections import deque34from .globals import resolve_color_default56from ._compat import text_type, open_stream, get_filesystem_encoding, \
14 unmodified lines
21def _posixify(name):22 return '-'.join(name.split()).lower()232426def 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.3031 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.3334 Missing items are filled with `None`.3536 Examples:3738 >>> 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 = None5354 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 None6263 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)7980 # 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:])8687 return tuple(rv), list(args)888925def safecall(func):26 """Wraps a function so that it swallows exceptions."""27 def wrapper(*args, **kwargs):28 try:
387 unmodified lines
modified:tests/test_arguments.py+18 added
256 unmodified lines
257 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 ]261262263def 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)269270 result = runner.invoke(cmd, [])271 assert result.output.strip() == '3'272273 result = runner.invoke(cmd, ['3', '4'])274 assert result.output.strip() == '7'275276 result = runner.invoke(cmd, ['3'])277 assert result.exception is not None278 assert 'argument a takes 2 values' in result.output
modified:CHANGES+3 added
37 unmodified lines
38 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.4546Version 5.147-----------48
251 unmodified lines