Fixed `invoked_subcommand`.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This is actually a very painful commit to make because it has to change behavior. On the bright side, this has actually been broken from 3.1 and people have not noticed much yet, so maybe it's not a big deal. The docs also kinda left out the invoked subcommands bit so I presume it is fine. This fixes #205
authored by Armin Ronacher · committed by Armin Ronacher · parent 04f795c · Browse files · 6 files·+109 added−45 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+109 added−45 removed
- tests:+30 added−2 removed
- other:+79 added−43 removed
Provenance
- Commit
5fc29ba- Tree
0e5b2d9- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
04f795c
6 files changed+109 added−45 removed
modified:click/core.py+43 added-40 removed
171 unmodified lines172 and parent.default_map is not None:173 default_map = parent.default_map.get(info_name)174 self.default_map = default_map175 176- #: This is similar to :attr:`invoked_subcommand` but it holds a177- #: list of multiple subcommand names. This is useful if multi command178- #: chaining is enabled.176+ #: This flag indicates if a subcommand is going to be executed. A177+ #: group callback can use this information to figure out if it's178+ #: being executed directly or because the execution flow passes179+ #: onwards to a subcommand. By default it's None, but it can be180+ #: the name of the subcommand to execute.181 #:180- #: This property and :attr:`invoked_subcommand` are synchronized.181- #:182- #: .. versionadded:: 3.0183- self.invoked_subcommands = []182+ #: If chaining is enabled this will be set to ``'*'`` in case183+ #: any commands are executed. It is however not possible to184+ #: figure out which ones. If you require this knowledge you185+ #: should use a :func:`resultcallback`.186+ self.invoked_subcommand = None187 188 if terminal_width is None and parent is not None:189 terminal_width = parent.terminal_width190 #: The width of the terminal (None is autodetection).59 unmodified lines250 self._depth -= 1251 if self._depth == 0:252 self.close()253 251- def _get_invoked_subcommand(self):252- """This flag indicates if a subcommand is going to be executed. A253- group callback can use this information to figure out if it's254- being executed directly or because the execution flow passes255- onwards to a subcommand. By default it's `None`, but it can be256- the name of the subcommand to execute.254+ def _get_invoked_subcommands(self):255+ from warnings import warn256+ warn(Warning('This API does not work properly and has been largely '257+ 'removed in Click 3.2 to fix a regression the '258+ 'introduction of this API caused. Consult the '259+ 'upgrade documentation for more information. For '260+ 'more information about this see '261+ 'http://click.pocoo.org/upgrading/#upgrading-to-3.2'),262+ stacklevel=2)263+ if self.invoked_subcommand is None:264+ return []265+ return [self.invoked_subcommand]266+ def _set_invoked_subcommands(self, value):267+ self.invoked_subcommand = \268+ len(value) > 1 and '*' or value and value[0] or None269+ invoked_subcommands = property(_get_invoked_subcommands,270+ _set_invoked_subcommands)271+ del _get_invoked_subcommands, _set_invoked_subcommands272 258- If chaining is enabled and more than one subcommand is invoked259- then the value will be the string ``'*'``. For chaining you260- should be using :attr:`invoked_subcommands` instead.261- """262- if len(self.invoked_subcommands) == 1:263- return self.invoked_subcommands[0]264- if len(self.invoked_subcommands) > 1:265- return '*'266- def _set_invoked_subcommand(self, value):267- if value is not None:268- value = [value]269- self.invoked_subcommands = value270- invoked_subcommand = property(_get_invoked_subcommand,271- _set_invoked_subcommand)272- del _get_invoked_subcommand, _set_invoked_subcommand273-273 def make_formatter(self):274 """Creates the formatter for the help and usage output."""275 return HelpFormatter(width=self.terminal_width)276 649 unmodified lines926 if not self.chain:927 # Make sure the context is entered so we do not clean up928 # resources until the result processor has worked.929 with ctx:930+ cmd_name, cmd, args = self.resolve_command(ctx, args)931+ ctx.invoked_subcommand = cmd_name932 Command.invoke(self, ctx)932- sub_ctx = self.handle_subcommand(ctx, args)933- ctx.invoked_subcommands = [sub_ctx.info_name]933+ sub_ctx = cmd.make_context(cmd_name, args, parent=ctx)934 with sub_ctx:935 return _process_result(sub_ctx.command.invoke(sub_ctx))936 937- # Make sure the context is entered so we do not clean up938- # resources until the result processor has worked.937+ # In chain mode we create the contexts step by step, but after the938+ # base command has been invoked. Because at that point we do not939+ # know the subcommands yet, the invoked subcommand attribute is940+ # set to ``*`` to inform the command that subcommands are executed941+ # but nothing else.942 with ctx:943+ ctx.invoked_subcommand = args and '*' or None944 Command.invoke(self, ctx)945 946 # Otherwise we make every single context and invoke them in a947 # chain. In that case the return value to the result processor948 # is the list of all invoked subcommand's results.949 contexts = []950 while args:951+ cmd_name, cmd, args = self.resolve_command(ctx, args)952+ sub_ctx = cmd.make_context(cmd_name, args, parent=ctx,947- sub_ctx = self.handle_subcommand(ctx, args, allow_extra_args=True,948- allow_interspersed_args=False)953+ allow_extra_args=True,954+ allow_interspersed_args=False)955 contexts.append(sub_ctx)956 args = sub_ctx.args957 952- # Now that we have all contexts, we can invoke them.953- ctx.invoked_subcommands = [x.info_name for x in contexts]954-958 rv = []959 for sub_ctx in contexts:960 with sub_ctx:961 rv.append(sub_ctx.command.invoke(sub_ctx))962 return _process_result(rv)963 961- def handle_subcommand(self, ctx, args, **extra):964+ def resolve_command(self, ctx, args):965 cmd_name = make_str(args[0])966 original_cmd_name = cmd_name967 968 # Get the command15 unmodified lines984 if split_opt(cmd_name)[0]:985 self.parse_args(ctx, ctx.args)986 ctx.fail('No such command "%s".' % original_cmd_name)987 985- return cmd.make_context(cmd_name, args[1:], parent=ctx, **extra)988+ return cmd_name, cmd, args[1:]989 990 def get_command(self, ctx, cmd_name):991 """Given a context and a command name, this returns a992 :class:`Command` object if it exists or returns `None`.582 unmodified linesmodified:docs/commands.rst+3 added-3 removed
313 unmodified lines314 normal.315 316 Another note: the :attr:`Context.invoked_subcommand` attribute is a bit317 useless for multi commands as it will give ``'*'`` as value if more than318-one command is invoked. Instead you should be using the319-:attr:`Context.invoked_subcommands` attribute instead which is a list320-(note the trailing "s").318+one command is invoked. This is necessary because the handling of319+subcommands happens one after another so the exact subcommands that will320+be handled are not yet available when the callback fires.321 322 323 Multi Command Pipelines324 -----------------------180 unmodified linesmodified:docs/upgrading.rst+28 added
9 unmodified lines10 11 Upgrading to 3.212 ----------------13 14+Click 3.2 had to perform two changes to multi commands which were15+triggered by a change between Click 2 and Click 3 that had bigger16+consequences than anticipated.17+18+Context Invokes19+```````````````20+21 Click 3.2 contains a fix for the :meth:`Context.invoke` function when used22 with other commands. The original intention of this function was to23 invoke the other command as as if it came from the command line when it24 was passed a context object instead of a function. This use was only15 unmodified lines40 41 This also allowed us to fix the issue that defaults were not handled42 properly by this function.43 44+Multicommand Chaining API45+`````````````````````````46+47+Click 3 introduced multicommand chaning. This required a change in how48+Click internally dispatches. Unfortunately this change was not correctly49+implemented and it appeared that it was possible to provide an API that50+can inform the super command about all the subcommands that will be51+invoked.52+53+This assumption however does not work with one of the API guarantees that54+have been given in the past. As such this functionality has been removed55+in 3.2 as it was already broken. Instead the accidentally broken56+functionality of the :attr:`Context.invoked_subcommand` attribute was57+restored.58+59+If you do require the know which exact commands will be invoked there are60+different ways to cope with this. The first one is to let the subcommands61+all return functions and then to invoke the functions in a62+:meth:`Context.resultcallback`.63+64+65 .. _upgrade-to-2.0:66 67 Upgrading to 2.068 ----------------32 unmodified linesmodified:tests/test_chain.py+7 added-2 removed
101 unmodified lines102 'sdist called 2',103 ]104 105 106-def test_context_subcommand_info_sync():106+def test_context_subcommand_info_sync(recwarn):107 @click.command()108 def cli():109 pass110 111+ def _assert_warning():112+ assert 'removed in Click 3.2' in str(recwarn.pop(Warning).message)113+114 ctx = click.Context(cli, info_name='cli')115 116 assert ctx.invoked_subcommand is None117 10 unmodified lines128 assert ctx.invoked_subcommands == []129 130 ctx.invoked_subcommands = ['foo', 'bar']131 assert ctx.invoked_subcommand == '*'129- assert ctx.invoked_subcommands == ['foo', 'bar']132+ assert ctx.invoked_subcommands == ['*']133 134+ assert 'removed in Click 3.2' in str(recwarn.pop(Warning).message)135 136+137 def test_pipeline(runner):138 @click.group(chain=True, invoke_without_command=True)139 @click.option('-i', '--input', type=click.File('r'))140 def cli(input):45 unmodified linesmodified:tests/test_commands.py+23 added
227 unmodified lines228 229 result = runner.invoke(cli, [])230 assert not result.exception231 assert result.output == '42\n'232+233+234+def test_invoked_subcommand(runner):235+ @click.group(invoke_without_command=True)236+ @click.pass_context237+ def cli(ctx):238+ if ctx.invoked_subcommand is None:239+ click.echo('no subcommand, use default')240+ ctx.invoke(sync)241+ else:242+ click.echo('invoke subcommand')243+244+ @cli.command()245+ def sync():246+ click.echo('in subcommand')247+248+ result = runner.invoke(cli, ['sync'])249+ assert not result.exception250+ assert result.output == 'invoke subcommand\nin subcommand\n'251+252+ result = runner.invoke(cli)253+ assert not result.exception254+ assert result.output == 'no subcommand, use default\nin subcommand\n'modified:CHANGES+5 added
10 unmodified lines11 - Added missing `err` parameter forwarding to the `secho` function.12 - Fixed default parameters not being handled properly by the context13 invoke method. This is a backwards incompatible change if the function14 was used improperly. See :ref:`upgrade-to-3.2` for more information.15+- Removed the `invoked_subcommands` attribute largely. It is not possible16+ to provide it to work error free due to how the parsing works so this17+ API has been deprecated. See :ref:`upgrade-to-3.2` for more information.18+- Restored the functionality of `invoked_subcommand` which was broken as19+ a regression in 3.1.20 21 Version 3.122 -----------23 153 unmodified lines