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
Provenance
- Commit
2e8354a- Tree
4033f38- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
db9a9c2
5 files changed+145 added−62 removed
modified:click/core.py+9 added-31 removed
692 unmodified lines693 694 def add_to_parser(self, parser, ctx):695 pass696 697+ 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 value702+703 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 lines738 return rv739 else:740 return os.environ.get(self.envvar)741 736- def consume_value(self, ctx, opts, args):737- return None, args738-742 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 lines967 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)970 968- 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, args971 974-972 class 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 lines1005 1006 def get_usage_pieces(self, ctx):1007 return [self.make_metavar()]1008 1012- 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)1011 1012 1013 # Circular dependency between decorators and core1014 from .decorators import command, group, help_optionmodified:click/parser.py+19 added-23 removed
14 unmodified lines15 generated and optparse in the stdlib uses gettext for no good reason16 and might cause us issues.17 """18 from .exceptions import UsageError19+from .utils import unpack_args20 21 22 class Option(object):23 ATTRS = ['action', 'type', 'dest', 'nargs', 'const']49 unmodified lines73 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 = []79 80 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')89-90- 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] = option86 96- return option87+ def add_argument(self, dest, nargs=1):88+ self._arg_dest.append(dest)89+ self._nargs.append(nargs)90 98- 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 = []95 106- 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)98 108- args = largs + rargs99 return opts, args100 111- 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 args106+107+ 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 the136 unmodified linesmodified:click/utils.py+60 added-1 removed
1 import sys2 import codecs3+from collections import deque4 4-from ._compat import PY2, text_type5+from ._compat import text_type6 7 8+def 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.12+13+ 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.15+16+ Missing items are filled with `None`.17+18+ Examples:19+20+ >>> 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 = None33+34+ def _fetch(c):35+ try:36+ return (spos is not None and c.pop() or c.popleft())37+ except IndexError:38+ return None39+40+ 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)56+57+ # 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 = []62+63+ return rv, list(args)64+65+66 def safecall(func):67 """Wraps a function so that it swallows exceptions."""68 def wrapper(*args, **kwargs):69 try:55 unmodified linesmodified:docs/arguments.rst+8 added-7 removed
36 unmodified lines37 unlimited) number of arguments is accepted. This can be controlled with38 the ``nargs`` parameter. If it's set to ``-1`` then an unlimited number39 of arguments is accepted.40 41-The value is then passed as a tuple. Note that only one argument really42-can be set to ``nargs=-1`` and right now only the last.41+The value is then passed as a tuple. Note that only one argument can be42+set to ``nargs=-1`` as this will eat up all arguments.43 44 Example:45 46 .. click:example::47 48 @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))54 55 And what it looks like:56 57 .. click:run::58 58- invoke(touch, args=['foo.txt', 'bar.txt'])59+ invoke(touch, args=['foo.txt', 'bar.txt', 'my_folder'])60 61 .. _file-args:62 63 File Arguments64 unmodified linesadded:tests/test_arguments.py+49 added
1+# -*- coding: utf-8 -*-2+import click3+4+5+def 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)12+13+ 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+ ]19+20+21+def 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)28+29+ result = runner.invoke(copy, ['peter', '1', '2'])30+ assert not result.exception31+ assert result.output.splitlines() == [32+ 'name=peter',33+ 'point=1/2',34+ ]35+36+37+def test_nargs_err(runner):38+ @click.command()39+ @click.argument('x')40+ def copy(x):41+ click.echo(x)42+43+ result = runner.invoke(copy, ['foo'])44+ assert not result.exception45+ assert result.output == 'foo\n'46+47+ result = runner.invoke(copy, ['foo', 'bar'])48+ assert result.exit_code == 249+ assert 'Got unexpected extra argument (bar)' in result.output