Debian Codegraph @

tasks/_inv/util.py

raw symbols SCIP
1 # -*- coding: ascii -*-
2 #
3 # Copyright 2024 - 2025
4 # Andr\xe9 Malo or his licensors, as applicable
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 """
18 Utilities
19 ~~~~~~~~~
20
21 """
22
23 import functools as _ft
24
25 basestring_ = (
26 str
27 if str is not bytes
28 else basestring # noqa pylint: disable = undefined-variable
29 )
30
31
32 def cached(func):
33 """
34 Caching decorator
35
36 Parameters:
37 func (callable):
38 The function to cache the result of
39
40 Returns:
41 The decorated function
42 """
43 cache = getattr(_ft, "cache", None)
44 if cache is not None:
45 return cache(func)
46
47 store = {}
48
49 @_ft.wraps(func)
50 def inner(*args, **kwargs):
51 """The cache wrapper"""
52 key = tuple(list(args) + sorted(kwargs.items()))
53 try:
54 return store[key]
55 except KeyError:
56 store[key] = result = func(*args, **kwargs)
57 return result
58
59 return inner
60
61
62 def dictmerge(dict1, dict2, resolve_left=None):
63 """
64 Merge nested dict2 into dict1
65
66 Parameters:
67 dict1 (dict or adict):
68 Dict to update
69
70 dict2 (dict or adict):
71 Dict to merge
72
73 resolve_left (callable):
74 A resolver to be called on each callable left-side item. If omitted or
75 ``None``, the items will be passed through as-is
76
77 Returns:
78 dict or adict: The updated dict1. If it was an adict, a new adict is
79 returned.
80 """
81 type1 = type(dict1)
82 if isinstance(dict2, adict):
83 type1 = adict
84 elif type1 not in (dict, adict):
85 type1 = adict
86
87 if dict1 is None:
88 if not isinstance(dict2, (dict, adict)):
89 return dict2
90 dict1 = {}
91
92 dict1 = dict(dict1.items())
93 if resolve_left is not None:
94 for key, value in list(dict1.items()):
95 if callable(value) and isinstance(dict2.get(key), (adict, dict)):
96 dict1[key] = resolve_left(value)
97
98 for key, value in dict2.items():
99 if isinstance(value, (dict, adict)):
100 value = dictmerge(
101 dict1.get(key, {}),
102 value,
103 resolve_left=resolve_left,
104 )
105 dict1[key] = value
106
107 return type1(dict1)
108
109
110 class adict(object):
111 """attribute dict"""
112
113 # pylint: disable = invalid-name, missing-docstring
114
115 def __init__(self, *args, **kwargs):
116 """
117 Initialization
118
119 Parameters:
120 *args:
121 Positional dict args
122
123 **kwargs:
124 Keyword dict args
125 """
126 self.__x__ = dict(*args, **kwargs)
127
128 def __repr__(self):
129 """
130 Return debug representation
131
132 Returns:
133 str: Debug representation
134 """
135 return "%s(%r)" % (self.__class__.__name__, self.__x__)
136
137 def __bool__(self):
138 """
139 Return bool value of the object
140
141 Returns:
142 bool: False if empty, True otherwise
143 """
144 return bool(self.__x__)
145
146 __nonzero__ = __bool__
147
148 def __iter__(self):
149 """
150 Return key iterator
151
152 Returns:
153 iterable: New key iterator
154 """
155 return iter(self.__x__)
156
157 def __getitem__(self, name):
158 """
159 Get value by subscript
160
161 Parameters:
162 name (str):
163 The key
164
165 Returns:
166 any: The value
167
168 Raises:
169 KeyError: Key not found
170 """
171 return self.__x__[name]
172
173 def __setitem__(self, name, value):
174 """
175 Set value by subscript
176
177 Parameters:
178 name (str):
179 The key
180
181 value (any):
182 The value
183 """
184 self.__x__[name] = value
185
186 def __getattr__(self, name):
187 """
188 Get value for dot notation
189
190 Parameters:
191 name (str):
192 The key
193
194 Returns:
195 any: The value
196
197 Raises:
198 AttributeError: Key not found
199 """
200 if name == "__setstate__":
201 raise AttributeError(name)
202 try:
203 return super(adict, self).__getattr__(name)
204 except AttributeError:
205 try:
206 return self.__x__[name]
207 except KeyError:
208 raise AttributeError( # pylint: disable = raise-missing-from
209 name
210 )
211
212 def __setattr__(self, name, value):
213 """
214 Set value with dot notation
215
216 Parameters:
217 name (str):
218 The key
219
220 value (any):
221 The value
222 """
223 if name == "__x__" or hasattr(self.__class__, name):
224 super(adict, self).__setattr__(name, value)
225 else:
226 self.__x__[name] = value
227
228 def keys(self):
229 """
230 Create key iterator
231
232 Returns:
233 iterable: New key iterator
234 """
235 return self.__x__.keys()
236
237 def items(self):
238 """
239 Create key/value iterator
240
241 Returns:
242 iterable: New key/value iterator
243 """
244 return self.__x__.items()
245
246 def get(self, *args, **kwargs):
247 """
248 Get value with default
249
250 Parameters:
251 *args:
252 Positional dict.get args
253
254 **kwargs:
255 Keyword dict.get args
256
257 Returns:
258 any: The value or the default (if the key doesn't exist)
259 """
260 return self.__x__.get(*args, **kwargs)
261
262 def pop(self, *args, **kwargs):
263 """
264 Pop value
265
266 Parameters:
267 *args:
268 Positional dict.pop args
269
270 **kwargs:
271 Keyword dict.pop args
272
273 Returns:
274 any: The value or the default (if the key doesn't exist)
275 """
276 return self.__x__.pop(*args, **kwargs)