|
1 | 1 | """Basic parser implementation."""
|
2 | 2 |
|
3 |
| -import inspect |
| 3 | +# pyright: reportAny=false |
| 4 | + |
4 | 5 | import logging
|
5 | 6 | from abc import ABC
|
6 | 7 | from abc import abstractmethod
|
7 |
| -from types import UnionType |
8 |
| -from typing import Any |
9 |
| -from typing import Literal |
10 |
| -from typing import TypeVar |
11 | 8 | from typing import Callable
|
12 |
| -from typing import TypeGuard |
13 |
| -from typing import get_args |
14 | 9 | from typing import overload
|
15 |
| -from typing import get_origin |
16 | 10 | from pathlib import Path
|
17 | 11 | from crx_repo.config.config import Config
|
18 | 12 |
|
19 | 13 |
|
20 |
| -PathOrStr = Path | str |
21 |
| -T = TypeVar("T") |
22 |
| -ConfigJsonType = dict[str, Any] |
23 |
| -KeyConverterType = Callable[[str], str] | None |
| 14 | +type PathOrStr = Path | str |
| 15 | +type ConfigJsonType = dict[str, str | int | None | ConfigJsonType] |
| 16 | +type KeyConverterType = Callable[[str], str] | None |
24 | 17 |
|
25 | 18 | _logger = logging.getLogger(__name__)
|
26 | 19 |
|
@@ -55,101 +48,3 @@ async def support_async(self, path: Path) -> bool:
|
55 | 48 | @abstractmethod
|
56 | 49 | async def support_async(self, path: PathOrStr) -> bool:
|
57 | 50 | """Check if path is supported by the parser."""
|
58 |
| - |
59 |
| - @staticmethod |
60 |
| - def deserialize( |
61 |
| - cls_: type[T], |
62 |
| - json: ConfigJsonType, |
63 |
| - key_convert: KeyConverterType = None, |
64 |
| - ) -> T: |
65 |
| - """Deserialize json to a class. |
66 |
| -
|
67 |
| - Args: |
68 |
| - cls_(type[T]): The class itself, it must have a no-argument constructor. |
69 |
| - json(ConfigJsonType): The json data. |
70 |
| - key_convert(KeyConverterType): A converter to convert key between json and class. |
71 |
| - It should accept key in json and return a string, |
72 |
| - which represents the attribute name of cls_ instance. |
73 |
| - It defaults to None, means do not convert. |
74 |
| -
|
75 |
| - Returns: |
76 |
| - T: The instance of cls_ |
77 |
| -
|
78 |
| - Remarks: |
79 |
| - This method is slow because using setattr() and getattr(), |
80 |
| - please cache its result to speed up. |
81 |
| - """ |
82 |
| - instance = cls_() |
83 |
| - type_of_instance = inspect.get_annotations(cls_) |
84 |
| - for k, v in json.items(): # pyright: ignore[reportAny] |
85 |
| - attr_name = key_convert(k) if key_convert is not None else k |
86 |
| - if hasattr(instance, attr_name): |
87 |
| - type_of_attr = type_of_instance.get(attr_name) |
88 |
| - _logger.debug("Type of %s is %s", k, type_of_attr) |
89 |
| - if type_of_attr is None: |
90 |
| - _logger.debug( |
91 |
| - "%s does not have a type hint, ignoring its deserialization.", |
92 |
| - attr_name, |
93 |
| - ) |
94 |
| - elif ConfigParser._is_config_json(v): # pyright: ignore[reportAny] |
95 |
| - _logger.debug("Calling deserialize() recursively.") |
96 |
| - v_deserialized = ConfigParser.deserialize( # pyright: ignore[reportUnknownVariableType] |
97 |
| - ConfigParser._ensure_instanceable(type_of_attr), # pyright: ignore[reportAny] |
98 |
| - v, |
99 |
| - key_convert, |
100 |
| - ) |
101 |
| - setattr(instance, attr_name, v_deserialized) |
102 |
| - elif ConfigParser._is_generics_valid( |
103 |
| - v, # pyright: ignore[reportAny] |
104 |
| - type_of_attr, # pyright: ignore[reportAny] |
105 |
| - ) or isinstance(v, type_of_attr): |
106 |
| - _logger.debug("Type match, assigning value of %s directly.", k) |
107 |
| - setattr(instance, attr_name, v) |
108 |
| - else: |
109 |
| - _logger.debug("Do not know how to deserialize %s, ignoring.", k) |
110 |
| - return instance |
111 |
| - |
112 |
| - @staticmethod |
113 |
| - def _is_config_json(obj: object) -> TypeGuard[ConfigJsonType]: |
114 |
| - return isinstance(obj, dict) and all(isinstance(k, str) for k in obj) # pyright: ignore[reportUnknownVariableType] |
115 |
| - |
116 |
| - @staticmethod |
117 |
| - def _is_generics_valid(v: object, t: type) -> bool: |
118 |
| - args = get_args(t) |
119 |
| - if len(args) > 0: |
120 |
| - origin = get_origin(t) |
121 |
| - if origin is Literal or origin is UnionType: |
122 |
| - return v in args |
123 |
| - if origin is list: |
124 |
| - return isinstance(v, list) and ConfigParser._is_list_valid(v, t) # pyright: ignore[reportUnknownArgumentType] |
125 |
| - raise NotImplementedError("Unsupported type", origin) |
126 |
| - return False |
127 |
| - |
128 |
| - @staticmethod |
129 |
| - def _is_list_valid(v: list[T], t: type[list[T]]) -> bool: |
130 |
| - return (len(v) == 0) or all(isinstance(value, get_args(t)[0]) for value in v) |
131 |
| - |
132 |
| - @staticmethod |
133 |
| - def _ensure_instanceable( |
134 |
| - i: type, |
135 |
| - checker: Callable[[type], bool] = callable, |
136 |
| - ) -> type: |
137 |
| - _logger.debug("Ensuring object %s is instanceable...", i) |
138 |
| - if checker(i): |
139 |
| - return i |
140 |
| - if ConfigParser._is_union_type(i): |
141 |
| - args = get_args(i) |
142 |
| - matches = (arg for arg in args if checker(arg)) # pyright: ignore[reportAny] |
143 |
| - found = next(matches, None) |
144 |
| - if found is None: |
145 |
| - raise ValueError("No instanceable object can be extracted in UnionType") |
146 |
| - return found # pyright: ignore[reportAny] |
147 |
| - raise NotImplementedError("Unsupported type", i) |
148 |
| - |
149 |
| - @staticmethod |
150 |
| - def _is_union_type(i: type) -> TypeGuard[UnionType]: |
151 |
| - args = get_args(i) |
152 |
| - if len(args) > 0: |
153 |
| - origin = get_origin(i) |
154 |
| - return origin is UnionType |
155 |
| - return False |
0 commit comments