from __future__ import annotations from copy import deepcopy from pathlib import Path from typing import Any, cast, TypeAlias import re # noqa: E402 import yaml # type: ignore[import-untyped] IncludeSpec: TypeAlias = tuple[bool, Path, tuple[str, ...]] Includes: TypeAlias = list[IncludeSpec] 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 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: 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('.')) 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, 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)] if isinstance(specs, list): ret: Includes = [] for spec in specs: if not isinstance(spec, str): raise TypeError(f'Unsupported include entry: {spec!r}') ret.append(_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('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 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) _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[str, ...], 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[str, ...] = current_path target: Any = 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[str, ...] = () 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[str | int, ...], resolved: dict[tuple[tuple[str | int, ...], str], Any], resolving: set[tuple[tuple[str | int, ...], str]], ) -> Any: """Recursively walk *node* and expand all 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): # --- 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: base_value: dict[str, Any] | Any = resolved[link_key] else: resolving.add(link_key) _, _, path = _parse_link(link_spec) # 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 ) 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 ) # Deep-merge siblings into resolved dict (siblings win on conflict) if isinstance(base_value, dict) and expanded_remaining: return _deep_merge(base_value, expanded_remaining) return base_value # --- jw.link (sole key): inplace or named replacement --- 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) # 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 ) 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 link markers in *root* and return the result. Three 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. - **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. 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[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) ) def load_yaml(path: str | Path, optional: bool = False) -> dict[str, Any]: # export seen: set[Path] = set() return _expand_links(_load_yaml(path, optional, seen)) if __name__ == '__main__': import json import sys print(json.dumps(load_yaml(sys.argv[1]), indent = 2))