|
| 1 | +"""Preconfigured converters for tomllib.""" |
| 2 | + |
| 3 | +from base64 import b85decode, b85encode |
| 4 | +from collections.abc import Set |
| 5 | +from datetime import date, datetime |
| 6 | +from enum import Enum |
| 7 | +from operator import attrgetter |
| 8 | +from typing import Any, TypeVar, Union |
| 9 | + |
| 10 | +try: |
| 11 | + from tomllib import loads |
| 12 | +except ImportError: |
| 13 | + from tomli import loads |
| 14 | + |
| 15 | +try: |
| 16 | + from tomli_w import dumps |
| 17 | +except ImportError: # pragma: nocover |
| 18 | + dumps = None |
| 19 | + |
| 20 | +from .._compat import is_mapping, is_subclass |
| 21 | +from ..converters import BaseConverter, Converter |
| 22 | +from ..fns import identity |
| 23 | +from ..strategies import configure_union_passthrough |
| 24 | +from . import validate_datetime, wrap |
| 25 | + |
| 26 | +__all__ = ["TomllibConverter", "configure_converter", "make_converter"] |
| 27 | + |
| 28 | +T = TypeVar("T") |
| 29 | +_enum_value_getter = attrgetter("_value_") |
| 30 | + |
| 31 | + |
| 32 | +class TomllibConverter(Converter): |
| 33 | + """A converter subclass specialized for tomllib.""" |
| 34 | + |
| 35 | + if dumps is not None: |
| 36 | + |
| 37 | + def dumps(self, obj: Any, unstructure_as: Any = None, **kwargs: Any) -> str: |
| 38 | + return dumps(self.unstructure(obj, unstructure_as=unstructure_as), **kwargs) |
| 39 | + |
| 40 | + def loads(self, data: str, cl: type[T], **kwargs: Any) -> T: |
| 41 | + return self.structure(loads(data, **kwargs), cl) |
| 42 | + |
| 43 | + |
| 44 | +def configure_converter(converter: BaseConverter): |
| 45 | + """ |
| 46 | + Configure the converter for use with the tomllib library. |
| 47 | +
|
| 48 | + * bytes are serialized as base85 strings |
| 49 | + * sets are serialized as lists |
| 50 | + * tuples are serializas as lists |
| 51 | + * mapping keys are coerced into strings when unstructuring |
| 52 | + * dates and datetimes are left for tomllib to handle |
| 53 | + """ |
| 54 | + converter.register_structure_hook(bytes, lambda v, _: b85decode(v)) |
| 55 | + converter.register_unstructure_hook( |
| 56 | + bytes, lambda v: (b85encode(v) if v else b"").decode("utf8") |
| 57 | + ) |
| 58 | + |
| 59 | + @converter.register_unstructure_hook_factory(is_mapping) |
| 60 | + def gen_unstructure_mapping(cl: Any, unstructure_to=None): |
| 61 | + key_handler = str |
| 62 | + args = getattr(cl, "__args__", None) |
| 63 | + if args: |
| 64 | + if is_subclass(args[0], str): |
| 65 | + key_handler = _enum_value_getter if is_subclass(args[0], Enum) else None |
| 66 | + elif is_subclass(args[0], bytes): |
| 67 | + |
| 68 | + def key_handler(k: bytes): |
| 69 | + return b85encode(k).decode("utf8") |
| 70 | + |
| 71 | + return converter.gen_unstructure_mapping( |
| 72 | + cl, unstructure_to=unstructure_to, key_handler=key_handler |
| 73 | + ) |
| 74 | + |
| 75 | + converter.register_unstructure_hook(datetime, identity) |
| 76 | + converter.register_structure_hook(datetime, validate_datetime) |
| 77 | + converter.register_unstructure_hook(date, identity) |
| 78 | + converter.register_structure_hook( |
| 79 | + date, lambda v, _: v if isinstance(v, date) else date.fromisoformat(v) |
| 80 | + ) |
| 81 | + configure_union_passthrough(Union[str, int, float, bool], converter) |
| 82 | + |
| 83 | + |
| 84 | +@wrap(TomllibConverter) |
| 85 | +def make_converter(*args: Any, **kwargs: Any) -> TomllibConverter: |
| 86 | + kwargs["unstruct_collection_overrides"] = { |
| 87 | + Set: list, |
| 88 | + tuple: list, |
| 89 | + **kwargs.get("unstruct_collection_overrides", {}), |
| 90 | + } |
| 91 | + res = TomllibConverter(*args, **kwargs) |
| 92 | + configure_converter(res) |
| 93 | + |
| 94 | + return res |
0 commit comments