Skip to content
Myr

deprecate MultiCommand

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by David Lord · parent 9dd1207 · Browse files · 4 files+251 added−241 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+251 added−241 removed

  • other:+251 added−241 removed

4 files+251 added−241 removed

modified:src/click/__init__.py+11 added-1 removed
7 unmodified lines
8from .core import Command as Command9from .core import CommandCollection as CommandCollection10from .core import Context as Context11from .core import Group as Group12from .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
68 unmodified lines
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+236 added-238 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 return72 if register:73 hint = (74 "It is not possible to add multi commands as children to"
1136 unmodified lines
12111212 while ctx.parent is not None:1213 ctx = ctx.parent12141215 if isinstance(ctx.command, MultiCommand) and ctx.command.chain:1215 if isinstance(ctx.command, Group) and ctx.command.chain:1216 results.extend(1217 CompletionItem(name, help=command.get_short_help_str())1218 for name, command in _complete_visible_commands(ctx, incomplete)1219 if name not in ctx.protected_args
187 unmodified lines
1407 Will be removed in Click 9.0. Use ``Command`` instead.1408 """140914101411class Group(Command):1412 """A group is a command that nests other commands (or more groups).14131412class MultiCommand(Command):1413 """A multi command is the basic implementation of a command that1414 dispatches to subcommands. The most common version is the1415 :class:`Group`.1414 :param name: The name of the group command.1415 :param commands: Map names to :class:`Command` objects. Can be a list, which1416 will use :attr:`Command.name` as the keys.1417 :param invoke_without_command: Invoke the group's callback even if a1418 subcommand is not given.1419 :param no_args_is_help: If no arguments are given, show the group's help and1420 exit. Defaults to the opposite of ``invoke_without_command``.1421 :param subcommand_metavar: How to represent the subcommand argument in help.1422 The default will represent whether ``chain`` is set or not.1423 :param chain: Allow passing more than one subcommand argument. After parsing1424 a command's arguments, if any arguments remain another command will be1425 matched, and so on.1426 :param result_callback: A function to call after the group's and1427 subcommand's callbacks. The value returned by the subcommand is passed.1428 If ``chain`` is enabled, the value will be a list of values returned by1429 all the commands. If ``invoke_without_command`` is enabled, the value1430 will be the value returned by the group's callback, or an empty list if1431 ``chain`` is enabled.1432 :param kwargs: Other arguments passed to :class:`Command`.14331417 :param invoke_without_command: this controls how the multi command itself1418 is invoked. By default it's only invoked1419 if a subcommand is provided.1420 :param no_args_is_help: this controls what happens if no arguments are1421 provided. This option is enabled by default if1422 `invoke_without_command` is disabled or disabled1423 if it's enabled. If enabled this will add1424 ``--help`` as argument if no arguments are1425 passed.1426 :param subcommand_metavar: the string that is used in the documentation1427 to indicate the subcommand place.1428 :param chain: if this is set to `True` chaining of multiple subcommands1429 is enabled. This restricts the form of commands in that1430 they cannot have optional arguments but it allows1431 multiple commands to be chained together.1432 :param result_callback: The result callback to attach to this multi1433 command. This can be set or changed later with the1434 :meth:`result_callback` decorator.1435 :param attrs: Other command arguments described in :class:`Command`.1434 .. versionchanged:: 8.21435 Merged with and replaces the ``MultiCommand`` base class.14361437 .. versionchanged:: 8.01438 The ``commands`` argument can be a list of command objects.1439 """14401441 allow_extra_args = True1442 allow_interspersed_args = False14431444 #: If set, this is used by the group's :meth:`command` decorator1445 #: as the default :class:`Command` class. This is useful to make all1446 #: subcommands use a custom command class.1447 #:1448 #: .. versionadded:: 8.01449 command_class: t.Optional[t.Type[Command]] = None14501451 #: If set, this is used by the group's :meth:`group` decorator1452 #: as the default :class:`Group` class. This is useful to make all1453 #: subgroups use a custom group class.1454 #:1455 #: If set to the special value :class:`type` (literally1456 #: ``group_class = type``), this group's class will be used as the1457 #: default class. This makes a custom group class continue to make1458 #: custom groups.1459 #:1460 #: .. versionadded:: 8.01461 group_class: t.Optional[t.Union[t.Type["Group"], t.Type[type]]] = None1462 # Literal[type] isn't valid, so use Type[type]14631464 def __init__(1465 self,1466 name: t.Optional[str] = None,1467 commands: t.Optional[1468 t.Union[t.MutableMapping[str, Command], t.Sequence[Command]]1469 ] = None,1470 invoke_without_command: bool = False,1471 no_args_is_help: t.Optional[bool] = None,1472 subcommand_metavar: t.Optional[str] = None,1473 chain: bool = False,1474 result_callback: t.Optional[t.Callable[..., t.Any]] = None,1449 **attrs: t.Any,1475 **kwargs: t.Any,1476 ) -> None:1451 super().__init__(name, **attrs)1477 super().__init__(name, **kwargs)14781479 if commands is None:1480 commands = {}1481 elif isinstance(commands, abc.Sequence):1482 commands = {c.name: c for c in commands if c.name is not None}14831484 #: The registered subcommands by their exported names.1485 self.commands: t.MutableMapping[str, Command] = commands14861487 if no_args_is_help is None:1488 no_args_is_help = not invoke_without_command14891490 self.no_args_is_help = no_args_is_help
36 unmodified lines
15271528 info_dict.update(commands=commands, chain=self.chain)1529 return info_dict15301497 def collect_usage_pieces(self, ctx: Context) -> t.List[str]:1498 rv = super().collect_usage_pieces(ctx)1499 rv.append(self.subcommand_metavar)1500 return rv1531 def add_command(self, cmd: Command, name: t.Optional[str] = None) -> None:1532 """Registers another :class:`Command` with this group. If the name1533 is not provided, the name of the command is used.1534 """1535 name = name or cmd.name1536 if name is None:1537 raise TypeError("Command has no name.")1538 _check_nested_chain(self, name, cmd, register=True)1539 self.commands[name] = cmd15401502 def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:1503 super().format_options(ctx, formatter)1504 self.format_commands(ctx, formatter)1541 @t.overload1542 def command(self, __func: t.Callable[..., t.Any]) -> Command:1543 ...15441545 @t.overload1546 def command(1547 self, *args: t.Any, **kwargs: t.Any1548 ) -> t.Callable[[t.Callable[..., t.Any]], Command]:1549 ...15501551 def command(1552 self, *args: t.Any, **kwargs: t.Any1553 ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], Command], Command]:1554 """A shortcut decorator for declaring and attaching a command to1555 the group. This takes the same arguments as :func:`command` and1556 immediately registers the created command with this group by1557 calling :meth:`add_command`.15581559 To customize the command class used, set the1560 :attr:`command_class` attribute.15611562 .. versionchanged:: 8.11563 This decorator can be applied without parentheses.15641565 .. versionchanged:: 8.01566 Added the :attr:`command_class` attribute.1567 """1568 from .decorators import command15691570 func: t.Optional[t.Callable[..., t.Any]] = None15711572 if args and callable(args[0]):1573 assert (1574 len(args) == 1 and not kwargs1575 ), "Use 'command(**kwargs)(callable)' to provide arguments."1576 (func,) = args1577 args = ()15781579 if self.command_class and kwargs.get("cls") is None:1580 kwargs["cls"] = self.command_class15811582 def decorator(f: t.Callable[..., t.Any]) -> Command:1583 cmd: Command = command(*args, **kwargs)(f)1584 self.add_command(cmd)1585 return cmd15861587 if func is not None:1588 return decorator(func)15891590 return decorator15911592 @t.overload1593 def group(self, __func: t.Callable[..., t.Any]) -> "Group":1594 ...15951596 @t.overload1597 def group(1598 self, *args: t.Any, **kwargs: t.Any1599 ) -> t.Callable[[t.Callable[..., t.Any]], "Group"]:1600 ...16011602 def group(1603 self, *args: t.Any, **kwargs: t.Any1604 ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], "Group"], "Group"]:1605 """A shortcut decorator for declaring and attaching a group to1606 the group. This takes the same arguments as :func:`group` and1607 immediately registers the created group with this group by1608 calling :meth:`add_command`.16091610 To customize the group class used, set the :attr:`group_class`1611 attribute.16121613 .. versionchanged:: 8.11614 This decorator can be applied without parentheses.16151616 .. versionchanged:: 8.01617 Added the :attr:`group_class` attribute.1618 """1619 from .decorators import group16201621 func: t.Optional[t.Callable[..., t.Any]] = None16221623 if args and callable(args[0]):1624 assert (1625 len(args) == 1 and not kwargs1626 ), "Use 'group(**kwargs)(callable)' to provide arguments."1627 (func,) = args1628 args = ()16291630 if self.group_class is not None and kwargs.get("cls") is None:1631 if self.group_class is type:1632 kwargs["cls"] = type(self)1633 else:1634 kwargs["cls"] = self.group_class16351636 def decorator(f: t.Callable[..., t.Any]) -> "Group":1637 cmd: Group = group(*args, **kwargs)(f)1638 self.add_command(cmd)1639 return cmd16401641 if func is not None:1642 return decorator(func)16431644 return decorator16451646 def result_callback(self, replace: bool = False) -> t.Callable[[F], F]:1647 """Adds a result callback to the command. By default if a1648 result callback is already registered this will chain them but1649 this can be disabled with the `replace` parameter. The result
37 unmodified lines
1687 return rv16881689 return decorator16901691 def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:1692 """Given a context and a command name, this returns a :class:`Command`1693 object if it exists or returns ``None``.1694 """1695 return self.commands.get(cmd_name)16961697 def list_commands(self, ctx: Context) -> t.List[str]:1698 """Returns a list of subcommand names in the order they should appear."""1699 return sorted(self.commands)17001701 def collect_usage_pieces(self, ctx: Context) -> t.List[str]:1702 rv = super().collect_usage_pieces(ctx)1703 rv.append(self.subcommand_metavar)1704 return rv17051706 def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:1707 super().format_options(ctx, formatter)1708 self.format_commands(ctx, formatter)17091710 def format_commands(self, ctx: Context, formatter: HelpFormatter) -> None:1711 """Extra format methods for multi methods that adds all the commands1712 after the options.1713 """
130 unmodified lines
1844 self.parse_args(ctx, ctx.args)1845 ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name))1846 return cmd_name if cmd else None, cmd, args[1:]18471689 def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:1690 """Given a context and a command name, this returns a1691 :class:`Command` object if it exists or returns `None`.1692 """1693 raise NotImplementedError16941695 def list_commands(self, ctx: Context) -> t.List[str]:1696 """Returns a list of subcommand names in the order they should1697 appear.1698 """1699 return []17001848 def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:1849 """Return a list of completions for the incomplete value. Looks1850 at the names of options, subcommands, and chained1851 multi-commands.
12 unmodified lines
1864 results.extend(super().shell_complete(ctx, incomplete))1865 return results186618671721class Group(MultiCommand):1722 """A group allows a command to have subcommands attached. This is1723 the most common way to implement nesting in Click.17241725 :param name: The name of the group command.1726 :param commands: A dict mapping names to :class:`Command` objects.1727 Can also be a list of :class:`Command`, which will use1728 :attr:`Command.name` to create the dict.1729 :param attrs: Other command arguments described in1730 :class:`MultiCommand`, :class:`Command`, and1731 :class:`BaseCommand`.17321733 .. versionchanged:: 8.01734 The ``commands`` argument can be a list of command objects.1868class _MultiCommand(Group, metaclass=_FakeSubclassCheck):1869 """1870 .. deprecated:: 8.21871 Will be removed in Click 9.0. Use ``Group`` instead.1872 """18731737 #: If set, this is used by the group's :meth:`command` decorator1738 #: as the default :class:`Command` class. This is useful to make all1739 #: subcommands use a custom command class.1740 #:1741 #: .. versionadded:: 8.01742 command_class: t.Optional[t.Type[Command]] = None18741744 #: If set, this is used by the group's :meth:`group` decorator1745 #: as the default :class:`Group` class. This is useful to make all1746 #: subgroups use a custom group class.1747 #:1748 #: If set to the special value :class:`type` (literally1749 #: ``group_class = type``), this group's class will be used as the1750 #: default class. This makes a custom group class continue to make1751 #: custom groups.1752 #:1753 #: .. versionadded:: 8.01754 group_class: t.Optional[t.Union[t.Type["Group"], t.Type[type]]] = None1755 # Literal[type] isn't valid, so use Type[type]1875class CommandCollection(Group):1876 """A :class:`Group` that looks up subcommands on other groups. If a command1877 is not found on this group, each registered source is checked in order.1878 Parameters on a source are not added to this group, and a source's callback1879 is not invoked when invoking its commands. In other words, this "flattens"1880 commands in many groups into this one group.18811757 def __init__(1758 self,1759 name: t.Optional[str] = None,1760 commands: t.Optional[1761 t.Union[t.MutableMapping[str, Command], t.Sequence[Command]]1762 ] = None,1763 **attrs: t.Any,1764 ) -> None:1765 super().__init__(name, **attrs)1882 :param name: The name of the group command.1883 :param sources: A list of :class:`Group` objects to look up commands from.1884 :param kwargs: Other arguments passed to :class:`Group`.18851767 if commands is None:1768 commands = {}1769 elif isinstance(commands, abc.Sequence):1770 commands = {c.name: c for c in commands if c.name is not None}17711772 #: The registered subcommands by their exported names.1773 self.commands: t.MutableMapping[str, Command] = commands17741775 def add_command(self, cmd: Command, name: t.Optional[str] = None) -> None:1776 """Registers another :class:`Command` with this group. If the name1777 is not provided, the name of the command is used.1778 """1779 name = name or cmd.name1780 if name is None:1781 raise TypeError("Command has no name.")1782 _check_multicommand(self, name, cmd, register=True)1783 self.commands[name] = cmd17841785 @t.overload1786 def command(self, __func: t.Callable[..., t.Any]) -> Command:1787 ...17881789 @t.overload1790 def command(1791 self, *args: t.Any, **kwargs: t.Any1792 ) -> t.Callable[[t.Callable[..., t.Any]], Command]:1793 ...17941795 def command(1796 self, *args: t.Any, **kwargs: t.Any1797 ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], Command], Command]:1798 """A shortcut decorator for declaring and attaching a command to1799 the group. This takes the same arguments as :func:`command` and1800 immediately registers the created command with this group by1801 calling :meth:`add_command`.18021803 To customize the command class used, set the1804 :attr:`command_class` attribute.18051806 .. versionchanged:: 8.11807 This decorator can be applied without parentheses.18081809 .. versionchanged:: 8.01810 Added the :attr:`command_class` attribute.1811 """1812 from .decorators import command18131814 func: t.Optional[t.Callable[..., t.Any]] = None18151816 if args and callable(args[0]):1817 assert (1818 len(args) == 1 and not kwargs1819 ), "Use 'command(**kwargs)(callable)' to provide arguments."1820 (func,) = args1821 args = ()18221823 if self.command_class and kwargs.get("cls") is None:1824 kwargs["cls"] = self.command_class18251826 def decorator(f: t.Callable[..., t.Any]) -> Command:1827 cmd: Command = command(*args, **kwargs)(f)1828 self.add_command(cmd)1829 return cmd18301831 if func is not None:1832 return decorator(func)18331834 return decorator18351836 @t.overload1837 def group(self, __func: t.Callable[..., t.Any]) -> "Group":1838 ...18391840 @t.overload1841 def group(1842 self, *args: t.Any, **kwargs: t.Any1843 ) -> t.Callable[[t.Callable[..., t.Any]], "Group"]:1844 ...18451846 def group(1847 self, *args: t.Any, **kwargs: t.Any1848 ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], "Group"], "Group"]:1849 """A shortcut decorator for declaring and attaching a group to1850 the group. This takes the same arguments as :func:`group` and1851 immediately registers the created group with this group by1852 calling :meth:`add_command`.18531854 To customize the group class used, set the :attr:`group_class`1855 attribute.18561857 .. versionchanged:: 8.11858 This decorator can be applied without parentheses.18591860 .. versionchanged:: 8.01861 Added the :attr:`group_class` attribute.1862 """1863 from .decorators import group18641865 func: t.Optional[t.Callable[..., t.Any]] = None18661867 if args and callable(args[0]):1868 assert (1869 len(args) == 1 and not kwargs1870 ), "Use 'group(**kwargs)(callable)' to provide arguments."1871 (func,) = args1872 args = ()18731874 if self.group_class is not None and kwargs.get("cls") is None:1875 if self.group_class is type:1876 kwargs["cls"] = type(self)1877 else:1878 kwargs["cls"] = self.group_class18791880 def decorator(f: t.Callable[..., t.Any]) -> "Group":1881 cmd: Group = group(*args, **kwargs)(f)1882 self.add_command(cmd)1883 return cmd18841885 if func is not None:1886 return decorator(func)18871888 return decorator18891890 def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:1891 return self.commands.get(cmd_name)18921893 def list_commands(self, ctx: Context) -> t.List[str]:1894 return sorted(self.commands)189518961897class CommandCollection(MultiCommand):1898 """A command collection is a multi command that merges multiple multi1899 commands together into one. This is a straightforward implementation1900 that accepts a list of different multi commands as sources and1901 provides all the commands for each of them.19021903 See :class:`MultiCommand` and :class:`Command` for the description of1904 ``name`` and ``attrs``.1886 .. versionchanged:: 8.21887 This is a subclass of ``Group``. Commands are looked up first on this1888 group, then each of its sources.1889 """18901891 def __init__(1892 self,1893 name: t.Optional[str] = None,1910 sources: t.Optional[t.List[MultiCommand]] = None,1911 **attrs: t.Any,1894 sources: t.Optional[t.List[Group]] = None,1895 **kwargs: t.Any,1896 ) -> None:1913 super().__init__(name, **attrs)1914 #: The list of registered multi commands.1915 self.sources: t.List[MultiCommand] = sources or []1897 super().__init__(name, **kwargs)1898 #: The list of registered groups.1899 self.sources: t.List[Group] = sources or []19001917 def add_source(self, multi_cmd: MultiCommand) -> None:1918 """Adds a new multi command to the chain dispatcher."""1919 self.sources.append(multi_cmd)1901 def add_source(self, group: Group) -> None:1902 """Add a group as a source of commands."""1903 self.sources.append(group)19041905 def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:1906 rv = super().get_command(ctx, cmd_name)19071908 if rv is not None:1909 return rv19101911 for source in self.sources:1912 rv = source.get_command(ctx, cmd_name)19131914 if rv is not None:1915 if self.chain:1927 _check_multicommand(self, cmd_name, rv)1916 _check_nested_chain(self, cmd_name, rv)19171918 return rv19191920 return None19211922 def list_commands(self, ctx: Context) -> t.List[str]:1934 rv: t.Set[str] = set()1923 rv: t.Set[str] = set(super().list_commands(ctx))19241925 for source in self.sources:1926 rv.update(source.list_commands(ctx))1927
1054 unmodified lines
2982 stacklevel=2,2983 )2984 return _BaseCommand29852986 if name == "MultiCommand":2987 warnings.warn(2988 "'MultiCommand' is deprecated and will be removed in Click 9.0. Use"2989 " 'Group' instead.",2990 DeprecationWarning,2991 stacklevel=2,2992 )2993 return _MultiCommand29942995 raise AttributeError(name)
modified:src/click/shell_completion.py+2 added-2 removed
4 unmodified lines
56from .core import Argument7from .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_string
498 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:
76 unmodified lines
modified:CHANGES.rst+2 added
9 unmodified lines
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