load_yaml: Add module

Add load_yaml.load_yaml(), adding little over yaml.safe_load(), aside
from supporting a toplevel entry "include", which can contain a list
of included paths.

Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
Jan Lindemann 2026-06-13 20:31:42 +02:00 • committed by janware DevOps
commit 69c81ada43
Signed by: DevOps
SSH key fingerprint: SHA256:cZiw7ExG5q3KAVm7Jse3rGITowu0VjgUgNMPbifmY8g

View file

@ -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))