diff --git a/src/python/jw/util/load_yaml.py b/src/python/jw/util/load_yaml.py index 1afa862..a4c3f3c 100644 --- a/src/python/jw/util/load_yaml.py +++ b/src/python/jw/util/load_yaml.py @@ -5,8 +5,8 @@ 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 an - empty document). File names may use glob characters (``*``, ``?``, + ``-`` marks the include as optional (a missing file contributes + nothing). 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 @@ -430,6 +430,11 @@ def _load_yaml(path: str | Path, optional: bool, seen: set[Path]) -> dict[str, A for include in includes: opt, inc_path, target = include included_next = _load_yaml(inc_path, optional = opt, seen = seen) + 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) diff --git a/test/unit/python/jw/util/load_yaml/test.py b/test/unit/python/jw/util/load_yaml/test.py index 658ecd4..63666fa 100644 --- a/test/unit/python/jw/util/load_yaml/test.py +++ b/test/unit/python/jw/util/load_yaml/test.py @@ -988,6 +988,29 @@ class TestIncludeWithPath: data = load_yaml(pathlib.Path(base) / 'main.yaml') assert data['section']['opt'] == 'val' + def test_optional_include_missing_target(self, temp_dir: Callable) -> None: + """A missing optional include at a target path creates no key.""" + base = temp_dir( + [ + ('main.yaml', 'jw.include: -a.b|missing.yaml\nlocal: yes\n'), + ] + ) + data = load_yaml(pathlib.Path(base) / 'main.yaml') + assert data == {'local': True} + + def test_optional_include_missing_existing_target(self, temp_dir: Callable) -> None: + """A missing optional include leaves an existing target untouched.""" + base = temp_dir( + [ + ( + 'main.yaml', + 'jw.include: -section|missing.yaml\nsection:\n kept: yes\n', + ), + ] + ) + data = load_yaml(pathlib.Path(base) / 'main.yaml') + assert data == {'section': {'kept': True}} + def test_include_pipe_in_filename(self, temp_dir: Callable) -> None: """The first pipe separates target and file, pipes stay in the file.""" base = temp_dir(