2026-06-13 20:31:42 +02:00
|
|
|
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
|
|
|
|
|
|
load_yaml: Implement jw.link expansion
Implement link expansion in _expand_links() to resolve jw.link markers
in YAML documents after the include/merge phase. Two link forms are
supported:
- Inplace links jw.link: "path.to.target" replace the marker entirely
with the resolved value at the target path.
- Named links jw.link: "name|path.to.target" replace the marker with
{name: resolved_value}, using the first path segment as the key.
Paths use dot-separated segments. Relative paths start with ".."
(like Python imports): "." stays at the current level, ".." goes up
one level, "..." two, and so on. A single pipe character in the link
value separates the link name from the target path for named links.
The implementation includes:
- _parse_link(): splits a link value into (is_named, name, path)
- _resolve_path(): resolves an absolute or relative path to a value
- _expand_links_recursive(): walks the structure, expands links,
detects cycles via a resolving set, and memoises via a resolved dict.
Cyclic links and missing targets both raise ValueError/KeyError.
jw.link markers with sibling keys are left unexpanded.
Add 86 unit tests covering the entire load_yaml module:
- Basic YAML loading, optional loading, root type checking
- Include directive (single, multiple, deep merge, circular detect)
- Inplace links, named links, relative paths (up, descend, same level)
- Transitive links, cycle detection, missing targets
- Regression tests, combined include+links, edge cases, type preservation
Signed-off-by: Jan Lindemann <jan@janware.com>
2026-07-03 11:26:06 +02:00
|
|
|
import re # noqa: E402
|
|
|
|
|
|
2026-06-13 20:31:42 +02:00
|
|
|
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)
|
|
|
|
|
|
load_yaml: Implement jw.link expansion
Implement link expansion in _expand_links() to resolve jw.link markers
in YAML documents after the include/merge phase. Two link forms are
supported:
- Inplace links jw.link: "path.to.target" replace the marker entirely
with the resolved value at the target path.
- Named links jw.link: "name|path.to.target" replace the marker with
{name: resolved_value}, using the first path segment as the key.
Paths use dot-separated segments. Relative paths start with ".."
(like Python imports): "." stays at the current level, ".." goes up
one level, "..." two, and so on. A single pipe character in the link
value separates the link name from the target path for named links.
The implementation includes:
- _parse_link(): splits a link value into (is_named, name, path)
- _resolve_path(): resolves an absolute or relative path to a value
- _expand_links_recursive(): walks the structure, expands links,
detects cycles via a resolving set, and memoises via a resolved dict.
Cyclic links and missing targets both raise ValueError/KeyError.
jw.link markers with sibling keys are left unexpanded.
Add 86 unit tests covering the entire load_yaml module:
- Basic YAML loading, optional loading, root type checking
- Include directive (single, multiple, deep merge, circular detect)
- Inplace links, named links, relative paths (up, descend, same level)
- Transitive links, cycle detection, missing targets
- Regression tests, combined include+links, edge cases, type preservation
Signed-off-by: Jan Lindemann <jan@janware.com>
2026-07-03 11:26:06 +02:00
|
|
|
_LINK_NAME_RE = re.compile(r'^([a-zA-Z0-9_-]+)\|')
|
|
|
|
|
|
|
|
|
|
def _parse_link(value: str) -> tuple[bool, str | None, str]:
|
|
|
|
|
"""Parse a link value into (is_named, name_or_None, path_string).
|
|
|
|
|
|
|
|
|
|
A named link uses a single pipe to separate the link name from the
|
|
|
|
|
target path, e.g. ``"name|path|to|target"``. Otherwise the entire
|
|
|
|
|
string is treated as an absolute or relative target path.
|
|
|
|
|
"""
|
|
|
|
|
m = _LINK_NAME_RE.match(value)
|
|
|
|
|
if m:
|
|
|
|
|
return (True, m.group(1), value[len(m.group(1)) + 1:])
|
|
|
|
|
return (False, None, value)
|
|
|
|
|
|
|
|
|
|
def _resolve_path(path_str: str, current_path: tuple,
|
|
|
|
|
root: dict[str, Any]) -> tuple[tuple[str, ...], Any]:
|
|
|
|
|
"""Resolve *path_str* and return ``(path, value)`` at that location.
|
|
|
|
|
|
|
|
|
|
Absolute paths are resolved from the document root; relative paths
|
|
|
|
|
(starting with ``.``) are resolved from *current_path*. Path segments
|
|
|
|
|
are separated by dots.
|
|
|
|
|
"""
|
|
|
|
|
if not path_str:
|
|
|
|
|
resolved_path: tuple = current_path
|
|
|
|
|
target = root
|
|
|
|
|
for key in current_path:
|
|
|
|
|
target = target[key]
|
|
|
|
|
return (resolved_path, target)
|
|
|
|
|
|
|
|
|
|
if path_str.startswith('.'):
|
|
|
|
|
# Count consecutive leading dots to determine levels to go up
|
|
|
|
|
# from the link's parent. 1 dot = stay, 2 dots = up 1, etc.
|
|
|
|
|
dot_count = 0
|
|
|
|
|
for ch in path_str:
|
|
|
|
|
if ch == '.':
|
|
|
|
|
dot_count += 1
|
|
|
|
|
else:
|
|
|
|
|
break
|
|
|
|
|
levels_up = dot_count - 1
|
|
|
|
|
rest = path_str[dot_count:]
|
|
|
|
|
|
|
|
|
|
# Start from the link's parent (the dict that contains the link)
|
|
|
|
|
if not current_path:
|
|
|
|
|
parent_path: tuple = ()
|
|
|
|
|
else:
|
|
|
|
|
parent_path = current_path[:-1]
|
|
|
|
|
|
|
|
|
|
if levels_up > 0:
|
|
|
|
|
if levels_up > len(parent_path):
|
|
|
|
|
raise ValueError(f"Link target path goes above root: {path_str!r}")
|
|
|
|
|
new_path = parent_path[:-levels_up]
|
|
|
|
|
else:
|
|
|
|
|
new_path = parent_path
|
|
|
|
|
|
|
|
|
|
# Navigate from root to the base (new_path)
|
|
|
|
|
resolved_path = new_path
|
|
|
|
|
target = root
|
|
|
|
|
for key in new_path:
|
|
|
|
|
target = target[key]
|
|
|
|
|
|
|
|
|
|
if rest:
|
|
|
|
|
for key in rest.split('.'):
|
|
|
|
|
resolved_path = resolved_path + (key, )
|
|
|
|
|
target = target[key]
|
|
|
|
|
|
|
|
|
|
return (resolved_path, target)
|
|
|
|
|
# Absolute path from root
|
|
|
|
|
resolved_path = tuple(path_str.split('.'))
|
|
|
|
|
target = root
|
|
|
|
|
for key in path_str.split('.'):
|
|
|
|
|
target = target[key]
|
|
|
|
|
return (resolved_path, target)
|
|
|
|
|
|
|
|
|
|
def _expand_links_recursive(
|
|
|
|
|
node: Any,
|
|
|
|
|
root: dict[str, Any],
|
|
|
|
|
current_path: tuple,
|
|
|
|
|
resolved: dict,
|
|
|
|
|
resolving: set,
|
|
|
|
|
) -> Any:
|
|
|
|
|
"""Recursively walk *node* and expand all ``jw.link`` markers.
|
|
|
|
|
|
|
|
|
|
``resolved`` is a memoisation cache mapping ``(path, link_spec)`` →
|
|
|
|
|
expanded value. ``resolving`` tracks links currently being expanded
|
|
|
|
|
to detect cycles.
|
|
|
|
|
"""
|
|
|
|
|
if isinstance(node, dict):
|
|
|
|
|
# Link node: dict with only jw.link as key
|
|
|
|
|
if 'jw.link' in node and len(node) == 1:
|
|
|
|
|
link_spec = node['jw.link']
|
|
|
|
|
link_key = (current_path, link_spec)
|
|
|
|
|
|
|
|
|
|
if link_key in resolving:
|
|
|
|
|
raise ValueError(f"Cyclic link detected: {link_spec!r}")
|
|
|
|
|
if link_key in resolved:
|
|
|
|
|
return resolved[link_key]
|
|
|
|
|
|
|
|
|
|
resolving.add(link_key)
|
|
|
|
|
is_named, name, path = _parse_link(link_spec)
|
|
|
|
|
target_path, target_value = _resolve_path(path, current_path, root)
|
|
|
|
|
expanded_target = _expand_links_recursive(
|
|
|
|
|
target_value, root, target_path, resolved, resolving
|
|
|
|
|
)
|
|
|
|
|
resolving.discard(link_key)
|
|
|
|
|
|
|
|
|
|
if is_named:
|
|
|
|
|
result = {name: expanded_target}
|
|
|
|
|
else:
|
|
|
|
|
result = expanded_target
|
|
|
|
|
|
|
|
|
|
resolved[link_key] = result
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
# Normal dict — expand values recursively
|
|
|
|
|
expanded: dict[str, Any] = {}
|
|
|
|
|
for key, value in node.items():
|
|
|
|
|
expanded[key] = _expand_links_recursive(
|
|
|
|
|
value, root, current_path + (key, ), resolved, resolving
|
|
|
|
|
)
|
|
|
|
|
return expanded
|
|
|
|
|
|
|
|
|
|
if isinstance(node, list):
|
|
|
|
|
return [
|
|
|
|
|
_expand_links_recursive(
|
|
|
|
|
item, root, current_path + (i, ), resolved, resolving
|
|
|
|
|
) for i, item in enumerate(node)
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
return node # scalar or None
|
|
|
|
|
|
|
|
|
|
def _expand_links(root: dict[str, Any]) -> dict[str, Any]:
|
|
|
|
|
r"""Expand all ``jw.link`` markers in *root* and return the result.
|
|
|
|
|
|
|
|
|
|
Two link forms are supported:
|
|
|
|
|
|
|
|
|
|
- **Inplace** ``jw.link: "target.path"`` — the ``jw.link`` key
|
|
|
|
|
disappears and is replaced by the resolved value, inline.
|
|
|
|
|
- **Named** ``jw.link: "name|target.path"`` — the ``jw.link`` key
|
|
|
|
|
is renamed to ``name`` and its value is the resolved target.
|
|
|
|
|
|
|
|
|
|
Paths use dot-separated segments. A relative path starts with ``.``
|
|
|
|
|
(Python-import style): ``.`` stays at the current level, ``..`` goes
|
|
|
|
|
up one level, ``...`` two, and so on. The first ``/`` in the link
|
|
|
|
|
value (only when the prefix matches ``[a-zA-Z0-9_-]+/``) separates
|
|
|
|
|
the link name from the target path for named links.
|
|
|
|
|
|
|
|
|
|
Cyclic links raise ``ValueError``; missing targets also raise.
|
|
|
|
|
"""
|
|
|
|
|
resolved: dict = {}
|
|
|
|
|
resolving: set = set()
|
|
|
|
|
return _expand_links_recursive(root, root, (), resolved, resolving)
|
|
|
|
|
|
2026-06-13 20:31:42 +02:00
|
|
|
def load_yaml(path: str | Path, optional: bool = False) -> dict[str, Any]: # export
|
|
|
|
|
seen: set[Path] = set()
|
load_yaml: Implement jw.link expansion
Implement link expansion in _expand_links() to resolve jw.link markers
in YAML documents after the include/merge phase. Two link forms are
supported:
- Inplace links jw.link: "path.to.target" replace the marker entirely
with the resolved value at the target path.
- Named links jw.link: "name|path.to.target" replace the marker with
{name: resolved_value}, using the first path segment as the key.
Paths use dot-separated segments. Relative paths start with ".."
(like Python imports): "." stays at the current level, ".." goes up
one level, "..." two, and so on. A single pipe character in the link
value separates the link name from the target path for named links.
The implementation includes:
- _parse_link(): splits a link value into (is_named, name, path)
- _resolve_path(): resolves an absolute or relative path to a value
- _expand_links_recursive(): walks the structure, expands links,
detects cycles via a resolving set, and memoises via a resolved dict.
Cyclic links and missing targets both raise ValueError/KeyError.
jw.link markers with sibling keys are left unexpanded.
Add 86 unit tests covering the entire load_yaml module:
- Basic YAML loading, optional loading, root type checking
- Include directive (single, multiple, deep merge, circular detect)
- Inplace links, named links, relative paths (up, descend, same level)
- Transitive links, cycle detection, missing targets
- Regression tests, combined include+links, edge cases, type preservation
Signed-off-by: Jan Lindemann <jan@janware.com>
2026-07-03 11:26:06 +02:00
|
|
|
return _expand_links(_load_yaml(path, optional, seen))
|
2026-06-13 20:31:42 +02:00
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
|
import json
|
|
|
|
|
import sys
|
|
|
|
|
|
|
|
|
|
print(json.dumps(load_yaml(sys.argv[1]), indent = 2))
|