Created
August 30, 2022 16:43
-
-
Save pivotaljohn/e87cdf0ede71209a25f78180cb473c15 to your computer and use it in GitHub Desktop.
Deep merge of dictionaries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#@ load("@ytt:yaml", "yaml") | |
#@ load("@ytt:overlay", "overlay") | |
#@ load("@ytt:struct", "struct") | |
#@ def _doc(map): | |
--- #@ map | |
#@ end | |
--- | |
#@ def _missing_ok(map): | |
#@overlay/match by=overlay.all | |
#@overlay/match-child-defaults missing_ok=True | |
--- #@ map | |
#@ end | |
--- | |
#! merges all of "dict_b" into "dict_a" via overlaying | |
#@ def _deep(dict_a, dict_b): | |
#@ a_yaml = _doc(dict_a) | |
#@ b_yaml = _missing_ok(dict_b) | |
#@ merged_yaml = overlay.apply(a_yaml, b_yaml)[0] | |
#@ merged_dict = yaml.decode(yaml.encode(merged_yaml)) | |
#@ return merged_dict | |
#@ end | |
#@ merge = struct.make(deep=_deep) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#@ load("merge.lib.yaml", "merge") | |
#@ a = { | |
#@ "spec": { | |
#@ "template": { | |
#@ "spec": { | |
#@ "name": "maximus" | |
#@ } | |
#@ } | |
#@ } | |
#@ } | |
#@ b = { | |
#@ "spec": { | |
#@ "replicas": 5, | |
#@ "template": { | |
#@ "spec": { | |
#@ "metadata": { | |
#@ "annotations": { | |
#@ "app.kubernetes.io/managed-by": "carvel" | |
#@ } | |
#@ } | |
#@ } | |
#@ }, | |
#@ } | |
#@ } | |
--- | |
desc: "a and b; no merge" | |
a: #@ a | |
b: #@ b | |
--- | |
desc: "b merged into a (via dict.update())" | |
#@ b_in_a = dict(a) | |
#@ b_in_a.update(b) | |
b_in_a: #@ b_in_a | |
--- | |
desc: "a merged into b (via dict.update())" | |
#@ a_in_b = dict(b) | |
#@ a_in_b.update(a) | |
a_in_b: #@ a_in_b | |
--- | |
desc: "b merged into a (via merge.deep())" | |
b_in_a: #@ merge.deep(a, b) | |
--- | |
desc: "a merged into b (via merge.deep())" | |
a_in_b: #@ merge.deep(b, a) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment