Debian Codegraph @

ansible_collections/splunk/es/plugins/module_utils/dict_utils.py

raw
1 # -*- coding: utf-8 -*-
2 # Copyright (c) 2018 Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 """Dictionary utility functions for Ansible Splunk ES collection.
6
7 These functions were originally provided by ansible.netcommon's
8 ``network.common.utils`` module and are inlined here to remove
9 that collection dependency.
10 """
11
12 from __future__ import annotations
13
14 from collections.abc import Mapping
15 from copy import deepcopy
16 from itertools import chain
17
18
19 def sort_list(val):
20 """Sort a value if it is a list, otherwise return as-is.
21
22 Args:
23 val: Any value. If it is a list of dicts, each dict is
24 converted to a sorted-tuple representation for comparison.
25
26 Returns:
27 A sorted copy of the list, or the original value unchanged.
28 """
29 if isinstance(val, list):
30 if all(isinstance(x, dict) for x in val):
31 return sorted(val, key=lambda x: sorted(x.items()))
32 return sorted(val)
33 return val
34
35
36 def remove_empties(cfg_dict: dict) -> dict:
37 """Recursively remove keys with empty/None values from a dictionary.
38
39 Args:
40 cfg_dict: A dictionary to clean.
41
42 Returns:
43 A new dictionary with all None, empty-list, empty-dict,
44 empty-tuple, and empty-string values removed.
45 """
46 final_cfg: dict = {}
47 if not cfg_dict:
48 return final_cfg
49
50 for key, val in cfg_dict.items():
51 dct = None
52 if isinstance(val, dict):
53 child_val = remove_empties(val)
54 if child_val:
55 dct = {key: child_val}
56 elif isinstance(val, list) and val and all(isinstance(x, dict) for x in val):
57 child_val = [remove_empties(x) for x in val]
58 if child_val:
59 dct = {key: child_val}
60 elif val not in [None, [], {}, (), ""]:
61 dct = {key: val}
62 if dct:
63 final_cfg.update(dct)
64 return final_cfg
65
66
67 def dict_diff(base: dict, comparable: dict) -> dict:
68 """Compute the difference between two dictionaries.
69
70 For scalar values the key reflects the updated value from *comparable*.
71 Keys absent from *comparable* are ignored. Lists are replaced wholly.
72 Nested dicts are compared recursively.
73
74 Args:
75 base: The reference dictionary.
76 comparable: The dictionary to compare against *base*.
77
78 Returns:
79 A new dictionary containing only the differences.
80
81 Raises:
82 AssertionError: If *base* or *comparable* is not a dict
83 (None is accepted for *comparable*).
84 """
85 if not isinstance(base, dict):
86 raise AssertionError("`base` must be of type <dict>")
87 if not isinstance(comparable, dict):
88 if comparable is None:
89 comparable = {}
90 else:
91 raise AssertionError("`comparable` must be of type <dict>")
92
93 updates: dict = {}
94
95 for key, value in base.items():
96 if isinstance(value, dict):
97 item = comparable.get(key)
98 if item is not None:
99 sub_diff = dict_diff(value, comparable[key])
100 if sub_diff:
101 updates[key] = sub_diff
102 else:
103 comparable_value = comparable.get(key)
104 if comparable_value is not None:
105 if sort_list(base[key]) != sort_list(comparable_value):
106 updates[key] = comparable_value
107
108 for key in set(comparable.keys()).difference(base.keys()):
109 updates[key] = comparable.get(key)
110
111 return updates
112
113
114 def dict_merge(base: dict, other: dict) -> dict:
115 """Deep-merge two dictionaries, preferring values from *other*.
116
117 When both keys exist the value is taken from *other*. Lists are
118 combined with duplicates removed. Nested dicts are merged recursively.
119
120 Args:
121 base: The base dictionary.
122 other: The dictionary to merge into *base*.
123
124 Returns:
125 A new combined dictionary.
126
127 Raises:
128 AssertionError: If either argument is not a dict.
129 """
130 if not isinstance(base, dict):
131 raise AssertionError("`base` must be of type <dict>")
132 if not isinstance(other, dict):
133 raise AssertionError("`other` must be of type <dict>")
134
135 combined: dict = {}
136
137 for key, value in deepcopy(base).items():
138 if isinstance(value, dict):
139 if key in other:
140 item = other.get(key)
141 if item is not None:
142 if isinstance(other[key], Mapping):
143 combined[key] = dict_merge(value, other[key])
144 else:
145 combined[key] = other[key]
146 else:
147 combined[key] = item
148 else:
149 combined[key] = value
150 elif isinstance(value, list):
151 if key in other:
152 item = other.get(key)
153 if item is not None:
154 try:
155 combined[key] = list(set(chain(value, item)))
156 except TypeError:
157 value.extend([i for i in item if i not in value])
158 combined[key] = value
159 else:
160 combined[key] = item
161 else:
162 combined[key] = value
163 else:
164 if key in other:
165 other_value = other.get(key)
166 if other_value is not None:
167 if sort_list(base[key]) != sort_list(other_value):
168 combined[key] = other_value
169 else:
170 combined[key] = value
171 else:
172 combined[key] = other_value
173 else:
174 combined[key] = value
175
176 for key in set(other.keys()).difference(base.keys()):
177 combined[key] = other.get(key)
178
179 return combined