jw-python/src/python/jw/util/load_yaml.py

459 lines
18 KiB
Python
Raw Normal View History

"""YAML loading with includes, links, and deep merging.
load_yaml() loads a YAML file whose root must be a mapping and
supports three extensions:
- ``jw.include`` — deep-merges other YAML files into the document,
either at the root or at a dot-separated target path. A leading
``-`` marks the include as optional (a missing file contributes
nothing). In a YAML block list the list dash is not the marker;
the item itself must carry it, as in ``- -file.yaml`` or
``- "-file.yaml"``. File names may use glob characters (``*``, ``?``,
``[...]``); all matches are included in lexical order, and a
non-optional glob that matches no files raises ValueError. A spec
that starts with a glob character such as ``*`` or ``[`` must be
quoted in YAML.
- ``jw.link`` — replaces a node with the value found at a dot-separated
target path. A prefix before the first ``|`` names the resulting
key instead of replacing the node in place.
- ``jw.inplace-link`` — like ``jw.link``, but sibling keys of the link
node are deep-merged into the resolved target mapping.
Target paths use dot-separated segments. Relative paths start with
``.`` and work like Python imports: a single dot stays in the dict
that contains the link, each additional dot goes up one level.
Because segments are separated by dots, keys that themselves contain
a dot cannot be addressed. Path navigation operates on the
unexpanded tree, so intermediate segments must not be link nodes
themselves.
"""
from __future__ import annotations
import re
from copy import deepcopy
from pathlib import Path
from typing import Any, TypeAlias, cast
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 yaml # type: ignore[import-untyped]
# -- Constants ------------------------------------------------------------------
IncludeSpec: TypeAlias = tuple[bool, Path, tuple[str, ...]]
Includes: TypeAlias = list[IncludeSpec]
_LINK_NAME_RE = re.compile(r'^([a-zA-Z0-9_-]+)\|')
_INCLUDE_PATH_RE = re.compile(r'^([a-zA-Z0-9_.-]+)\|')
_GLOB_CHARS = frozenset('*?[')
# -- 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():
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
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
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 is recognized by a prefix matching ``[a-zA-Z0-9_-]+``
followed by a pipe. The first pipe then separates the link name
from the target path, e.g. ``"name|path|to|target"`` yields the
name ``name`` and the target path ``path|to|target``. Otherwise
the entire string is treated as an absolute or relative target
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
"""
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[str, ...],
root: dict[str, Any],
) -> tuple[tuple[str, ...], Any]:
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
"""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[str, ...] = current_path
target: Any = root
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
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[str, ...] = ()
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
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)
# -- Include helpers ------------------------------------------------------------
def _glob_include(file_spec: str, parent: Path) -> list[Path]:
"""Resolve *file_spec* against *parent* and expand glob characters.
A spec without glob characters resolves to a single path, which
need not exist yet. A spec with glob characters is expanded to
the matching paths in lexical order (possibly an empty list).
"""
parts = file_spec.split('/')
for i, part in enumerate(parts):
if _GLOB_CHARS & set(part):
prefix = '/'.join(parts[:i])
if file_spec.startswith('/'):
base = Path(prefix)
else:
base = parent / prefix
return sorted(base.glob('/'.join(parts[i:])))
path = Path(file_spec)
return [path if path.is_absolute() else parent / path]
def _parse_include_spec(spec: str, parent: Path) -> list[IncludeSpec]:
"""Parse a jw.include spec into one or more IncludeSpec entries.
The file part may use glob characters; every match becomes a
separate entry. A non-optional glob that matches no files raises
ValueError.
"""
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('.'))
spec = spec[len(m.group(1)) + 1:]
paths = _glob_include(spec, parent)
if not paths and not optional:
raise ValueError(f'Include glob {spec!r} matches no files')
return [(optional, path, target_path) for path in paths]
def _normalize_include_specs(specs: Any, parent: Path) -> Includes:
if specs is None:
return []
if isinstance(specs, str):
specs = [specs]
if not isinstance(specs, list):
raise TypeError(f'Unsupported include format: {specs!r}')
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
# -- 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. Raises ``ValueError`` when
an existing value on or at the target path is not a mapping.
Returns the modified root.
"""
if not path:
return _deep_merge(root, value)
path_str = '.'.join(path)
current = root
for i, key in enumerate(path[:-1]):
if key in current and not isinstance(current[key], dict):
raise ValueError(
f'Include target path {path_str}: value at '
f'{".".join(path[:i + 1])} is not a mapping'
)
if key not in current:
current[key] = {}
current = current[key]
last_key = path[-1]
if last_key in current:
if not isinstance(current[last_key], dict) or not isinstance(value, dict):
raise ValueError(
f'Include target path {path_str}: value at {path_str} '
f'is not a mapping'
)
# 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 _resolve_link(
kind: str,
spec: Any,
current_path: tuple[str | int, ...],
root: dict[str, Any],
) -> tuple[bool, str | None, tuple[str, ...], Any]:
"""Parse *spec* and resolve its target path against *root*.
Returns ``(is_named, name, target_path, target_value)``. A
non-string spec raises ``TypeError``; a missing or invalid target
raises ``ValueError`` naming the link and its location. Path
navigation operates on the unexpanded tree, so intermediate
segments must not be link nodes themselves.
"""
if not isinstance(spec, str):
raise TypeError(
f'{kind} value must be a string, got {type(spec).__name__}: {spec!r}'
)
is_named, name, path = _parse_link(spec)
where = '.'.join(str(part) for part in current_path)
if not where:
where = '<root>'
try:
# current_path may contain int indices from list traversal,
# but _resolve_path only uses string keys for navigation
target_path, target_value = _resolve_path(
path, cast('tuple[str, ...]', current_path), root
)
except (KeyError, IndexError, TypeError) as exc:
raise ValueError(
f'{kind} {spec!r} at {where}: cannot resolve target path: {exc}'
) from None
return (is_named, name, target_path, target_value)
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
def _expand_links_recursive(
node: Any,
root: dict[str, Any],
current_path: tuple[str | int, ...],
resolved: dict[tuple[tuple[str | int, ...], str], Any],
resolving: set[tuple[tuple[str | int, ...], str]],
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
) -> Any:
"""Recursively walk *node* and expand all link markers.
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
``resolved`` is a memoisation cache mapping ``(path, link_spec)`` →
expanded value. ``resolving`` tracks links currently being expanded
to detect cycles.
"""
if isinstance(node, dict):
# --- jw.inplace-link: can have siblings, merges into resolved target ---
if 'jw.inplace-link' in node:
link_spec = node['jw.inplace-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:
# Deepcopy so that cached results are not aliased into
# multiple places of the output tree
base_value: Any = deepcopy(resolved[link_key])
else:
resolving.add(link_key)
_, _, target_path, target_value = _resolve_link(
'jw.inplace-link', link_spec, current_path, root
)
base_value = _expand_links_recursive(
target_value, root, target_path, resolved, resolving
)
resolved[link_key] = base_value
resolving.discard(link_key)
# Expand sibling keys
expanded_remaining: dict[str, Any] = {}
for key, value in node.items():
if key == 'jw.inplace-link':
continue
expanded_remaining[key] = _expand_links_recursive(
value, root, current_path + (key, ), resolved, resolving
)
if not expanded_remaining:
return base_value
if not isinstance(base_value, dict):
raise ValueError(
f'jw.inplace-link {link_spec!r}: resolved value is not '
f'a mapping, cannot merge siblings'
)
# Deep-merge siblings into resolved dict (siblings win on conflict)
return _deep_merge(base_value, expanded_remaining)
# --- jw.link (sole key): inplace or named replacement ---
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
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:
# Deepcopy so that cached results are not aliased into
# multiple places of the output tree
return deepcopy(resolved[link_key])
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
resolving.add(link_key)
is_named, name, target_path, target_value = _resolve_link(
'jw.link', link_spec, current_path, root
)
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
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 ---
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
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 link markers in *root* and return the result.
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
Three link forms are supported:
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
- **Inplace** ``jw.link: "target.path"`` — the ``jw.link`` key
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
disappears and is replaced by the resolved value, inline.
- **Named** ``jw.link: "name|target.path"`` — the ``jw.link`` key
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
is renamed to ``name`` and its value is the resolved target.
- **Inplace** ``jw.inplace-link: "target.path"`` — the ``jw.inplace-link``
key disappears and its value is deep-merged into the resolved target
dict. Sibling keys (if any) override the target on conflict.
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
Paths use dot-separated segments. A relative path starts with
``.`` (Python-import style): a single dot stays in the dict that
contains the link, ``..`` 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.
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
A ``jw.link`` node with additional sibling keys is not a link. The
``jw.link`` key and its raw value are left as-is in the output.
Cyclic links and unresolvable targets raise ``ValueError`` naming
the link. Non-string link values raise ``TypeError``.
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
"""
resolved: dict[tuple[tuple[str | int, ...], str], Any] = {}
resolving: set[tuple[tuple[str | int, ...], str]] = set()
return cast(
'dict[str, Any]', _expand_links_recursive(root, root, (), resolved, resolving)
)
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
# -- 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, encoding = 'utf-8') 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 not included_next:
# An empty document contributes nothing; in particular
# it must not create the target key of a path-addressed
# include
continue
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()
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))
if __name__ == '__main__':
import json
import sys
if len(sys.argv) != 2:
sys.exit(f'usage: {sys.argv[0]} FILE.yaml')
print(json.dumps(load_yaml(sys.argv[1]), indent = 2, default = str))