load_yaml: Add jw.include-map

This commit adds support for interpreting a new syntax:

  jw.include-map:
    - /etc/some/file.conf: ../../../file.conf
    - /opt/blah/another/config.yaml: ../../../config.yaml

Production configs include absolute paths outside the repository tree, so a
test that runs a production-style document against repository-local copies
must redirect those includes, ideally without modifying the
files meant to be installed as is.

Add a jw.include-map key to the top-level document: an ordered list
of single-key mappings from LHS pattern to RHS pattern or 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. Relative LHS and RHS values are interpreted against
the directory of the document that declares the map, so matching runs on
canonical paths and same-named includes from different directories stay
distinguishable. The optional marker and the target path are decomposed
before the rewrite: every rewritten source inherits the spec's optionality,
and the target path applies to the merged result.

- _parse_include_map(): parse and validate the table; only '*' is supported
  in an LHS, a RHS may not have more '*' than its LHS, and RHS values
  expand $(VAR) and ${VAR} from the environment
- _canonicalize_path(): join a relative path with a base directory and
  normalize, without disk access
- _compile_lhs_pattern(): compile a canonical LHS into an anchored regex
  whose '*' groups match runs that are not '/'
- _apply_include_map(): match the first entry and fill the LHS captures
  into every RHS pattern; log the rewrite at DEBUG
- _load_yaml(): parse the map once in the top-level document, reject it in
  included documents, thread it through the include tree

Signed-off-by: Jan Lindemann <jan@janware.com>
Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.6.0
This commit is contained in:
Jan Lindemann 2026-11-13 13:14:59 +01:00
commit 5d94a1fcee
Signed by: Jan Lindemann
GPG key ID: 3750640C9E25DD61

View file

@ -16,6 +16,21 @@ supports three extensions:
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.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.
@ -42,10 +57,14 @@ 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_.-]+)\|')
@ -158,6 +177,27 @@ def _expand_include_vars(value: str, where: str) -> str:
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.
@ -177,18 +217,123 @@ def _glob_include(file_spec: str, parent: Path) -> list[Path]:
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,
) -> 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. When *expand_vars* is true (the top-level document
only), $(VAR) and ${VAR} references in the file part are expanded
from the environment before resolution.
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.
"""
if not spec:
raise ValueError('Empty include spec')
@ -206,14 +351,21 @@ def _parse_include_spec(
spec = spec[len(m.group(1)) + 1:]
if expand_vars:
spec = _expand_include_vars(spec, str(path))
paths = _glob_include(spec, path.parent)
qualified = _canonicalize_path(spec, path.parent)
rewrites = _apply_include_map(qualified, include_map)
if rewrites is None:
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, path, target_path) for path in paths]
return [(optional, inc, target_path) for inc in paths]
def _normalize_include_specs(
specs: Any,
path: Path,
include_map: IncludeMap,
expand_vars: bool,
) -> Includes:
if specs is None:
@ -226,7 +378,7 @@ def _normalize_include_specs(
for spec in specs:
if not isinstance(spec, str):
raise TypeError(f'Unsupported include entry: {spec!r}')
ret.extend(_parse_include_spec(spec, path, expand_vars))
ret.extend(_parse_include_spec(spec, path, include_map, expand_vars))
return ret
# -- Include target-path merging -----------------------------------------------
@ -441,6 +593,7 @@ def _load_yaml(
optional: bool,
seen: set[Path],
depth: int,
include_map: IncludeMap | None,
) -> dict[str, Any]:
path = Path(path).resolve()
if path in seen:
@ -464,15 +617,31 @@ def _load_yaml(
if optional:
return {}
raise
if include_map is None:
include_map = _parse_include_map(
ret.pop('jw.include-map', None), path.parent, str(path)
)
elif 'jw.include-map' in ret:
raise ValueError(
f'jw.include-map is only allowed in the top-level '
f'document: {path}'
)
includes = _normalize_include_specs(
ret.get('jw.include', []), path, expand_vars = depth == 0
ret.get('jw.include', []),
path,
include_map = include_map,
expand_vars = depth == 0
)
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
inc_path,
optional = opt,
seen = seen,
depth = depth + 1,
include_map = include_map
)
if not included_next:
# An empty document contributes nothing; in particular
@ -490,7 +659,9 @@ def _load_yaml(
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))
return _expand_links(
_load_yaml(path, optional, seen, depth = 0, include_map = None)
)
if __name__ == '__main__':
import json