|
| 1 | +import json |
| 2 | +import pathlib |
| 3 | +import typing as t |
| 4 | + |
| 5 | +import yaml |
| 6 | + |
| 7 | +if t.TYPE_CHECKING: |
| 8 | + from typing_extensions import Literal, TypeAlias |
| 9 | + |
| 10 | + FormatLiteral = Literal["json", "yaml"] |
| 11 | + |
| 12 | + RawConfigData: TypeAlias = t.Dict[t.Any, t.Any] |
| 13 | + |
| 14 | + |
| 15 | +class ConfigReader: |
| 16 | + """Reads raw config data""" |
| 17 | + |
| 18 | + def __init__( |
| 19 | + self, |
| 20 | + content: "RawConfigData", |
| 21 | + ): |
| 22 | + self.content = content |
| 23 | + |
| 24 | + @staticmethod |
| 25 | + def _load(format: "FormatLiteral", content: str): |
| 26 | + """Load raw config data.""" |
| 27 | + if format == "yaml": |
| 28 | + return yaml.load(content, Loader=yaml.SafeLoader) |
| 29 | + elif format == "json": |
| 30 | + return json.loads(content) |
| 31 | + else: |
| 32 | + raise NotImplementedError(f"{format} not supported in configuration") |
| 33 | + |
| 34 | + @classmethod |
| 35 | + def load(cls, format: "FormatLiteral", content: str): |
| 36 | + """Load raw config data.""" |
| 37 | + return cls(content=cls._load(format=format, content=content)) |
| 38 | + |
| 39 | + @classmethod |
| 40 | + def _from_file(cls, path: pathlib.Path): |
| 41 | + """Load data from file path""" |
| 42 | + assert isinstance(path, pathlib.Path) |
| 43 | + content = open(path).read() |
| 44 | + if path.suffix in [".yaml", ".yml"]: |
| 45 | + format: FormatLiteral = "yaml" |
| 46 | + elif path.suffix == ".json": |
| 47 | + format = "json" |
| 48 | + else: |
| 49 | + raise NotImplementedError(f"{path.suffix} not supported in {path}") |
| 50 | + return cls._load( |
| 51 | + format=format, |
| 52 | + content=content, |
| 53 | + ) |
| 54 | + |
| 55 | + @classmethod |
| 56 | + def from_file(cls, path: pathlib.Path): |
| 57 | + return cls(content=cls._from_file(path=path)) |
| 58 | + |
| 59 | + @staticmethod |
| 60 | + def _dump( |
| 61 | + format: "FormatLiteral", |
| 62 | + content: "RawConfigData", |
| 63 | + indent: int = 2, |
| 64 | + **kwargs: t.Any, |
| 65 | + ) -> str: |
| 66 | + if format == "yaml": |
| 67 | + return yaml.dump( |
| 68 | + content, indent=2, default_flow_style=False, Dumper=yaml.SafeDumper |
| 69 | + ) |
| 70 | + elif format == "json": |
| 71 | + return json.dumps(content, indent=2) |
| 72 | + else: |
| 73 | + raise NotImplementedError(f"{format} not supported in config") |
| 74 | + |
| 75 | + def dump(self, format: "FormatLiteral", indent: int = 2, **kwargs: t.Any) -> str: |
| 76 | + return self._dump(format=format, content=self.content, indent=indent, **kwargs) |
0 commit comments