Debian Codegraph @

lib/ansible/module_utils/common/dict_transformations.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: (c) 2018, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import annotations
7
8
9 import re
10 from collections.abc import MutableMapping
11 from copy import deepcopy
12
13
14 def camel_dict_to_snake_dict(camel_dict, reversible=False, ignore_list=()):
15 """
16 reversible allows two way conversion of a camelized dict
17 such that snake_dict_to_camel_dict(camel_dict_to_snake_dict(x)) == x
18
19 This is achieved through mapping e.g. HTTPEndpoint to h_t_t_p_endpoint
20 where the default would be simply http_endpoint, which gets turned into
21 HttpEndpoint if recamelized.
22
23 ignore_list is used to avoid converting a sub-tree of a dict. This is
24 particularly important for tags, where keys are case-sensitive. We convert
25 the 'Tags' key but nothing below.
26 """
27
28 def value_is_list(camel_list):
29
30 checked_list = []
31 for item in camel_list:
32 if isinstance(item, dict):
33 checked_list.append(camel_dict_to_snake_dict(item, reversible))
34 elif isinstance(item, list):
35 checked_list.append(value_is_list(item))
36 else:
37 checked_list.append(item)
38
39 return checked_list
40
41 snake_dict = {}
42 for k, v in camel_dict.items():
43 if isinstance(v, dict) and k not in ignore_list:
44 snake_dict[_camel_to_snake(k, reversible=reversible)] = camel_dict_to_snake_dict(v, reversible)
45 elif isinstance(v, list) and k not in ignore_list:
46 snake_dict[_camel_to_snake(k, reversible=reversible)] = value_is_list(v)
47 else:
48 snake_dict[_camel_to_snake(k, reversible=reversible)] = v
49
50 return snake_dict
51
52
53 def snake_dict_to_camel_dict(snake_dict, capitalize_first=False):
54 """
55 Perhaps unexpectedly, snake_dict_to_camel_dict returns dromedaryCase
56 rather than true CamelCase. Passing capitalize_first=True returns
57 CamelCase. The default remains False as that was the original implementation
58 """
59
60 def camelize(complex_type, capitalize_first=False):
61 if complex_type is None:
62 return
63 new_type = type(complex_type)()
64 if isinstance(complex_type, dict):
65 for key in complex_type:
66 new_type[_snake_to_camel(key, capitalize_first)] = camelize(complex_type[key], capitalize_first)
67 elif isinstance(complex_type, list):
68 for i in range(len(complex_type)):
69 new_type.append(camelize(complex_type[i], capitalize_first))
70 else:
71 return complex_type
72 return new_type
73
74 return camelize(snake_dict, capitalize_first)
75
76
77 def _snake_to_camel(snake, capitalize_first=False):
78 if capitalize_first:
79 return ''.join(x.capitalize() or '_' for x in snake.split('_'))
80 else:
81 return snake.split('_')[0] + ''.join(x.capitalize() or '_' for x in snake.split('_')[1:])
82
83
84 def _camel_to_snake(name, reversible=False):
85
86 def prepend_underscore_and_lower(m):
87 return '_' + m.group(0).lower()
88
89 if reversible:
90 upper_pattern = r'[A-Z]'
91 else:
92 # Cope with pluralized abbreviations such as TargetGroupARNs
93 # that would otherwise be rendered target_group_ar_ns
94 upper_pattern = r'[A-Z]{3,}s$'
95
96 s1 = re.sub(upper_pattern, prepend_underscore_and_lower, name)
97 # Handle when there was nothing before the plural_pattern
98 if s1.startswith("_") and not name.startswith("_"):
99 s1 = s1[1:]
100 if reversible:
101 return s1
102
103 # Remainder of solution seems to be https://stackoverflow.com/a/1176023
104 first_cap_pattern = r'(.)([A-Z][a-z]+)'
105 all_cap_pattern = r'([a-z0-9])([A-Z]+)'
106 s2 = re.sub(first_cap_pattern, r'\1_\2', s1)
107 return re.sub(all_cap_pattern, r'\1_\2', s2).lower()
108
109
110 def dict_merge(a, b):
111 """recursively merges dicts. not just simple a['key'] = b['key'], if
112 both a and b have a key whose value is a dict then dict_merge is called
113 on both values and the result stored in the returned dictionary."""
114 if not isinstance(b, dict):
115 return b
116 result = deepcopy(a)
117 for k, v in b.items():
118 if k in result and isinstance(result[k], dict):
119 result[k] = dict_merge(result[k], v)
120 else:
121 result[k] = deepcopy(v)
122 return result
123
124
125 def recursive_diff(dict1, dict2):
126 """Recursively diff two dictionaries
127
128 Raises ``TypeError`` for incorrect argument type.
129
130 :arg dict1: Dictionary to compare against.
131 :arg dict2: Dictionary to compare with ``dict1``.
132 :return: Tuple of dictionaries of differences or ``None`` if there are no differences.
133 """
134
135 if not all((isinstance(item, MutableMapping) for item in (dict1, dict2))):
136 raise TypeError("Unable to diff 'dict1' %s and 'dict2' %s. "
137 "Both must be a dictionary." % (type(dict1), type(dict2)))
138
139 left = dict((k, v) for (k, v) in dict1.items() if k not in dict2)
140 right = dict((k, v) for (k, v) in dict2.items() if k not in dict1)
141 for k in (set(dict1.keys()) & set(dict2.keys())):
142 if isinstance(dict1[k], dict) and isinstance(dict2[k], dict):
143 result = recursive_diff(dict1[k], dict2[k])
144 if result:
145 left[k] = result[0]
146 right[k] = result[1]
147 elif dict1[k] != dict2[k]:
148 left[k] = dict1[k]
149 right[k] = dict2[k]
150 if left or right:
151 return left, right
152 return None