|
1 | 1 | from __future__ import annotations
|
2 | 2 |
|
| 3 | +import dataclasses |
3 | 4 | import enum
|
4 | 5 | import re
|
5 |
| -from typing import Any |
6 |
| -from typing import Tuple |
| 6 | +from abc import ABCMeta |
| 7 | +from typing import TYPE_CHECKING |
7 | 8 |
|
8 | 9 | from codemagic.models import DictSerializable
|
9 | 10 | from codemagic.models import JsonSerializable
|
| 11 | +from codemagic.models import JsonSerializableMeta |
| 12 | +from codemagic.utilities import log |
10 | 13 |
|
| 14 | +if TYPE_CHECKING: |
| 15 | + from typing import Any |
| 16 | + from typing import Dict |
| 17 | + from typing import Mapping |
| 18 | + from typing import Tuple |
| 19 | + from typing import Type |
| 20 | + from typing import TypeVar |
| 21 | + |
| 22 | + R = TypeVar("R", bound="Resource") |
| 23 | + |
| 24 | + |
| 25 | +class ResourceAbcMeta(JsonSerializableMeta, ABCMeta): |
| 26 | + pass |
| 27 | + |
| 28 | + |
| 29 | +@dataclasses.dataclass |
| 30 | +class Resource(DictSerializable, JsonSerializable, metaclass=ResourceAbcMeta): |
| 31 | + @classmethod |
| 32 | + def _get_defined_fields(cls, given_fields: Mapping[str, Any]) -> Dict[str, Any]: |
| 33 | + logger = log.get_logger(cls, log_to_stream=False) |
| 34 | + defined_fields = {f.name for f in dataclasses.fields(cls)} |
| 35 | + fields = {} |
| 36 | + for field_name, field_value in given_fields.items(): |
| 37 | + if field_name in defined_fields: |
| 38 | + fields[field_name] = field_value |
| 39 | + else: |
| 40 | + logger.warning("Unknown field %r for resource %s", field_name, cls.__name__) |
| 41 | + return fields |
| 42 | + |
| 43 | + @classmethod |
| 44 | + def from_api_response(cls: Type[R], api_response: Mapping[str, Any]) -> R: |
| 45 | + defined_fields = cls._get_defined_fields(api_response) |
| 46 | + return cls(**defined_fields) |
11 | 47 |
|
12 |
| -class Resource(DictSerializable, JsonSerializable): |
13 | 48 | @staticmethod
|
14 | 49 | def _format_attribute_name(name: str) -> str:
|
15 | 50 | name = re.sub(r"([a-z])([A-Z])", r"\1 \2", name)
|
|
0 commit comments