Added strong support for a defined parameter callback evaluation order.
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 0b08568 · Browse files · 5 files·+220 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
5 files+220 added−78 removed
- tests:+45 added−0 removed
- other:+175 added−78 removed
Provenance
- Commit
5381d65- Tree
e3e7329- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
0b08568
5 files changed+220 added−78 removed
modified:click/core.py+24 added-24 removed
13 unmodified lines14 15 _missing = object()16 17 18+def iter_params_for_processing(invocation_order, declaration_order):19+ """Given a sequence of parameters in the order as should be considered20+ for processing and an iterable of parameters that exist, this returns21+ a list in the correct order as they should be processed.22+ """23+ def sort_key(item):24+ try:25+ idx = invocation_order.index(item)26+ except ValueError:27+ idx = float('inf')28+ return (not item.is_eager, idx)29+30+ return sorted(declaration_order, key=sort_key)31+32+33 class Context(object):34 """The context is a special internal object that holds state relevant35 for the script execution at every single level. It's normally invisible36 to commands unless they opt-in to getting access to it.205 unmodified lines242 # might not have a callback.243 if not isinstance(cmd, Command):244 raise TypeError('Callback is not a command.')245 231- for param_name in cmd.iter_param_names():232- if param_name in self.params and \233- param_name not in kwargs:234- kwargs[param_name] = self.params[param_name]246+ for param in self.params:247+ if param.name in self.params and \248+ param.name not in kwargs:249+ kwargs[param.name] = self.params[param.name]250 251 return self.invoke(cmd, **kwargs)252 253 43 unmodified lines297 def add_help_option(self):298 """Adds a help option to the command."""299 help_option()(self)300 286- def iter_params_for_processing(self):287- """This returns an iterator over all attached parameters in the288- order of processing. This iterator returns all eager parameters289- first, followed by all non-eager parameters.290- """291- for param in self.params:292- if param.is_eager:293- yield param294- for param in self.params:295- if not param.is_eager:296- yield param297-298- def iter_param_names(self):299- """Iterates over all parameter names."""300- for param in self.iter_params_for_processing():301- yield param.name302-301 def make_parser(self, ctx):302 """Creates the underlying option parser for this command."""303 parser = OptionParser(ctx)304 for param in self.params:86 unmodified lines391 default_map = parent.default_map.get(info_name)392 extra['default_map'] = default_map393 ctx = Context(self, info_name=info_name, parent=parent, **extra)394 parser = self.make_parser(ctx)397- opts, args = parser.parse_args(args=args)395+ opts, args, param_order = parser.parse_args(args=args)396 399- for param in ctx.command.iter_params_for_processing():397+ for param in iter_params_for_processing(param_order, self.params):398 value, args = param.handle_parse_result(ctx, opts, args)399 400 if args and not self.allow_extra_args:401 ctx.fail('Got unexpected extra argument%s (%s)'531 unmodified lines933 def add_to_parser(self, parser, ctx):934 kwargs = {935 'dest': self.name,936 'nargs': self.nargs,937+ 'obj': self,938 }939 940 if self.multiple:941 action = 'append'129 unmodified lines1071 def get_usage_pieces(self, ctx):1072 return [self.make_metavar()]1073 1074 def add_to_parser(self, parser, ctx):1076- parser.add_argument(dest=self.name, nargs=self.nargs)1075+ parser.add_argument(dest=self.name, nargs=self.nargs,1076+ obj=self)1077 1078 1079 # Circular dependency between decorators and core1080 from .decorators import command, group, help_optionmodified:click/parser.py+89 added-53 removed
28 unmodified lines29 30 31 class Option(object):32 33- def __init__(self, opts, dest, action=None, nargs=1, const=None):33+ def __init__(self, opts, dest, action=None, nargs=1, const=None, obj=None):34 self._short_opts = []35 self._long_opts = []36 self.prefixes = set()37 15 unmodified lines53 self.dest = dest54 self.action = action55 self.nargs = nargs56 self.const = const57+ self.obj = obj58 59 @property60 def takes_value(self):61 return self.action in ('store', 'append')62 62- def process(self, opt, value, opts, parser):63+ def process(self, value, state):64 if self.action == 'store':64- opts[self.dest] = value65+ state.opts[self.dest] = value66 elif self.action == 'store_const':66- opts[self.dest] = self.const67+ state.opts[self.dest] = self.const68 elif self.action == 'append':68- opts.setdefault(self.dest, []).append(value)69+ state.opts.setdefault(self.dest, []).append(value)70 elif self.action == 'append_const':70- opts.setdefault(self.dest, []).append(self.const)71+ state.opts.setdefault(self.dest, []).append(self.const)72 elif self.action == 'count':72- opts[self.dest] = opts.get(self.dest, 0) + 173+ state.opts[self.dest] = state.opts.get(self.dest, 0) + 174 else:75 raise ValueError('unknown action %r' % self.action)76+ state.order.append(self.obj)77 78 79+class Argument(object):80+81+ def __init__(self, dest, nargs=1, obj=None):82+ self.dest = dest83+ self.nargs = nargs84+ self.obj = obj85+86+ def process(self, value, state):87+ state.opts[self.dest] = value88+ state.order.append(self.obj)89+90+91+class ParsingState(object):92+93+ def __init__(self, rargs):94+ self.opts = {}95+ self.largs = []96+ self.rargs = rargs97+ self.order = []98+99+100 class OptionParser(object):101 """The option parser is an internal class that is ultimately used to102 parse options and arguments. It's modelled after optparse and brings103 a similar but vastly simplified API. It should generally not be used17 unmodified lines121 #: safely.122 self.allow_interspersed_args = True123 self._short_opt = {}124 self._long_opt = {}102- self._arg_dest = []103- self._nargs = []125 self._opt_prefixes = set(['-', '--'])126+ self._args = []127 106- def add_option(self, opts, dest, action=None, nargs=1, const=None):128+ def add_option(self, opts, dest, action=None, nargs=1, const=None,129+ obj=None):130 """Adds a new option named `dest` to the parser. The destination131 is not inferred unlike with optparse and needs to be explicitly132 provided. Action can be any of ``store``, ``store_const``,133 ``append``, ``appnd_const`` or ``count``.134+135+ The `obj` can be used to identify the option in the order list136+ that is returned from the parser.137 """138+ if obj is None:139+ obj = dest112- option = Option(opts, dest, action=action, nargs=nargs, const=const)140+ option = Option(opts, dest, action=action, nargs=nargs,141+ const=const, obj=obj)142 self._opt_prefixes.update(option.prefixes)143 for opt in option._short_opts:144 self._short_opt[opt] = option145 for opt in option._long_opts:146 self._long_opt[opt] = option147 119- def add_argument(self, dest, nargs=1):120- """Adds a positional argument named `dest` to the parser."""121- self._arg_dest.append(dest)122- self._nargs.append(nargs)148+ def add_argument(self, dest, nargs=1, obj=None):149+ """Adds a positional argument named `dest` to the parser.150 151+ The `obj` can be used to identify the option in the order list152+ that is returned from the parser.153+ """154+ if obj is None:155+ obj = dest156+ self._args.append(Argument(dest=dest, nargs=nargs, obj=obj))157+158 def parse_args(self, args):125- """Parses positional arguments and returns ``(values, args)`` for126- the parsed options and arguments as well as the leftover arguments127- if there are any.159+ """Parses positional arguments and returns ``(values, args, order)``160+ for the parsed options and arguments as well as the leftover161+ arguments if there are any. The order is a list of objects as they162+ appear on the command line. If arguments appear multiple times they163+ will be memorized multiple times as well.164 """129- rargs = args130- opts = {}131- largs = []165+ state = ParsingState(args)166+ self._process_args_for_options(state)167+ self._process_args_for_args(state)168+ return state.opts, state.largs, state.order169 133- self._process_args_for_options(largs, rargs, opts)134- args = self._process_args_for_args(largs, rargs, opts)170+ def _process_args_for_args(self, state):171+ pargs, args = unpack_args(state.largs + state.rargs,172+ [x.nargs for x in self._args])173 136- return opts, args174+ for idx, arg in enumerate(self._args):175+ arg.process(pargs[idx], state)176 138- def _process_args_for_args(self, largs, rargs, opts):139- pargs, args = unpack_args(largs + rargs, self._nargs)140- for idx, arg_name in enumerate(self._arg_dest):141- opts[arg_name] = pargs[idx]142- return args177+ state.largs = args178+ state.rargs = []179 144- def _process_args_for_options(self, largs, rargs, opts):145- while rargs:146- arg = rargs[0]180+ def _process_args_for_options(self, state):181+ while state.rargs:182+ arg = state.rargs[0]183 # Double dash es always handled explicitly regardless of what184 # prefixes are valid.185 if arg == '--':150- del rargs[0]186+ del state.rargs[0]187 return188 elif arg[0:2] in self._opt_prefixes:189 # process a single long option (possibly with value(s))154- self._process_long_opt(rargs, opts)190+ self._process_long_opt(state)191 elif arg[:1] in self._opt_prefixes and len(arg) > 1:192 # process a cluster of short options (possibly with193 # value(s) for the last one only)158- self._process_short_opts(rargs, opts)194+ self._process_short_opts(state)195 elif self.allow_interspersed_args:160- largs.append(arg)161- del rargs[0]196+ state.largs.append(arg)197+ del state.rargs[0]198 else:199 return200 201 # Say this is the original argument list:37 unmodified lines239 possibilities.sort()240 self._error('no such option: %s. (Possible options: %s)'241 % (opt, ', '.join(possibilities)))242 207- def _process_long_opt(self, rargs, opts):208- arg = rargs.pop(0)243+ def _process_long_opt(self, state):244+ arg = state.rargs.pop(0)245 246 # Value explicitly attached to arg? Pretend it's the next247 # argument.248 if '=' in arg:249 opt, next_arg = arg.split('=', 1)214- rargs.insert(0, next_arg)250+ state.rargs.insert(0, next_arg)251 had_explicit_value = True252 else:253 opt = arg254 had_explicit_value = False1 unmodified line256 opt = self._match_long_opt(opt)257 option = self._long_opt[opt]258 if option.takes_value:259 nargs = option.nargs224- if len(rargs) < nargs:260+ if len(state.rargs) < nargs:261 if nargs == 1:262 self._error('%s option requires an argument' % opt)263 else:264 self._error('%s option requires %d arguments' % (opt, nargs))265 elif nargs == 1:230- value = rargs.pop(0)266+ value = state.rargs.pop(0)267 else:232- value = tuple(rargs[:nargs])233- del rargs[:nargs]268+ value = tuple(state.rargs[:nargs])269+ del state.rargs[:nargs]270 271 elif had_explicit_value:272 self._error('%s option does not take a value' % opt)273 274 else:275 value = None276 241- option.process(opt, value, opts, self)277+ option.process(value, state)278 243- def _process_short_opts(self, rargs, opts):244- arg = rargs.pop(0)279+ def _process_short_opts(self, state):280+ arg = state.rargs.pop(0)281 stop = False282 i = 1283 prefix = arg[0]284 for ch in arg[1:]:6 unmodified lines291 if option.takes_value:292 # Any characters left in arg? Pretend they're the293 # next arg, and stop consuming characters of arg.294 if i < len(arg):259- rargs.insert(0, arg[i:])295+ state.rargs.insert(0, arg[i:])296 stop = True297 298 nargs = option.nargs263- if len(rargs) < nargs:299+ if len(state.rargs) < nargs:300 if nargs == 1:301 self._error('%s option requires an argument' % opt)302 else:303 self._error('%s option requires %d arguments' %304 (opt, nargs))305 elif nargs == 1:270- value = rargs.pop(0)306+ value = state.rargs.pop(0)307 else:272- value = tuple(rargs[:nargs])273- del rargs[:nargs]308+ value = tuple(state.rargs[:nargs])309+ del state.rargs[:nargs]310 311 else:312 value = None313 278- option.process(opt, value, opts, self)314+ option.process(value, state)315 316 if stop:317 break318 2 unmodified linesmodified:docs/advanced.rst+60 added
115 unmodified lines116 @click.command()117 def less():118 click.echo_via_pager('\n'.join('Line %d' % idx119 for idx in range(200)))120+121+122+.. _callback-evaluation-order:123+124+Callback Evaluation Order125+-------------------------126+127+Click works a bit different than some other command line parsers in that128+it attempts to reconsiliate the order of arguments as defined by the129+programmer with the order of arguments as defined by the user before130+invoking any callbacks.131+132+This is an important concept to understand when implementing complex133+patterns ported from optparse or other systems to click. A parameter134+callback invocation in optparse happens as part of the parsing step135+whereas a callback invocation in click happens after the parsing.136+137+The main difference is that in optparse callbacks are invoked with the raw138+value as it happens whereas a callback in click is invoked after the value139+as fully converted.140+141+Generally the order of invocation is driven by the order in which the user142+provides the arguments to the script. So if there is an option called143+``--foo`` and an option called ``--bar`` and the user calls it as ``--bar144+--foo`` then the callback for ``bar`` will fire before the one of ``foo``.145+146+There are two exceptions to this rule which are important to know:147+148+Eagerness:149+ An option can be set to be "eager". All eager parameters are150+ evaluated before all non-eager parameters, but again in the order as151+ they were provided on the command line by the user.152+153+ This is important for parameters that execute and exit like ``--help``154+ and ``--version``. Both are eager parameters but whatever paramter155+ comes first on the command line will win and exit the program.156+157+Repeated parameters:158+ If an option or argument is split up on the command line into multiple159+ places because it's repeated (for instance ``--exclude foo --include160+ baz --exclude bar``) the callback will fire based on the position of161+ the first option. So in this case the callback will fire for162+ ``exclude`` and it will be passed both options (``foo`` and163+ ``bar``), then the callback for ``include`` will fire with ``baz``164+ only.165+166+ Note that even if an parameter does not allow multiple versions click167+ will still accept the position of the first, but it will ignore every168+ value with the exception of the first. The reason for this is to169+ allow composability through shell aliases that set defaults.170+171+Missing parameters:172+ If an parameter is not defined on the command line the callback will173+ still fire. This is different from how it works in optparse where174+ not defined values do not fire the callback. Missing parameters fire175+ their callbacks at the very end which makes it possible for them to176+ default to values from a parameter that came before.177+178+Most of the time you don't need to be concerned about any of this stuff,179+but it's important to know how it works for some advanced cases.modified:docs/options.rst+2 added-1 removed
288 unmodified lines289 callback is what executes after the parameter is handled. The eagerness290 is necessary so that an earlier required parameter does not produce an291 error message. For instance if ``--version`` was not eager and a292 parameter ``--foo`` was required and defined before, you would need to293-specify it for ``--version`` to work.293+specify it for ``--version`` to work. For more information see294+:ref:`callback-evaluation-order`.295 296 A callback is a function that is invoked with two parameters: the current297 :class:`Context` and the value. The context provides some useful features298 such as quitting the application and gives access to other already192 unmodified linesmodified:tests/test_basic.py+45 added
290 unmodified lines291 292 result = runner.invoke(cli, [])293 assert result.exit_code == 2294 assert 'Missing option "--foo"' in result.output295+296+297+def test_evaluation_order(runner):298+ called = []299+300+ def memo(ctx, value):301+ called.append(value)302+ return value303+304+ @click.command()305+ @click.option('--missing', default='missing',306+ is_eager=False, callback=memo)307+ @click.option('--eager-flag1', flag_value='eager1',308+ is_eager=True, callback=memo)309+ @click.option('--eager-flag2', flag_value='eager2',310+ is_eager=True, callback=memo)311+ @click.option('--eager-flag3', flag_value='eager3',312+ is_eager=True, callback=memo)313+ @click.option('--normal-flag1', flag_value='normal1',314+ is_eager=False, callback=memo)315+ @click.option('--normal-flag2', flag_value='normal2',316+ is_eager=False, callback=memo)317+ @click.option('--normal-flag3', flag_value='normal3',318+ is_eager=False, callback=memo)319+ def cli(**x):320+ pass321+322+ result = runner.invoke(cli, ['--eager-flag2',323+ '--eager-flag1',324+ '--normal-flag2',325+ '--eager-flag3',326+ '--normal-flag3',327+ '--normal-flag3',328+ '--normal-flag1',329+ '--normal-flag1'])330+ assert not result.exception331+ assert called == [332+ 'eager2',333+ 'eager1',334+ 'eager3',335+ 'normal2',336+ 'normal3',337+ 'normal1',338+ 'missing',339+ ]