|
| 1 | +"""DefaultGroup allows a subcommand to act as the main command |
| 2 | +
|
| 3 | +In particular, this class is what allows ``manim`` to act as ``manim render``. |
| 4 | +""" |
| 5 | +import cloup |
| 6 | + |
| 7 | +from .. import logger |
| 8 | + |
| 9 | +__all__ = ["DefaultGroup"] |
| 10 | + |
| 11 | + |
| 12 | +class DefaultGroup(cloup.Group): |
| 13 | + """Invokes a subcommand marked with ``default=True`` if any subcommand not |
| 14 | + chosen. |
| 15 | + """ |
| 16 | + |
| 17 | + def __init__(self, *args, **kwargs): |
| 18 | + # To resolve as the default command. |
| 19 | + if not kwargs.get("ignore_unknown_options", True): |
| 20 | + raise ValueError("Default group accepts unknown options") |
| 21 | + self.ignore_unknown_options = True |
| 22 | + self.default_cmd_name = kwargs.pop("default", None) |
| 23 | + self.default_if_no_args = kwargs.pop("default_if_no_args", False) |
| 24 | + super().__init__(*args, **kwargs) |
| 25 | + |
| 26 | + def set_default_command(self, command): |
| 27 | + """Sets a command function as the default command.""" |
| 28 | + cmd_name = command.name |
| 29 | + self.add_command(command) |
| 30 | + self.default_cmd_name = cmd_name |
| 31 | + |
| 32 | + def parse_args(self, ctx, args): |
| 33 | + if not args and self.default_if_no_args: |
| 34 | + args.insert(0, self.default_cmd_name) |
| 35 | + return super().parse_args(ctx, args) |
| 36 | + |
| 37 | + def get_command(self, ctx, cmd_name): |
| 38 | + if cmd_name not in self.commands: |
| 39 | + # No command name matched. |
| 40 | + ctx.arg0 = cmd_name |
| 41 | + cmd_name = self.default_cmd_name |
| 42 | + return super().get_command(ctx, cmd_name) |
| 43 | + |
| 44 | + def resolve_command(self, ctx, args): |
| 45 | + base = super() |
| 46 | + cmd_name, cmd, args = base.resolve_command(ctx, args) |
| 47 | + if hasattr(ctx, "arg0"): |
| 48 | + args.insert(0, ctx.arg0) |
| 49 | + cmd_name = cmd.name |
| 50 | + return cmd_name, cmd, args |
| 51 | + |
| 52 | + def command(self, *args, **kwargs): |
| 53 | + default = kwargs.pop("default", False) |
| 54 | + decorator = super().command(*args, **kwargs) |
| 55 | + if not default: |
| 56 | + return decorator |
| 57 | + logger.log( |
| 58 | + "Use default param of DefaultGroup or " "set_default_command() instead", |
| 59 | + DeprecationWarning, |
| 60 | + ) |
| 61 | + |
| 62 | + def _decorator(f): |
| 63 | + cmd = decorator(f) |
| 64 | + self.set_default_command(cmd) |
| 65 | + return cmd |
| 66 | + |
| 67 | + return _decorator |
0 commit comments