Skip to content
Myr

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

6 files+109 added−45 removed

modified:click/core.py+43 added-40 removed
171 unmodified lines
172 and parent.default_map is not None:173 default_map = parent.default_map.get(info_name)174 self.default_map = default_map175176 #: 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 = None187188 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 lines
250 self._depth -= 1251 if self._depth == 0:252 self.close()253251 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_subcommands272258 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_subcommand273273 def make_formatter(self):274 """Creates the formatter for the help and usage output."""275 return HelpFormatter(width=self.terminal_width)276
649 unmodified lines
926 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))936937 # 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)945946 # 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.args957952 # Now that we have all contexts, we can invoke them.953 ctx.invoked_subcommands = [x.info_name for x in contexts]954958 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)963961 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_name967968 # Get the command
15 unmodified lines
984 if split_opt(cmd_name)[0]:985 self.parse_args(ctx, ctx.args)986 ctx.fail('No such command "%s".' % original_cmd_name)987985 return cmd.make_context(cmd_name, args[1:], parent=ctx, **extra)988 return cmd_name, cmd, args[1:]989990 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 lines
modified:docs/commands.rst+3 added-3 removed
313 unmodified lines
314normal.315316Another note: the :attr:`Context.invoked_subcommand` attribute is a bit317useless for multi commands as it will give ``'*'`` as value if more than318one command is invoked. Instead you should be using the319:attr:`Context.invoked_subcommands` attribute instead which is a list320(note the trailing "s").318one command is invoked. This is necessary because the handling of319subcommands happens one after another so the exact subcommands that will320be handled are not yet available when the callback fires.321322323Multi Command Pipelines324-----------------------
180 unmodified lines
modified:docs/upgrading.rst+28 added
9 unmodified lines
1011Upgrading to 3.212----------------1314Click 3.2 had to perform two changes to multi commands which were15triggered by a change between Click 2 and Click 3 that had bigger16consequences than anticipated.1718Context Invokes19```````````````2021Click 3.2 contains a fix for the :meth:`Context.invoke` function when used22with other commands. The original intention of this function was to23invoke the other command as as if it came from the command line when it24was passed a context object instead of a function. This use was only
15 unmodified lines
4041This also allowed us to fix the issue that defaults were not handled42properly by this function.4344Multicommand Chaining API45`````````````````````````4647Click 3 introduced multicommand chaning. This required a change in how48Click internally dispatches. Unfortunately this change was not correctly49implemented and it appeared that it was possible to provide an API that50can inform the super command about all the subcommands that will be51invoked.5253This assumption however does not work with one of the API guarantees that54have been given in the past. As such this functionality has been removed55in 3.2 as it was already broken. Instead the accidentally broken56functionality of the :attr:`Context.invoked_subcommand` attribute was57restored.5859If you do require the know which exact commands will be invoked there are60different ways to cope with this. The first one is to let the subcommands61all return functions and then to invoke the functions in a62:meth:`Context.resultcallback`.636465.. _upgrade-to-2.0:6667Upgrading to 2.068----------------
32 unmodified lines
modified:tests/test_chain.py+7 added-2 removed
101 unmodified lines
102 'sdist called 2',103 ]104105106def test_context_subcommand_info_sync():106def test_context_subcommand_info_sync(recwarn):107 @click.command()108 def cli():109 pass110111 def _assert_warning():112 assert 'removed in Click 3.2' in str(recwarn.pop(Warning).message)113114 ctx = click.Context(cli, info_name='cli')115116 assert ctx.invoked_subcommand is None117
10 unmodified lines
128 assert ctx.invoked_subcommands == []129130 ctx.invoked_subcommands = ['foo', 'bar']131 assert ctx.invoked_subcommand == '*'129 assert ctx.invoked_subcommands == ['foo', 'bar']132 assert ctx.invoked_subcommands == ['*']133134 assert 'removed in Click 3.2' in str(recwarn.pop(Warning).message)135136137def 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 lines
modified:tests/test_commands.py+23 added
227 unmodified lines
228229 result = runner.invoke(cli, [])230 assert not result.exception231 assert result.output == '42\n'232233234def 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')243244 @cli.command()245 def sync():246 click.echo('in subcommand')247248 result = runner.invoke(cli, ['sync'])249 assert not result.exception250 assert result.output == 'invoke subcommand\nin subcommand\n'251252 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 lines
11- 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.2021Version 3.122-----------23
153 unmodified lines