load_yaml: Reorder functions from leaves to trunk
Reorder functions so that call-graph leaves appear first and the
trunk (top-level entry points) appear last:
_deep_merge — leaf, no internal calls
_parse_link — leaf
_resolve_path — leaf
_parse_include_spec — leaf
_normalize_include_specs — calls _parse_include_spec
_merge_at_path — calls _deep_merge
_expand_links_recursive — calls _parse_link, _resolve_path
_expand_links — calls _expand_links_recursive
_load_yaml — calls _normalize_include_specs,
_merge_at_path
load_yaml — trunk, calls _load_yaml, _expand_links
Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
parent
b18b2f0b65
commit
9d0a3f8857
1 changed files with 110 additions and 100 deletions
|
|
@ -11,6 +11,8 @@ import yaml # type: ignore[import-untyped]
|
|||
IncludeSpec: TypeAlias = tuple[bool, Path, tuple[str, ...]]
|
||||
Includes: TypeAlias = list[IncludeSpec]
|
||||
|
||||
# -- Low-level helpers (call graph leaves) --------------------------------------
|
||||
|
||||
def _deep_merge(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:
|
||||
ret = deepcopy(base)
|
||||
for key, val in override.items():
|
||||
|
|
@ -20,106 +22,6 @@ def _deep_merge(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any
|
|||
ret[key] = deepcopy(val)
|
||||
return ret
|
||||
|
||||
def _merge_at_path(root: dict[str, Any], path: tuple[str, ...],
|
||||
value: Any) -> dict[str, Any]:
|
||||
"""Deep-merge *value* into *root* at the given *path*.
|
||||
|
||||
Creates intermediate dicts as needed. Returns the modified root.
|
||||
"""
|
||||
if not path:
|
||||
return _deep_merge(root, value)
|
||||
current = root
|
||||
for i, key in enumerate(path[:-1]):
|
||||
if key not in current or not isinstance(current[key], dict):
|
||||
current[key] = {}
|
||||
current = current[key]
|
||||
last_key = path[-1]
|
||||
if (last_key in current and isinstance(current[last_key], dict)
|
||||
and isinstance(value, dict)):
|
||||
# root's existing content wins (merge value into root)
|
||||
current[last_key] = _deep_merge(value, current[last_key])
|
||||
else:
|
||||
current[last_key] = deepcopy(value)
|
||||
return root
|
||||
|
||||
_INCLUDE_PATH_RE = re.compile(r'^([a-zA-Z0-9_.|-]+)\|')
|
||||
|
||||
def _parse_include_spec(spec: str, parent: Path) -> IncludeSpec:
|
||||
if not spec:
|
||||
raise ValueError('Empty include spec')
|
||||
optional = spec.startswith('-')
|
||||
if optional:
|
||||
spec = spec[1:]
|
||||
if not spec:
|
||||
raise ValueError('Empty include spec after removing optional marker')
|
||||
# Check for target path syntax: "path.to.target|/file.yaml" (like named links)
|
||||
target_path: tuple[str, ...] = ()
|
||||
if '|' in spec:
|
||||
m = _INCLUDE_PATH_RE.match(spec)
|
||||
if m:
|
||||
target_path = tuple(m.group(1).split('.'))
|
||||
file_spec = spec[len(m.group(1)) + 1:]
|
||||
else:
|
||||
file_spec = spec
|
||||
else:
|
||||
file_spec = spec
|
||||
path = Path(file_spec)
|
||||
if not path.is_absolute():
|
||||
path = parent / path
|
||||
return (optional, path, target_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.append(_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('jw.include', []), path.parent)
|
||||
ret.pop('jw.include', None)
|
||||
included_all: dict[str, Any] = {}
|
||||
for include in includes:
|
||||
opt, inc_path, target = include
|
||||
included_next = _load_yaml(inc_path, optional = opt, seen = seen)
|
||||
if target:
|
||||
# Merge at specific target path in the main document
|
||||
ret = _merge_at_path(ret, target, included_next)
|
||||
else:
|
||||
included_all = _deep_merge(included_all, included_next)
|
||||
return _deep_merge(included_all, ret)
|
||||
finally:
|
||||
seen.remove(path)
|
||||
|
||||
_LINK_NAME_RE = re.compile(r'^([a-zA-Z0-9_-]+)\|')
|
||||
|
||||
def _parse_link(value: str) -> tuple[bool, str | None, str]:
|
||||
|
|
@ -196,6 +98,74 @@ def _resolve_path(
|
|||
target = target[key]
|
||||
return (resolved_path, target)
|
||||
|
||||
# -- Include helpers ------------------------------------------------------------
|
||||
|
||||
_INCLUDE_PATH_RE = re.compile(r'^([a-zA-Z0-9_.|-]+)\|')
|
||||
|
||||
def _parse_include_spec(spec: str, parent: Path) -> IncludeSpec:
|
||||
if not spec:
|
||||
raise ValueError('Empty include spec')
|
||||
optional = spec.startswith('-')
|
||||
if optional:
|
||||
spec = spec[1:]
|
||||
if not spec:
|
||||
raise ValueError('Empty include spec after removing optional marker')
|
||||
# Check for target path syntax: "path.to.target|/file.yaml" (like named links)
|
||||
target_path: tuple[str, ...] = ()
|
||||
if '|' in spec:
|
||||
m = _INCLUDE_PATH_RE.match(spec)
|
||||
if m:
|
||||
target_path = tuple(m.group(1).split('.'))
|
||||
file_spec = spec[len(m.group(1)) + 1:]
|
||||
else:
|
||||
file_spec = spec
|
||||
else:
|
||||
file_spec = spec
|
||||
path = Path(file_spec)
|
||||
if not path.is_absolute():
|
||||
path = parent / path
|
||||
return (optional, path, target_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.append(_parse_include_spec(spec, parent))
|
||||
return ret
|
||||
raise TypeError(f'Unsupported include format: {specs!r}')
|
||||
|
||||
# -- Include target-path merging -----------------------------------------------
|
||||
|
||||
def _merge_at_path(root: dict[str, Any], path: tuple[str, ...],
|
||||
value: Any) -> dict[str, Any]:
|
||||
"""Deep-merge *value* into *root* at the given *path*.
|
||||
|
||||
Creates intermediate dicts as needed. Returns the modified root.
|
||||
"""
|
||||
if not path:
|
||||
return _deep_merge(root, value)
|
||||
current = root
|
||||
for i, key in enumerate(path[:-1]):
|
||||
if key not in current or not isinstance(current[key], dict):
|
||||
current[key] = {}
|
||||
current = current[key]
|
||||
last_key = path[-1]
|
||||
if (last_key in current and isinstance(current[last_key], dict)
|
||||
and isinstance(value, dict)):
|
||||
# root's existing content wins (merge value into root)
|
||||
current[last_key] = _deep_merge(value, current[last_key])
|
||||
else:
|
||||
current[last_key] = deepcopy(value)
|
||||
return root
|
||||
|
||||
# -- Link expansion -------------------------------------------------------------
|
||||
|
||||
def _expand_links_recursive(
|
||||
node: Any,
|
||||
root: dict[str, Any],
|
||||
|
|
@ -321,6 +291,46 @@ def _expand_links(root: dict[str, Any]) -> dict[str, Any]:
|
|||
'dict[str, Any]', _expand_links_recursive(root, root, (), resolved, resolving)
|
||||
)
|
||||
|
||||
# -- Top-level entry points -----------------------------------------------------
|
||||
|
||||
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('jw.include', []), path.parent)
|
||||
ret.pop('jw.include', None)
|
||||
included_all: dict[str, Any] = {}
|
||||
for include in includes:
|
||||
opt, inc_path, target = include
|
||||
included_next = _load_yaml(inc_path, optional = opt, seen = seen)
|
||||
if target:
|
||||
# Merge at specific target path in the main document
|
||||
ret = _merge_at_path(ret, target, included_next)
|
||||
else:
|
||||
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 _expand_links(_load_yaml(path, optional, seen))
|
||||
|
|
|
|||
Loading…
Reference in a new issue