remove mentions of deprecated base classes
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent 9e0d0b2 · Browse files · 10 files·+194 added−217 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+194 added−217 removed
- tests:+2 added−2 removed
- other:+192 added−215 removed
Provenance
- Commit
238ee07- Tree
7a14b63- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
9e0d0b2
10 files changed+194 added−217 removed
modified:docs/advanced.rst+33 added-26 removed
5 unmodified lines6 In addition to common functionality that is implemented in the library7 itself, there are countless patterns that can be implemented by extending8 Click. This page should give some insight into what can be accomplished.9 10+11 .. _aliases:12 13 Command Aliases14 ---------------15 15-Many tools support aliases for commands (see `Command alias example16-<https://github.com/pallets/click/tree/main/examples/aliases>`_).17-For instance, you can configure ``git`` to accept ``git ci`` as alias for18-``git commit``. Other tools also support auto-discovery for aliases by19-automatically shortening them.16+Many tools support aliases for commands. For example, you can configure17+``git`` to accept ``git ci`` as alias for ``git commit``. Other tools also18+support auto-discovery for aliases by automatically shortening them.19 21-Click does not support this out of the box, but it's very easy to customize22-the :class:`Group` or any other :class:`MultiCommand` to provide this23-functionality.20+It's possible to customize :class:`Group` to provide this functionality. As21+explained in :ref:`custom-groups`, a group provides two methods:22+:meth:`~Group.list_commands` and :meth:`~Group.get_command`. In this particular23+case, you only need to override the latter as you generally don't want to24+enumerate the aliases on the help page in order to avoid confusion.25 25-As explained in :ref:`custom-multi-commands`, a multi command can provide26-two methods: :meth:`~MultiCommand.list_commands` and27-:meth:`~MultiCommand.get_command`. In this particular case, you only need28-to override the latter as you generally don't want to enumerate the29-aliases on the help page in order to avoid confusion.26+The following example implements a subclass of :class:`Group` that accepts a27+prefix for a command. If there was a command called ``push``, it would accept28+``pus`` as an alias (so long as it was unique):29 31-This following example implements a subclass of :class:`Group` that32-accepts a prefix for a command. If there were a command called ``push``,33-it would accept ``pus`` as an alias (so long as it was unique):34-30 .. click:example::31 32 class AliasedGroup(click.Group):33 def get_command(self, ctx, cmd_name):39- rv = click.Group.get_command(self, ctx, cmd_name)34+ rv = super().get_command(ctx, cmd_name)35+36 if rv is not None:37 return rv38+39+ matches = [42- matches = [x for x in self.list_commands(ctx)43- if x.startswith(cmd_name)]40+ x for x in self.list_commands(ctx)41+ if x.startswith(cmd_name)42+ ]43+44 if not matches:45 return None46+46- elif len(matches) == 1:47+ if len(matches) == 1:48 return click.Group.get_command(self, ctx, matches[0])49+50 ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")51 52 def resolve_command(self, ctx, args):53 # always return the full command name54 _, cmd, args = super().resolve_command(ctx, args)55 return cmd.name, cmd, args56 55-And it can then be used like this:57+It can be used like this:58 59 .. click:example::60 59- @click.command(cls=AliasedGroup)61+ @click.group(cls=AliasedGroup)62 def cli():63 pass64 63- @cli.command()65+ @cli.command66 def push():67 pass68 67- @cli.command()69+ @cli.command70 def pop():71 pass72 73+See the `alias example`_ in Click's repository for another example.74+75+.. _alias example: https://github.com/pallets/click/tree/main/examples/aliases76+77+78 Parameter Modifications79 -----------------------80 81 Parameters (options and arguments) are forwarded to the command callbacks190 unmodified lines272 273 This can generally be activated in two different ways:274 275 1. It can be enabled on custom :class:`Command` subclasses by changing269- the :attr:`~BaseCommand.ignore_unknown_options` attribute.276+ the :attr:`~Command.ignore_unknown_options` attribute.277 2. It can be enabled by changing the attribute of the same name on the278 context class (:attr:`Context.ignore_unknown_options`). This is best279 changed through the ``context_settings`` dictionary on the command.280 215 unmodified linesmodified:docs/commands.rst+126 added-157 removed
1 unmodified line2 ===================3 4 .. currentmodule:: click5 6-The most important feature of Click is the concept of arbitrarily nesting7-command line utilities. This is implemented through the :class:`Command`8-and :class:`Group` (actually :class:`MultiCommand`).6+The structure of a Click application is defined with :class:`Command`, which7+defines an individual named command, and :class:`Group`, which defines a nested8+collection of commands (or more groups) under a name.9 10+11 Callback Invocation12 -------------------13 14 For a regular command, the callback is executed whenever the command runs.15 If the script is the only command, it will always fire (unless a parameter16 callback prevents it. This for instance happens if someone passes17 ``--help`` to the script).18 18-For groups and multi commands, the situation looks different. In this case,19-the callback fires whenever a subcommand fires (unless this behavior is20-changed). What this means in practice is that an outer command runs21-when an inner command runs:19+For groups, the situation looks different. In this case, the callback fires20+whenever a subcommand fires. What this means in practice is that an outer21+command runs when an inner command runs:22 23 .. click:example::24 25 @click.group()121 unmodified lines147 148 Group Invocation Without Command149 --------------------------------150 151-By default, a group or multi command is not invoked unless a subcommand is152-passed. In fact, not providing a command automatically passes ``--help``153-by default. This behavior can be changed by passing154-``invoke_without_command=True`` to a group. In that case, the callback is155-always invoked instead of showing the help page. The context object also156-includes information about whether or not the invocation would go to a157-subcommand.151+By default, a group is not invoked unless a subcommand is passed. In fact, not152+providing a command automatically passes ``--help`` by default. This behavior153+can be changed by passing ``invoke_without_command=True`` to a group. In that154+case, the callback is always invoked instead of showing the help page. The155+context object also includes information about whether or not the invocation156+would go to a subcommand.157 159-Example:160-158 .. click:example::159 160 @click.group(invoke_without_command=True)161 @click.pass_context6 unmodified lines168 @cli.command()169 def sync():170 click.echo('The subcommand')171 175-And how it works in practice:176-172 .. click:run::173 174 invoke(cli, prog_name='tool', args=[])175 invoke(cli, prog_name='tool', args=['sync'])176 182-.. _custom-multi-commands:177 184-Custom Multi Commands185----------------------178+.. _custom-groups:179 187-In addition to using :func:`click.group`, you can also build your own188-custom multi commands. This is useful when you want to support commands189-being loaded lazily from plugins.180+Custom Groups181+-------------182 191-A custom multi command just needs to implement a list and load method:183+You can customize the behavior of a group beyond the arguments it accepts by184+subclassing :class:`click.Group`.185 193-.. click:example::186+The most common methods to override are :meth:`~click.Group.get_command` and187+:meth:`~click.Group.list_commands`.188 195- import click196- import os189+The following example implements a basic plugin system that loads commands from190+Python files in a folder. The command is lazily loaded to avoid slow startup.191 198- plugin_folder = os.path.join(os.path.dirname(__file__), 'commands')192+.. code-block:: python193 200- class MyCLI(click.MultiCommand):194+ import importlib.util195+ import os196+ import click197 198+ class PluginGroup(click.Group):199+ def __init__(self, name=None, plugin_folder="commands", **kwargs):200+ super().__init__(name=name, **kwargs)201+ self.plugin_folder = plugin_folder202+203 def list_commands(self, ctx):204 rv = []205+204- for filename in os.listdir(plugin_folder):205- if filename.endswith('.py') and filename != '__init__.py':206+ for filename in os.listdir(self.plugin_folder):207+ if filename.endswith(".py"):208 rv.append(filename[:-3])209+210 rv.sort()211 return rv212 213 def get_command(self, ctx, name):211- ns = {}212- fn = os.path.join(plugin_folder, name + '.py')213- with open(fn) as f:214- code = compile(f.read(), fn, 'exec')215- eval(code, ns, ns)216- return ns['cli']214+ path = os.path.join(self.plugin_folder, f"{name}.py")215+ spec = importlib.util.spec_from_file_location(name, path)216+ module = importlib.util.module_from_spec(spec)217+ spec.loader.exec_module(module)218+ return module.cli219 218- cli = MyCLI(help='This tool\'s subcommands are loaded from a '219- 'plugin folder dynamically.')220+ cli = PluginGroup(221+ plugin_folder=os.path.join(os.path.dirname(__file__), "commands")222+ )223 221- if __name__ == '__main__':224+ if __name__ == "__main__":225 cli()226 224-These custom classes can also be used with decorators:227+Custom classes can also be used with decorators:228 226-.. click:example::229+.. code-block:: python230 228- @click.command(cls=MyCLI)231+ @click.group(232+ cls=PluginGroup,233+ plugin_folder=os.path.join(os.path.dirname(__file__), "commands")234+ )235 def cli():236 pass237 232-Merging Multi Commands233-----------------------238 235-In addition to implementing custom multi commands, it can also be236-interesting to merge multiple together into one script. While this is237-generally not as recommended as it nests one below the other, the merging238-approach can be useful in some circumstances for a nicer shell experience.239+.. _command-chaining:240 240-The default implementation for such a merging system is the241-:class:`CommandCollection` class. It accepts a list of other multi242-commands and makes the commands available on the same level.241+Command Chaining242+----------------243 244-Example usage:244+It is useful to invoke more than one subcommand in one call. For example,245+``my-app validate build upload`` would invoke ``validate``, then ``build``, then246+``upload``. To implement this, pass ``chain=True`` when creating a group.247 248 .. click:example::249 248- import click249-250- @click.group()251- def cli1():250+ @click.group(chain=True)251+ def cli():252 pass253 254- @cli1.command()255- def cmd1():256- """Command on cli1"""254+ @cli.command('validate')255+ def validate():256+ click.echo('validate')257 258- @click.group()259- def cli2():260- pass258+ @cli.command('build')259+ def build():260+ click.echo('build')261 262- @cli2.command()263- def cmd2():264- """Command on cli2"""262+You can invoke it like this:263 266- cli = click.CommandCollection(sources=[cli1, cli2])267-268- if __name__ == '__main__':269- cli()270-271-And what it looks like:272-264 .. click:run::265 275- invoke(cli, prog_name='cli', args=['--help'])266+ invoke(cli, prog_name='my-app', args=['validate', 'build'])267 277-In case a command exists in more than one source, the first source wins.268+When using chaining, there are a few restrictions:269 270+- Only the last command may use ``nargs=-1`` on an argument, otherwise the271+ parser will not be able to find further commands.272+- It is not possible to nest groups below a chain group.273+- On the command line, options must be specified before arguments for each274+ command in the chain.275+- The :attr:`Context.invoked_subcommand` attribute will be ``'*'`` because the276+ parser doesn't know the full list of commands that will run yet.277 280-.. _multi-command-chaining:278 282-Multi Command Chaining283-----------------------279+Command Pipelines280+-----------------281 285-.. versionadded:: 3.0282+When using chaining, a common pattern is to have each command process the283+result of the previous command.284 287-Sometimes it is useful to be allowed to invoke more than one subcommand in288-one go. For example, ``my-app validate build upload`` would invoke ``validate``,289-then ``build``, then ``upload``. To implement this in Click, pass ``chain=True``290-when creating a group.285+A straightforward way to do this is to use :func:`make_pass_decorator` to pass286+a context object to each command, and store and read the data on that object.287 288 .. click:example::289 290+ pass_ns = click.make_pass_decorator(dict, ensure=True)291+292 @click.group(chain=True)295- def cli():296- pass293+ @click.argument("name")294+ @pass_ns295+ def cli(ns, name):296+ ns["name"] = name297 298+ @cli.command299+ @pass_ns300+ def lower(ns):301+ ns["name"] = ns["name"].lower()302 299- @cli.command('sdist')300- def sdist():301- click.echo('sdist called')303+ @cli.command304+ @pass_ns305+ def show(ns):306+ click.echo(ns["name"])307 303-304- @cli.command('bdist_wheel')305- def bdist_wheel():306- click.echo('bdist_wheel called')307-308-Now you can invoke it like this:309-308 .. click:run::309 312- invoke(cli, prog_name='setup.py', args=['sdist', 'bdist_wheel'])310+ invoke(cli, prog_name="process", args=["Click", "show", "lower", "show"])311 314-When using multi command chaining you can only have one command (the last)315-use ``nargs=-1`` on an argument. It is also not possible to nest multi316-commands below chained multicommands. Other than that there are no317-restrictions on how they work. They can accept options and arguments as318-normal. The order between options and arguments is limited for chained319-commands. Currently only ``--options argument`` order is allowed.312+Another way to do this is to collect data returned by each command, then process313+it at the end of the chain. Use the group's :meth:`~Group.result_callback`314+decorator to register a function that is called after the chain is finished. It315+is passed the list of return values as well as any parameters registered on the316+group.317 321-Another note: the :attr:`Context.invoked_subcommand` attribute is a bit322-useless for multi commands as it will give ``'*'`` as value if more than323-one command is invoked. This is necessary because the handling of324-subcommands happens one after another so the exact subcommands that will325-be handled are not yet available when the callback fires.318+A command can return anything, including a function. Here's an example of that,319+where each subcommand creates a function that processes the input, then the320+result callback calls each function. The command takes a file, processes each321+line, then outputs it. If no subcommands are given, it outputs the contents322+of the file unchanged.323 327-.. note::324+.. code-block:: python325 329- It is currently not possible for chain commands to be nested. This330- will be fixed in future versions of Click.331-332-333-Multi Command Pipelines334------------------------335-336-.. versionadded:: 3.0337-338-A very common usecase of multi command chaining is to have one command339-process the result of the previous command. There are various ways in340-which this can be facilitated. The most obvious way is to store a value341-on the context object and process it from function to function. This342-works by decorating a function with :func:`pass_context` after which the343-context object is provided and a subcommand can store its data there.344-345-Another way to accomplish this is to setup pipelines by returning346-processing functions. Think of it like this: when a subcommand gets347-invoked it processes all of its parameters and comes up with a plan of348-how to do its processing. At that point it then returns a processing349-function and returns.350-351-Where do the returned functions go? The chained multicommand can register352-a callback with :meth:`MultiCommand.result_callback` that goes over all353-these functions and then invoke them.354-355-To make this a bit more concrete consider this example:356-357-.. click:example::358-326 @click.group(chain=True, invoke_without_command=True)360- @click.option('-i', '--input', type=click.File('r'))361- def cli(input):327+ @click.argument("fin", type=click.File("r"))328+ def cli(fin):329 pass330 331 @cli.result_callback()365- def process_pipeline(processors, input):366- iterator = (x.rstrip('\r\n') for x in input)332+ def process_pipeline(processors, fin):333+ iterator = (x.rstrip("\r\n") for x in input)334+335 for processor in processors:336 iterator = processor(iterator)337+338 for item in iterator:339 click.echo(item)340 372- @cli.command('uppercase')341+ @cli.command("upper")342 def make_uppercase():343 def processor(iterator):344 for line in iterator:345 yield line.upper()346 return processor347 379- @cli.command('lowercase')348+ @cli.command("lower")349 def make_lowercase():350 def processor(iterator):351 for line in iterator:352 yield line.lower()353 return processor354 386- @cli.command('strip')355+ @cli.command("strip")356 def make_strip():357 def processor(iterator):358 for line in iterator:359 yield line.strip()26 unmodified lines386 make resource handling much more complicated. For such it's recommended387 to not use the file type and manually open the file through388 :func:`open_file`.389 421-For a more complex example that also improves upon handling of the422-pipelines have a look at the `imagepipe multi command chaining demo423-<https://github.com/pallets/click/tree/main/examples/imagepipe>`__ in424-the Click repository. It implements a pipeline based image editing tool425-that has a nice internal structure for the pipelines.390+For a more complex example that also improves upon handling of the pipelines,391+see the `imagepipe example`_ in the Click repository. It implements a392+pipeline based image editing tool that has a nice internal structure.393 394+.. _imagepipe example: https://github.com/pallets/click/tree/main/examples/imagepipe395 396+397 Overriding Defaults398 -------------------399 400 By default, the default value for a parameter is pulled from the100 unmodified lines501 that were previously hard to implement.502 503 In essence any command callback can now return a value. This return value504 is bubbled to certain receivers. One usecase for this has already been536-show in the example of :ref:`multi-command-chaining` where it has been537-demonstrated that chained multi commands can have callbacks that process505+show in the example of :ref:`command-chaining` where it has been506+demonstrated that chained groups can have callbacks that process507 all return values.508 509 When working with command return values in Click, this is what you need to510 know:511 512 - The return value of a command callback is generally returned from the544- :meth:`BaseCommand.invoke` method. The exception to this rule has to513+ :meth:`Command.invoke` method. The exception to this rule has to514 do with :class:`Group`\s:515 516 * In a group the return value is generally the return value of the517 subcommand invoked. The only exception to this rule is that the1 unmodified line519 invoked without arguments and `invoke_without_command` is enabled.520 * If a group is set up for chaining then the return value is a list521 of all subcommands' results.522 * Return values of groups can be processed through a554- :attr:`MultiCommand.result_callback`. This is invoked with the523+ :attr:`Group.result_callback`. This is invoked with the524 list of all return values in chain mode, or the single return525 value in case of non chained commands.526 527 - The return value is bubbled through from the :meth:`Context.invoke`1 unmodified line529 where you internally want to call into another command.530 531 - Click does not have any hard requirements for the return values and532 does not use them itself. This allows return values to be used for564- custom decorators or workflows (like in the multi command chaining533+ custom decorators or workflows (like in the command chaining534 example).535 536 - When a Click script is invoked as command line application (through568- :meth:`BaseCommand.main`) the return value is ignored unless the537+ :meth:`Command.main`) the return value is ignored unless the538 `standalone_mode` is disabled in which case it's bubbled through.modified:docs/complex.rst+15 added-9 removed
222 unmodified lines223 --------------------------224 225 Large CLIs and CLIs with slow imports may benefit from deferring the loading of226 subcommands. The interfaces which support this mode of use are227-:meth:`MultiCommand.list_commands` and :meth:`MultiCommand.get_command`. A custom228-:class:`MultiCommand` subclass can implement a lazy loader by storing extra data such229-that :meth:`MultiCommand.get_command` is responsible for running imports.227+:meth:`Group.list_commands` and :meth:`Group.get_command`. A custom228+:class:`Group` subclass can implement a lazy loader by storing extra data such229+that :meth:`Group.get_command` is responsible for running imports.230 231 Since the primary case for this is a :class:`Group` which loads its subcommands lazily,232 the following example shows a lazy-group implementation.233 44 unmodified lines278 mod = importlib.import_module(modname)279 # get the Command object from that module280 cmd_object = getattr(mod, cmd_object_name)281 # check the result to make debugging easier282- if not isinstance(cmd_object, click.BaseCommand):282+ if not isinstance(cmd_object, click.Command):283 raise ValueError(284 f"Lazy loading of {import_path} failed by returning "285 "a non-command object"286 )18 unmodified lines305 )306 def cli():307 pass308 309+.. code-block:: python310+311 # in foo.py312 import click313 314 @click.group(help="foo command for lazy example")315 def cli():316 pass317 318+.. code-block:: python319+320 # in bar.py321 import click322 from lazy_group import LazyGroup323 4 unmodified lines328 )329 def cli():330 pass331 332+.. code-block:: python333+334 # in baz.py335 import click336 337 @click.group(help="baz command for lazy example")4 unmodified lines342 What triggers Lazy Loading?343 ```````````````````````````344 345 There are several events which may trigger lazy loading by running the340-:meth:`MultiCommand.get_command` function.346+:meth:`Group.get_command` function.347 Some are intuititve, and some are less so.348 349 All cases are described with respect to the above example, assuming the main program350 name is ``cli``.12 unmodified lines363 364 It is possible to make the process even lazier, but it is generally more difficult the365 more you want to defer work.366 361-For example, subcommands could be represented as a custom :class:`BaseCommand` subclass367+For example, subcommands could be represented as a custom :class:`Command` subclass368 which defers importing the command until it is invoked, but which provides363-:meth:`BaseCommand.get_short_help_str` in order to support completions and helptext.369+:meth:`Command.get_short_help_str` in order to support completions and helptext.370 More simply, commands can be constructed whose callback functions defer any actual work371 until after an import.372 373 This command definition provides ``foo``, but any of the work associated with importing8 unmodified lines382 from mylibrary import foo_concrete383 384 foo_concrete(n, w)385 380-Because ``click`` builds helptext and usage info from options, arguments, and command386+Because Click builds helptext and usage info from options, arguments, and command387 attributes, it has no awareness that the underlying function is in any way handling a382-deferred import. Therefore, all ``click``-provided utilities and functionality will work388+deferred import. Therefore, all Click-provided utilities and functionality will work389 as normal on such a command.modified:docs/exceptions.rst+1 added-1 removed
8 unmodified lines9 10 Where are Errors Handled?11 -------------------------12 13-Click's main error handling is happening in :meth:`BaseCommand.main`. In13+Click's main error handling is happening in :meth:`Command.main`. In14 there it handles all subclasses of :exc:`ClickException` as well as the15 standard :exc:`EOFError` and :exc:`KeyboardInterrupt` exceptions. The16 latter are internally translated into an :exc:`Abort`.17 56 unmodified linesmodified:docs/quickstart.rst+1 added-1 removed
91 unmodified lines92 * ``colors``: `Color support demo93 <https://github.com/pallets/click/tree/main/examples/colors>`_94 * ``termui``: `Terminal UI functions demo95 <https://github.com/pallets/click/tree/main/examples/termui>`_96-* ``imagepipe``: `Multi command chaining demo96+* ``imagepipe``: `Command chaining demo97 <https://github.com/pallets/click/tree/main/examples/imagepipe>`_98 99 Basic Concepts - Creating a Command100 -----------------------------------176 unmodified linesmodified:docs/upgrading.rst+4 added-4 removed
40 unmodified lines41 42 Upgrading to 3.243 ----------------44 45-Click 3.2 had to perform two changes to multi commands which were45+Click 3.2 had to perform two changes to groups which were46 triggered by a change between Click 2 and Click 3 that had bigger47 consequences than anticipated.48 49 Context Invokes21 unmodified lines71 72 This also allowed us to fix the issue that defaults were not handled73 properly by this function.74 75-Multicommand Chaining API76-`````````````````````````75+Command Chaining API76+````````````````````77 78-Click 3 introduced multicommand chaining. This required a change in how78+Click 3 introduced command chaining. This required a change in how79 Click internally dispatches. Unfortunately this change was not correctly80 implemented and it appeared that it was possible to provide an API that81 can inform the super command about all the subcommands that will be82 invoked.49 unmodified linesmodified:examples/complex/complex/cli.py+1 added-1 removed
26 unmodified lines27 pass_environment = click.make_pass_decorator(Environment, ensure=True)28 cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), "commands"))29 30 31-class ComplexCLI(click.MultiCommand):31+class ComplexCLI(click.Group):32 def list_commands(self, ctx):33 rv = []34 for filename in os.listdir(cmd_folder):35 if filename.endswith(".py") and filename.startswith("cmd_"):25 unmodified linesmodified:examples/imagepipe/README+1 added-1 removed
1 $ imagepipe_2 3 imagepipe is an example application that implements some4- multi commands that chain image processing instructions4+ commands that chain image processing instructions5 together.6 7 This requires pillow.8 5 unmodified linesmodified:src/click/core.py+10 added-15 removed
67 unmodified lines68 base_command: "Group", cmd_name: str, cmd: "Command", register: bool = False69 ) -> None:70 if not base_command.chain or not isinstance(cmd, Group):71 return72+73 if register:73- hint = (74- "It is not possible to add multi commands as children to"75- " another multi command that is in chain mode."74+ message = (75+ f"It is not possible to add the group {cmd_name!r} to another"76+ f" group {base_command.name!r} that is in chain mode."77 )78 else:78- hint = (79- "Found a multi command as subcommand to a multi command"80- " that is in chain mode. This is not supported."79+ message = (80+ f"Found the group {cmd_name!r} as subcommand to another group "81+ f" {base_command.name!r} that is in chain mode. This is not supported."82 )82- raise RuntimeError(83- f"{hint}. Command {base_command.name!r} is set to chain and"84- f" {cmd_name!r} was added as a subcommand but it in itself is a"85- f" multi command. ({cmd_name!r} is a {type(cmd).__name__}"86- f" within a chained {type(base_command).__name__} named"87- f" {base_command.name!r})."88- )83 84+ raise RuntimeError(message)85 86+87 def batch(iterable: t.Iterable[V], batch_size: int) -> t.List[t.Tuple[V, ...]]:88 return list(zip(*repeat(iter(iterable), batch_size)))89 90 1410 unmodified lines1501 if self.chain:1502 for param in self.params:1503 if isinstance(param, Argument) and not param.required:1504 raise RuntimeError(1509- "Multi commands in chain mode cannot have"1510- " optional arguments."1505+ "A group in chain mode cannot have optional arguments."1506 )1507 1508 def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]:1509 info_dict = super().to_info_dict(ctx)1481 unmodified linesmodified:tests/test_chain.py+2 added-2 removed
187 unmodified lines188 assert not result.exception189 assert result.output.splitlines() == ["cli=", "a=", "b=", "c="]190 191 192-def test_multicommand_arg_behavior(runner):192+def test_group_arg_behavior(runner):193 with pytest.raises(RuntimeError):194 195 @click.group(chain=True)196 @click.argument("forbidden", required=False)21 unmodified lines218 assert result.output.splitlines() == ["cli:foo", "a"]219 220 221 @pytest.mark.xfail222-def test_multicommand_chaining(runner):222+def test_group_chaining(runner):223 @click.group(chain=True)224 def cli():225 debug()226 19 unmodified lines