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: