From 911c78ff997cfc42155e370065e8b6075b57a608 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Fri, 13 Nov 2026 13:01:08 +0100 Subject: [PATCH 1/3] load_yaml: Expand variables in top-level include specs Test wrappers that mimic production invocations redirect the includes of production documents to tree-local copies; the target location depends on where the tree is checked out, so it would be nice if the wrapper could take TOPDIR from the environment instead of hardcoding it. Allow the file part of a top-level include spec to reference environment variables as $(VAR) or ${VAR}. _load_yaml() receives a depth counter, zero at the top level and one per include level, and threads it to _normalize_include_specs() and _parse_include_spec(); the file part passes through _expand_include_vars() only at depth zero, after the optional marker and the target path have been split off. Specs in included documents keep their literal behaviour. An undefined variable raises ValueError, naming the reference and the file it came from. Signed-off-by: Jan Lindemann Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.6.0 --- src/python/jw/util/load_yaml.py | 64 ++++++++++++++++++---- test/unit/python/jw/util/load_yaml/test.py | 60 ++++++++++++++++++++ 2 files changed, 113 insertions(+), 11 deletions(-) diff --git a/src/python/jw/util/load_yaml.py b/src/python/jw/util/load_yaml.py index eead98d..6ac8579 100644 --- a/src/python/jw/util/load_yaml.py +++ b/src/python/jw/util/load_yaml.py @@ -12,7 +12,10 @@ supports three extensions: ``[...]``); 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. + 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.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. @@ -30,6 +33,7 @@ themselves. from __future__ import annotations +import os import re from copy import deepcopy @@ -137,6 +141,23 @@ def _resolve_path( # -- 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 _glob_include(file_spec: str, parent: Path) -> list[Path]: """Resolve *file_spec* against *parent* and expand glob characters. @@ -156,12 +177,18 @@ 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_spec(spec: str, parent: Path) -> list[IncludeSpec]: +def _parse_include_spec( + spec: str, + path: Path, + 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. + 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. """ if not spec: raise ValueError('Empty include spec') @@ -177,12 +204,18 @@ def _parse_include_spec(spec: str, parent: Path) -> list[IncludeSpec]: if m: target_path = tuple(m.group(1).split('.')) spec = spec[len(m.group(1)) + 1:] - paths = _glob_include(spec, parent) + if expand_vars: + spec = _expand_include_vars(spec, str(path)) + paths = _glob_include(spec, path.parent) if not paths and not optional: - raise ValueError(f'Include glob {spec!r} matches no files') + raise ValueError(f'Include glob {spec!r} matches no files in {path}') return [(optional, path, target_path) for path in paths] -def _normalize_include_specs(specs: Any, parent: Path) -> Includes: +def _normalize_include_specs( + specs: Any, + path: Path, + expand_vars: bool, +) -> Includes: if specs is None: return [] if isinstance(specs, str): @@ -193,7 +226,7 @@ def _normalize_include_specs(specs: Any, parent: Path) -> 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.extend(_parse_include_spec(spec, path, expand_vars)) return ret # -- Include target-path merging ----------------------------------------------- @@ -403,7 +436,12 @@ def _expand_links(root: dict[str, Any]) -> dict[str, Any]: # -- Top-level entry points ----------------------------------------------------- -def _load_yaml(path: str | Path, optional: bool, seen: set[Path]) -> dict[str, Any]: +def _load_yaml( + path: str | Path, + optional: bool, + seen: set[Path], + depth: int, +) -> dict[str, Any]: path = Path(path).resolve() if path in seen: raise ValueError(f'Cyclic YAML include detected: {path}') @@ -426,12 +464,16 @@ def _load_yaml(path: str | Path, optional: bool, seen: set[Path]) -> dict[str, A if optional: return {} raise - includes = _normalize_include_specs(ret.get('jw.include', []), path.parent) + includes = _normalize_include_specs( + ret.get('jw.include', []), path, 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) + included_next = _load_yaml( + inc_path, optional = opt, seen = seen, depth = depth + 1 + ) if not included_next: # An empty document contributes nothing; in particular # it must not create the target key of a path-addressed @@ -448,7 +490,7 @@ def _load_yaml(path: str | Path, optional: bool, seen: set[Path]) -> dict[str, A 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)) + return _expand_links(_load_yaml(path, optional, seen, depth = 0)) if __name__ == '__main__': import json diff --git a/test/unit/python/jw/util/load_yaml/test.py b/test/unit/python/jw/util/load_yaml/test.py index c5ec481..0595c62 100644 --- a/test/unit/python/jw/util/load_yaml/test.py +++ b/test/unit/python/jw/util/load_yaml/test.py @@ -1153,6 +1153,66 @@ class TestIncludeGlobbing: with pytest.raises(ValueError, match = 'Cyclic YAML include'): load_yaml(pathlib.Path(base) / 'main.yaml') +class TestIncludeVarExpansion: + """Tests for $(VAR) and ${VAR} expansion in include specs.""" + + def test_expand_braced_var( + self, temp_dir: _TempDir, monkeypatch: pytest.MonkeyPatch + ) -> None: + """${VAR} in a top-level include spec is expanded.""" + base = temp_dir([('conf/a.yaml', 'from_a: 1\n')]) + monkeypatch.setenv('LOAD_YAML_TEST_TOP', base) + main = pathlib.Path(base) / 'main.yaml' + main.write_text('jw.include: ${LOAD_YAML_TEST_TOP}/conf/a.yaml\n') + data = load_yaml(main) + assert data['from_a'] == 1 + + def test_expand_paren_var( + self, temp_dir: _TempDir, monkeypatch: pytest.MonkeyPatch + ) -> None: + """$(VAR) in a top-level include spec is expanded.""" + base = temp_dir([('conf/a.yaml', 'from_a: 1\n')]) + monkeypatch.setenv('LOAD_YAML_TEST_TOP', base) + main = pathlib.Path(base) / 'main.yaml' + main.write_text('jw.include: $(LOAD_YAML_TEST_TOP)/conf/a.yaml\n') + data = load_yaml(main) + assert data['from_a'] == 1 + + def test_expand_var_with_glob( + self, temp_dir: _TempDir, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Expansion and glob expansion compose.""" + base = temp_dir( + [ + ('conf/a.yaml', 'from_a: 1\n'), + ('conf/b.yaml', 'from_b: 2\n'), + ] + ) + monkeypatch.setenv('LOAD_YAML_TEST_TOP', base) + main = pathlib.Path(base) / 'main.yaml' + main.write_text('jw.include: ${LOAD_YAML_TEST_TOP}/conf/*.yaml\n') + data = load_yaml(main) + assert data['from_a'] == 1 + assert data['from_b'] == 2 + + def test_undefined_var_raises(self, temp_dir: _TempDir) -> None: + """An undefined variable in a top-level spec raises.""" + base = temp_dir([('main.yaml', 'jw.include: ${LOAD_YAML_TEST_NOPE}/x.yaml\n')]) + with pytest.raises(ValueError, match = 'Undefined variable'): + load_yaml(pathlib.Path(base) / 'main.yaml') + + def test_nested_spec_not_expanded(self, temp_dir: _TempDir) -> None: + """Specs in included documents are never expanded.""" + base = temp_dir( + [ + ('main.yaml', 'jw.include: nested/real.yaml\n'), + ('nested/real.yaml', 'jw.include: ${HOME}/x.yaml\n'), + ('nested/${HOME}/x.yaml', 'literal: yes\n'), + ] + ) + data = load_yaml(pathlib.Path(base) / 'main.yaml') + assert data['literal'] is True + # -- jw.include with target path ------------------------------------------------ class TestPathResolution: -- 2.56.1 From 5d94a1fcee9398dbb438a48a6d0a96f6de30eaeb Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Fri, 13 Nov 2026 13:14:59 +0100 Subject: [PATCH 2/3] 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 Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.6.0 --- src/python/jw/util/load_yaml.py | 189 +++++++++++++- test/unit/python/jw/util/load_yaml/test.py | 274 +++++++++++++++++++++ 2 files changed, 454 insertions(+), 9 deletions(-) diff --git a/src/python/jw/util/load_yaml.py b/src/python/jw/util/load_yaml.py index 6ac8579..9870f4d 100644 --- a/src/python/jw/util/load_yaml.py +++ b/src/python/jw/util/load_yaml.py @@ -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 diff --git a/test/unit/python/jw/util/load_yaml/test.py b/test/unit/python/jw/util/load_yaml/test.py index 0595c62..39e1ea5 100644 --- a/test/unit/python/jw/util/load_yaml/test.py +++ b/test/unit/python/jw/util/load_yaml/test.py @@ -1213,6 +1213,280 @@ class TestIncludeVarExpansion: data = load_yaml(pathlib.Path(base) / 'main.yaml') assert data['literal'] is True +class TestIncludeMap: + """Tests for the jw.include-map include spec rewrite table.""" + + def test_exact_rewrite(self, temp_dir: _TempDir) -> None: + """An exact LHS rewrites the spec to the RHS.""" + base = temp_dir( + [ + ( + 'wrapper.yaml', + 'jw.include-map:\n' + ' - /prod/etc/app.yaml: test/app.yaml\n' + 'jw.include: /prod/etc/app.yaml\n' + ), + ('test/app.yaml', 'from_test: 1\n'), + ] + ) + data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') + assert data['from_test'] == 1 + + def test_glob_rewrite(self, temp_dir: _TempDir) -> None: + """A glob LHS captures into a glob RHS.""" + base = temp_dir( + [ + ('prod.d/one.yaml', 'one: prod\n'), + ('prod.d/two.yaml', 'two: prod\n'), + ('test.d/one.yaml', 'one: test\n'), + ('test.d/two.yaml', 'two: test\n'), + ( + 'wrapper.yaml', + 'jw.include-map:\n' + ' - prod.d/*.yaml: test.d/*.yaml\n' + 'jw.include: prod.d/*.yaml\n' + ), + ] + ) + data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') + assert data['one'] == 'test' + assert data['two'] == 'test' + + def test_rhs_list(self, temp_dir: _TempDir) -> None: + """A list RHS expands to multiple sources in list order.""" + base = temp_dir( + [ + ('t1/a.yaml', 'one: 1\nshared: t1a\n'), + ('t1/b.yaml', 'shared: t1b\ntwo: 2\n'), + ('t2/a.yaml', 'shared: t2a\nthree: 3\n'), + ( + 'wrapper.yaml', + 'jw.include-map:\n' + ' - prod.d/*.yaml: [t1/*.yaml, t2/*.yaml]\n' + 'jw.include: prod.d/*.yaml\n' + ), + ] + ) + data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') + assert data['one'] == 1 + assert data['two'] == 2 + assert data['three'] == 3 + # Sources merge in RHS list order, later files win + assert data['shared'] == 't2a' + + def test_rewrite_before_disk_lookup(self, temp_dir: _TempDir) -> None: + """The LHS pattern need not match anything on disk.""" + base = temp_dir( + [ + ('test.d/one.yaml', 'one: 1\n'), + ( + 'wrapper.yaml', + 'jw.include-map:\n' + ' - prod.d/*.yaml: test.d/*.yaml\n' + 'jw.include: prod.d/one.yaml\n' + ), + ] + ) + data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') + assert data['one'] == 1 + + def test_first_match_wins(self, temp_dir: _TempDir) -> None: + """The first matching entry wins; later entries are ignored.""" + base = temp_dir( + [ + ('first.yaml', 'source: first\n'), + ('second.yaml', 'source: second\n'), + ( + 'wrapper.yaml', + 'jw.include-map:\n' + ' - /prod/etc/app.yaml: first.yaml\n' + ' - /prod/etc/app.yaml: second.yaml\n' + 'jw.include: /prod/etc/app.yaml\n' + ), + ] + ) + data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') + assert data['source'] == 'first' + + def test_relative_lhs_collision(self, temp_dir: _TempDir) -> None: + """Same-named relative includes are disambiguated by directory.""" + base = temp_dir( + [ + ('prod/a/doc.yaml', 'jw.include: x.yaml\n'), + ('prod/b/doc.yaml', 'jw.include: x.yaml\n'), + ('ax.yaml', 'from_ax: 1\n'), + ('bx.yaml', 'from_bx: 2\n'), + ( + 'wrapper.yaml', + 'jw.include-map:\n' + ' - prod/a/x.yaml: ax.yaml\n' + ' - prod/b/x.yaml: bx.yaml\n' + 'jw.include:\n' + ' - prod/a/doc.yaml\n' + ' - prod/b/doc.yaml\n' + ), + ] + ) + data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') + assert data['from_ax'] == 1 + assert data['from_bx'] == 2 + + def test_relative_rhs_against_wrapper(self, temp_dir: _TempDir) -> None: + """A relative RHS resolves against the wrapper's directory.""" + base = temp_dir( + [ + ('prod/app.yaml', 'jw.include: deep.yaml\n'), + ('copies/deep.yaml', 'deep: ok\n'), + ( + 'wrapper.yaml', + 'jw.include-map:\n' + ' - prod/deep.yaml: copies/deep.yaml\n' + 'jw.include: prod/app.yaml\n' + ), + ] + ) + data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') + assert data['deep'] == 'ok' + + def test_absolute_lhs(self, temp_dir: _TempDir) -> None: + """Absolute LHS patterns match production-style includes.""" + base = temp_dir( + [ + ('prod.yaml', 'jw.include: /etc/jw/app/*.yaml\n'), + ('test/app.yaml', 'from_test: 1\n'), + ( + 'wrapper.yaml', + 'jw.include-map:\n' + ' - /etc/jw/app/*.yaml: test/app.yaml\n' + 'jw.include: prod.yaml\n' + ), + ] + ) + data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') + assert data['from_test'] == 1 + + def test_optional_flag_inherited(self, temp_dir: _TempDir) -> None: + """Rewritten sources inherit the original spec's optionality.""" + base = temp_dir( + [ + ( + 'wrapper.yaml', + 'jw.include-map:\n' + ' - prod/*.yaml: nowhere/*.yaml\n' + 'jw.include: -prod/missing.yaml\n' + ), + ] + ) + data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') + assert data == {} + + def test_non_optional_rewrite_missing_raises(self, temp_dir: _TempDir) -> None: + """A rewritten plain path that does not exist raises.""" + base = temp_dir( + [ + ( + 'wrapper.yaml', + 'jw.include-map:\n' + ' - prod/*.yaml: nowhere/*.yaml\n' + 'jw.include: prod/missing.yaml\n' + ), + ] + ) + with pytest.raises(FileNotFoundError): + load_yaml(pathlib.Path(base) / 'wrapper.yaml') + + def test_target_path_preserved(self, temp_dir: _TempDir) -> None: + """The target path prefix survives the rewrite.""" + base = temp_dir( + [ + ('t/one.yaml', 'a: 1\n'), + ('t/two.yaml', 'b: 2\n'), + ( + 'wrapper.yaml', + 'jw.include-map:\n' + ' - prod/*.yaml: t/*.yaml\n' + 'jw.include: section|prod/*.yaml\n' + ), + ] + ) + data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') + assert data['section'] == {'a': 1, 'b': 2} + + def test_nested_map_raises(self, temp_dir: _TempDir) -> None: + """jw.include-map in a non-top-level document raises.""" + base = temp_dir( + [ + ('inner.yaml', 'jw.include-map:\n - a.yaml: b.yaml\n'), + ('wrapper.yaml', 'jw.include: inner.yaml\n'), + ] + ) + with pytest.raises(ValueError, match = 'top-level'): + load_yaml(pathlib.Path(base) / 'wrapper.yaml') + + def test_empty_map_is_noop(self, temp_dir: _TempDir) -> None: + """An empty map leaves all includes untouched.""" + base = temp_dir( + [ + ('app.yaml', 'ok: 1\n'), + ('wrapper.yaml', 'jw.include-map: []\n' + 'jw.include: app.yaml\n'), + ] + ) + data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') + assert data['ok'] == 1 + + def test_map_not_a_list_raises(self, temp_dir: _TempDir) -> None: + """A non-list jw.include-map value raises.""" + base = temp_dir([('wrapper.yaml', 'jw.include-map: {}\n')]) + with pytest.raises(TypeError, match = 'must be a list'): + load_yaml(pathlib.Path(base) / 'wrapper.yaml') + + def test_multi_key_entry_raises(self, temp_dir: _TempDir) -> None: + """A map entry with two keys raises.""" + base = temp_dir( + [ + ( + 'wrapper.yaml', + 'jw.include-map:\n' + ' - a.yaml: b.yaml\n' + ' c.yaml: d.yaml\n' + ), + ] + ) + with pytest.raises(ValueError, match = 'single-key'): + load_yaml(pathlib.Path(base) / 'wrapper.yaml') + + def test_rhs_star_overflow_raises(self, temp_dir: _TempDir) -> None: + """A RHS with more stars than the LHS raises.""" + base = temp_dir( + [ + ('wrapper.yaml', 'jw.include-map:\n - a/*.yaml: b/*/*.yaml\n'), + ] + ) + with pytest.raises(ValueError, match = r'more "\*"'): + load_yaml(pathlib.Path(base) / 'wrapper.yaml') + + def test_lhs_question_mark_raises(self, temp_dir: _TempDir) -> None: + """A '?' in the LHS raises; only '*' is supported.""" + base = temp_dir([('wrapper.yaml', 'jw.include-map:\n - a/?.yaml: b.yaml\n')]) + with pytest.raises(ValueError, match = r'only "\*"'): + load_yaml(pathlib.Path(base) / 'wrapper.yaml') + + def test_var_in_rhs( + self, temp_dir: _TempDir, monkeypatch: pytest.MonkeyPatch + ) -> None: + """RHS values expand environment variables.""" + base = temp_dir([('app.yaml', 'ok: 1\n')]) + monkeypatch.setenv('LOAD_YAML_TEST_TOP', base) + main = pathlib.Path(base) / 'wrapper.yaml' + main.write_text( + 'jw.include-map:\n' + ' - /etc/app.yaml: ${LOAD_YAML_TEST_TOP}/app.yaml\n' + 'jw.include: /etc/app.yaml\n' + ) + data = load_yaml(main) + assert data['ok'] == 1 + # -- jw.include with target path ------------------------------------------------ class TestPathResolution: -- 2.56.1 From 2e85f3ccf894b1d151182a9869a604553398d473 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Fri, 13 Nov 2026 13:19:32 +0100 Subject: [PATCH 3/3] load_yaml: Support jw.include-map-no-absolute A test that redirects production includes with jw.include-map can silently read a real production path when the map misses a spec, making the test depend on the host's /etc without any warning. Add a jw.include-map-no-absolute key next to the map. When true, an absolute include spec that matched no map entry raises ValueError, naming the spec and the including file; an identity entry whitelists an absolute path that may be read. The key defaults to false and applies to the whole include tree: _load_yaml() pops it in the top-level document, rejects it in included documents, and threads it to _parse_include_spec(), where the check runs before the normal disk lookup. Signed-off-by: Jan Lindemann Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.6.0 --- src/python/jw/util/load_yaml.py | 41 +++++++-- test/unit/python/jw/util/load_yaml/test.py | 100 +++++++++++++++++++++ 2 files changed, 133 insertions(+), 8 deletions(-) diff --git a/src/python/jw/util/load_yaml.py b/src/python/jw/util/load_yaml.py index 9870f4d..70c7938 100644 --- a/src/python/jw/util/load_yaml.py +++ b/src/python/jw/util/load_yaml.py @@ -31,6 +31,13 @@ supports three extensions: 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. @@ -323,6 +330,7 @@ def _parse_include_spec( path: Path, include_map: IncludeMap, expand_vars: bool, + no_absolute: bool, ) -> list[IncludeSpec]: """Parse a jw.include spec into one or more IncludeSpec entries. @@ -333,7 +341,9 @@ def _parse_include_spec( *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. + 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') @@ -354,6 +364,11 @@ def _parse_include_spec( 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: @@ -367,6 +382,7 @@ def _normalize_include_specs( path: Path, include_map: IncludeMap, expand_vars: bool, + no_absolute: bool, ) -> Includes: if specs is None: return [] @@ -378,7 +394,9 @@ 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, include_map, expand_vars)) + ret.extend( + _parse_include_spec(spec, path, include_map, expand_vars, no_absolute) + ) return ret # -- Include target-path merging ----------------------------------------------- @@ -594,6 +612,7 @@ def _load_yaml( seen: set[Path], depth: int, include_map: IncludeMap | None, + no_absolute: bool, ) -> dict[str, Any]: path = Path(path).resolve() if path in seen: @@ -618,19 +637,22 @@ def _load_yaml( 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: + elif 'jw.include-map' in ret \ + or 'jw.include-map-no-absolute' in ret: raise ValueError( - f'jw.include-map is only allowed in the top-level ' - f'document: {path}' + 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 + expand_vars = depth == 0, + no_absolute = no_absolute ) ret.pop('jw.include', None) included_all: dict[str, Any] = {} @@ -641,7 +663,8 @@ def _load_yaml( optional = opt, seen = seen, depth = depth + 1, - include_map = include_map + include_map = include_map, + no_absolute = no_absolute ) if not included_next: # An empty document contributes nothing; in particular @@ -660,7 +683,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, include_map = None) + _load_yaml( + path, optional, seen, depth = 0, include_map = None, no_absolute = False + ) ) if __name__ == '__main__': diff --git a/test/unit/python/jw/util/load_yaml/test.py b/test/unit/python/jw/util/load_yaml/test.py index 39e1ea5..49edb53 100644 --- a/test/unit/python/jw/util/load_yaml/test.py +++ b/test/unit/python/jw/util/load_yaml/test.py @@ -1487,6 +1487,106 @@ class TestIncludeMap: data = load_yaml(main) assert data['ok'] == 1 +class TestIncludeMapNoAbsolute: + """Tests for the jw.include-map-no-absolute guard.""" + + def test_absolute_uncovered_raises(self, temp_dir: _TempDir) -> None: + """An absolute spec with no matching entry raises.""" + base = temp_dir( + [ + ( + 'wrapper.yaml', + 'jw.include-map: []\n' + 'jw.include-map-no-absolute: true\n' + 'jw.include: /etc/app.yaml\n' + ), + ] + ) + with pytest.raises(ValueError, match = 'not covered by the include map'): + load_yaml(pathlib.Path(base) / 'wrapper.yaml') + + def test_absolute_covered_ok(self, temp_dir: _TempDir) -> None: + """An absolute spec covered by the map loads.""" + base = temp_dir( + [ + ('app.yaml', 'ok: 1\n'), + ( + 'wrapper.yaml', + 'jw.include-map:\n' + ' - /etc/app.yaml: app.yaml\n' + 'jw.include-map-no-absolute: true\n' + 'jw.include: /etc/app.yaml\n' + ), + ] + ) + data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') + assert data['ok'] == 1 + + def test_nested_absolute_uncovered_raises(self, temp_dir: _TempDir) -> None: + """The guard covers nested includes, not just the wrapper's own.""" + base = temp_dir( + [ + ('prod.yaml', 'jw.include: /etc/app.yaml\n'), + ( + 'wrapper.yaml', + 'jw.include-map: []\n' + 'jw.include-map-no-absolute: true\n' + 'jw.include: prod.yaml\n' + ), + ] + ) + with pytest.raises(ValueError, match = 'not covered by the include map'): + load_yaml(pathlib.Path(base) / 'wrapper.yaml') + + def test_relative_specs_pass(self, temp_dir: _TempDir) -> None: + """Relative specs are unaffected by the guard.""" + base = temp_dir( + [ + ('app.yaml', 'ok: 1\n'), + ( + 'wrapper.yaml', + 'jw.include-map: []\n' + 'jw.include-map-no-absolute: true\n' + 'jw.include: app.yaml\n' + ), + ] + ) + data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') + assert data['ok'] == 1 + + def test_identity_entry_whitelists(self, temp_dir: _TempDir) -> None: + """An identity entry whitelists an absolute path.""" + base = temp_dir([('real.yaml', 'ok: 1\n')]) + main = pathlib.Path(base) / 'wrapper.yaml' + main.write_text( + 'jw.include-map:\n' + f' - {base}/real.yaml: {base}/real.yaml\n' + 'jw.include-map-no-absolute: true\n' + f'jw.include: {base}/real.yaml\n' + ) + data = load_yaml(main) + assert data['ok'] == 1 + + def test_default_is_false(self, temp_dir: _TempDir) -> None: + """Without the flag, an uncovered absolute spec is read from disk.""" + base = temp_dir( + [('wrapper.yaml', 'jw.include-map: []\n' + 'jw.include: /etc/app.yaml\n')] + ) + with pytest.raises(FileNotFoundError): + load_yaml(pathlib.Path(base) / 'wrapper.yaml') + + def test_nested_flag_raises(self, temp_dir: _TempDir) -> None: + """The flag in a non-top-level document raises.""" + base = temp_dir( + [ + ('inner.yaml', 'jw.include-map-no-absolute: true\n'), + ('wrapper.yaml', 'jw.include: inner.yaml\n'), + ] + ) + with pytest.raises(ValueError, match = 'top-level'): + load_yaml(pathlib.Path(base) / 'wrapper.yaml') + # -- jw.include with target path ------------------------------------------------ class TestPathResolution: -- 2.56.1