From a8d105b702a7dfa1b2ea3d52b19e247bacf702ac Mon Sep 17 00:00:00 2001 From: Guillaume Mazoyer Date: Tue, 14 Jan 2025 11:45:10 +0100 Subject: [PATCH] Allow merging lists within dicts merge --- infrahub_sdk/utils.py | 6 +++++- tests/unit/sdk/test_utils.py | 3 +++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/infrahub_sdk/utils.py b/infrahub_sdk/utils.py index ee93edf..aa065e2 100644 --- a/infrahub_sdk/utils.py +++ b/infrahub_sdk/utils.py @@ -136,8 +136,12 @@ def deep_merge_dict(dicta: dict, dictb: dict, path: list | None = None) -> dict: if key in dicta: if isinstance(dicta[key], dict) and isinstance(dictb[key], dict): deep_merge_dict(dicta[key], dictb[key], path + [str(key)]) + elif isinstance(dicta[key], list) and isinstance(dictb[key], list): + # Merge lists + # Cannot use compare_list because list of dicts won't work (dict not hashable) + dicta[key] = [i for i in dicta[key] if i not in dictb[key]] + dictb[key] elif dicta[key] == dictb[key]: - pass + continue else: raise ValueError("Conflict at %s" % ".".join(path + [str(key)])) else: diff --git a/tests/unit/sdk/test_utils.py b/tests/unit/sdk/test_utils.py index 33d2414..114a35c 100644 --- a/tests/unit/sdk/test_utils.py +++ b/tests/unit/sdk/test_utils.py @@ -87,8 +87,11 @@ def test_deep_merge_dict(): a = {"keyA": 1} b = {"keyB": {"sub1": 10}} c = {"keyB": {"sub2": 20}} + d = {"keyA": [10, 20]} + e = {"keyA": [20, 30]} assert deep_merge_dict(a, b) == {"keyA": 1, "keyB": {"sub1": 10}} assert deep_merge_dict(c, b) == {"keyB": {"sub1": 10, "sub2": 20}} + assert deep_merge_dict(d, e) == {"keyA": [10, 20, 30]} def test_str_to_bool():