|
| 1 | +import json |
| 2 | +import pathlib |
| 3 | +from typing import Final, Any |
| 4 | + |
| 5 | + |
| 6 | +class DuplicateKeyException(Exception): |
| 7 | + def __init__(self, msg: str): |
| 8 | + super().__init__(msg) |
| 9 | + |
| 10 | + |
| 11 | +class OrderingException(Exception): |
| 12 | + def __init__(self, msg: str): |
| 13 | + super().__init__(msg) |
| 14 | + |
| 15 | + |
| 16 | +class InvalidStructureException(Exception): |
| 17 | + def __init__(self, msg: str): |
| 18 | + super().__init__(msg) |
| 19 | + |
| 20 | + |
| 21 | +class OrderValidator: |
| 22 | + def __init__(self): |
| 23 | + self._SOURCE_DIR: Final[str] = "src" |
| 24 | + self._TECH_DIR: Final[str] = "technologies" |
| 25 | + self._FULL_TECH_DIR: Final[pathlib.Path] = pathlib.Path(self._SOURCE_DIR).joinpath(self._TECH_DIR) |
| 26 | + |
| 27 | + def validate(self) -> None: |
| 28 | + if not self._FULL_TECH_DIR.is_dir(): |
| 29 | + raise InvalidStructureException(f"{self._FULL_TECH_DIR} is not a valid directory") |
| 30 | + for tech_file in sorted(self._FULL_TECH_DIR.iterdir()): |
| 31 | + if not tech_file.name.endswith(".json"): |
| 32 | + continue |
| 33 | + self._check_ordering(tech_file) |
| 34 | + |
| 35 | + def _check_ordering(self, tech_file: pathlib.Path) -> None: |
| 36 | + with tech_file.open("r", encoding="utf8") as f: |
| 37 | + data: dict = json.load(f, object_pairs_hook=self._duplicate_key_validator) |
| 38 | + if not isinstance(data, dict): |
| 39 | + raise InvalidStructureException(f"{tech_file.name} root must be an object") |
| 40 | + keys: list[str] = list(data.keys()) |
| 41 | + sorted_keys: list[str] = sorted(keys, key=lambda x: x.lower()) |
| 42 | + if keys != sorted_keys: |
| 43 | + mismatches: list[str] = [ |
| 44 | + f"Found '{actual}' expected '{expected}'" |
| 45 | + for actual, expected in zip(keys, sorted_keys) |
| 46 | + if actual != expected |
| 47 | + ] |
| 48 | + raise OrderingException( |
| 49 | + f"{tech_file.name} entries are not ordered alphabetically by keys:\n " + |
| 50 | + "\n ".join(mismatches) |
| 51 | + ) |
| 52 | + |
| 53 | + @classmethod |
| 54 | + def _duplicate_key_validator(cls, pairs: list[tuple[str, Any]]) -> dict[str, Any]: |
| 55 | + result: dict[str, Any] = {} |
| 56 | + for key, value in pairs: |
| 57 | + if key in result: |
| 58 | + raise DuplicateKeyException(f"Duplicate key found: '{key}'") |
| 59 | + result[key] = value |
| 60 | + return result |
| 61 | + |
| 62 | + |
| 63 | +if __name__ == '__main__': |
| 64 | + OrderValidator().validate() |
0 commit comments