import argparse from typing import Type from .base import BaseCommand class CommandManager: def __init__(self): self._commands = self._get_commands() @classmethod def _get_command_clss(cls, command_cls: Type[BaseCommand] = BaseCommand) -> set[Type[BaseCommand]]: subclasses = set(command_cls.__subclasses__()) for subclass in command_cls.__subclasses__(): subclasses |= cls._get_command_clss(subclass) return subclasses @classmethod def _get_commands(cls) -> dict[str, BaseCommand]: commands = {} for command_cls in cls._get_command_clss(): command = command_cls() commands[command.name] = command return commands def register_commands(self, parser: argparse.ArgumentParser): subparsers = parser.add_subparsers(dest="command_name", help="Subcommands", required=True) for command in self._commands.values(): command_parser = subparsers.add_parser(command.name, help=command.description) command.add_arguments(command_parser) def execute_command(self, command_name: str, **kwargs): command = self._commands[command_name] command.run(**kwargs)