Implemented nesting below chain commands.
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 e68766c · Browse files · 4 files·+81 added−37 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+81 added−37 removed
- tests:+38 added−6 removed
- other:+43 added−31 removed
Provenance
- Commit
0a2919f- Tree
304f3bd- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
e68766c
4 files changed+81 added−37 removed
modified:click/core.py+19 added-28 removed
35 unmodified lines36 if bashcomplete(cmd, prog_name, complete_var, complete_instr):37 sys.exit(1)38 39 40-def _check_multicommand(base_command, cmd_name, cmd, register=False):41- if not base_command.chain or not isinstance(cmd, MultiCommand):42- return43- if register:44- hint = 'It is not possible to add multi commands as children to ' \45- 'another multi command that is in chain mode'46- else:47- hint = 'Found a multi command as subcommand to a multi command ' \48- 'that is in chain mode. This is not supported'49- raise RuntimeError('%s. Command "%s" is set to chain and "%s" was '50- 'added as subcommand but it in itself is a '51- 'multi command. ("%s" is a %s within a chained '52- '%s named "%s")' % (53- hint, base_command.name, cmd_name,54- cmd_name, cmd.__class__.__name__,55- base_command.__class__.__name__,56- base_command.name))57-58-40 def batch(iterable, batch_size):41 return list(zip(*repeat(iter(iterable), batch_size)))42 43 142 unmodified lines186 #: case it's not remembered.187 self.params = {}188 #: the leftover arguments.189 self.args = []190+ #: protected arguments. These are arguments that are prepended191+ #: to `args` when certain parsing scenarios are encountered but192+ #: must be never propagated to another arguments. This is used193+ #: to implement nested parsing.194+ self.protected_args = []195 if obj is None and parent is not None:196 obj = parent.obj197 #: the user object stored.198 self.obj = obj787 unmodified lines986 def parse_args(self, ctx, args):987 if not args and self.no_args_is_help and not ctx.resilient_parsing:988 echo(ctx.get_help(), color=ctx.color)989 ctx.exit()1004- return Command.parse_args(self, ctx, args)990 991+ rest = Command.parse_args(self, ctx, args)992+ if self.chain:993+ ctx.protected_args = rest994+ ctx.args = []995+ elif rest:996+ ctx.protected_args, ctx.args = rest[:1], rest[1:]997+998+ return ctx.args999+1000 def invoke(self, ctx):1001 def _process_result(value):1002 if self.result_callback is not None:1003 value = ctx.invoke(self.result_callback, value,1004 **ctx.params)1005 return value1006 1013- if not ctx.args:1007+ if not ctx.protected_args:1008 # If we are invoked without command the chain flag controls1009 # how this happens. If we are not in chain mode, the return1010 # value here is the return value of the command.1011 # If however we are in chain mode, the return value is the6 unmodified lines1018 Command.invoke(self, ctx)1019 return _process_result([])1020 ctx.fail('Missing command.')1021 1028- args = ctx.args1022+ # Fetch args back out1023+ args = ctx.protected_args + ctx.args1024+ ctx.args = []1025+ ctx.protected_args = []1026 1027 # If we're not in chain mode, we only allow the invocation of a1028 # single command but we also inform the current context about the1029 # name of the command to invoke.13 unmodified lines1043 # know the subcommands yet, the invoked subcommand attribute is1044 # set to ``*`` to inform the command that subcommands are executed1045 # but nothing else.1046 with ctx:1050- # The master command does not receive any arguments. That1051- # would be silly.1052- ctx.args = []1047 ctx.invoked_subcommand = args and '*' or None1048 Command.invoke(self, ctx)1049 1050 # Otherwise we make every single context and invoke them in a71 unmodified lines1122 """1123 name = name or cmd.name1124 if name is None:1125 raise TypeError('Command has no name.')1132- _check_multicommand(self, name, cmd, register=True)1126 self.commands[name] = cmd1127 1128 def command(self, *args, **kwargs):1129 """A shortcut decorator for declaring and attaching a command to44 unmodified lines1174 1175 def get_command(self, ctx, cmd_name):1176 for source in self.sources:1177 rv = source.get_command(ctx, cmd_name)1185- if self.chain:1186- _check_multicommand(self, cmd_name, rv)1178 if rv is not None:1179 return rv1180 1181 def list_commands(self, ctx):533 unmodified linesmodified:docs/commands.rst+22 added
320 unmodified lines321 subcommands happens one after another so the exact subcommands that will322 be handled are not yet available when the callback fires.323 324 325+Nested Group Commands with Chaining326+-----------------------------------327+328+.. versionadded:: 6.0329+330+Before Click 6 it was not possible for chain commands to be nested as331+behavior was not entirely defined. In Click 6 this has been corrected332+and group commands can now be nested below chain commands. The following333+logic applies as a result:334+335+* if a chain command is used below a chain command it will not be336+ possible for the outer command to accept any more arguments with the337+ start of the sub command. This is done in order to ensure that338+ commands do not change behavior when nested below other commands.339+* Click now internally has the concept of protected arguments which is340+ what is used to ensure nested parsing does not accidentally mix341+ rest arguments intended for the callbacks with leftover arguments for342+ parsing. This change has cleaned up some accidental bugs in the past343+ where the context showed arguments that were not actually intended for344+ the command.345+346+347 Multi Command Pipelines348 -----------------------349 350 .. versionadded:: 3.0225 unmodified linesmodified:tests/test_chain.py+38 added-6 removed
1 unmodified line2 import click3 import pytest4 5 6+def debug():7+ click.echo('%s=%s' % (8+ sys._getframe(1).f_code.co_name,9+ '|'.join(click.get_current_context().args),10+ ))11+12+13 def test_basic_chaining(runner):14 @click.group(chain=True)15 def cli():16 pass146 unmodified lines163 ]164 165 166 def test_args_and_chain(runner):160- def debug():161- click.echo('%s=%s' % (162- sys._getframe(1).f_code.co_name,163- '|'.join(click.get_current_context().args),164- ))165-167 @click.group(chain=True)168 def cli():169 debug()170 46 unmodified lines217 assert result.output.splitlines() == [218 'cli:foo',219 'a',220 ]221+222+223+def test_multicommand_chaining(runner):224+ @click.group(chain=True)225+ def cli():226+ debug()227+228+ @cli.group()229+ def l1a():230+ debug()231+232+ @l1a.command()233+ def l2a():234+ debug()235+236+ @l1a.command()237+ def l2b():238+ debug()239+240+ @cli.command()241+ def l1b():242+ debug()243+244+ result = runner.invoke(cli, ['l1a', 'l2a', 'l1b'])245+ assert not result.exception246+ assert result.output.splitlines() == [247+ 'cli=',248+ 'l1a=',249+ 'l2a=',250+ 'l1b=',251+ ]modified:CHANGES+2 added-3 removed
8 unmodified lines9 (codename and release date to be decided)10 11 - Optimized the progressbar rendering to not render when it did not12 actually change.13-- Actively reject multi commands within chained multi commands. This14- cannot be supported with the current setup of how the invocation for15- subcommands works.13 - Explicitly disallow nargs=-1 with a set default.14 - The context is now closed before it's popped from the stack.15 - Added support for short aliases for the false flag on toggles.16 - Click will now attempt to aid you with debugging locale errors19 unmodified lines36 - Multi commands in chain mode no longer propagate arguments left over37 from parsing to the callbacks. It's also now disallowed through an38 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 43 Version 5.144 -----------45 251 unmodified lines