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

39 lines
1.1 KiB
Python
Raw Permalink Normal View History

import json
import pathlib
import pydantic
class Configuration(pydantic.BaseModel):
"""Command line application configuration options"""
api_baseurl: str
@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