diff --git a/src/python/jw/util/load_yaml.py b/src/python/jw/util/load_yaml.py new file mode 100644 index 0000000..405bb11 --- /dev/null +++ b/src/python/jw/util/load_yaml.py @@ -0,0 +1,91 @@ +from __future__ import annotations + +from copy import deepcopy +from pathlib import Path +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from typing import Any, TypeAlias + +import yaml # type: ignore[import-untyped] + +Includes: TypeAlias = list[tuple[bool, Path]] + +def _deep_merge(base: dict, override: dict) -> dict: + ret = deepcopy(base) + for key, val in override.items(): + if (key in ret and isinstance(ret[key], dict) and isinstance(val, dict)): + ret[key] = _deep_merge(ret[key], val) + continue + ret[key] = deepcopy(val) + return ret + +def _parse_include_spec(spec: str, parent: Path) -> Includes: + if not spec: + return [] + optional = spec.startswith('-') + if optional: + spec = spec[1:] + if not spec: + return [] + path = Path(spec) + if not path.is_absolute(): + path = parent / path + return [(optional, path)] + +def _normalize_include_specs(specs: Any, parent: Path) -> Includes: + if specs is None: + return [] + if isinstance(specs, str): + return _parse_include_spec(specs, parent) + if isinstance(specs, list): + ret: Includes = [] + for spec in specs: + if not isinstance(spec, str): + raise TypeError(f'Unsupported include entry: {spec!r}') + ret.extend(_parse_include_spec(spec, parent)) + return ret + raise TypeError(f'Unsupported include format: {specs!r}') + +def _load_yaml(path: str | Path, optional: bool, seen: set[Path]) -> dict[str, Any]: + path = Path(path).resolve() + if path in seen: + raise ValueError(f'Cyclic YAML include detected: {path}') + seen.add(path) + try: + try: + with open(path) as f: + loaded = yaml.safe_load(f) + if loaded is None: + ret: dict[str, Any] = {} + elif isinstance(loaded, dict): + ret = loaded + else: + raise TypeError( + f'YAML root must be a mapping in {path!r}, ' + f'got {type(loaded).__name__}' + ) + ret = dict(ret) + except FileNotFoundError: + if optional: + return {} + raise + includes = _normalize_include_specs(ret.get('include', []), path.parent) + ret.pop('include', None) + included_all: dict[str, Any] = {} + for include in includes: + included_next = _load_yaml(include[1], optional = include[0], seen = seen) + included_all = _deep_merge(included_all, included_next) + return _deep_merge(included_all, ret) + finally: + seen.remove(path) + +def load_yaml(path: str | Path, optional: bool = False) -> dict[str, Any]: # export + seen: set[Path] = set() + return _load_yaml(path, optional, seen) + +if __name__ == '__main__': + import json + import sys + + print(json.dumps(load_yaml(sys.argv[1]), indent = 2))