This repository has been archived on 2024-06-02. You can view files and clone it, but cannot push or open issues or pull requests.
spud-py/spud/config.py
Marc Cataford 3dad2071ff
All checks were successful
/ Tests (push) Successful in 52s
/ Static Analysis (push) Successful in 1m4s
refactor: extract configuration handling to own class
2024-04-13 23:17:42 -04:00

36 lines
1.1 KiB
Python

import json
import pathlib
import pydantic
class Configuration(pydantic.BaseModel):
"""Command line application configuration options"""
@classmethod
def from_file(cls, path: pathlib.Path) -> "Configuration":
"""
Generates a Configuration object from the file found at {path}.
Raises if:
- The file does not exist
- The file is not valid JSON
- The file does not respect the expected schema
"""
if not path.exists():
raise RuntimeError(f"Configuration file not found: {str(path)}.")
with open(path, "r", encoding="utf8") as config_file:
config_data = config_file.read()
try:
parsed_configuration = json.loads(config_data)
return cls(**parsed_configuration)
except json.decoder.JSONDecodeError as exc:
raise RuntimeError(
f"Configuration file is not valid JSON ({str(path)})."
) from exc
except pydantic.ValidationError as exc:
raise RuntimeError(
f"Configuration file has wrong schema ({str(path)})."
) from exc