|
| 1 | +import argparse |
| 2 | +import sys |
| 3 | +from typing import Type |
| 4 | + |
| 5 | +from .commands import BaseCommand, InfoCommand |
| 6 | + |
| 7 | + |
| 8 | +class CLI: |
| 9 | + def __init__(self): |
| 10 | + self.commands: dict[str, BaseCommand] = {} |
| 11 | + self.prog: str = "arcade" |
| 12 | + self.description: str = "Arcade Game Library CLI" |
| 13 | + |
| 14 | + def register_command(self, command_class: Type[BaseCommand]) -> None: |
| 15 | + command = command_class() # type: ignore BaseCommand has different constructor than it's implementations |
| 16 | + self.commands[command.name] = command |
| 17 | + |
| 18 | + def create_parser(self) -> argparse.ArgumentParser: |
| 19 | + parser = argparse.ArgumentParser( |
| 20 | + prog=self.prog, |
| 21 | + description=self.description, |
| 22 | + formatter_class=argparse.RawDescriptionHelpFormatter, |
| 23 | + ) |
| 24 | + |
| 25 | + subparsers = parser.add_subparsers(dest="command", help="Available commands") |
| 26 | + |
| 27 | + for command_name, command in self.commands.items(): |
| 28 | + command_parser = subparsers.add_parser( |
| 29 | + command_name, |
| 30 | + help=command.help, |
| 31 | + description=command.description, |
| 32 | + formatter_class=argparse.RawDescriptionHelpFormatter, |
| 33 | + ) |
| 34 | + command.add_arguments(command_parser) |
| 35 | + |
| 36 | + return parser |
| 37 | + |
| 38 | + def run(self) -> int: |
| 39 | + parser = self.create_parser() |
| 40 | + args = parser.parse_args() |
| 41 | + |
| 42 | + if args.command is None: |
| 43 | + parser.print_help() |
| 44 | + return 0 |
| 45 | + |
| 46 | + try: |
| 47 | + command = self.commands[args.command] |
| 48 | + return command.handle(args) |
| 49 | + except Exception as e: |
| 50 | + print(f"Error: {e}", file=sys.stderr) |
| 51 | + return 1 |
| 52 | + |
| 53 | + |
| 54 | +def run_arcade_cli(): |
| 55 | + cli = CLI() |
| 56 | + cli.register_command(InfoCommand) |
| 57 | + return cli.run() |
0 commit comments