From ff80bd82d2eaf8701fb403fd429e3870a94273ad Mon Sep 17 00:00:00 2001 From: Adi Muraru Date: Mon, 2 Nov 2026 18:53:21 +0100 Subject: [PATCH 1/2] Support deleting inherited YAML keys with !delete (#158) Consume explicit deletion directives during per-file merging while preserving nulls and configured strategies. Cover includes, interpolation, empty results, and precomputed/parallel hierarchy processing. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 51 ++++++++++ himl/config_generator.py | 38 ++++++- himl/config_merger.py | 4 +- himl/yaml_tags.py | 33 ++++++ tests/test_config_generator.py | 181 +++++++++++++++++++++++++++++++++ tests/test_config_merger.py | 60 +++++++++++ 6 files changed, 364 insertions(+), 3 deletions(-) create mode 100644 himl/yaml_tags.py diff --git a/README.md b/README.md index 1bbb7b4a..139a73e3 100644 --- a/README.md +++ b/README.md @@ -285,6 +285,57 @@ tagging: "{{projects.{{project.name}}.tagging}}" It's possible to have the same key (eg. a dict/list) in multiple files and combine them using a deep merge. See an example [here](https://github.com/adobe/himl#deep-merge-example). +#### Removing inherited keys + +Use the custom YAML tag `!delete` to remove a dictionary key inherited from an +earlier file. Unlike `null`, this removes the key rather than assigning a value. + +`data/globals.yaml`: + +```yaml +modules_to_deploy: + module1: config-mod1 + module2: config-mod2 + module3: config-mod3 +``` + +`data/special_dr_site/site.yaml`: + +```yaml +modules_to_deploy: + module2: !delete +``` + +Running `himl --cwd data special_dr_site` produces: + +```yaml +modules_to_deploy: + module1: config-mod1 + module3: config-mod3 +``` + +Deletion works at any dictionary depth through the Python API, `himl`, and +`himl-config-merger`, including precomputed and parallel processing. It is applied +as each file is merged, before interpolation, environment variables, or secrets +are resolved. Files follow the existing hierarchy order and alphabetical order +within each directory. A later file can recreate a deleted key without restoring +its old contents. + +Deleting a missing key does nothing. Deleting a dictionary removes its entire +subtree; deleting its final child leaves an empty dictionary. Deleting all +top-level keys produces `{}`. References to deleted keys elsewhere still follow +the normal interpolation-validation rules. + +Only the empty tag form shown above is accepted: do not supply a payload such as +`!delete null`. The tag is supported only as a dictionary value, not as a key, +a whole document, or anywhere inside a list or set. Quoted `"!delete"` remains +an ordinary string, and existing `null` behavior is unchanged. The tag also works +in files loaded with the merger's [existing `!include` support](#extra-merger-features). + +`!delete` is a Himl-specific extension using standard YAML tag syntax. Other +tools reading these source files need a registered constructor for the tag; +generated YAML/JSON contains no deletion markers and needs no custom loader. + ### Secrets retrieval #### [AWS SSM](https://docs.aws.amazon.com/systems-manager/latest/userguide/integration-ps-secretsmanager.html) diff --git a/himl/config_generator.py b/himl/config_generator.py index 6b9e277c..1f1c3148 100755 --- a/himl/config_generator.py +++ b/himl/config_generator.py @@ -22,6 +22,7 @@ from .interpolation import InterpolationResolver, EscapingResolver, InterpolationValidator, SecretResolver, \ DictIterator, replace_parent_working_directory, EnvVarResolver, collect_pending_keys from .python_compat import iteritems, primitive_types, PY3 +from .yaml_tags import DELETE, loader_with_delete_tag logger = logging.getLogger(__name__) @@ -29,10 +30,42 @@ @functools.lru_cache(maxsize=None) def _yaml_get_content_cached(yaml_file): with open(yaml_file, 'r') as f: - content = yaml.load(f, Loader=yaml.SafeLoader) + content = yaml.load(f, Loader=loader_with_delete_tag(yaml.SafeLoader)) return content if content else {} +def _reject_delete_markers(value, path): + if value is DELETE: + location = ".".join(path) or "" + raise ValueError("!delete is only supported as a dictionary value at {}".format(location)) + if isinstance(value, dict): + for key, child in iteritems(value): + _reject_delete_markers(key, path + ("",)) + _reject_delete_markers(child, path + (str(key),)) + elif isinstance(value, (list, tuple, set)): + for index, child in enumerate(value): + _reject_delete_markers(child, path + (str(index),)) + + +def _prepare_deletions(reference, incoming, path=()): + if incoming is DELETE: + _reject_delete_markers(incoming, path) + cleaned = {} + for key, value in iteritems(incoming): + key_path = path + (str(key),) + _reject_delete_markers(key, key_path) + if value is DELETE: + if isinstance(reference, dict): + reference.pop(key, None) + elif isinstance(value, dict): + inherited = reference.get(key) if isinstance(reference, dict) else None + cleaned[key] = _prepare_deletions(inherited, value, key_path) + else: + _reject_delete_markers(value, key_path) + cleaned[key] = value + return cleaned + + class ConfigProcessor(object): def process(self, cwd=None, @@ -261,6 +294,7 @@ def merge_value(reference, new_value, type_strategies, fallback_strategies, type @staticmethod def merge_yamls(values, yaml_content, type_strategies, fallback_strategies, type_conflict_strategies): + yaml_content = _prepare_deletions(values, yaml_content) for key, value in iteritems(yaml_content): if key in values and not isinstance(values[key], type(value)) and not isinstance(value, type(values[key])): raise Exception("Failed to merge key '{}', because of mismatch in type: {} vs {}" @@ -353,7 +387,7 @@ def process_hierarchy_with_precomputed(self, precomputed_state): self.fallback_strategies, self.type_conflict_strategies) self.resolve_simple_interpolations(merged_values, yaml_file) - if not merged_values: + if not precomputed_state and not any(self.hierarchy): raise Exception("No YAML files found to process in the hierarchy") self.generated_data = merged_values diff --git a/himl/config_merger.py b/himl/config_merger.py index 45cc9d13..91790bef 100755 --- a/himl/config_merger.py +++ b/himl/config_merger.py @@ -17,6 +17,7 @@ from .config_generator import ConfigProcessor from multiprocessing import Pool, cpu_count from .filter_rules import FilterRules +from .yaml_tags import construct_delete logging.basicConfig() logging.root.setLevel(logging.INFO) @@ -87,6 +88,7 @@ def __traverse_path(self, path: str, yaml_dict: dict): # Register the include constructor Loader.add_constructor('!include', Loader.include) +Loader.add_constructor('!delete', construct_delete) def _group_by_parent(directories): @@ -108,7 +110,7 @@ def build_parent_cache(directories, cwd=None): # Patch SafeLoader so !include tags work in yaml_get_content (same patch # that merge_logic applies, but build_parent_cache runs before merge_logic). Loader.add_constructor('!include', Loader.include) - yaml.SafeLoader.add_constructor('!include', Loader.include) + yaml.SafeLoader = Loader # type: ignore cwd = cwd or os.getcwd() cache = {} for leaf_path in directories: diff --git a/himl/yaml_tags.py b/himl/yaml_tags.py new file mode 100644 index 00000000..d4ea37b3 --- /dev/null +++ b/himl/yaml_tags.py @@ -0,0 +1,33 @@ +# Copyright 2026 Adobe. All rights reserved. +# This file is licensed to you under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. You may obtain a copy +# of the License at http://www.apache.org/licenses/LICENSE-2.0 + +# Unless required by applicable law or agreed to in writing, software distributed under +# the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS +# OF ANY KIND, either express or implied. See the License for the specific language +# governing permissions and limitations under the License. + +from enum import Enum +from typing import cast + +import yaml + + +class _DeleteMarker(Enum): + DELETE = "delete" + + +DELETE = _DeleteMarker.DELETE + + +def construct_delete(loader, node): + if not isinstance(node, yaml.ScalarNode) or node.value != "": + raise yaml.constructor.ConstructorError(None, None, "!delete requires an empty scalar", node.start_mark) + return DELETE + + +def loader_with_delete_tag(base_loader): + loader = cast(type[yaml.SafeLoader], type("HimlDeleteLoader", (base_loader,), {})) + loader.add_constructor("!delete", construct_delete) + return loader diff --git a/tests/test_config_generator.py b/tests/test_config_generator.py index 8580ecba..5f77e3d5 100644 --- a/tests/test_config_generator.py +++ b/tests/test_config_generator.py @@ -8,6 +8,8 @@ # OF ANY KIND, either express or implied. See the License for the specific language # governing permissions and limitations under the License. +import copy +import json import os import tempfile import shutil @@ -17,11 +19,90 @@ from himl import ConfigProcessor, ConfigGenerator +from himl.yaml_tags import DELETE class TestConfigProcessor: """Test cases for ConfigProcessor class""" + @pytest.mark.parametrize("output_format", ["yaml", "json"]) + def test_delete_hierarchy_output_before_interpolation(self, tmp_path, output_format): + (tmp_path / 'globals.yaml').write_text( + 'modules_to_deploy:\n module1: config-mod1\n module2: config-mod2\n module3: config-mod3\n' + 'discarded:\n invalid: "{{missing.key}}"\n' + 'copy: "{{modules_to_deploy}}"\nnullable: null\nliteral: "!delete"\n' + ) + site = tmp_path / 'special_dr_site' + site.mkdir() + (site / 'site.yaml').write_text( + 'modules_to_deploy:\n module2: !delete\ndiscarded: !delete\n' + ) + output = tmp_path / ('merged.' + output_format) + + result = self.config_processor.process( + cwd=str(tmp_path), path='special_dr_site', + output_format=output_format, output_file=str(output), + ) + + expected = { + 'modules_to_deploy': {'module1': 'config-mod1', 'module3': 'config-mod3'}, + 'copy': {'module1': 'config-mod1', 'module3': 'config-mod3'}, + 'nullable': None, + 'literal': '!delete', + } + assert result == expected + parsed = yaml.safe_load(output.read_text()) if output_format == 'yaml' else json.loads(output.read_text()) + assert parsed == expected + + def test_delete_hierarchy_file_order_and_reintroduction(self, tmp_path): + (tmp_path / 'a_default.yaml').write_text('config:\n old: inherited\n') + (tmp_path / 'b_remove.yaml').write_text('config: !delete\n') + site = tmp_path / 'site' + site.mkdir() + (site / 'config.yaml').write_text('config:\n new: recreated\n') + + result = self.config_processor.process(cwd=str(tmp_path), path='site') + + assert result == {'config': {'new': 'recreated'}} + + @pytest.mark.parametrize("skip_validation", [False, True]) + def test_delete_leaves_references_subject_to_validation(self, tmp_path, skip_validation): + (tmp_path / 'a_default.yaml').write_text('config:\n gone: inherited\nreference: "{{config.gone}}"\n') + (tmp_path / 'b_remove.yaml').write_text('config:\n gone: !delete\n') + kwargs = dict( + cwd=str(tmp_path), path='.', + skip_interpolation_validation=skip_validation, + ) + + if skip_validation: + result = self.config_processor.process(**kwargs) + assert result == {'config': {}, 'reference': '{{config.gone}}'} + else: + with pytest.raises(Exception, match="Interpolation could not be resolved"): + self.config_processor.process(**kwargs) + + @pytest.mark.parametrize("precompute", [False, True]) + @pytest.mark.parametrize("delete_in_parent", [False, True]) + def test_delete_all_keys_accepts_empty_output(self, tmp_path, monkeypatch, precompute, delete_in_parent): + from himl.config_merger import build_parent_cache + + monkeypatch.setattr(yaml, 'SafeLoader', yaml.SafeLoader) + (tmp_path / 'a_default.yaml').write_text('gone: inherited\n') + site = tmp_path / 'site' + site.mkdir() + location = tmp_path if delete_in_parent else site + (location / 'b_remove.yaml').write_text('gone: !delete\n') + state = None + if precompute: + cache = build_parent_cache([str(site)], cwd=str(tmp_path)) + state = cache[str(tmp_path)] + + result = self.config_processor.process( + cwd=str(tmp_path), path='site', precomputed_state=state, + ) + + assert result == {} + def setup_method(self): """Set up test fixtures""" self.temp_dir = tempfile.mkdtemp() @@ -414,6 +495,25 @@ def test_yaml_content_loading(self): content = generator.yaml_get_content(yaml_file) assert content == config_data + def test_yaml_delete_tag_loading_and_cache_copy(self, tmp_path): + source = tmp_path / 'config.yaml' + source.write_text('gone: !delete\nnull_value: null\nliteral: "!delete"\n') + constructors = dict(yaml.SafeLoader.yaml_constructors) + + content = ConfigGenerator.yaml_get_content(str(source)) + assert content == {'gone': DELETE, 'null_value': None, 'literal': '!delete'} + content.pop('gone') + assert ConfigGenerator.yaml_get_content(str(source))['gone'] is DELETE + assert yaml.SafeLoader.yaml_constructors == constructors + + @pytest.mark.parametrize("payload", ["value", "{}", "[]"]) + def test_yaml_delete_tag_rejects_payload(self, tmp_path, payload): + source = tmp_path / 'config.yaml' + source.write_text('gone: !delete ' + payload + '\n') + + with pytest.raises(yaml.constructor.ConstructorError): + ConfigGenerator.yaml_get_content(str(source)) + def test_yaml_merging(self): """Test YAML merging functionality""" generator = ConfigGenerator( @@ -443,6 +543,87 @@ def test_yaml_merging(self): assert 'f3' in base_config['features'] assert base_config['new_key'] == 'value' + @pytest.mark.parametrize( + "base, incoming, expected", + [ + ({'gone': 42, 'keep': 1}, {'gone': DELETE}, {'keep': 1}), + ({'gone': {'child': 1}}, {'gone': DELETE}, {}), + ({'gone': None}, {'gone': DELETE}, {}), + ({'keep': 1}, {'missing': DELETE}, {'keep': 1}), + ({}, {'new': {'gone': DELETE}}, {'new': {}}), + ( + {'modules': {'module1': 1, 'module2': 2, 'module3': 3}}, + {'modules': {'module2': DELETE}}, + {'modules': {'module1': 1, 'module3': 3}}, + ), + ( + {'outer': {'inner': {'gone': 1}}}, + {'outer': {'inner': {'gone': DELETE}}}, + {'outer': {'inner': {}}}, + ), + ( + {'module.name': 1, 'module': {'name': 2}}, + {'module.name': DELETE}, + {'module': {'name': 2}}, + ), + ], + ) + def test_delete_mapping_keys(self, base, incoming, expected): + original = copy.deepcopy(incoming) + + ConfigGenerator.merge_yamls( + base, incoming, [(list, ["append_unique"]), (dict, ["merge"])], ["override"], ["override"] + ) + + assert base == expected + assert incoming == original + + def test_delete_can_be_repeated_and_reintroduced(self): + base = {'config': {'old': 1}} + for incoming in [{'config': DELETE}, {'config': DELETE}, {'config': {'new': 2}}]: + ConfigGenerator.merge_yamls(base, incoming, [(dict, ["merge"])], ["override"], ["override"]) + + assert base == {'config': {'new': 2}} + + @pytest.mark.parametrize( + "incoming", + [ + DELETE, + {DELETE: 'invalid key'}, + {'items': [DELETE]}, + {'items': [{'nested': DELETE}]}, + {'items': {DELETE}}, + {'items': (DELETE,)}, + ], + ) + def test_delete_rejects_unsupported_locations(self, incoming): + with pytest.raises(ValueError, match="!delete"): + ConfigGenerator.merge_yamls({}, incoming, [(dict, ["merge"])], ["override"], ["override"]) + + def test_delete_preserves_nulls_and_literal_tag_strings(self): + base = {'config': {'nullable': 'old', 'gone': 1}} + incoming = {'config': {'nullable': None, 'gone': DELETE}, 'new_null': None, 'literal': '!delete'} + + ConfigGenerator.merge_yamls(base, incoming, [(dict, ["merge"])], ["override"], ["override"]) + + assert base == {'config': {'nullable': None}, 'new_null': None, 'literal': '!delete'} + with pytest.raises(Exception, match="mismatch in type"): + ConfigGenerator.merge_yamls( + {'existing': 'text'}, {'existing': None}, [(dict, ["merge"])], ["override"], ["override"] + ) + + def test_delete_preserves_custom_dictionary_strategy(self): + def capture_inputs(config, path, base, incoming): + return {'base': base, 'incoming': incoming} + + base = {'config': {'gone': 1, 'keep': 2}} + ConfigGenerator.merge_yamls( + base, {'config': {'gone': DELETE, 'new': 3}}, + [(dict, capture_inputs)], ["override"], ["override"] + ) + + assert base == {'config': {'base': {'keep': 2}, 'incoming': {'new': 3}}} + def test_output_data_yaml(self): """Test YAML output formatting""" generator = ConfigGenerator( diff --git a/tests/test_config_merger.py b/tests/test_config_merger.py index 0ac60d49..7efd9f75 100644 --- a/tests/test_config_merger.py +++ b/tests/test_config_merger.py @@ -8,6 +8,7 @@ # OF ANY KIND, either express or implied. See the License for the specific language # governing permissions and limitations under the License. +import copy import os import tempfile import shutil @@ -19,11 +20,26 @@ Loader, merge_configs, merge_logic, get_leaf_directories, get_parser, run, _group_by_parent, merge_logic_batch, build_parent_cache ) +from himl.yaml_tags import DELETE class TestLoader: """Test custom YAML Loader with include functionality""" + def test_include_delete_tag(self, tmp_path): + included = tmp_path / 'included.yaml' + included.write_text('module2: !delete\n') + source = tmp_path / 'config.yaml' + source.write_text( + f'whole: !include {included}\nselected: !include {included} module2\n' + ) + + with source.open() as stream: + result = yaml.load(stream, Loader=Loader) + + assert result['whole'] == {'module2': DELETE} + assert result['selected'] is DELETE + def test_loader_initialization(self): """Test Loader initialization""" with tempfile.NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) as f: @@ -76,6 +92,50 @@ def test_include_constructor(self): class TestConfigMergerFunctions: """Test config merger utility functions""" + @pytest.mark.parametrize("parallel", [False, True]) + @pytest.mark.parametrize("precompute", [False, True]) + def test_delete_merger_execution_modes(self, tmp_path, monkeypatch, parallel, precompute): + from himl import ConfigProcessor + + monkeypatch.chdir(tmp_path) + monkeypatch.setattr(yaml, 'SafeLoader', yaml.SafeLoader) + monkeypatch.setattr('himl.config_merger.cpu_count', lambda: 2) + (tmp_path / 'default.yaml').write_text( + 'modules:\n module1: keep1\n module2: inherited\n module3: keep3\n' + 'obsolete: "{{missing.key}}"\n' + ) + parent = tmp_path / 'env=dev' + parent.mkdir() + included = parent / 'deletions.inc' + included.write_text('module2: !delete\n') + (parent / 'env.yaml').write_text( + f'env: dev\nobsolete: !delete\nmodules: !include {included}\n' + ) + leaves = [parent / 'cluster=a', parent / 'cluster=b'] + for leaf in leaves: + leaf.mkdir() + (leaves[0] / 'config.yaml').write_text('cluster: a\nmodules:\n module1: !delete\n module2: fresh\n') + (leaves[1] / 'config.yaml').write_text('cluster: b\nmodules:\n module3: !delete\n') + directories = [str(leaf) for leaf in leaves] + cache = build_parent_cache(directories) + original_cache = copy.deepcopy(cache) + assert cache[str(parent)] == {'env': 'dev', 'modules': {'module1': 'keep1', 'module3': 'keep3'}} + + output = tmp_path / 'output' + merge_configs( + directories, ['env', 'cluster'], str(output), enable_parallel=parallel, + filter_rules=None, allow_unicode=False, enable_precompute=precompute, + ) + + expected_a = {'env': 'dev', 'cluster': 'a', 'modules': {'module2': 'fresh', 'module3': 'keep3'}} + expected_b = {'env': 'dev', 'cluster': 'b', 'modules': {'module1': 'keep1'}} + assert yaml.load((output / 'dev' / 'a.yaml').read_text(), Loader=yaml.loader.SafeLoader) == expected_a + assert yaml.load((output / 'dev' / 'b.yaml').read_text(), Loader=yaml.loader.SafeLoader) == expected_b + processor = ConfigProcessor() + processor.process(path=str(leaves[0]), precomputed_state=cache[str(parent)]) + assert processor.process(path=str(leaves[1]), precomputed_state=cache[str(parent)]) == expected_b + assert cache == original_cache + def setup_method(self): """Set up test fixtures""" self.temp_dir = tempfile.mkdtemp() From 29bcd4ed98276369cdb17615478474360570cb9f Mon Sep 17 00:00:00 2001 From: Adi Muraru Date: Mon, 2 Nov 2026 18:57:52 +0100 Subject: [PATCH 2/2] Document scoped SafeLoader for CI security lint Suppress only Bandit's unrecognized factory-loader false positive, following the existing safe include-loader convention. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- himl/config_generator.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/himl/config_generator.py b/himl/config_generator.py index 1f1c3148..cf5b0a11 100755 --- a/himl/config_generator.py +++ b/himl/config_generator.py @@ -30,7 +30,8 @@ @functools.lru_cache(maxsize=None) def _yaml_get_content_cached(yaml_file): with open(yaml_file, 'r') as f: - content = yaml.load(f, Loader=loader_with_delete_tag(yaml.SafeLoader)) + loader = loader_with_delete_tag(yaml.SafeLoader) + content = yaml.load(f, Loader=loader) # nosec B506 # Scoped subclass of SafeLoader return content if content else {}