From 7595bfc21e0cbc56b0e9e278e7219cd0ee4e50e6 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Wed, 8 Jul 2026 15:37:06 +0200 Subject: [PATCH] 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 --- src/python/jw/util/load_yaml.py | 64 ++++++++-- test/unit/python/jw/util/load_yaml/test.py | 137 ++++++++++++++++++++- 2 files changed, 188 insertions(+), 13 deletions(-) diff --git a/src/python/jw/util/load_yaml.py b/src/python/jw/util/load_yaml.py index 7150af6..09cef83 100644 --- a/src/python/jw/util/load_yaml.py +++ b/src/python/jw/util/load_yaml.py @@ -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) diff --git a/test/unit/python/jw/util/load_yaml/test.py b/test/unit/python/jw/util/load_yaml/test.py index 1b3513b..e0ceb1e 100644 --- a/test/unit/python/jw/util/load_yaml/test.py +++ b/test/unit/python/jw/util/load_yaml/test.py @@ -787,7 +787,142 @@ class TestInplaceLink: assert data['entry']['from'] == 'include' assert data['entry']['local'] == 'here' -# -- jw.link expansion - Path resolution -------------------------------------- + def test_inplace_link_transitive_relative(self, yaml_file: Callable) -> None: + """jw.inplace-link with relative paths resolves through chain. + + Target A's relative link '.chat-janware-com' should resolve from + A's position in the tree, not from the position of the link that + references A. + """ + data = load_yaml( + yaml_file( + 'section:\n' + ' a:\n' + ' jw.inplace-link: .b\n' + ' b:\n' + ' interface: open-ai\n' + ' base_uri: http://example.com\n' + 'ref:\n' + ' jw.inplace-link: section.a\n' + ) + ) + # ref -> section.a -> .b (relative from section.a -> section.b) + assert data['ref']['interface'] == 'open-ai' + assert data['ref']['base_uri'] == 'http://example.com' + +# -- jw.include with target path ------------------------------------------------ + +class TestIncludeWithPath: + """Tests for jw.include with target path specification.""" + + def test_include_at_root(self, temp_dir: Callable) -> None: + """Plain include merges at root (original behavior).""" + base = temp_dir( + [ + ('base.yaml', 'shared: from_base\n'), + ('main.yaml', 'jw.include: base.yaml\n') + ] + ) + data = load_yaml(pathlib.Path(base) / 'main.yaml') + assert data['shared'] == 'from_base' + + def test_include_at_nested_path(self, temp_dir: Callable) -> None: + """Include with path merges at the specified location.""" + base = temp_dir( + [ + ('base.yaml', 'nested: value\n'), + ('main.yaml', 'jw.include: entry|base.yaml\n') + ] + ) + data = load_yaml(pathlib.Path(base) / 'main.yaml') + assert data['entry']['nested'] == 'value' + + def test_include_at_deep_path(self, temp_dir: Callable) -> None: + """Include at deep nested path creates intermediate dicts.""" + base = temp_dir( + [ + ('base.yaml', 'deep: nested\n'), + ('main.yaml', 'jw.include: a.b.c|base.yaml\n') + ] + ) + data = load_yaml(pathlib.Path(base) / 'main.yaml') + assert data['a']['b']['c']['deep'] == 'nested' + + def test_include_merge_with_existing(self, temp_dir: Callable) -> None: + """Include merges with existing content at target path.""" + base = temp_dir( + [ + ('base.yaml', 'from_include: included\n'), + ( + 'main.yaml', + 'entry:\n existing: here\njw.include: entry|base.yaml\n' + ), + ] + ) + data = load_yaml(pathlib.Path(base) / 'main.yaml') + assert data['entry']['existing'] == 'here' + assert data['entry']['from_include'] == 'included' + + def test_include_override_existing(self, temp_dir: Callable) -> None: + """Include overrides existing values at target path.""" + base = temp_dir( + [ + ('base.yaml', 'existing: overwritten\n'), + ( + 'main.yaml', + 'entry:\n existing: original\njw.include: entry|base.yaml\n' + ), + ] + ) + data = load_yaml(pathlib.Path(base) / 'main.yaml') + assert data['entry']['existing'] == 'overwritten' + + def test_multiple_includes_different_paths(self, temp_dir: Callable) -> None: + """Multiple includes can target different paths.""" + base = temp_dir( + [ + ('base1.yaml', 'a: 1\n'), + ('base2.yaml', 'b: 2\n'), + ( + 'main.yaml', + 'jw.include:\n - section1|base1.yaml\n' + ' - section2|base2.yaml\n' + ), + ] + ) + data = load_yaml(pathlib.Path(base) / 'main.yaml') + assert data['section1']['a'] == 1 + assert data['section2']['b'] == 2 + + def test_include_with_optional(self, temp_dir: Callable) -> None: + """Optional includes with path work correctly.""" + base = temp_dir( + [ + ('base.yaml', 'opt: val\n'), + ('main.yaml', 'jw.include: -section|base.yaml\n'), + ] + ) + data = load_yaml(pathlib.Path(base) / 'main.yaml') + assert data['section']['opt'] == 'val' + + def test_include_plain_and_path_mixed(self, temp_dir: Callable) -> None: + """Mix plain and path-based includes in same document.""" + base = temp_dir( + [ + ('plain.yaml', 'plain_key: plain_val\n'), + ('target.yaml', 'target_key: target_val\n'), + ( + 'main.yaml', + 'jw.include:\n - plain.yaml\n' + ' - section|target.yaml\n' + ), + ] + ) + data = load_yaml(pathlib.Path(base) / 'main.yaml') + assert data['plain_key'] == 'plain_val' + assert data['section']['target_key'] == 'target_val' + +# -- jw.include with target path ------------------------------------------------ class TestPathResolution: """Tests for path resolution logic."""