Skip to content
Myr

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

15 files+767 added−807 removed

modified:docs/advanced.rst+33 added-26 removed
5 unmodified lines
6In addition to common functionality that is implemented in the library7itself, there are countless patterns that can be implemented by extending8Click. This page should give some insight into what can be accomplished.91011.. _aliases:1213Command Aliases14---------------1515Many tools support aliases for commands (see `Command alias example16<https://github.com/pallets/click/tree/main/examples/aliases>`_).17For instance, you can configure ``git`` to accept ``git ci`` as alias for18``git commit``. Other tools also support auto-discovery for aliases by19automatically shortening them.16Many tools support aliases for commands. For example, you can configure17``git`` to accept ``git ci`` as alias for ``git commit``. Other tools also18support auto-discovery for aliases by automatically shortening them.1921Click does not support this out of the box, but it's very easy to customize22the :class:`Group` or any other :class:`MultiCommand` to provide this23functionality.20It's possible to customize :class:`Group` to provide this functionality. As21explained in :ref:`custom-groups`, a group provides two methods:22:meth:`~Group.list_commands` and :meth:`~Group.get_command`. In this particular23case, you only need to override the latter as you generally don't want to24enumerate the aliases on the help page in order to avoid confusion.2525As explained in :ref:`custom-multi-commands`, a multi command can provide26two methods: :meth:`~MultiCommand.list_commands` and27:meth:`~MultiCommand.get_command`. In this particular case, you only need28to override the latter as you generally don't want to enumerate the29aliases on the help page in order to avoid confusion.26The following example implements a subclass of :class:`Group` that accepts a27prefix for a command. If there was a command called ``push``, it would accept28``pus`` as an alias (so long as it was unique):2931This following example implements a subclass of :class:`Group` that32accepts a prefix for a command. If there were a command called ``push``,33it would accept ``pus`` as an alias (so long as it was unique):3430.. click:example::3132 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)3536 if rv is not None:37 return rv3839 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 ]4344 if not matches:45 return None4646 elif len(matches) == 1:47 if len(matches) == 1:48 return click.Group.get_command(self, ctx, matches[0])4950 ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")5152 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, args5655And it can then be used like this:57It can be used like this:5859.. click:example::6059 @click.command(cls=AliasedGroup)61 @click.group(cls=AliasedGroup)62 def cli():63 pass6463 @cli.command()65 @cli.command66 def push():67 pass6867 @cli.command()69 @cli.command70 def pop():71 pass7273See the `alias example`_ in Click's repository for another example.7475.. _alias example: https://github.com/pallets/click/tree/main/examples/aliases767778Parameter Modifications79-----------------------8081Parameters (options and arguments) are forwarded to the command callbacks
190 unmodified lines
272273This can generally be activated in two different ways:2742751. 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.2772. 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 lines
modified:docs/commands.rst+126 added-157 removed
1 unmodified line
2===================34.. currentmodule:: click56The most important feature of Click is the concept of arbitrarily nesting7command line utilities. This is implemented through the :class:`Command`8and :class:`Group` (actually :class:`MultiCommand`).6The structure of a Click application is defined with :class:`Command`, which7defines an individual named command, and :class:`Group`, which defines a nested8collection of commands (or more groups) under a name.91011Callback Invocation12-------------------1314For a regular command, the callback is executed whenever the command runs.15If the script is the only command, it will always fire (unless a parameter16callback prevents it. This for instance happens if someone passes17``--help`` to the script).1818For groups and multi commands, the situation looks different. In this case,19the callback fires whenever a subcommand fires (unless this behavior is20changed). What this means in practice is that an outer command runs21when an inner command runs:19For groups, the situation looks different. In this case, the callback fires20whenever a subcommand fires. What this means in practice is that an outer21command runs when an inner command runs:2223.. click:example::2425 @click.group()
121 unmodified lines
147148Group Invocation Without Command149--------------------------------150151By default, a group or multi command is not invoked unless a subcommand is152passed. In fact, not providing a command automatically passes ``--help``153by default. This behavior can be changed by passing154``invoke_without_command=True`` to a group. In that case, the callback is155always invoked instead of showing the help page. The context object also156includes information about whether or not the invocation would go to a157subcommand.151By default, a group is not invoked unless a subcommand is passed. In fact, not152providing a command automatically passes ``--help`` by default. This behavior153can be changed by passing ``invoke_without_command=True`` to a group. In that154case, the callback is always invoked instead of showing the help page. The155context object also includes information about whether or not the invocation156would go to a subcommand.157159Example:160158.. click:example::159160 @click.group(invoke_without_command=True)161 @click.pass_context
6 unmodified lines
168 @cli.command()169 def sync():170 click.echo('The subcommand')171175And how it works in practice:176172.. click:run::173174 invoke(cli, prog_name='tool', args=[])175 invoke(cli, prog_name='tool', args=['sync'])176182.. _custom-multi-commands:177184Custom Multi Commands185---------------------178.. _custom-groups:179187In addition to using :func:`click.group`, you can also build your own188custom multi commands. This is useful when you want to support commands189being loaded lazily from plugins.180Custom Groups181-------------182191A custom multi command just needs to implement a list and load method:183You can customize the behavior of a group beyond the arguments it accepts by184subclassing :class:`click.Group`.185193.. click:example::186The most common methods to override are :meth:`~click.Group.get_command` and187:meth:`~click.Group.list_commands`.188195 import click196 import os189The following example implements a basic plugin system that loads commands from190Python files in a folder. The command is lazily loaded to avoid slow startup.191198 plugin_folder = os.path.join(os.path.dirname(__file__), 'commands')192.. code-block:: python193200 class MyCLI(click.MultiCommand):194 import importlib.util195 import os196 import click197198 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_folder202203 def list_commands(self, ctx):204 rv = []205204 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])209210 rv.sort()211 return rv212213 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.cli219218 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 )223221 if __name__ == '__main__':224 if __name__ == "__main__":225 cli()226224These custom classes can also be used with decorators:227Custom classes can also be used with decorators:228226.. click:example::229.. code-block:: python230228 @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 pass237232Merging Multi Commands233----------------------238235In addition to implementing custom multi commands, it can also be236interesting to merge multiple together into one script. While this is237generally not as recommended as it nests one below the other, the merging238approach can be useful in some circumstances for a nicer shell experience.239.. _command-chaining:240240The default implementation for such a merging system is the241:class:`CommandCollection` class. It accepts a list of other multi242commands and makes the commands available on the same level.241Command Chaining242----------------243244Example usage:244It 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.247248.. click:example::249248 import click249250 @click.group()251 def cli1():250 @click.group(chain=True)251 def cli():252 pass253254 @cli1.command()255 def cmd1():256 """Command on cli1"""254 @cli.command('validate')255 def validate():256 click.echo('validate')257258 @click.group()259 def cli2():260 pass258 @cli.command('build')259 def build():260 click.echo('build')261262 @cli2.command()263 def cmd2():264 """Command on cli2"""262You can invoke it like this:263266 cli = click.CommandCollection(sources=[cli1, cli2])267268 if __name__ == '__main__':269 cli()270271And what it looks like:272264.. click:run::265275 invoke(cli, prog_name='cli', args=['--help'])266 invoke(cli, prog_name='my-app', args=['validate', 'build'])267277In case a command exists in more than one source, the first source wins.268When using chaining, there are a few restrictions:269270- 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.277280.. _multi-command-chaining:278282Multi Command Chaining283----------------------279Command Pipelines280-----------------281285.. versionadded:: 3.0282When using chaining, a common pattern is to have each command process the283result of the previous command.284287Sometimes it is useful to be allowed to invoke more than one subcommand in288one go. For example, ``my-app validate build upload`` would invoke ``validate``,289then ``build``, then ``upload``. To implement this in Click, pass ``chain=True``290when creating a group.285A straightforward way to do this is to use :func:`make_pass_decorator` to pass286a context object to each command, and store and read the data on that object.287288.. click:example::289290 pass_ns = click.make_pass_decorator(dict, ensure=True)291292 @click.group(chain=True)295 def cli():296 pass293 @click.argument("name")294 @pass_ns295 def cli(ns, name):296 ns["name"] = name297298 @cli.command299 @pass_ns300 def lower(ns):301 ns["name"] = ns["name"].lower()302299 @cli.command('sdist')300 def sdist():301 click.echo('sdist called')303 @cli.command304 @pass_ns305 def show(ns):306 click.echo(ns["name"])307303304 @cli.command('bdist_wheel')305 def bdist_wheel():306 click.echo('bdist_wheel called')307308Now you can invoke it like this:309308.. click:run::309312 invoke(cli, prog_name='setup.py', args=['sdist', 'bdist_wheel'])310 invoke(cli, prog_name="process", args=["Click", "show", "lower", "show"])311314When using multi command chaining you can only have one command (the last)315use ``nargs=-1`` on an argument. It is also not possible to nest multi316commands below chained multicommands. Other than that there are no317restrictions on how they work. They can accept options and arguments as318normal. The order between options and arguments is limited for chained319commands. Currently only ``--options argument`` order is allowed.312Another way to do this is to collect data returned by each command, then process313it at the end of the chain. Use the group's :meth:`~Group.result_callback`314decorator to register a function that is called after the chain is finished. It315is passed the list of return values as well as any parameters registered on the316group.317321Another note: the :attr:`Context.invoked_subcommand` attribute is a bit322useless for multi commands as it will give ``'*'`` as value if more than323one command is invoked. This is necessary because the handling of324subcommands happens one after another so the exact subcommands that will325be handled are not yet available when the callback fires.318A command can return anything, including a function. Here's an example of that,319where each subcommand creates a function that processes the input, then the320result callback calls each function. The command takes a file, processes each321line, then outputs it. If no subcommands are given, it outputs the contents322of the file unchanged.323327.. note::324.. code-block:: python325329 It is currently not possible for chain commands to be nested. This330 will be fixed in future versions of Click.331332333Multi Command Pipelines334-----------------------335336.. versionadded:: 3.0337338A very common usecase of multi command chaining is to have one command339process the result of the previous command. There are various ways in340which this can be facilitated. The most obvious way is to store a value341on the context object and process it from function to function. This342works by decorating a function with :func:`pass_context` after which the343context object is provided and a subcommand can store its data there.344345Another way to accomplish this is to setup pipelines by returning346processing functions. Think of it like this: when a subcommand gets347invoked it processes all of its parameters and comes up with a plan of348how to do its processing. At that point it then returns a processing349function and returns.350351Where do the returned functions go? The chained multicommand can register352a callback with :meth:`MultiCommand.result_callback` that goes over all353these functions and then invoke them.354355To make this a bit more concrete consider this example:356357.. click:example::358326 @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 pass330331 @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)334335 for processor in processors:336 iterator = processor(iterator)337338 for item in iterator:339 click.echo(item)340372 @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 processor347379 @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 processor354386 @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 lines
386make resource handling much more complicated. For such it's recommended387to not use the file type and manually open the file through388:func:`open_file`.389421For a more complex example that also improves upon handling of the422pipelines have a look at the `imagepipe multi command chaining demo423<https://github.com/pallets/click/tree/main/examples/imagepipe>`__ in424the Click repository. It implements a pipeline based image editing tool425that has a nice internal structure for the pipelines.390For a more complex example that also improves upon handling of the pipelines,391see the `imagepipe example`_ in the Click repository. It implements a392pipeline based image editing tool that has a nice internal structure.393394.. _imagepipe example: https://github.com/pallets/click/tree/main/examples/imagepipe395396397Overriding Defaults398-------------------399400By default, the default value for a parameter is pulled from the
100 unmodified lines
501that were previously hard to implement.502503In essence any command callback can now return a value. This return value504is bubbled to certain receivers. One usecase for this has already been536show in the example of :ref:`multi-command-chaining` where it has been537demonstrated that chained multi commands can have callbacks that process505show in the example of :ref:`command-chaining` where it has been506demonstrated that chained groups can have callbacks that process507all return values.508509When working with command return values in Click, this is what you need to510know:511512- 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:515516 * In a group the return value is generally the return value of the517 subcommand invoked. The only exception to this rule is that the
1 unmodified line
519 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.526527- The return value is bubbled through from the :meth:`Context.invoke`
1 unmodified line
529 where you internally want to call into another command.530531- 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).535536- 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 lines
223--------------------------224225Large CLIs and CLIs with slow imports may benefit from deferring the loading of226subcommands. 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 such229that :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 such229that :meth:`Group.get_command` is responsible for running imports.230231Since the primary case for this is a :class:`Group` which loads its subcommands lazily,232the following example shows a lazy-group implementation.233
44 unmodified lines
278 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 lines
305 )306 def cli():307 pass308309.. code-block:: python310311 # in foo.py312 import click313314 @click.group(help="foo command for lazy example")315 def cli():316 pass317318.. code-block:: python319320 # in bar.py321 import click322 from lazy_group import LazyGroup323
4 unmodified lines
328 )329 def cli():330 pass331332.. code-block:: python333334 # in baz.py335 import click336337 @click.group(help="baz command for lazy example")
4 unmodified lines
342What triggers Lazy Loading?343```````````````````````````344345There are several events which may trigger lazy loading by running the340:meth:`MultiCommand.get_command` function.346:meth:`Group.get_command` function.347Some are intuititve, and some are less so.348349All cases are described with respect to the above example, assuming the main program350name is ``cli``.
12 unmodified lines
363364It is possible to make the process even lazier, but it is generally more difficult the365more you want to defer work.366361For example, subcommands could be represented as a custom :class:`BaseCommand` subclass367For example, subcommands could be represented as a custom :class:`Command` subclass368which 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.370More simply, commands can be constructed whose callback functions defer any actual work371until after an import.372373This command definition provides ``foo``, but any of the work associated with importing
8 unmodified lines
382 from mylibrary import foo_concrete383384 foo_concrete(n, w)385380Because ``click`` builds helptext and usage info from options, arguments, and command386Because Click builds helptext and usage info from options, arguments, and command387attributes, it has no awareness that the underlying function is in any way handling a382deferred import. Therefore, all ``click``-provided utilities and functionality will work388deferred import. Therefore, all Click-provided utilities and functionality will work389as normal on such a command.
modified:docs/exceptions.rst+1 added-1 removed
8 unmodified lines
910Where are Errors Handled?11-------------------------1213Click's main error handling is happening in :meth:`BaseCommand.main`. In13Click's main error handling is happening in :meth:`Command.main`. In14there it handles all subclasses of :exc:`ClickException` as well as the15standard :exc:`EOFError` and :exc:`KeyboardInterrupt` exceptions. The16latter are internally translated into an :exc:`Abort`.17
56 unmodified lines
modified:docs/quickstart.rst+1 added-1 removed
91 unmodified lines
92* ``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>`_9899Basic Concepts - Creating a Command100-----------------------------------
176 unmodified lines
modified:docs/upgrading.rst+4 added-4 removed
40 unmodified lines
4142Upgrading to 3.243----------------4445Click 3.2 had to perform two changes to multi commands which were45Click 3.2 had to perform two changes to groups which were46triggered by a change between Click 2 and Click 3 that had bigger47consequences than anticipated.4849Context Invokes
21 unmodified lines
7172This also allowed us to fix the issue that defaults were not handled73properly by this function.7475Multicommand Chaining API76`````````````````````````75Command Chaining API76````````````````````7778Click 3 introduced multicommand chaining. This required a change in how78Click 3 introduced command chaining. This required a change in how79Click internally dispatches. Unfortunately this change was not correctly80implemented and it appeared that it was possible to provide an API that81can inform the super command about all the subcommands that will be82invoked.
49 unmodified lines
modified:examples/complex/complex/cli.py+1 added-1 removed
26 unmodified lines
27pass_environment = click.make_pass_decorator(Environment, ensure=True)28cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), "commands"))293031class ComplexCLI(click.MultiCommand):31class 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 lines
modified:examples/imagepipe/README+1 added-1 removed
1$ imagepipe_23 imagepipe is an example application that implements some4 multi commands that chain image processing instructions4 commands that chain image processing instructions5 together.67 This requires pillow.8
5 unmodified lines
modified:src/click/__init__.py+28 added-2 removed
3 unmodified lines
4around a simple API that does not come with too much magic and is5composable.6"""7from .core import Argument as Argument8from .core import BaseCommand as BaseCommand8from .core import Command as Command9from .core import CommandCollection as CommandCollection10from .core import Context as Context11from .core import Group as Group13from .core import MultiCommand as MultiCommand12from .core import Option as Option13from .core import Parameter as Parameter14from .decorators import argument as argument15from .decorators import command as command
52 unmodified lines
68from .utils import get_text_stream as get_text_stream69from .utils import open_file as open_file7071__version__ = "8.2.0.dev0"727374def __getattr__(name: str) -> object:75 import warnings7677 if name == "BaseCommand":78 from .core import _BaseCommand7980 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 _BaseCommand8788 if name == "MultiCommand":89 from .core import _MultiCommand9091 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 _MultiCommand9899 raise AttributeError(name)
modified:src/click/core.py+539 added-591 removed
52 unmodified lines
5354 :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)5859 for name in multi.list_commands(ctx):60 if name.startswith(incomplete):61 command = multi.get_command(ctx, name)
1 unmodified line
63 if command is not None and not command.hidden:64 yield name, command656667def _check_multicommand(68 base_command: "MultiCommand", cmd_name: str, cmd: "Command", register: bool = False67def _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 return7273 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 )8384 raise RuntimeError(message)858687def batch(iterable: t.Iterable[V], batch_size: int) -> t.List[t.Tuple[V, ...]]:88 return list(zip(*repeat(iter(iterable), batch_size)))8990
735 unmodified lines
826 """827 return self._parameter_source.get(name)828829834class 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.839840 For instance, this can be used to bridge Click and other systems like841 argparse or docopt.842843 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.847848 .. versionchanged:: 2.0849 Added the `context_settings` parameter.850851 :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 """855856 #: 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 = False866867 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 = name877878 if context_settings is None:879 context_settings = {}880881 #: an optional dictionary with defaults passed to the context.882 self.context_settings: t.MutableMapping[str, t.Any] = context_settings883884 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.888889 Use :meth:`click.Context.to_info_dict` to traverse the entire890 CLI structure.891892 :param ctx: A :class:`Context` representing this command.893894 .. versionadded:: 8.0895 """896 return {"name": self.name}897898 def __repr__(self) -> str:899 return f"<{self.__class__.__name__} {self.name}>"900901 def get_usage(self, ctx: Context) -> str:902 raise NotImplementedError("Base commands cannot get usage")903904 def get_help(self, ctx: Context) -> str:905 raise NotImplementedError("Base commands cannot get help")906907 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.917918 To quickly customize the context class used without overriding919 this method, set the :attr:`context_class` attribute.920921 :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.930931 .. 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] = value937938 ctx = self.context_class(939 self, info_name=info_name, parent=parent, **extra # type: ignore940 )941942 with ctx.scope(cleanup=False):943 self.parse_args(ctx, args)944 return ctx945946 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.")952953 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")958959 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.962963 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.966967 :param ctx: Invocation context for this command.968 :param incomplete: Value being completed. May be empty.969970 .. versionadded:: 8.0971 """972 from click.shell_completion import CompletionItem973974 results: t.List["CompletionItem"] = []975976 while ctx.parent is not None:977 ctx = ctx.parent978979 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 )985986 return results987988 @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 ...998999 @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 ...10091010 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.10231024 This method is also available by directly calling the instance of1025 a :class:`Command`.10261027 :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.10491050 .. versionchanged:: 8.0.11051 Added the ``windows_expand_args`` parameter to allow1052 disabling command line arg expansion on Windows.10531054 .. versionchanged:: 8.01055 When taking arguments from ``sys.argv`` on Windows, glob1056 patterns, user dir, and env vars are expanded.10571058 .. versionchanged:: 3.01059 Added the ``standalone_mode`` parameter.1060 """1061 if args is None:1062 args = sys.argv[1:]10631064 if os.name == "nt" and windows_expand_args:1065 args = _expand_args(args)1066 else:1067 args = list(args)10681069 if prog_name is None:1070 prog_name = _detect_program_name()10711072 # Process shell completion requests and exit early.1073 self._main_shell_completion(extra, prog_name, complete_var)10741075 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)11221123 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.11321133 :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``.11371138 .. 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()11441145 instruction = os.environ.get(complete_var)11461147 if not instruction:1148 return11491150 from .shell_completion import shell_complete11511152 rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)1153 sys.exit(rv)11541155 def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any:1156 """Alias for :meth:`main`."""1157 return self.main(*args, **kwargs)115811591160class Command(BaseCommand):830class 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 lines
853854 :param deprecated: issues a message indicating that855 the command is deprecated.856857 .. versionchanged:: 8.2858 This is the base class for all commands, not ``BaseCommand``.859860 .. 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 lines
871 .. versionchanged:: 2.0872 Added the ``context_settings`` parameter.873 """874875 #: The context class to create with :meth:`make_context`.876 #:877 #: .. versionadded:: 8.0878 context_class: t.Type[Context] = Context879880 #: the default for the :attr:`Context.allow_extra_args` flag.881 allow_extra_args = False882883 #: the default for the :attr:`Context.allow_interspersed_args` flag.884 allow_interspersed_args = True885886 #: the default for the :attr:`Context.ignore_unknown_options` flag.887 ignore_unknown_options = False888889 def __init__(890 self,891 name: t.Optional[str],892 context_settings: t.Optional[t.MutableMapping[str, t.Any]] = None,
7 unmodified lines
900 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 = name909910 if context_settings is None:911 context_settings = {}912913 #: an optional dictionary with defaults passed to the context.914 self.context_settings: t.MutableMapping[str, t.Any] = context_settings915916 #: 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 they
9 unmodified lines
929 self.hidden = hidden930 self.deprecated = deprecated931932 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 }942943 def __repr__(self) -> str:944 return f"<{self.__class__.__name__} {self.name}>"945946 def get_usage(self, ctx: Context) -> str:947 """Formats the usage line into a string and returns it.948949 Calls :meth:`format_usage` internally.
145 unmodified lines
10951096 with formatter.indentation():1097 formatter.write_text(epilog)10981099 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.11091110 To quickly customize the context class used without overriding1111 this method, set the :attr:`context_class` attribute.11121113 :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.11221123 .. 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] = value11291130 ctx = self.context_class(self, info_name=info_name, parent=parent, **extra)11311132 with ctx.scope(cleanup=False):1133 self.parse_args(ctx, args)1134 return ctx11351136 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 lines
1173 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.11761177 Any command could be part of a chained multi-command, so sibling1178 commands are valid at any point during command completion.11791180 :param ctx: Invocation context for this command.1181 :param incomplete: Value being completed. May be empty.11821183 .. versionadded:: 8.0
20 unmodified lines
1204 for name in [*param.opts, *param.secondary_opts]1205 if name.startswith(incomplete)1206 )12071468 results.extend(super().shell_complete(ctx, incomplete))1208 while ctx.parent is not None:1209 ctx = ctx.parent12101211 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 )12171218 return results12191220 @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 ...12301472class 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 ...12411477 :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.12551256 This method is also available by directly calling the instance of1257 a :class:`Command`.12581259 :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.12811282 .. versionchanged:: 8.0.11283 Added the ``windows_expand_args`` parameter to allow1284 disabling command line arg expansion on Windows.12851286 .. versionchanged:: 8.01287 When taking arguments from ``sys.argv`` on Windows, glob1288 patterns, user dir, and env vars are expanded.12891290 .. versionchanged:: 3.01291 Added the ``standalone_mode`` parameter.1292 """1293 if args is None:1294 args = sys.argv[1:]12951296 if os.name == "nt" and windows_expand_args:1297 args = _expand_args(args)1298 else:1299 args = list(args)13001301 if prog_name is None:1302 prog_name = _detect_program_name()13031304 # Process shell completion requests and exit early.1305 self._main_shell_completion(extra, prog_name, complete_var)13061307 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)13541355 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.13641365 :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``.13691370 .. 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()13761377 instruction = os.environ.get(complete_var)13781379 if not instruction:1380 return13811382 from .shell_completion import shell_complete13831384 rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)1385 sys.exit(rv)13861387 def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any:1388 """Alias for :meth:`main`."""1389 return self.main(*args, **kwargs)139013911392class _FakeSubclassCheck(type):1393 def __subclasscheck__(cls, subclass: type) -> bool:1394 return issubclass(subclass, cls.__bases__[0])13951396 def __instancecheck__(cls, instance: t.Any) -> bool:1397 return isinstance(instance, cls.__bases__[0])139813991400class _BaseCommand(Command, metaclass=_FakeSubclassCheck):1401 """1402 .. deprecated:: 8.21403 Will be removed in Click 9.0. Use ``Command`` instead.1404 """140514061407class Group(Command):1408 """A group is a command that nests other commands (or more groups).14091410 :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`.14291430 .. versionchanged:: 8.21431 Merged with and replaces the ``MultiCommand`` base class.14321433 .. versionchanged:: 8.01434 The ``commands`` argument can be a list of command objects.1435 """14361437 allow_extra_args = True1438 allow_interspersed_args = False14391440 #: 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]] = None14461447 #: 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]14591460 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)14741475 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}14791480 #: The registered subcommands by their exported names.1481 self.commands: t.MutableMapping[str, Command] = commands14821483 if no_args_is_help is None:1484 no_args_is_help = not invoke_without_command14851486 self.no_args_is_help = no_args_is_help
14 unmodified lines
1501 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 )15071508 def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]:1509 info_dict = super().to_info_dict(ctx)
12 unmodified lines
15221523 info_dict.update(commands=commands, chain=self.chain)1524 return info_dict15251557 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] = cmd15351562 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 ...15391540 @t.overload1541 def command(1542 self, *args: t.Any, **kwargs: t.Any1543 ) -> t.Callable[[t.Callable[..., t.Any]], Command]:1544 ...15451546 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`.15531554 To customize the command class used, set the1555 :attr:`command_class` attribute.15561557 .. versionchanged:: 8.11558 This decorator can be applied without parentheses.15591560 .. versionchanged:: 8.01561 Added the :attr:`command_class` attribute.1562 """1563 from .decorators import command15641565 func: t.Optional[t.Callable[..., t.Any]] = None15661567 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 = ()15731574 if self.command_class and kwargs.get("cls") is None:1575 kwargs["cls"] = self.command_class15761577 def decorator(f: t.Callable[..., t.Any]) -> Command:1578 cmd: Command = command(*args, **kwargs)(f)1579 self.add_command(cmd)1580 return cmd15811582 if func is not None:1583 return decorator(func)15841585 return decorator15861587 @t.overload1588 def group(self, __func: t.Callable[..., t.Any]) -> "Group":1589 ...15901591 @t.overload1592 def group(1593 self, *args: t.Any, **kwargs: t.Any1594 ) -> t.Callable[[t.Callable[..., t.Any]], "Group"]:1595 ...15961597 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`.16041605 To customize the group class used, set the :attr:`group_class`1606 attribute.16071608 .. versionchanged:: 8.11609 This decorator can be applied without parentheses.16101611 .. versionchanged:: 8.01612 Added the :attr:`group_class` attribute.1613 """1614 from .decorators import group16151616 func: t.Optional[t.Callable[..., t.Any]] = None16171618 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 = ()16241625 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_class16301631 def decorator(f: t.Callable[..., t.Any]) -> "Group":1632 cmd: Group = group(*args, **kwargs)(f)1633 self.add_command(cmd)1634 return cmd16351636 if func is not None:1637 return decorator(func)16381639 return decorator16401641 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 result
37 unmodified lines
1682 return rv16831684 return decorator16851686 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)16911692 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)16951696 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 rv17001701 def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:1702 super().format_options(ctx, formatter)1703 self.format_commands(ctx, formatter)17041705 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 lines
1839 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:]18421749 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 NotImplementedError17541755 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 []17601843 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 lines
1859 results.extend(super().shell_complete(ctx, incomplete))1860 return results186118621781class Group(MultiCommand):1782 """A group allows a command to have subcommands attached. This is1783 the most common way to implement nesting in Click.17841785 :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`.17921793 .. versionchanged:: 8.01794 The ``commands`` argument can be a list of command objects.1863class _MultiCommand(Group, metaclass=_FakeSubclassCheck):1864 """1865 .. deprecated:: 8.21866 Will be removed in Click 9.0. Use ``Group`` instead.1867 """18681797 #: 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]] = None18691804 #: 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]1870class 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.18761817 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`.18801827 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}18311832 #: The registered subcommands by their exported names.1833 self.commands: t.MutableMapping[str, Command] = commands18341835 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] = cmd18441845 @t.overload1846 def command(self, __func: t.Callable[..., t.Any]) -> Command:1847 ...18481849 @t.overload1850 def command(1851 self, *args: t.Any, **kwargs: t.Any1852 ) -> t.Callable[[t.Callable[..., t.Any]], Command]:1853 ...18541855 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`.18621863 To customize the command class used, set the1864 :attr:`command_class` attribute.18651866 .. versionchanged:: 8.11867 This decorator can be applied without parentheses.18681869 .. versionchanged:: 8.01870 Added the :attr:`command_class` attribute.1871 """1872 from .decorators import command18731874 func: t.Optional[t.Callable[..., t.Any]] = None18751876 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 = ()18821883 if self.command_class and kwargs.get("cls") is None:1884 kwargs["cls"] = self.command_class18851886 def decorator(f: t.Callable[..., t.Any]) -> Command:1887 cmd: Command = command(*args, **kwargs)(f)1888 self.add_command(cmd)1889 return cmd18901891 if func is not None:1892 return decorator(func)18931894 return decorator18951896 @t.overload1897 def group(self, __func: t.Callable[..., t.Any]) -> "Group":1898 ...18991900 @t.overload1901 def group(1902 self, *args: t.Any, **kwargs: t.Any1903 ) -> t.Callable[[t.Callable[..., t.Any]], "Group"]:1904 ...19051906 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`.19131914 To customize the group class used, set the :attr:`group_class`1915 attribute.19161917 .. versionchanged:: 8.11918 This decorator can be applied without parentheses.19191920 .. versionchanged:: 8.01921 Added the :attr:`group_class` attribute.1922 """1923 from .decorators import group19241925 func: t.Optional[t.Callable[..., t.Any]] = None19261927 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 = ()19331934 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_class19391940 def decorator(f: t.Callable[..., t.Any]) -> "Group":1941 cmd: Group = group(*args, **kwargs)(f)1942 self.add_command(cmd)1943 return cmd19441945 if func is not None:1946 return decorator(func)19471948 return decorator19491950 def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:1951 return self.commands.get(cmd_name)19521953 def list_commands(self, ctx: Context) -> t.List[str]:1954 return sorted(self.commands)195519561957class 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.19621963 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 """18851886 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 []18951977 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)18991900 def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:1901 rv = super().get_command(ctx, cmd_name)19021903 if rv is not None:1904 return rv19051906 for source in self.sources:1907 rv = source.get_command(ctx, cmd_name)19081909 if rv is not None:1910 if self.chain:1987 _check_multicommand(self, cmd_name, rv)1911 _check_nested_chain(self, cmd_name, rv)19121913 return rv19141915 return None19161917 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))19191920 for source in self.sources:1921 rv.update(source.list_commands(ctx))1922
1040 unmodified lines
2963 return f"'{self.make_metavar()}'"29642965 def add_to_parser(self, parser: OptionParser, ctx: Context) -> None:2966 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)296729682969def __getattr__(name: str) -> object:2970 import warnings29712972 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 _BaseCommand29802981 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 _MultiCommand29892990 raise AttributeError(name)
modified:src/click/shell_completion.py+7 added-7 removed
2 unmodified lines
3import typing as t4from gettext import gettext as _56from .core import Argument7from .core import BaseCommand7from .core import Command8from .core import Context9from .core import MultiCommand9from .core import Group10from .core import Option11from .core import Parameter12from .core import ParameterSource13from .parser import split_arg_string14from .utils import echo151617def 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 lines
214 """215216 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 lines
492 return last_option is not None and last_option in param.opts493494495def _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 lines
512513 while args:514 command = ctx.command515516 if isinstance(command, MultiCommand):516 if isinstance(command, Group):517 if not command.chain:518 name, cmd, args = command.resolve_command(ctx, args)519520 if cmd is None:
29 unmodified lines
550551552def _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.557558 :param ctx: Invocation context for the command represented by
38 unmodified lines
modified:src/click/testing.py+3 added-3 removed
12 unmodified lines
13from . import utils14from ._compat import _find_binary_reader1516if t.TYPE_CHECKING:17 from .core import BaseCommand17 from .core import Command181920class EchoingStdin:21 def __init__(self, input: t.BinaryIO, output: t.BinaryIO) -> None:
164 unmodified lines
186 self.env: t.Mapping[str, t.Optional[str]] = env or {}187 self.echo_stdin = echo_stdin188 self.mix_stderr = mix_stderr189190 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 lines
347 formatting.FORCED_WIDTH = old_forced_width348349 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 lines
modified:tests/test_chain.py+2 added-2 removed
187 unmodified lines
188 assert not result.exception189 assert result.output.splitlines() == ["cli=", "a=", "b=", "c="]190191192def test_multicommand_arg_behavior(runner):192def test_group_arg_behavior(runner):193 with pytest.raises(RuntimeError):194195 @click.group(chain=True)196 @click.argument("forbidden", required=False)
21 unmodified lines
218 assert result.output.splitlines() == ["cli:foo", "a"]219220221@pytest.mark.xfail222def test_multicommand_chaining(runner):222def test_group_chaining(runner):223 @click.group(chain=True)224 def cli():225 debug()226
19 unmodified lines
modified:tests/test_commands.py+2 added-2 removed
143 unmodified lines
144 assert result.exit_code == exit_code145 assert expect in result.output146147148def test_base_command(runner):148def test_custom_parser(runner):149 import optparse150151 @click.group()152 def cli():153 pass154155 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 = callback
252 unmodified lines
modified:CHANGES.rst+4 added
7 unmodified lines
8- 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`161718Version 8.1.719-------------
1102 unmodified lines