|
| 1 | +# ignoring mypy on the import as it catches ForwardRef as invalid, and we are using it |
| 2 | +# for introspection https://docs.python.org/3/library/typing.html#typing.ForwardRef |
| 3 | +from typing import Any, Dict, ForwardRef, List, Mapping # type: ignore |
| 4 | + |
| 5 | +from .exceptions import InvalidRequest |
| 6 | + |
| 7 | + |
| 8 | +# CloudFormation recasts all primitive types as strings, this tries to set them back to |
| 9 | +# the types in the type hints |
| 10 | +def recast_object( |
| 11 | + cls: Any, json_data: Mapping[str, Any], classes: Dict[str, Any] |
| 12 | +) -> None: |
| 13 | + if not isinstance(json_data, dict): |
| 14 | + raise InvalidRequest(f"Can only parse dict items, not {type(json_data)}") |
| 15 | + for k, v in json_data.items(): |
| 16 | + if isinstance(v, dict): |
| 17 | + child_cls = _field_to_type(cls.__dataclass_fields__[k].type, k, classes) |
| 18 | + recast_object(child_cls, v, classes) |
| 19 | + elif isinstance(v, list): |
| 20 | + json_data[k] = _recast_lists(cls, k, v, classes) |
| 21 | + elif isinstance(v, str): |
| 22 | + dest_type = _field_to_type(cls.__dataclass_fields__[k].type, k, classes) |
| 23 | + json_data[k] = _recast_primitive(dest_type, k, v) |
| 24 | + else: |
| 25 | + raise InvalidRequest(f"Unsupported type: {type(v)} for {k}") |
| 26 | + |
| 27 | + |
| 28 | +def _recast_lists(cls: Any, k: str, v: List[Any], classes: Dict[str, Any]) -> List[Any]: |
| 29 | + casted_list: List[Any] = [] |
| 30 | + if k in cls.__dataclass_fields__: |
| 31 | + cls = _field_to_type(cls.__dataclass_fields__[k].type, k, classes) |
| 32 | + for item in v: |
| 33 | + if isinstance(item, str): |
| 34 | + casted_item: Any = _recast_primitive(cls, k, item) |
| 35 | + elif isinstance(item, list): |
| 36 | + casted_item = _recast_lists(cls, k, item, classes) |
| 37 | + elif isinstance(item, dict): |
| 38 | + recast_object(cls, item, classes) |
| 39 | + casted_item = item |
| 40 | + else: |
| 41 | + raise InvalidRequest(f"Unsupported type: {type(v)} for {k}") |
| 42 | + casted_list.append(casted_item) |
| 43 | + return casted_list |
| 44 | + |
| 45 | + |
| 46 | +def _recast_primitive(cls: Any, k: str, v: str) -> Any: |
| 47 | + if cls == bool: |
| 48 | + if v.lower() == "true": |
| 49 | + return True |
| 50 | + if v.lower() == "false": |
| 51 | + return False |
| 52 | + raise InvalidRequest(f'value for {k} "{v}" is not boolean') |
| 53 | + return cls(v) |
| 54 | + |
| 55 | + |
| 56 | +def _field_to_type(field: Any, key: str, classes: Dict[str, Any]) -> Any: |
| 57 | + if field in [int, float, str, bool]: |
| 58 | + return field |
| 59 | + # If it's a ForwardRef we need to find base type |
| 60 | + if isinstance(field, ForwardRef): |
| 61 | + # Assuming codegen added an _ as a prefix, removing it and then gettting the |
| 62 | + # class from model classes |
| 63 | + return classes[field.__forward_arg__[1:]] |
| 64 | + # Assuming this is a generic object created by typing.Union |
| 65 | + try: |
| 66 | + possible_types = field.__args__ |
| 67 | + except AttributeError: |
| 68 | + raise InvalidRequest(f"Cannot process type {field.__repr__()} for field {key}") |
| 69 | + # Assuming that the union is generated from typing.Optional, so only |
| 70 | + # contains one type and None |
| 71 | + # pylint: disable=unidiomatic-typecheck |
| 72 | + fields = [t for t in possible_types if type(None) != t] |
| 73 | + if len(fields) != 1: |
| 74 | + raise InvalidRequest(f"Cannot process type {field.__repr__()} for field {key}") |
| 75 | + field = fields[0] |
| 76 | + # If it's a primitive we're done |
| 77 | + if field in [int, float, str, bool]: |
| 78 | + return field |
| 79 | + # If it's a ForwardRef we need to find base type |
| 80 | + if isinstance(field, ForwardRef): |
| 81 | + # Assuming codegen added an _ as a prefix, removing it and then gettting the |
| 82 | + # class from model classes |
| 83 | + return classes[field.__forward_arg__[1:]] |
| 84 | + # If it's not a type we don't know how to handle we bail |
| 85 | + if field._name not in ["Sequence"]: # pylint: disable=protected-access |
| 86 | + raise InvalidRequest(f"Cannot process type {field.__repr__()} for field {key}") |
| 87 | + return _field_to_type(field.__args__[0], key, classes) |
0 commit comments