"""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. In the top-level document, the file part of an include spec may reference environment variables as ``$(VAR)`` or ``${VAR}``; an undefined variable raises ValueError. Specs in included documents are never expanded. - ``jw.include-map`` — a table that rewrites include specs to other paths, for testing against tree-local copies of production configs. The value is a list of single-key mappings; the key is the LHS pattern, the value a RHS pattern or a list of RHS patterns. Before resolution, the file part of each include spec is qualified against the including file's directory and matched against the LHS patterns in table order; the first match rewrites the spec to every RHS pattern of that entry. ``*`` matches any run of characters that is not ``/``; the i-th ``*`` of the LHS captures into the i-th ``*`` of the RHS, so a glob spec rewrites to a glob RHS. A relative LHS or RHS is interpreted relative to the directory of the document that declares the map, and RHS values may reference environment variables as ``$(VAR)`` or ``${VAR}``. Only the top-level document may declare ``jw.include-map``. - ``jw.include-map-no-absolute`` — when true, an absolute include spec that matched no map entry raises ValueError, naming the spec and the file, guarding a test against silently reading a real production path. An identity entry (LHS and RHS the same) whitelists a path that may be read. The key defaults to false and applies to the whole include tree; only the top-level document may set it. - ``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 os import re from copy import deepcopy from pathlib import Path from typing import Any, TypeAlias, cast import yaml # type: ignore[import-untyped] from jw.util.log import DEBUG, log_m # -- Constants ------------------------------------------------------------------ IncludeSpec: TypeAlias = tuple[bool, Path, tuple[str, ...]] Includes: TypeAlias = list[IncludeSpec] IncludeMapEntry: TypeAlias = tuple[re.Pattern[str], tuple[str, ...]] IncludeMap: TypeAlias = tuple[list[IncludeMapEntry], Path] _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 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. """ 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) # -- Include helpers ------------------------------------------------------------ _VAR_RE = re.compile(r'\$\(([A-Za-z_][A-Za-z0-9_]*)\)|\$\{([A-Za-z_][A-Za-z0-9_]*)\}') def _expand_include_vars(value: str, where: str) -> str: """Expand $(VAR) and ${VAR} references in *value* from the environment. Raises ValueError naming the reference and *where* when a variable is not set. """ def __sub(m: re.Match[str]) -> str: name = m.group(1) if m.group(1) is not None else m.group(2) if name not in os.environ: raise ValueError(f'Undefined variable {m.group(0)} in {where}') return os.environ[name] return _VAR_RE.sub(__sub, value) def _canonicalize_path(path_str: str, base: Path) -> str: """Return *path_str* as a normalized absolute path string. Relative paths are joined with *base* first. Pure path arithmetic: no disk access, glob characters pass through untouched. """ if path_str.startswith('/'): return os.path.normpath(path_str) return os.path.normpath(str(base / path_str)) def _compile_lhs_pattern(lhs: str) -> re.Pattern[str]: """Compile a canonical LHS pattern into an anchored regex. Literal pieces are escaped; each '*' becomes a capture group that matches any run of characters that is not '/'. """ pieces = lhs.split('*') body = '([^/]*)'.join(re.escape(piece) for piece in pieces) return re.compile('^' + body + '$') 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_map(value: Any, base: Path, where: str) -> IncludeMap: """Parse and validate a jw.include-map value. The value is a list of single-key mappings: the key is the LHS pattern, the value a RHS pattern or a list of RHS patterns. Only '*' is supported as a glob character in an LHS, and a RHS may not contain more '*' than its LHS. Relative LHS and RHS paths are interpreted relative to *base*, the directory of the document that declares the map; $(VAR) and ${VAR} references in RHS values are expanded from the environment. Returns the compiled entries together with *base*. """ if value is None: return ([], base) if not isinstance(value, list): raise TypeError(f'jw.include-map must be a list, got {type(value).__name__}') entries: list[IncludeMapEntry] = [] for i, item in enumerate(value): if not isinstance(item, dict) or len(item) != 1: raise ValueError( f'jw.include-map entry {i}: expected a single-key ' f'mapping, got {item!r}' ) lhs, rhs = next(iter(item.items())) if not isinstance(lhs, str): raise ValueError( f'jw.include-map entry {i}: LHS must be a string, ' f'got {type(lhs).__name__}' ) if not lhs: raise ValueError(f'jw.include-map entry {i}: empty LHS') if lhs.startswith('-') or '|' in lhs: raise ValueError( f'jw.include-map entry {i}: LHS must be a plain path ' f'pattern without optional marker or target path: ' f'{lhs!r}' ) if set(lhs) & (_GLOB_CHARS - frozenset('*')): raise ValueError( f'jw.include-map entry {i}: only "*" is supported as ' f'a glob character in the LHS: {lhs!r}' ) if isinstance(rhs, str): if not rhs: raise ValueError(f'jw.include-map entry {i}: empty RHS') rhs_list: list[str] = [rhs] elif isinstance(rhs, list): rhs_list = [] for entry in rhs: if not isinstance(entry, str) or not entry: raise ValueError( f'jw.include-map entry {i}: RHS list items must ' f'be non-empty strings, got {entry!r}' ) rhs_list.append(entry) if not rhs_list: raise ValueError(f'jw.include-map entry {i}: empty RHS list') else: raise ValueError( f'jw.include-map entry {i}: RHS must be a string or a ' f'list of strings, got {type(rhs).__name__}' ) for entry in rhs_list: if entry.count('*') > lhs.count('*'): raise ValueError( f'jw.include-map entry {i}: RHS has more "*" than ' f'the LHS: {lhs!r} -> {entry!r}' ) expanded = tuple( _expand_include_vars(entry, f'{where} (jw.include-map entry {i})') for entry in rhs_list ) pattern = _compile_lhs_pattern(_canonicalize_path(lhs, base)) entries.append((pattern, expanded)) return (entries, base) def _apply_include_map(spec: str, include_map: IncludeMap) -> list[str] | None: """Rewrite the canonical *spec* via the first matching map entry. The captures of the LHS match fill the '*' slots of every RHS pattern; a relative result is resolved against the map's base directory. Returns the rewritten canonical specs, or None when no entry matches. """ entries, base = include_map for pattern, rhs_list in entries: m = pattern.fullmatch(spec) if m is None: continue captures = m.groups() rewrites: list[str] = [] for rhs in rhs_list: pieces = rhs.split('*') ret = pieces[0] for piece, capture in zip(pieces[1:], captures): ret += capture + piece rewrites.append(_canonicalize_path(ret, base)) log_m(DEBUG, f'include-map: {spec} -> {rewrites}') return rewrites return None def _parse_include_spec( spec: str, path: Path, include_map: IncludeMap, expand_vars: bool, no_absolute: bool, ) -> 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. The file part is qualified against the including file's directory and rewritten by the first matching entry of *include_map* before resolution; the rewritten specs are resolved and glob-expanded by the normal pipeline. When *expand_vars* is true (the top-level document only), $(VAR) and ${VAR} references in the file part are expanded from the environment first. When *no_absolute* is true, an absolute spec that matched no entry raises ValueError instead of being read from disk. """ 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:] if expand_vars: spec = _expand_include_vars(spec, str(path)) qualified = _canonicalize_path(spec, path.parent) rewrites = _apply_include_map(qualified, include_map) if rewrites is None: if no_absolute and spec.startswith('/'): raise ValueError( f'jw.include-map-no-absolute: absolute include ' f'{spec!r} in {path} is not covered by the include map' ) rewrites = [qualified] paths: list[Path] = [] for rewrite in rewrites: paths.extend(_glob_include(rewrite, path.parent)) if not paths and not optional: raise ValueError(f'Include glob {spec!r} matches no files in {path}') return [(optional, inc, target_path) for inc in paths] def _normalize_include_specs( specs: Any, path: Path, include_map: IncludeMap, expand_vars: bool, no_absolute: bool, ) -> 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, path, include_map, expand_vars, no_absolute) ) 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 = '' 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) 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: # 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 --- 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]) resolving.add(link_key) is_named, name, target_path, target_value = _resolve_link( 'jw.link', link_spec, 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): 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. 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``. """ 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) ) # -- Top-level entry points ----------------------------------------------------- def _load_yaml( path: str | Path, optional: bool, seen: set[Path], depth: int, include_map: IncludeMap | None, no_absolute: bool, ) -> 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 if include_map is None: no_absolute = bool(ret.pop('jw.include-map-no-absolute', False)) include_map = _parse_include_map( ret.pop('jw.include-map', None), path.parent, str(path) ) elif 'jw.include-map' in ret \ or 'jw.include-map-no-absolute' in ret: raise ValueError( f'jw.include-map and jw.include-map-no-absolute are ' f'only allowed in the top-level document: {path}' ) includes = _normalize_include_specs( ret.get('jw.include', []), path, include_map = include_map, expand_vars = depth == 0, no_absolute = no_absolute ) 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, depth = depth + 1, include_map = include_map, no_absolute = no_absolute ) 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() return _expand_links( _load_yaml( path, optional, seen, depth = 0, include_map = None, no_absolute = False ) ) 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))