Source code for codegen.config

from typing import TYPE_CHECKING, Any

from pydantic import BaseModel, ConfigDict, ValidationError

from codegen import jsonnet
from codegen.errors import ConfigError

if TYPE_CHECKING:
    from collections.abc import Mapping
    from pathlib import Path


[docs] class CodegenConfig(BaseModel): package_prefix: str = ""
[docs] class ExtensibleConfig(BaseModel): model_config = ConfigDict(extra="allow") @property def options(self) -> dict[str, Any]: return self.model_extra or {}
def load_config( path: Path, schema: type[CodegenConfig], stdlibs: Mapping[str, Path] | None = None, ) -> CodegenConfig: raw = _read_source(path, stdlibs or {}) try: return schema.model_validate_json(raw) except ValidationError as exc: msg = f"Invalid config in {path}: {exc}" raise ConfigError(msg) from exc def _read_source(path: Path, stdlibs: Mapping[str, Path]) -> str: suffix = path.suffix.lower() try: if suffix == ".jsonnet": return jsonnet.evaluate(path, stdlibs) if suffix == ".json": return path.read_text() except RuntimeError as exc: msg = f"Jsonnet evaluation failed for {path}: {exc}" raise ConfigError(msg) from exc except OSError as exc: msg = f"Could not read {path}: {exc}" raise ConfigError(msg) from exc msg = f"Unsupported config format: {suffix!r} (use .json or .jsonnet)" raise ConfigError(msg)