deprecate base classes `BaseCommand` and `MultiCommand` (#2591)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by GitHub · parents f5e47a6, 238ee07 · Browse files · 15 files·+767 added−807 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+767 added−807 removed
- tests:+4 added−4 removed
- other:+763 added−803 removed
Provenance
- Commit
edcd2dc- Tree
7a14b63- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
f5e47a6- Parent 2
238ee07
15 files changed+767 added−807 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/__init__.py+28 added-2 removed
3 unmodified lines4 around a simple API that does not come with too much magic and is5 composable.6 """7 from .core import Argument as Argument8-from .core import BaseCommand as BaseCommand8 from .core import Command as Command9 from .core import CommandCollection as CommandCollection10 from .core import Context as Context11 from .core import Group as Group13-from .core import MultiCommand as MultiCommand12 from .core import Option as Option13 from .core import Parameter as Parameter14 from .decorators import argument as argument15 from .decorators import command as command52 unmodified lines68 from .utils import get_text_stream as get_text_stream69 from .utils import open_file as open_file70 71 __version__ = "8.2.0.dev0"72+73+74+def __getattr__(name: str) -> object:75+ import warnings76+77+ if name == "BaseCommand":78+ from .core import _BaseCommand79+80+ warnings.warn(81+ "'BaseCommand' is deprecated and will be removed in Click 9.0. Use"82+ " 'Command' instead.",83+ DeprecationWarning,84+ stacklevel=2,85+ )86+ return _BaseCommand87+88+ if name == "MultiCommand":89+ from .core import _MultiCommand90+91+ warnings.warn(92+ "'MultiCommand' is deprecated and will be removed in Click 9.0. Use"93+ " 'Group' instead.",94+ DeprecationWarning,95+ stacklevel=2,96+ )97+ return _MultiCommand98+99+ raise AttributeError(name)modified:src/click/core.py+539 added-591 removed
52 unmodified lines53 54 :param ctx: Invocation context for the group.55 :param incomplete: Value being completed. May be empty.56 """57- multi = t.cast(MultiCommand, ctx.command)57+ multi = t.cast(Group, ctx.command)58 59 for name in multi.list_commands(ctx):60 if name.startswith(incomplete):61 command = multi.get_command(ctx, name)1 unmodified line63 if command is not None and not command.hidden:64 yield name, command65 66 67-def _check_multicommand(68- base_command: "MultiCommand", cmd_name: str, cmd: "Command", register: bool = False67+def _check_nested_chain(68+ base_command: "Group", cmd_name: str, cmd: "Command", register: bool = False69 ) -> None:70- if not base_command.chain or not isinstance(cmd, MultiCommand):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 735 unmodified lines826 """827 return self._parameter_source.get(name)828 829 834-class BaseCommand:835- """The base command implements the minimal API contract of commands.836- Most code will never use this as it does not implement a lot of useful837- functionality but it can act as the direct subclass of alternative838- parsing methods that do not depend on the Click parser.839-840- For instance, this can be used to bridge Click and other systems like841- argparse or docopt.842-843- Because base commands do not implement a lot of the API that other844- parts of Click take for granted, they are not supported for all845- operations. For instance, they cannot be used with the decorators846- usually and they have no built-in callback system.847-848- .. versionchanged:: 2.0849- Added the `context_settings` parameter.850-851- :param name: the name of the command to use unless a group overrides it.852- :param context_settings: an optional dictionary with defaults that are853- passed to the context object.854- """855-856- #: The context class to create with :meth:`make_context`.857- #:858- #: .. versionadded:: 8.0859- context_class: t.Type[Context] = Context860- #: the default for the :attr:`Context.allow_extra_args` flag.861- allow_extra_args = False862- #: the default for the :attr:`Context.allow_interspersed_args` flag.863- allow_interspersed_args = True864- #: the default for the :attr:`Context.ignore_unknown_options` flag.865- ignore_unknown_options = False866-867- def __init__(868- self,869- name: t.Optional[str],870- context_settings: t.Optional[t.MutableMapping[str, t.Any]] = None,871- ) -> None:872- #: the name the command thinks it has. Upon registering a command873- #: on a :class:`Group` the group will default the command name874- #: with this information. You should instead use the875- #: :class:`Context`\'s :attr:`~Context.info_name` attribute.876- self.name = name877-878- if context_settings is None:879- context_settings = {}880-881- #: an optional dictionary with defaults passed to the context.882- self.context_settings: t.MutableMapping[str, t.Any] = context_settings883-884- def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]:885- """Gather information that could be useful for a tool generating886- user-facing documentation. This traverses the entire structure887- below this command.888-889- Use :meth:`click.Context.to_info_dict` to traverse the entire890- CLI structure.891-892- :param ctx: A :class:`Context` representing this command.893-894- .. versionadded:: 8.0895- """896- return {"name": self.name}897-898- def __repr__(self) -> str:899- return f"<{self.__class__.__name__} {self.name}>"900-901- def get_usage(self, ctx: Context) -> str:902- raise NotImplementedError("Base commands cannot get usage")903-904- def get_help(self, ctx: Context) -> str:905- raise NotImplementedError("Base commands cannot get help")906-907- def make_context(908- self,909- info_name: t.Optional[str],910- args: t.List[str],911- parent: t.Optional[Context] = None,912- **extra: t.Any,913- ) -> Context:914- """This function when given an info name and arguments will kick915- off the parsing and create a new :class:`Context`. It does not916- invoke the actual command callback though.917-918- To quickly customize the context class used without overriding919- this method, set the :attr:`context_class` attribute.920-921- :param info_name: the info name for this invocation. Generally this922- is the most descriptive name for the script or923- command. For the toplevel script it's usually924- the name of the script, for commands below it's925- the name of the command.926- :param args: the arguments to parse as list of strings.927- :param parent: the parent context if available.928- :param extra: extra keyword arguments forwarded to the context929- constructor.930-931- .. versionchanged:: 8.0932- Added the :attr:`context_class` attribute.933- """934- for key, value in self.context_settings.items():935- if key not in extra:936- extra[key] = value937-938- ctx = self.context_class(939- self, info_name=info_name, parent=parent, **extra # type: ignore940- )941-942- with ctx.scope(cleanup=False):943- self.parse_args(ctx, args)944- return ctx945-946- def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]:947- """Given a context and a list of arguments this creates the parser948- and parses the arguments, then modifies the context as necessary.949- This is automatically invoked by :meth:`make_context`.950- """951- raise NotImplementedError("Base commands do not know how to parse arguments.")952-953- def invoke(self, ctx: Context) -> t.Any:954- """Given a context, this invokes the command. The default955- implementation is raising a not implemented error.956- """957- raise NotImplementedError("Base commands are not invocable by default")958-959- def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:960- """Return a list of completions for the incomplete value. Looks961- at the names of chained multi-commands.962-963- Any command could be part of a chained multi-command, so sibling964- commands are valid at any point during command completion. Other965- command classes will return more completions.966-967- :param ctx: Invocation context for this command.968- :param incomplete: Value being completed. May be empty.969-970- .. versionadded:: 8.0971- """972- from click.shell_completion import CompletionItem973-974- results: t.List["CompletionItem"] = []975-976- while ctx.parent is not None:977- ctx = ctx.parent978-979- if isinstance(ctx.command, MultiCommand) and ctx.command.chain:980- results.extend(981- CompletionItem(name, help=command.get_short_help_str())982- for name, command in _complete_visible_commands(ctx, incomplete)983- if name not in ctx.protected_args984- )985-986- return results987-988- @t.overload989- def main(990- self,991- args: t.Optional[t.Sequence[str]] = None,992- prog_name: t.Optional[str] = None,993- complete_var: t.Optional[str] = None,994- standalone_mode: "te.Literal[True]" = True,995- **extra: t.Any,996- ) -> "te.NoReturn":997- ...998-999- @t.overload1000- def main(1001- self,1002- args: t.Optional[t.Sequence[str]] = None,1003- prog_name: t.Optional[str] = None,1004- complete_var: t.Optional[str] = None,1005- standalone_mode: bool = ...,1006- **extra: t.Any,1007- ) -> t.Any:1008- ...1009-1010- def main(1011- self,1012- args: t.Optional[t.Sequence[str]] = None,1013- prog_name: t.Optional[str] = None,1014- complete_var: t.Optional[str] = None,1015- standalone_mode: bool = True,1016- windows_expand_args: bool = True,1017- **extra: t.Any,1018- ) -> t.Any:1019- """This is the way to invoke a script with all the bells and1020- whistles as a command line application. This will always terminate1021- the application after a call. If this is not wanted, ``SystemExit``1022- needs to be caught.1023-1024- This method is also available by directly calling the instance of1025- a :class:`Command`.1026-1027- :param args: the arguments that should be used for parsing. If not1028- provided, ``sys.argv[1:]`` is used.1029- :param prog_name: the program name that should be used. By default1030- the program name is constructed by taking the file1031- name from ``sys.argv[0]``.1032- :param complete_var: the environment variable that controls the1033- bash completion support. The default is1034- ``"_<prog_name>_COMPLETE"`` with prog_name in1035- uppercase.1036- :param standalone_mode: the default behavior is to invoke the script1037- in standalone mode. Click will then1038- handle exceptions and convert them into1039- error messages and the function will never1040- return but shut down the interpreter. If1041- this is set to `False` they will be1042- propagated to the caller and the return1043- value of this function is the return value1044- of :meth:`invoke`.1045- :param windows_expand_args: Expand glob patterns, user dir, and1046- env vars in command line args on Windows.1047- :param extra: extra keyword arguments are forwarded to the context1048- constructor. See :class:`Context` for more information.1049-1050- .. versionchanged:: 8.0.11051- Added the ``windows_expand_args`` parameter to allow1052- disabling command line arg expansion on Windows.1053-1054- .. versionchanged:: 8.01055- When taking arguments from ``sys.argv`` on Windows, glob1056- patterns, user dir, and env vars are expanded.1057-1058- .. versionchanged:: 3.01059- Added the ``standalone_mode`` parameter.1060- """1061- if args is None:1062- args = sys.argv[1:]1063-1064- if os.name == "nt" and windows_expand_args:1065- args = _expand_args(args)1066- else:1067- args = list(args)1068-1069- if prog_name is None:1070- prog_name = _detect_program_name()1071-1072- # Process shell completion requests and exit early.1073- self._main_shell_completion(extra, prog_name, complete_var)1074-1075- try:1076- try:1077- with self.make_context(prog_name, args, **extra) as ctx:1078- rv = self.invoke(ctx)1079- if not standalone_mode:1080- return rv1081- # it's not safe to `ctx.exit(rv)` here!1082- # note that `rv` may actually contain data like "1" which1083- # has obvious effects1084- # more subtle case: `rv=[None, None]` can come out of1085- # chained commands which all returned `None` -- so it's not1086- # even always obvious that `rv` indicates success/failure1087- # by its truthiness/falsiness1088- ctx.exit()1089- except (EOFError, KeyboardInterrupt) as e:1090- echo(file=sys.stderr)1091- raise Abort() from e1092- except ClickException as e:1093- if not standalone_mode:1094- raise1095- e.show()1096- sys.exit(e.exit_code)1097- except OSError as e:1098- if e.errno == errno.EPIPE:1099- sys.stdout = t.cast(t.TextIO, PacifyFlushWrapper(sys.stdout))1100- sys.stderr = t.cast(t.TextIO, PacifyFlushWrapper(sys.stderr))1101- sys.exit(1)1102- else:1103- raise1104- except Exit as e:1105- if standalone_mode:1106- sys.exit(e.exit_code)1107- else:1108- # in non-standalone mode, return the exit code1109- # note that this is only reached if `self.invoke` above raises1110- # an Exit explicitly -- thus bypassing the check there which1111- # would return its result1112- # the results of non-standalone execution may therefore be1113- # somewhat ambiguous: if there are codepaths which lead to1114- # `ctx.exit(1)` and to `return 1`, the caller won't be able to1115- # tell the difference between the two1116- return e.exit_code1117- except Abort:1118- if not standalone_mode:1119- raise1120- echo(_("Aborted!"), file=sys.stderr)1121- sys.exit(1)1122-1123- def _main_shell_completion(1124- self,1125- ctx_args: t.MutableMapping[str, t.Any],1126- prog_name: str,1127- complete_var: t.Optional[str] = None,1128- ) -> None:1129- """Check if the shell is asking for tab completion, process1130- that, then exit early. Called from :meth:`main` before the1131- program is invoked.1132-1133- :param prog_name: Name of the executable in the shell.1134- :param complete_var: Name of the environment variable that holds1135- the completion instruction. Defaults to1136- ``_{PROG_NAME}_COMPLETE``.1137-1138- .. versionchanged:: 8.2.01139- Dots (``.``) in ``prog_name`` are replaced with underscores (``_``).1140- """1141- if complete_var is None:1142- complete_name = prog_name.replace("-", "_").replace(".", "_")1143- complete_var = f"_{complete_name}_COMPLETE".upper()1144-1145- instruction = os.environ.get(complete_var)1146-1147- if not instruction:1148- return1149-1150- from .shell_completion import shell_complete1151-1152- rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)1153- sys.exit(rv)1154-1155- def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any:1156- """Alias for :meth:`main`."""1157- return self.main(*args, **kwargs)1158-1159-1160-class Command(BaseCommand):830+class Command:831 """Commands are the basic building block of command line interfaces in832 Click. A basic command handles command line parsing and might dispatch833 more parsing to commands nested below it.834 18 unmodified lines853 854 :param deprecated: issues a message indicating that855 the command is deprecated.856 857+ .. versionchanged:: 8.2858+ This is the base class for all commands, not ``BaseCommand``.859+860 .. versionchanged:: 8.1861 ``help``, ``epilog``, and ``short_help`` are stored unprocessed,862 all formatting is done when outputting help text, not at init,863 and is done even if not using the ``@command`` decorator.7 unmodified lines871 .. versionchanged:: 2.0872 Added the ``context_settings`` parameter.873 """874 875+ #: The context class to create with :meth:`make_context`.876+ #:877+ #: .. versionadded:: 8.0878+ context_class: t.Type[Context] = Context879+880+ #: the default for the :attr:`Context.allow_extra_args` flag.881+ allow_extra_args = False882+883+ #: the default for the :attr:`Context.allow_interspersed_args` flag.884+ allow_interspersed_args = True885+886+ #: the default for the :attr:`Context.ignore_unknown_options` flag.887+ ignore_unknown_options = False888+889 def __init__(890 self,891 name: t.Optional[str],892 context_settings: t.Optional[t.MutableMapping[str, t.Any]] = None,7 unmodified lines900 no_args_is_help: bool = False,901 hidden: bool = False,902 deprecated: bool = False,903 ) -> None:1217- super().__init__(name, context_settings)904+ #: the name the command thinks it has. Upon registering a command905+ #: on a :class:`Group` the group will default the command name906+ #: with this information. You should instead use the907+ #: :class:`Context`\'s :attr:`~Context.info_name` attribute.908+ self.name = name909+910+ if context_settings is None:911+ context_settings = {}912+913+ #: an optional dictionary with defaults passed to the context.914+ self.context_settings: t.MutableMapping[str, t.Any] = context_settings915+916 #: the callback to execute when the command fires. This might be917 #: `None` in which case nothing happens.918 self.callback = callback919 #: the list of parameters for this command in the order they9 unmodified lines929 self.hidden = hidden930 self.deprecated = deprecated931 932 def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]:1235- info_dict = super().to_info_dict(ctx)1236- info_dict.update(1237- params=[param.to_info_dict() for param in self.get_params(ctx)],1238- help=self.help,1239- epilog=self.epilog,1240- short_help=self.short_help,1241- hidden=self.hidden,1242- deprecated=self.deprecated,1243- )1244- return info_dict933+ return {934+ "name": self.name,935+ "params": [param.to_info_dict() for param in self.get_params(ctx)],936+ "help": self.help,937+ "epilog": self.epilog,938+ "short_help": self.short_help,939+ "hidden": self.hidden,940+ "deprecated": self.deprecated,941+ }942 943+ def __repr__(self) -> str:944+ return f"<{self.__class__.__name__} {self.name}>"945+946 def get_usage(self, ctx: Context) -> str:947 """Formats the usage line into a string and returns it.948 949 Calls :meth:`format_usage` internally.145 unmodified lines1095 1096 with formatter.indentation():1097 formatter.write_text(epilog)1098 1099+ def make_context(1100+ self,1101+ info_name: t.Optional[str],1102+ args: t.List[str],1103+ parent: t.Optional[Context] = None,1104+ **extra: t.Any,1105+ ) -> Context:1106+ """This function when given an info name and arguments will kick1107+ off the parsing and create a new :class:`Context`. It does not1108+ invoke the actual command callback though.1109+1110+ To quickly customize the context class used without overriding1111+ this method, set the :attr:`context_class` attribute.1112+1113+ :param info_name: the info name for this invocation. Generally this1114+ is the most descriptive name for the script or1115+ command. For the toplevel script it's usually1116+ the name of the script, for commands below it's1117+ the name of the command.1118+ :param args: the arguments to parse as list of strings.1119+ :param parent: the parent context if available.1120+ :param extra: extra keyword arguments forwarded to the context1121+ constructor.1122+1123+ .. versionchanged:: 8.01124+ Added the :attr:`context_class` attribute.1125+ """1126+ for key, value in self.context_settings.items():1127+ if key not in extra:1128+ extra[key] = value1129+1130+ ctx = self.context_class(self, info_name=info_name, parent=parent, **extra)1131+1132+ with ctx.scope(cleanup=False):1133+ self.parse_args(ctx, args)1134+ return ctx1135+1136 def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]:1137 if not args and self.no_args_is_help and not ctx.resilient_parsing:1138 echo(ctx.get_help(), color=ctx.color)1139 ctx.exit()33 unmodified lines1173 def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:1174 """Return a list of completions for the incomplete value. Looks1175 at the names of options and chained multi-commands.1176 1177+ Any command could be part of a chained multi-command, so sibling1178+ commands are valid at any point during command completion.1179+1180 :param ctx: Invocation context for this command.1181 :param incomplete: Value being completed. May be empty.1182 1183 .. versionadded:: 8.020 unmodified lines1204 for name in [*param.opts, *param.secondary_opts]1205 if name.startswith(incomplete)1206 )1207 1468- results.extend(super().shell_complete(ctx, incomplete))1208+ while ctx.parent is not None:1209+ ctx = ctx.parent1210+1211+ if isinstance(ctx.command, Group) and ctx.command.chain:1212+ results.extend(1213+ CompletionItem(name, help=command.get_short_help_str())1214+ for name, command in _complete_visible_commands(ctx, incomplete)1215+ if name not in ctx.protected_args1216+ )1217+1218 return results1219 1220+ @t.overload1221+ def main(1222+ self,1223+ args: t.Optional[t.Sequence[str]] = None,1224+ prog_name: t.Optional[str] = None,1225+ complete_var: t.Optional[str] = None,1226+ standalone_mode: "te.Literal[True]" = True,1227+ **extra: t.Any,1228+ ) -> "te.NoReturn":1229+ ...1230 1472-class MultiCommand(Command):1473- """A multi command is the basic implementation of a command that1474- dispatches to subcommands. The most common version is the1475- :class:`Group`.1231+ @t.overload1232+ def main(1233+ self,1234+ args: t.Optional[t.Sequence[str]] = None,1235+ prog_name: t.Optional[str] = None,1236+ complete_var: t.Optional[str] = None,1237+ standalone_mode: bool = ...,1238+ **extra: t.Any,1239+ ) -> t.Any:1240+ ...1241 1477- :param invoke_without_command: this controls how the multi command itself1478- is invoked. By default it's only invoked1479- if a subcommand is provided.1480- :param no_args_is_help: this controls what happens if no arguments are1481- provided. This option is enabled by default if1482- `invoke_without_command` is disabled or disabled1483- if it's enabled. If enabled this will add1484- ``--help`` as argument if no arguments are1485- passed.1486- :param subcommand_metavar: the string that is used in the documentation1487- to indicate the subcommand place.1488- :param chain: if this is set to `True` chaining of multiple subcommands1489- is enabled. This restricts the form of commands in that1490- they cannot have optional arguments but it allows1491- multiple commands to be chained together.1492- :param result_callback: The result callback to attach to this multi1493- command. This can be set or changed later with the1494- :meth:`result_callback` decorator.1495- :param attrs: Other command arguments described in :class:`Command`.1242+ def main(1243+ self,1244+ args: t.Optional[t.Sequence[str]] = None,1245+ prog_name: t.Optional[str] = None,1246+ complete_var: t.Optional[str] = None,1247+ standalone_mode: bool = True,1248+ windows_expand_args: bool = True,1249+ **extra: t.Any,1250+ ) -> t.Any:1251+ """This is the way to invoke a script with all the bells and1252+ whistles as a command line application. This will always terminate1253+ the application after a call. If this is not wanted, ``SystemExit``1254+ needs to be caught.1255+1256+ This method is also available by directly calling the instance of1257+ a :class:`Command`.1258+1259+ :param args: the arguments that should be used for parsing. If not1260+ provided, ``sys.argv[1:]`` is used.1261+ :param prog_name: the program name that should be used. By default1262+ the program name is constructed by taking the file1263+ name from ``sys.argv[0]``.1264+ :param complete_var: the environment variable that controls the1265+ bash completion support. The default is1266+ ``"_<prog_name>_COMPLETE"`` with prog_name in1267+ uppercase.1268+ :param standalone_mode: the default behavior is to invoke the script1269+ in standalone mode. Click will then1270+ handle exceptions and convert them into1271+ error messages and the function will never1272+ return but shut down the interpreter. If1273+ this is set to `False` they will be1274+ propagated to the caller and the return1275+ value of this function is the return value1276+ of :meth:`invoke`.1277+ :param windows_expand_args: Expand glob patterns, user dir, and1278+ env vars in command line args on Windows.1279+ :param extra: extra keyword arguments are forwarded to the context1280+ constructor. See :class:`Context` for more information.1281+1282+ .. versionchanged:: 8.0.11283+ Added the ``windows_expand_args`` parameter to allow1284+ disabling command line arg expansion on Windows.1285+1286+ .. versionchanged:: 8.01287+ When taking arguments from ``sys.argv`` on Windows, glob1288+ patterns, user dir, and env vars are expanded.1289+1290+ .. versionchanged:: 3.01291+ Added the ``standalone_mode`` parameter.1292+ """1293+ if args is None:1294+ args = sys.argv[1:]1295+1296+ if os.name == "nt" and windows_expand_args:1297+ args = _expand_args(args)1298+ else:1299+ args = list(args)1300+1301+ if prog_name is None:1302+ prog_name = _detect_program_name()1303+1304+ # Process shell completion requests and exit early.1305+ self._main_shell_completion(extra, prog_name, complete_var)1306+1307+ try:1308+ try:1309+ with self.make_context(prog_name, args, **extra) as ctx:1310+ rv = self.invoke(ctx)1311+ if not standalone_mode:1312+ return rv1313+ # it's not safe to `ctx.exit(rv)` here!1314+ # note that `rv` may actually contain data like "1" which1315+ # has obvious effects1316+ # more subtle case: `rv=[None, None]` can come out of1317+ # chained commands which all returned `None` -- so it's not1318+ # even always obvious that `rv` indicates success/failure1319+ # by its truthiness/falsiness1320+ ctx.exit()1321+ except (EOFError, KeyboardInterrupt) as e:1322+ echo(file=sys.stderr)1323+ raise Abort() from e1324+ except ClickException as e:1325+ if not standalone_mode:1326+ raise1327+ e.show()1328+ sys.exit(e.exit_code)1329+ except OSError as e:1330+ if e.errno == errno.EPIPE:1331+ sys.stdout = t.cast(t.TextIO, PacifyFlushWrapper(sys.stdout))1332+ sys.stderr = t.cast(t.TextIO, PacifyFlushWrapper(sys.stderr))1333+ sys.exit(1)1334+ else:1335+ raise1336+ except Exit as e:1337+ if standalone_mode:1338+ sys.exit(e.exit_code)1339+ else:1340+ # in non-standalone mode, return the exit code1341+ # note that this is only reached if `self.invoke` above raises1342+ # an Exit explicitly -- thus bypassing the check there which1343+ # would return its result1344+ # the results of non-standalone execution may therefore be1345+ # somewhat ambiguous: if there are codepaths which lead to1346+ # `ctx.exit(1)` and to `return 1`, the caller won't be able to1347+ # tell the difference between the two1348+ return e.exit_code1349+ except Abort:1350+ if not standalone_mode:1351+ raise1352+ echo(_("Aborted!"), file=sys.stderr)1353+ sys.exit(1)1354+1355+ def _main_shell_completion(1356+ self,1357+ ctx_args: t.MutableMapping[str, t.Any],1358+ prog_name: str,1359+ complete_var: t.Optional[str] = None,1360+ ) -> None:1361+ """Check if the shell is asking for tab completion, process1362+ that, then exit early. Called from :meth:`main` before the1363+ program is invoked.1364+1365+ :param prog_name: Name of the executable in the shell.1366+ :param complete_var: Name of the environment variable that holds1367+ the completion instruction. Defaults to1368+ ``_{PROG_NAME}_COMPLETE``.1369+1370+ .. versionchanged:: 8.2.01371+ Dots (``.``) in ``prog_name`` are replaced with underscores (``_``).1372+ """1373+ if complete_var is None:1374+ complete_name = prog_name.replace("-", "_").replace(".", "_")1375+ complete_var = f"_{complete_name}_COMPLETE".upper()1376+1377+ instruction = os.environ.get(complete_var)1378+1379+ if not instruction:1380+ return1381+1382+ from .shell_completion import shell_complete1383+1384+ rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)1385+ sys.exit(rv)1386+1387+ def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any:1388+ """Alias for :meth:`main`."""1389+ return self.main(*args, **kwargs)1390+1391+1392+class _FakeSubclassCheck(type):1393+ def __subclasscheck__(cls, subclass: type) -> bool:1394+ return issubclass(subclass, cls.__bases__[0])1395+1396+ def __instancecheck__(cls, instance: t.Any) -> bool:1397+ return isinstance(instance, cls.__bases__[0])1398+1399+1400+class _BaseCommand(Command, metaclass=_FakeSubclassCheck):1401 """1402+ .. deprecated:: 8.21403+ Will be removed in Click 9.0. Use ``Command`` instead.1404+ """1405 1406+1407+class Group(Command):1408+ """A group is a command that nests other commands (or more groups).1409+1410+ :param name: The name of the group command.1411+ :param commands: Map names to :class:`Command` objects. Can be a list, which1412+ will use :attr:`Command.name` as the keys.1413+ :param invoke_without_command: Invoke the group's callback even if a1414+ subcommand is not given.1415+ :param no_args_is_help: If no arguments are given, show the group's help and1416+ exit. Defaults to the opposite of ``invoke_without_command``.1417+ :param subcommand_metavar: How to represent the subcommand argument in help.1418+ The default will represent whether ``chain`` is set or not.1419+ :param chain: Allow passing more than one subcommand argument. After parsing1420+ a command's arguments, if any arguments remain another command will be1421+ matched, and so on.1422+ :param result_callback: A function to call after the group's and1423+ subcommand's callbacks. The value returned by the subcommand is passed.1424+ If ``chain`` is enabled, the value will be a list of values returned by1425+ all the commands. If ``invoke_without_command`` is enabled, the value1426+ will be the value returned by the group's callback, or an empty list if1427+ ``chain`` is enabled.1428+ :param kwargs: Other arguments passed to :class:`Command`.1429+1430+ .. versionchanged:: 8.21431+ Merged with and replaces the ``MultiCommand`` base class.1432+1433+ .. versionchanged:: 8.01434+ The ``commands`` argument can be a list of command objects.1435+ """1436+1437 allow_extra_args = True1438 allow_interspersed_args = False1439 1440+ #: If set, this is used by the group's :meth:`command` decorator1441+ #: as the default :class:`Command` class. This is useful to make all1442+ #: subcommands use a custom command class.1443+ #:1444+ #: .. versionadded:: 8.01445+ command_class: t.Optional[t.Type[Command]] = None1446+1447+ #: If set, this is used by the group's :meth:`group` decorator1448+ #: as the default :class:`Group` class. This is useful to make all1449+ #: subgroups use a custom group class.1450+ #:1451+ #: If set to the special value :class:`type` (literally1452+ #: ``group_class = type``), this group's class will be used as the1453+ #: default class. This makes a custom group class continue to make1454+ #: custom groups.1455+ #:1456+ #: .. versionadded:: 8.01457+ group_class: t.Optional[t.Union[t.Type["Group"], t.Type[type]]] = None1458+ # Literal[type] isn't valid, so use Type[type]1459+1460 def __init__(1461 self,1462 name: t.Optional[str] = None,1463+ commands: t.Optional[1464+ t.Union[t.MutableMapping[str, Command], t.Sequence[Command]]1465+ ] = None,1466 invoke_without_command: bool = False,1467 no_args_is_help: t.Optional[bool] = None,1468 subcommand_metavar: t.Optional[str] = None,1469 chain: bool = False,1470 result_callback: t.Optional[t.Callable[..., t.Any]] = None,1509- **attrs: t.Any,1471+ **kwargs: t.Any,1472 ) -> None:1511- super().__init__(name, **attrs)1473+ super().__init__(name, **kwargs)1474 1475+ if commands is None:1476+ commands = {}1477+ elif isinstance(commands, abc.Sequence):1478+ commands = {c.name: c for c in commands if c.name is not None}1479+1480+ #: The registered subcommands by their exported names.1481+ self.commands: t.MutableMapping[str, Command] = commands1482+1483 if no_args_is_help is None:1484 no_args_is_help = not invoke_without_command1485 1486 self.no_args_is_help = no_args_is_help14 unmodified lines1501 if self.chain:1502 for param in self.params:1503 if isinstance(param, Argument) and not param.required:1504 raise RuntimeError(1535- "Multi commands in chain mode cannot have"1536- " 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)12 unmodified lines1522 1523 info_dict.update(commands=commands, chain=self.chain)1524 return info_dict1525 1557- def collect_usage_pieces(self, ctx: Context) -> t.List[str]:1558- rv = super().collect_usage_pieces(ctx)1559- rv.append(self.subcommand_metavar)1560- return rv1526+ def add_command(self, cmd: Command, name: t.Optional[str] = None) -> None:1527+ """Registers another :class:`Command` with this group. If the name1528+ is not provided, the name of the command is used.1529+ """1530+ name = name or cmd.name1531+ if name is None:1532+ raise TypeError("Command has no name.")1533+ _check_nested_chain(self, name, cmd, register=True)1534+ self.commands[name] = cmd1535 1562- def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:1563- super().format_options(ctx, formatter)1564- self.format_commands(ctx, formatter)1536+ @t.overload1537+ def command(self, __func: t.Callable[..., t.Any]) -> Command:1538+ ...1539 1540+ @t.overload1541+ def command(1542+ self, *args: t.Any, **kwargs: t.Any1543+ ) -> t.Callable[[t.Callable[..., t.Any]], Command]:1544+ ...1545+1546+ def command(1547+ self, *args: t.Any, **kwargs: t.Any1548+ ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], Command], Command]:1549+ """A shortcut decorator for declaring and attaching a command to1550+ the group. This takes the same arguments as :func:`command` and1551+ immediately registers the created command with this group by1552+ calling :meth:`add_command`.1553+1554+ To customize the command class used, set the1555+ :attr:`command_class` attribute.1556+1557+ .. versionchanged:: 8.11558+ This decorator can be applied without parentheses.1559+1560+ .. versionchanged:: 8.01561+ Added the :attr:`command_class` attribute.1562+ """1563+ from .decorators import command1564+1565+ func: t.Optional[t.Callable[..., t.Any]] = None1566+1567+ if args and callable(args[0]):1568+ assert (1569+ len(args) == 1 and not kwargs1570+ ), "Use 'command(**kwargs)(callable)' to provide arguments."1571+ (func,) = args1572+ args = ()1573+1574+ if self.command_class and kwargs.get("cls") is None:1575+ kwargs["cls"] = self.command_class1576+1577+ def decorator(f: t.Callable[..., t.Any]) -> Command:1578+ cmd: Command = command(*args, **kwargs)(f)1579+ self.add_command(cmd)1580+ return cmd1581+1582+ if func is not None:1583+ return decorator(func)1584+1585+ return decorator1586+1587+ @t.overload1588+ def group(self, __func: t.Callable[..., t.Any]) -> "Group":1589+ ...1590+1591+ @t.overload1592+ def group(1593+ self, *args: t.Any, **kwargs: t.Any1594+ ) -> t.Callable[[t.Callable[..., t.Any]], "Group"]:1595+ ...1596+1597+ def group(1598+ self, *args: t.Any, **kwargs: t.Any1599+ ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], "Group"], "Group"]:1600+ """A shortcut decorator for declaring and attaching a group to1601+ the group. This takes the same arguments as :func:`group` and1602+ immediately registers the created group with this group by1603+ calling :meth:`add_command`.1604+1605+ To customize the group class used, set the :attr:`group_class`1606+ attribute.1607+1608+ .. versionchanged:: 8.11609+ This decorator can be applied without parentheses.1610+1611+ .. versionchanged:: 8.01612+ Added the :attr:`group_class` attribute.1613+ """1614+ from .decorators import group1615+1616+ func: t.Optional[t.Callable[..., t.Any]] = None1617+1618+ if args and callable(args[0]):1619+ assert (1620+ len(args) == 1 and not kwargs1621+ ), "Use 'group(**kwargs)(callable)' to provide arguments."1622+ (func,) = args1623+ args = ()1624+1625+ if self.group_class is not None and kwargs.get("cls") is None:1626+ if self.group_class is type:1627+ kwargs["cls"] = type(self)1628+ else:1629+ kwargs["cls"] = self.group_class1630+1631+ def decorator(f: t.Callable[..., t.Any]) -> "Group":1632+ cmd: Group = group(*args, **kwargs)(f)1633+ self.add_command(cmd)1634+ return cmd1635+1636+ if func is not None:1637+ return decorator(func)1638+1639+ return decorator1640+1641 def result_callback(self, replace: bool = False) -> t.Callable[[F], F]:1642 """Adds a result callback to the command. By default if a1643 result callback is already registered this will chain them but1644 this can be disabled with the `replace` parameter. The result37 unmodified lines1682 return rv1683 1684 return decorator1685 1686+ def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:1687+ """Given a context and a command name, this returns a :class:`Command`1688+ object if it exists or returns ``None``.1689+ """1690+ return self.commands.get(cmd_name)1691+1692+ def list_commands(self, ctx: Context) -> t.List[str]:1693+ """Returns a list of subcommand names in the order they should appear."""1694+ return sorted(self.commands)1695+1696+ def collect_usage_pieces(self, ctx: Context) -> t.List[str]:1697+ rv = super().collect_usage_pieces(ctx)1698+ rv.append(self.subcommand_metavar)1699+ return rv1700+1701+ def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:1702+ super().format_options(ctx, formatter)1703+ self.format_commands(ctx, formatter)1704+1705 def format_commands(self, ctx: Context, formatter: HelpFormatter) -> None:1706 """Extra format methods for multi methods that adds all the commands1707 after the options.1708 """130 unmodified lines1839 self.parse_args(ctx, ctx.args)1840 ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name))1841 return cmd_name if cmd else None, cmd, args[1:]1842 1749- def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:1750- """Given a context and a command name, this returns a1751- :class:`Command` object if it exists or returns `None`.1752- """1753- raise NotImplementedError1754-1755- def list_commands(self, ctx: Context) -> t.List[str]:1756- """Returns a list of subcommand names in the order they should1757- appear.1758- """1759- return []1760-1843 def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:1844 """Return a list of completions for the incomplete value. Looks1845 at the names of options, subcommands, and chained1846 multi-commands.12 unmodified lines1859 results.extend(super().shell_complete(ctx, incomplete))1860 return results1861 1862 1781-class Group(MultiCommand):1782- """A group allows a command to have subcommands attached. This is1783- the most common way to implement nesting in Click.1784-1785- :param name: The name of the group command.1786- :param commands: A dict mapping names to :class:`Command` objects.1787- Can also be a list of :class:`Command`, which will use1788- :attr:`Command.name` to create the dict.1789- :param attrs: Other command arguments described in1790- :class:`MultiCommand`, :class:`Command`, and1791- :class:`BaseCommand`.1792-1793- .. versionchanged:: 8.01794- The ``commands`` argument can be a list of command objects.1863+class _MultiCommand(Group, metaclass=_FakeSubclassCheck):1864 """1865+ .. deprecated:: 8.21866+ Will be removed in Click 9.0. Use ``Group`` instead.1867+ """1868 1797- #: If set, this is used by the group's :meth:`command` decorator1798- #: as the default :class:`Command` class. This is useful to make all1799- #: subcommands use a custom command class.1800- #:1801- #: .. versionadded:: 8.01802- command_class: t.Optional[t.Type[Command]] = None1869 1804- #: If set, this is used by the group's :meth:`group` decorator1805- #: as the default :class:`Group` class. This is useful to make all1806- #: subgroups use a custom group class.1807- #:1808- #: If set to the special value :class:`type` (literally1809- #: ``group_class = type``), this group's class will be used as the1810- #: default class. This makes a custom group class continue to make1811- #: custom groups.1812- #:1813- #: .. versionadded:: 8.01814- group_class: t.Optional[t.Union[t.Type["Group"], t.Type[type]]] = None1815- # Literal[type] isn't valid, so use Type[type]1870+class CommandCollection(Group):1871+ """A :class:`Group` that looks up subcommands on other groups. If a command1872+ is not found on this group, each registered source is checked in order.1873+ Parameters on a source are not added to this group, and a source's callback1874+ is not invoked when invoking its commands. In other words, this "flattens"1875+ commands in many groups into this one group.1876 1817- def __init__(1818- self,1819- name: t.Optional[str] = None,1820- commands: t.Optional[1821- t.Union[t.MutableMapping[str, Command], t.Sequence[Command]]1822- ] = None,1823- **attrs: t.Any,1824- ) -> None:1825- super().__init__(name, **attrs)1877+ :param name: The name of the group command.1878+ :param sources: A list of :class:`Group` objects to look up commands from.1879+ :param kwargs: Other arguments passed to :class:`Group`.1880 1827- if commands is None:1828- commands = {}1829- elif isinstance(commands, abc.Sequence):1830- commands = {c.name: c for c in commands if c.name is not None}1831-1832- #: The registered subcommands by their exported names.1833- self.commands: t.MutableMapping[str, Command] = commands1834-1835- def add_command(self, cmd: Command, name: t.Optional[str] = None) -> None:1836- """Registers another :class:`Command` with this group. If the name1837- is not provided, the name of the command is used.1838- """1839- name = name or cmd.name1840- if name is None:1841- raise TypeError("Command has no name.")1842- _check_multicommand(self, name, cmd, register=True)1843- self.commands[name] = cmd1844-1845- @t.overload1846- def command(self, __func: t.Callable[..., t.Any]) -> Command:1847- ...1848-1849- @t.overload1850- def command(1851- self, *args: t.Any, **kwargs: t.Any1852- ) -> t.Callable[[t.Callable[..., t.Any]], Command]:1853- ...1854-1855- def command(1856- self, *args: t.Any, **kwargs: t.Any1857- ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], Command], Command]:1858- """A shortcut decorator for declaring and attaching a command to1859- the group. This takes the same arguments as :func:`command` and1860- immediately registers the created command with this group by1861- calling :meth:`add_command`.1862-1863- To customize the command class used, set the1864- :attr:`command_class` attribute.1865-1866- .. versionchanged:: 8.11867- This decorator can be applied without parentheses.1868-1869- .. versionchanged:: 8.01870- Added the :attr:`command_class` attribute.1871- """1872- from .decorators import command1873-1874- func: t.Optional[t.Callable[..., t.Any]] = None1875-1876- if args and callable(args[0]):1877- assert (1878- len(args) == 1 and not kwargs1879- ), "Use 'command(**kwargs)(callable)' to provide arguments."1880- (func,) = args1881- args = ()1882-1883- if self.command_class and kwargs.get("cls") is None:1884- kwargs["cls"] = self.command_class1885-1886- def decorator(f: t.Callable[..., t.Any]) -> Command:1887- cmd: Command = command(*args, **kwargs)(f)1888- self.add_command(cmd)1889- return cmd1890-1891- if func is not None:1892- return decorator(func)1893-1894- return decorator1895-1896- @t.overload1897- def group(self, __func: t.Callable[..., t.Any]) -> "Group":1898- ...1899-1900- @t.overload1901- def group(1902- self, *args: t.Any, **kwargs: t.Any1903- ) -> t.Callable[[t.Callable[..., t.Any]], "Group"]:1904- ...1905-1906- def group(1907- self, *args: t.Any, **kwargs: t.Any1908- ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], "Group"], "Group"]:1909- """A shortcut decorator for declaring and attaching a group to1910- the group. This takes the same arguments as :func:`group` and1911- immediately registers the created group with this group by1912- calling :meth:`add_command`.1913-1914- To customize the group class used, set the :attr:`group_class`1915- attribute.1916-1917- .. versionchanged:: 8.11918- This decorator can be applied without parentheses.1919-1920- .. versionchanged:: 8.01921- Added the :attr:`group_class` attribute.1922- """1923- from .decorators import group1924-1925- func: t.Optional[t.Callable[..., t.Any]] = None1926-1927- if args and callable(args[0]):1928- assert (1929- len(args) == 1 and not kwargs1930- ), "Use 'group(**kwargs)(callable)' to provide arguments."1931- (func,) = args1932- args = ()1933-1934- if self.group_class is not None and kwargs.get("cls") is None:1935- if self.group_class is type:1936- kwargs["cls"] = type(self)1937- else:1938- kwargs["cls"] = self.group_class1939-1940- def decorator(f: t.Callable[..., t.Any]) -> "Group":1941- cmd: Group = group(*args, **kwargs)(f)1942- self.add_command(cmd)1943- return cmd1944-1945- if func is not None:1946- return decorator(func)1947-1948- return decorator1949-1950- def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:1951- return self.commands.get(cmd_name)1952-1953- def list_commands(self, ctx: Context) -> t.List[str]:1954- return sorted(self.commands)1955-1956-1957-class CommandCollection(MultiCommand):1958- """A command collection is a multi command that merges multiple multi1959- commands together into one. This is a straightforward implementation1960- that accepts a list of different multi commands as sources and1961- provides all the commands for each of them.1962-1963- See :class:`MultiCommand` and :class:`Command` for the description of1964- ``name`` and ``attrs``.1881+ .. versionchanged:: 8.21882+ This is a subclass of ``Group``. Commands are looked up first on this1883+ group, then each of its sources.1884 """1885 1886 def __init__(1887 self,1888 name: t.Optional[str] = None,1970- sources: t.Optional[t.List[MultiCommand]] = None,1971- **attrs: t.Any,1889+ sources: t.Optional[t.List[Group]] = None,1890+ **kwargs: t.Any,1891 ) -> None:1973- super().__init__(name, **attrs)1974- #: The list of registered multi commands.1975- self.sources: t.List[MultiCommand] = sources or []1892+ super().__init__(name, **kwargs)1893+ #: The list of registered groups.1894+ self.sources: t.List[Group] = sources or []1895 1977- def add_source(self, multi_cmd: MultiCommand) -> None:1978- """Adds a new multi command to the chain dispatcher."""1979- self.sources.append(multi_cmd)1896+ def add_source(self, group: Group) -> None:1897+ """Add a group as a source of commands."""1898+ self.sources.append(group)1899 1900 def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:1901+ rv = super().get_command(ctx, cmd_name)1902+1903+ if rv is not None:1904+ return rv1905+1906 for source in self.sources:1907 rv = source.get_command(ctx, cmd_name)1908 1909 if rv is not None:1910 if self.chain:1987- _check_multicommand(self, cmd_name, rv)1911+ _check_nested_chain(self, cmd_name, rv)1912 1913 return rv1914 1915 return None1916 1917 def list_commands(self, ctx: Context) -> t.List[str]:1994- rv: t.Set[str] = set()1918+ rv: t.Set[str] = set(super().list_commands(ctx))1919 1920 for source in self.sources:1921 rv.update(source.list_commands(ctx))1922 1040 unmodified lines2963 return f"'{self.make_metavar()}'"2964 2965 def add_to_parser(self, parser: OptionParser, ctx: Context) -> None:2966 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)2967+2968+2969+def __getattr__(name: str) -> object:2970+ import warnings2971+2972+ if name == "BaseCommand":2973+ warnings.warn(2974+ "'BaseCommand' is deprecated and will be removed in Click 9.0. Use"2975+ " 'Command' instead.",2976+ DeprecationWarning,2977+ stacklevel=2,2978+ )2979+ return _BaseCommand2980+2981+ if name == "MultiCommand":2982+ warnings.warn(2983+ "'MultiCommand' is deprecated and will be removed in Click 9.0. Use"2984+ " 'Group' instead.",2985+ DeprecationWarning,2986+ stacklevel=2,2987+ )2988+ return _MultiCommand2989+2990+ raise AttributeError(name)modified:src/click/shell_completion.py+7 added-7 removed
2 unmodified lines3 import typing as t4 from gettext import gettext as _5 6 from .core import Argument7-from .core import BaseCommand7+from .core import Command8 from .core import Context9-from .core import MultiCommand9+from .core import Group10 from .core import Option11 from .core import Parameter12 from .core import ParameterSource13 from .parser import split_arg_string14 from .utils import echo15 16 17 def shell_complete(18- cli: BaseCommand,18+ cli: Command,19 ctx_args: t.MutableMapping[str, t.Any],20 prog_name: str,21 complete_var: str,22 instruction: str,191 unmodified lines214 """215 216 def __init__(217 self,218- cli: BaseCommand,218+ cli: Command,219 ctx_args: t.MutableMapping[str, t.Any],220 prog_name: str,221 complete_var: str,222 ) -> None:269 unmodified lines492 return last_option is not None and last_option in param.opts493 494 495 def _resolve_context(496- cli: BaseCommand,496+ cli: Command,497 ctx_args: t.MutableMapping[str, t.Any],498 prog_name: str,499 args: t.List[str],500 ) -> Context:11 unmodified lines512 513 while args:514 command = ctx.command515 516- if isinstance(command, MultiCommand):516+ if isinstance(command, Group):517 if not command.chain:518 name, cmd, args = command.resolve_command(ctx, args)519 520 if cmd is None:29 unmodified lines550 551 552 def _resolve_incomplete(553 ctx: Context, args: t.List[str], incomplete: str554-) -> t.Tuple[t.Union[BaseCommand, Parameter], str]:554+) -> t.Tuple[t.Union[Command, Parameter], str]:555 """Find the Click object that will handle the completion of the556 incomplete value. Return the object and the incomplete value.557 558 :param ctx: Invocation context for the command represented by38 unmodified linesmodified:src/click/testing.py+3 added-3 removed
12 unmodified lines13 from . import utils14 from ._compat import _find_binary_reader15 16 if t.TYPE_CHECKING:17- from .core import BaseCommand17+ from .core import Command18 19 20 class EchoingStdin:21 def __init__(self, input: t.BinaryIO, output: t.BinaryIO) -> None:164 unmodified lines186 self.env: t.Mapping[str, t.Optional[str]] = env or {}187 self.echo_stdin = echo_stdin188 self.mix_stderr = mix_stderr189 190- def get_default_prog_name(self, cli: "BaseCommand") -> str:190+ def get_default_prog_name(self, cli: "Command") -> str:191 """Given a command object it will return the default program name192 for it. The default is the `name` attribute or ``"root"`` if not193 set.194 """152 unmodified lines347 formatting.FORCED_WIDTH = old_forced_width348 349 def invoke(350 self,351- cli: "BaseCommand",351+ cli: "Command",352 args: t.Optional[t.Union[str, t.Sequence[str]]] = None,353 input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]] = None,354 env: t.Optional[t.Mapping[str, t.Optional[str]]] = None,355 catch_exceptions: bool = True,124 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 linesmodified:tests/test_commands.py+2 added-2 removed
143 unmodified lines144 assert result.exit_code == exit_code145 assert expect in result.output146 147 148-def test_base_command(runner):148+def test_custom_parser(runner):149 import optparse150 151 @click.group()152 def cli():153 pass154 155- class OptParseCommand(click.BaseCommand):155+ class OptParseCommand(click.Command):156 def __init__(self, name, parser, callback):157 super().__init__(name)158 self.parser = parser159 self.callback = callback252 unmodified linesmodified:CHANGES.rst+4 added
7 unmodified lines8 - Drop support for Python 3.7. :pr:`2588`9 - Use modern packaging metadata with ``pyproject.toml`` instead of ``setup.cfg``.10 :pr:`326`11 - Use ``flit_core`` instead of ``setuptools`` as build backend.12+- ``BaseCommand`` is deprecated. ``Command`` is the base class for all13+ commands. :issue:`2589`14+- ``MultiCommand`` is deprecated. ``Group`` is the base class for all group15+ commands. :issue:`2590`16 17 18 Version 8.1.719 -------------1102 unmodified lines