Skip to content
Myr

Added support for nargs in other places

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 db9a9c2 · Browse files · 5 files+145 added−62 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+145 added−62 removed

  • tests:+49 added−0 removed
  • other:+96 added−62 removed

5 files+145 added−62 removed

modified:click/core.py+9 added-31 removed
692 unmodified lines
693694 def add_to_parser(self, parser, ctx):695 pass696697 def consume_value(self, ctx, opts):698 value = opts.get(self.name)699 if value is None:700 value = self.value_from_envvar(ctx)701 return value702703 def process_value(self, ctx, value):704 """Given a value and context this runs the logic to convert the705 value as necessary.706 """
31 unmodified lines
738 return rv739 else:740 return os.environ.get(self.envvar)741736 def consume_value(self, ctx, opts, args):737 return None, args738742 def handle_parse_result(self, ctx, opts, args):740 value, args = self.consume_value(ctx, opts, args)743 value = self.consume_value(ctx, opts)744 value = self.full_process_value(ctx, value)745 if self.callback is not None:746 value = self.callback(ctx, value)747 if self.expose_value:
219 unmodified lines
967 if value is None and self.prompt is not None:968 return self.prompt_for_value(ctx)969 return Parameter.full_process_value(self, ctx, value)970968 def consume_value(self, ctx, opts, args):969 value = opts.get(self.name)970 if value is None:971 value = self.value_from_envvar(ctx)972 return value, args971974972class Argument(Parameter):973 """Arguments are positional parameters to a command. They generally974 provide fewer features than options but can have infinite ``nargs``975 and are required by default.
29 unmodified lines
10051006 def get_usage_pieces(self, ctx):1007 return [self.make_metavar()]10081012 def consume_value(self, ctx, opts, args):1013 found = True1014 if self.nargs == 1:1015 try:1016 value = args.pop(0)1017 except IndexError:1018 found = False1019 elif self.nargs < 0:1020 value = tuple(args)1021 found = value1022 args = []1023 else:1024 values = args[:self.nargs]1025 args = args[self.nargs:]1026 value = tuple(values)1027 found = value1028 if not found:1029 value = self.value_from_envvar(ctx)1030 if self.nargs != 1:1031 value = value and (value,) or ()1032 return value, args1009 def add_to_parser(self, parser, ctx):1010 parser.add_argument(dest=self.name, nargs=self.nargs)101110121013# Circular dependency between decorators and core1014from .decorators import command, group, help_option
modified:click/parser.py+19 added-23 removed
14 unmodified lines
15 generated and optparse in the stdlib uses gettext for no good reason16 and might cause us issues.17"""18from .exceptions import UsageError19from .utils import unpack_args202122class Option(object):23 ATTRS = ['action', 'type', 'dest', 'nargs', 'const']
49 unmodified lines
73 self.ctx = ctx74 self.allow_interspersed_args = True75 self._short_opt = {}76 self._long_opt = {}76 self.rargs = None77 self.largs = None78 self.opts = None77 self._arg_dest = []78 self._nargs = []7980 def add_option(self, *args, **kwargs):81 if isinstance(args[0], str):82 option = Option(*args, **kwargs)81 option = Option(*args, **kwargs)83 elif len(args) == 1 and not kwargs:84 option = args[0]85 if not isinstance(option, Option):86 raise TypeError('not an Option instance: %r' % option)87 else:88 raise TypeError('invalid arguments')8990 option.container = self82 for opt in option._short_opts:83 self._short_opt[opt] = option84 for opt in option._long_opts:85 self._long_opt[opt] = option8696 return option87 def add_argument(self, dest, nargs=1):88 self._arg_dest.append(dest)89 self._nargs.append(nargs)9098 def parse_args(self, args, opts=None):91 def parse_args(self, args):92 rargs = args100 if opts is None:101 opts = {}102 self.rargs = rargs103 self.largs = largs = []104 self.opts = opts93 opts = {}94 largs = []95106 self._process_args(largs, rargs, opts)96 self._process_args_for_options(largs, rargs, opts)97 args = self._process_args_for_args(largs, rargs, opts)98108 args = largs + rargs99 return opts, args100111 def _process_args(self, largs, rargs, opts):101 def _process_args_for_args(self, largs, rargs, opts):102 pargs, args = unpack_args(largs + rargs, self._nargs)103 for idx, arg_name in enumerate(self._arg_dest):104 opts[arg_name] = pargs[idx]105 return args106107 def _process_args_for_options(self, largs, rargs, opts):108 while rargs:109 arg = rargs[0]110 # We handle bare '--' explicitly, and bare '-' is handled by the111 # standard arg handler since the short arg case ensures that the
136 unmodified lines
modified:click/utils.py+60 added-1 removed
1import sys2import codecs3from collections import deque44from ._compat import PY2, text_type5from ._compat import text_type678def unpack_args(args, nargs_spec):9 """Given an iterable of arguments and an iterable of nargs specifications10 it returns a tuple with all the unpacked arguments at the first index11 and all remaining arguments as the second.1213 The nargs specification is the number of arguments that should be consumed14 or `-1` to indicate that this position should eat up all the remainders.1516 Missing items are filled with `None`.1718 Examples:1920 >>> unpack_args(range(6), [1, 2, 1, -1])21 ((0, (1, 2), 3, (4, 5)), [])22 >>> unpack_args(range(6), [1, 2, 1])23 ((0, (1, 2), 3), [4, 5])24 >>> unpack_args(range(6), [-1])25 (((0, 1, 2, 3, 4, 5),), [])26 >>> unpack_args(range(6), [1, 1])27 ((0, 1), [2, 3, 4, 5])28 """29 args = deque(args)30 nargs_spec = deque(nargs_spec)31 rv = []32 spos = None3334 def _fetch(c):35 try:36 return (spos is not None and c.pop() or c.popleft())37 except IndexError:38 return None3940 while nargs_spec:41 nargs = _fetch(nargs_spec)42 if nargs == 1:43 rv.append(_fetch(args))44 elif nargs > 1:45 x = [_fetch(args) for _ in range(nargs)]46 # If we're reversed we're pulling in the arguments in reverse47 # so we need to turn them around.48 if spos is not None:49 x.reverse()50 rv.append(tuple(x))51 elif nargs < 0:52 if spos is not None:53 raise TypeError('Cannot have two nargs < 0')54 spos = len(rv)55 rv.append(None)5657 # spos is the position of the wildcard (star). If it's not None58 # we fill it with the remainder.59 if spos is not None:60 rv[spos] = tuple(args)61 args = []6263 return rv, list(args)646566def safecall(func):67 """Wraps a function so that it swallows exceptions."""68 def wrapper(*args, **kwargs):69 try:
55 unmodified lines
modified:docs/arguments.rst+8 added-7 removed
36 unmodified lines
37unlimited) number of arguments is accepted. This can be controlled with38the ``nargs`` parameter. If it's set to ``-1`` then an unlimited number39of arguments is accepted.4041The value is then passed as a tuple. Note that only one argument really42can be set to ``nargs=-1`` and right now only the last.41The value is then passed as a tuple. Note that only one argument can be42set to ``nargs=-1`` as this will eat up all arguments.4344Example:4546.. click:example::4748 @click.command()49 @click.argument('files', nargs=-1)50 def touch(files):51 for file in files:52 click.echo(file)49 @click.argument('src', nargs=-1)50 @click.argument('dst', nargs=1)51 def copy(src, dst):52 for fn in src:53 click.echo('move %s to folder %s' % (fn, dst))5455And what it looks like:5657.. click:run::5858 invoke(touch, args=['foo.txt', 'bar.txt'])59 invoke(touch, args=['foo.txt', 'bar.txt', 'my_folder'])6061.. _file-args:6263File Arguments
64 unmodified lines
added:tests/test_arguments.py+49 added
1# -*- coding: utf-8 -*-2import click345def test_nargs_star(runner):6 @click.command()7 @click.argument('src', nargs=-1)8 @click.argument('dst')9 def copy(src, dst):10 click.echo('src=%s' % '|'.join(src))11 click.echo('dst=%s' % dst)1213 result = runner.invoke(copy, ['foo.txt', 'bar.txt', 'dir'])14 assert not result.exception15 assert result.output.splitlines() == [16 'src=foo.txt|bar.txt',17 'dst=dir',18 ]192021def test_nargs_tup(runner):22 @click.command()23 @click.argument('name', nargs=1)24 @click.argument('point', nargs=2, type=click.INT)25 def copy(name, point):26 click.echo('name=%s' % name)27 click.echo('point=%d/%d' % point)2829 result = runner.invoke(copy, ['peter', '1', '2'])30 assert not result.exception31 assert result.output.splitlines() == [32 'name=peter',33 'point=1/2',34 ]353637def test_nargs_err(runner):38 @click.command()39 @click.argument('x')40 def copy(x):41 click.echo(x)4243 result = runner.invoke(copy, ['foo'])44 assert not result.exception45 assert result.output == 'foo\n'4647 result = runner.invoke(copy, ['foo', 'bar'])48 assert result.exit_code == 249 assert 'Got unexpected extra argument (bar)' in result.output