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
Provenance
- Commit
9e0d0b2- Tree
eea9548- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
9dd1207
4 files changed+251 added−241 removed
modified:src/click/__init__.py+11 added-1 removed
7 unmodified lines8 from .core import Command as Command9 from .core import CommandCollection as CommandCollection10 from .core import Context as Context11 from .core import Group as Group12-from .core import MultiCommand as MultiCommand12 from .core import Option as Option13 from .core import Parameter as Parameter14 from .decorators import argument as argument15 from .decorators import command as command68 unmodified lines84 stacklevel=2,85 )86 return _BaseCommand87 88+ if name == "MultiCommand":89+ from .core import _MultiCommand90+91+ warnings.warn(92+ "'MultiCommand' is deprecated and will be removed in Click 9.0. Use"93+ " 'Group' instead.",94+ DeprecationWarning,95+ stacklevel=2,96+ )97+ return _MultiCommand98+99 raise AttributeError(name)modified:src/click/core.py+236 added-238 removed
52 unmodified lines53 54 :param ctx: Invocation context for the group.55 :param incomplete: Value being completed. May be empty.56 """57- multi = t.cast(MultiCommand, ctx.command)57+ multi = t.cast(Group, ctx.command)58 59 for name in multi.list_commands(ctx):60 if name.startswith(incomplete):61 command = multi.get_command(ctx, name)1 unmodified line63 if command is not None and not command.hidden:64 yield name, command65 66 67-def _check_multicommand(68- base_command: "MultiCommand", cmd_name: str, cmd: "Command", register: bool = False67+def _check_nested_chain(68+ base_command: "Group", cmd_name: str, cmd: "Command", register: bool = False69 ) -> None:70- if not base_command.chain or not isinstance(cmd, MultiCommand):70+ if not base_command.chain or not isinstance(cmd, Group):71 return72 if register:73 hint = (74 "It is not possible to add multi commands as children to"1136 unmodified lines1211 1212 while ctx.parent is not None:1213 ctx = ctx.parent1214 1215- 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_args187 unmodified lines1407 Will be removed in Click 9.0. Use ``Command`` instead.1408 """1409 1410 1411+class Group(Command):1412+ """A group is a command that nests other commands (or more groups).1413 1412-class 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`.1433 1417- :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.1436+1437+ .. versionchanged:: 8.01438+ The ``commands`` argument can be a list of command objects.1439 """1440 1441 allow_extra_args = True1442 allow_interspersed_args = False1443 1444+ #: 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]] = None1450+1451+ #: 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]1463+1464 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)1478 1479+ 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}1483+1484+ #: The registered subcommands by their exported names.1485+ self.commands: t.MutableMapping[str, Command] = commands1486+1487 if no_args_is_help is None:1488 no_args_is_help = not invoke_without_command1489 1490 self.no_args_is_help = no_args_is_help36 unmodified lines1527 1528 info_dict.update(commands=commands, chain=self.chain)1529 return info_dict1530 1497- 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] = cmd1540 1502- 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+ ...1544 1545+ @t.overload1546+ def command(1547+ self, *args: t.Any, **kwargs: t.Any1548+ ) -> t.Callable[[t.Callable[..., t.Any]], Command]:1549+ ...1550+1551+ 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`.1558+1559+ To customize the command class used, set the1560+ :attr:`command_class` attribute.1561+1562+ .. versionchanged:: 8.11563+ This decorator can be applied without parentheses.1564+1565+ .. versionchanged:: 8.01566+ Added the :attr:`command_class` attribute.1567+ """1568+ from .decorators import command1569+1570+ func: t.Optional[t.Callable[..., t.Any]] = None1571+1572+ 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 = ()1578+1579+ if self.command_class and kwargs.get("cls") is None:1580+ kwargs["cls"] = self.command_class1581+1582+ def decorator(f: t.Callable[..., t.Any]) -> Command:1583+ cmd: Command = command(*args, **kwargs)(f)1584+ self.add_command(cmd)1585+ return cmd1586+1587+ if func is not None:1588+ return decorator(func)1589+1590+ return decorator1591+1592+ @t.overload1593+ def group(self, __func: t.Callable[..., t.Any]) -> "Group":1594+ ...1595+1596+ @t.overload1597+ def group(1598+ self, *args: t.Any, **kwargs: t.Any1599+ ) -> t.Callable[[t.Callable[..., t.Any]], "Group"]:1600+ ...1601+1602+ 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`.1609+1610+ To customize the group class used, set the :attr:`group_class`1611+ attribute.1612+1613+ .. versionchanged:: 8.11614+ This decorator can be applied without parentheses.1615+1616+ .. versionchanged:: 8.01617+ Added the :attr:`group_class` attribute.1618+ """1619+ from .decorators import group1620+1621+ func: t.Optional[t.Callable[..., t.Any]] = None1622+1623+ 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 = ()1629+1630+ 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_class1635+1636+ def decorator(f: t.Callable[..., t.Any]) -> "Group":1637+ cmd: Group = group(*args, **kwargs)(f)1638+ self.add_command(cmd)1639+ return cmd1640+1641+ if func is not None:1642+ return decorator(func)1643+1644+ return decorator1645+1646 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 result37 unmodified lines1687 return rv1688 1689 return decorator1690 1691+ 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)1696+1697+ 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)1700+1701+ 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 rv1705+1706+ def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:1707+ super().format_options(ctx, formatter)1708+ self.format_commands(ctx, formatter)1709+1710 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 lines1844 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:]1847 1689- 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 NotImplementedError1694-1695- 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 []1700-1848 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 lines1864 results.extend(super().shell_complete(ctx, incomplete))1865 return results1866 1867 1721-class Group(MultiCommand):1722- """A group allows a command to have subcommands attached. This is1723- the most common way to implement nesting in Click.1724-1725- :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`.1732-1733- .. versionchanged:: 8.01734- The ``commands`` argument can be a list of command objects.1868+class _MultiCommand(Group, metaclass=_FakeSubclassCheck):1869 """1870+ .. deprecated:: 8.21871+ Will be removed in Click 9.0. Use ``Group`` instead.1872+ """1873 1737- #: 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]] = None1874 1744- #: 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]1875+class 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.1881 1757- 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`.1885 1767- 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}1771-1772- #: The registered subcommands by their exported names.1773- self.commands: t.MutableMapping[str, Command] = commands1774-1775- 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] = cmd1784-1785- @t.overload1786- def command(self, __func: t.Callable[..., t.Any]) -> Command:1787- ...1788-1789- @t.overload1790- def command(1791- self, *args: t.Any, **kwargs: t.Any1792- ) -> t.Callable[[t.Callable[..., t.Any]], Command]:1793- ...1794-1795- 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`.1802-1803- To customize the command class used, set the1804- :attr:`command_class` attribute.1805-1806- .. versionchanged:: 8.11807- This decorator can be applied without parentheses.1808-1809- .. versionchanged:: 8.01810- Added the :attr:`command_class` attribute.1811- """1812- from .decorators import command1813-1814- func: t.Optional[t.Callable[..., t.Any]] = None1815-1816- 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 = ()1822-1823- if self.command_class and kwargs.get("cls") is None:1824- kwargs["cls"] = self.command_class1825-1826- def decorator(f: t.Callable[..., t.Any]) -> Command:1827- cmd: Command = command(*args, **kwargs)(f)1828- self.add_command(cmd)1829- return cmd1830-1831- if func is not None:1832- return decorator(func)1833-1834- return decorator1835-1836- @t.overload1837- def group(self, __func: t.Callable[..., t.Any]) -> "Group":1838- ...1839-1840- @t.overload1841- def group(1842- self, *args: t.Any, **kwargs: t.Any1843- ) -> t.Callable[[t.Callable[..., t.Any]], "Group"]:1844- ...1845-1846- 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`.1853-1854- To customize the group class used, set the :attr:`group_class`1855- attribute.1856-1857- .. versionchanged:: 8.11858- This decorator can be applied without parentheses.1859-1860- .. versionchanged:: 8.01861- Added the :attr:`group_class` attribute.1862- """1863- from .decorators import group1864-1865- func: t.Optional[t.Callable[..., t.Any]] = None1866-1867- 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 = ()1873-1874- 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_class1879-1880- def decorator(f: t.Callable[..., t.Any]) -> "Group":1881- cmd: Group = group(*args, **kwargs)(f)1882- self.add_command(cmd)1883- return cmd1884-1885- if func is not None:1886- return decorator(func)1887-1888- return decorator1889-1890- def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:1891- return self.commands.get(cmd_name)1892-1893- def list_commands(self, ctx: Context) -> t.List[str]:1894- return sorted(self.commands)1895-1896-1897-class 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.1902-1903- 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 """1890 1891 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 []1900 1917- 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)1904 1905 def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]:1906+ rv = super().get_command(ctx, cmd_name)1907+1908+ if rv is not None:1909+ return rv1910+1911 for source in self.sources:1912 rv = source.get_command(ctx, cmd_name)1913 1914 if rv is not None:1915 if self.chain:1927- _check_multicommand(self, cmd_name, rv)1916+ _check_nested_chain(self, cmd_name, rv)1917 1918 return rv1919 1920 return None1921 1922 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))1924 1925 for source in self.sources:1926 rv.update(source.list_commands(ctx))1927 1054 unmodified lines2982 stacklevel=2,2983 )2984 return _BaseCommand2985 2986+ 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 _MultiCommand2994+2995 raise AttributeError(name)modified:src/click/shell_completion.py+2 added-2 removed
4 unmodified lines5 6 from .core import Argument7 from .core import Command8 from .core import Context9-from .core import MultiCommand9+from .core import Group10 from .core import Option11 from .core import Parameter12 from .core import ParameterSource13 from .parser import split_arg_string498 unmodified lines512 513 while args:514 command = ctx.command515 516- if isinstance(command, MultiCommand):516+ if isinstance(command, Group):517 if not command.chain:518 name, cmd, args = command.resolve_command(ctx, args)519 520 if cmd is None:76 unmodified linesmodified:CHANGES.rst+2 added
9 unmodified lines10 :pr:`326`11 - Use ``flit_core`` instead of ``setuptools`` as build backend.12 - ``BaseCommand`` is deprecated. ``Command`` is the base class for all13 commands. :issue:`2589`14+- ``MultiCommand`` is deprecated. ``Group`` is the base class for all group15+ commands. :issue:`2590`16 17 18 Version 8.1.719 -------------1102 unmodified lines