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: