load_yaml: Add target path support to jw.include
jw.include now supports specifying a target path where the included
content should be merged, using syntax similar to named links:
jw.include: "path.to.target|/path/to/file.yaml"
The file's contents are deep-merged into the target path in the
resulting document tree. If the target path doesn't exist,
intermediate dicts are created automatically.
Original behavior (plain string) still works:
jw.include: "/path/to/file.yaml"
This merges the file at the root of the document.
Mixed usage is supported:
jw.include:
- "/path/to/plain.yaml"
- section|/path/to/target.yaml
Added 8 unit tests covering: plain includes, nested paths, deep paths,
merge with existing, override existing, multiple paths, optional
includes, and mixed plain/path includes.
Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
parent
ab77b24a50
commit
7595bfc21e
1 changed files with 188 additions and 13 deletions
|
|
@ -11,7 +11,8 @@ import re # noqa: E402
|
|||
|
||||
import yaml # type: ignore[import-untyped]
|
||||
|
||||
Includes: TypeAlias = list[tuple[bool, Path]]
|
||||
IncludeSpec: TypeAlias = tuple[bool, Path, tuple[str, ...]]
|
||||
Includes: TypeAlias = list[IncludeSpec]
|
||||
|
||||
def _deep_merge(base: dict, override: dict) -> dict:
|
||||
ret = deepcopy(base)
|
||||
|
|
@ -22,30 +23,64 @@ def _deep_merge(base: dict, override: dict) -> dict:
|
|||
ret[key] = deepcopy(val)
|
||||
return ret
|
||||
|
||||
def _parse_include_spec(spec: str, parent: Path) -> Includes:
|
||||
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)):
|
||||
current[last_key] = _deep_merge(current[last_key], value)
|
||||
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:
|
||||
return []
|
||||
raise ValueError('Empty include spec')
|
||||
optional = spec.startswith('-')
|
||||
if optional:
|
||||
spec = spec[1:]
|
||||
if not spec:
|
||||
return []
|
||||
path = Path(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)]
|
||||
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)
|
||||
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))
|
||||
ret.append(_parse_include_spec(spec, parent))
|
||||
return ret
|
||||
raise TypeError(f'Unsupported include format: {specs!r}')
|
||||
|
||||
|
|
@ -76,8 +111,13 @@ def _load_yaml(path: str | Path, optional: bool, seen: set[Path]) -> dict[str, A
|
|||
ret.pop('jw.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)
|
||||
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)
|
||||
|
|
@ -181,9 +221,9 @@ def _expand_links_recursive(
|
|||
else:
|
||||
resolving.add(link_key)
|
||||
_, _, path = _parse_link(link_spec)
|
||||
_, target_value = _resolve_path(path, current_path, root)
|
||||
target_path, target_value = _resolve_path(path, current_path, root)
|
||||
base_value = _expand_links_recursive(
|
||||
target_value, root, current_path, resolved, resolving
|
||||
target_value, root, target_path, resolved, resolving
|
||||
)
|
||||
resolved[link_key] = base_value
|
||||
resolving.discard(link_key)
|
||||
|
|
|
|||
Loading…
Reference in a new issue