|
| 1 | +# Copyright 2024 John Sirois. |
| 2 | +# Licensed under the Apache License, Version 2.0 (see LICENSE). |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +from dataclasses import dataclass |
| 7 | +from typing import Any, Dict, Iterable, Mapping, Optional, Tuple |
| 8 | + |
| 9 | +from dev_cmd.errors import InvalidModelError |
| 10 | + |
| 11 | + |
| 12 | +@dataclass(frozen=True) |
| 13 | +class Command: |
| 14 | + name: str |
| 15 | + env: Mapping[str, str] |
| 16 | + args: Tuple[str, ...] |
| 17 | + accepts_extra_args: bool |
| 18 | + |
| 19 | + |
| 20 | +@dataclass(frozen=True) |
| 21 | +class Dev: |
| 22 | + commands: Mapping[str, Command] |
| 23 | + aliases: Mapping[str, Tuple[Command, ...]] |
| 24 | + default: Optional[Tuple[str, Tuple[Command, ...]]] = None |
| 25 | + source: Any = "<code>" |
| 26 | + |
| 27 | + |
| 28 | +@dataclass(frozen=True) |
| 29 | +class Invocation: |
| 30 | + @classmethod |
| 31 | + def create(cls, *tasks: Tuple[str, Iterable[Command]]) -> Invocation: |
| 32 | + _tasks: Dict[str, Tuple[Command, ...]] = {} |
| 33 | + accepts_extra_args: Optional[Command] = None |
| 34 | + for task, commands in tasks: |
| 35 | + _tasks[task] = tuple(commands) |
| 36 | + for command in commands: |
| 37 | + if command.accepts_extra_args: |
| 38 | + if accepts_extra_args is not None: |
| 39 | + raise InvalidModelError( |
| 40 | + f"The command {command.name!r} accepts extra args, but only one " |
| 41 | + f"command can accept extra args per invocation and command " |
| 42 | + f"{accepts_extra_args.name!r} already does." |
| 43 | + ) |
| 44 | + accepts_extra_args = command |
| 45 | + |
| 46 | + return cls(tasks=_tasks, accepts_extra_args=accepts_extra_args is not None) |
| 47 | + |
| 48 | + tasks: Mapping[str, Tuple[Command, ...]] |
| 49 | + accepts_extra_args: bool |
0 commit comments