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>
This commit is contained in:
parent
69c81ada43
commit
d7454341e8
1 changed files with 850 additions and 1 deletions
|
|
@ -7,6 +7,8 @@ from typing import TYPE_CHECKING
|
|||
if TYPE_CHECKING:
|
||||
from typing import Any, TypeAlias
|
||||
|
||||
import re # noqa: E402
|
||||
|
||||
import yaml # type: ignore[import-untyped]
|
||||
|
||||
Includes: TypeAlias = list[tuple[bool, Path]]
|
||||
|
|
@ -80,9 +82,161 @@ def _load_yaml(path: str | Path, optional: bool, seen: set[Path]) -> dict[str, A
|
|||
finally:
|
||||
seen.remove(path)
|
||||
|
||||
_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)
|
||||
|
||||
def load_yaml(path: str | Path, optional: bool = False) -> dict[str, Any]: # export
|
||||
seen: set[Path] = set()
|
||||
return _load_yaml(path, optional, seen)
|
||||
return _expand_links(_load_yaml(path, optional, seen))
|
||||
|
||||
if __name__ == '__main__':
|
||||
import json
|
||||
|
|
|
|||
Loading…
Reference in a new issue