Debian Codegraph @

ansible_collections/community/general/plugins/module_utils/_vardict.py

raw
1 # (c) 2023, Alexei Znamensky <[email protected]>
2 # Copyright (c) 2023, Ansible Project
3 # Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause)
4 # SPDX-License-Identifier: BSD-2-Clause
5
6 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
7 # Do not use this from other collections or standalone plugins/modules!
8
9 from __future__ import annotations
10
11 import copy
12 import typing as t
13
14
15 class _Variable:
16 NOTHING = object()
17
18 def __init__(
19 self,
20 diff: bool = False,
21 output: bool = True,
22 change: bool | None = None,
23 fact: bool = False,
24 verbosity: int = 0,
25 ):
26 self.init = False
27 self.initial_value: t.Any = None
28 self.value: t.Any = None
29
30 self.diff: bool = None # type: ignore # will be changed in set_meta() call
31 self._change: bool | None = None
32 self.output: bool = None # type: ignore # will be changed in set_meta() call
33 self.fact: bool = None # type: ignore # will be changed in set_meta() call
34 self._verbosity: int = None # type: ignore # will be changed in set_meta() call
35 self.set_meta(output=output, diff=diff, change=change, fact=fact, verbosity=verbosity)
36
37 def getchange(self) -> bool:
38 return self.diff if self._change is None else self._change
39
40 def setchange(self, value: bool | None) -> None:
41 self._change = value
42
43 def getverbosity(self) -> int:
44 return self._verbosity
45
46 def setverbosity(self, v: int) -> None:
47 if not (0 <= v <= 4):
48 raise ValueError("verbosity must be an int in the range 0 to 4")
49 self._verbosity = v
50
51 change = property(getchange, setchange)
52 verbosity = property(getverbosity, setverbosity)
53
54 def set_meta(
55 self,
56 output: bool | None = None,
57 diff: bool | None = None,
58 change: bool | None = None,
59 fact: bool | None = None,
60 initial_value: t.Any = NOTHING,
61 verbosity: int | None = None,
62 ) -> None:
63 """Set the metadata for the variable
64
65 Args:
66 output (bool, optional): flag indicating whether the variable should be in the output of the module. Defaults to None.
67 diff (bool, optional): flag indicating whether to generate diff mode output for this variable. Defaults to None.
68 change (bool, optional): flag indicating whether to track if changes happened to this variable. Defaults to None.
69 fact (bool, optional): flag indicating whether the variable should be exposed as a fact of the module. Defaults to None.
70 initial_value (any, optional): initial value of the variable, to be used with `change`. Defaults to NOTHING.
71 verbosity (int, optional): level of verbosity in which this variable is reported by the module as `output`, `fact` or `diff`. Defaults to None.
72 """
73 if output is not None:
74 self.output = output
75 if change is not None:
76 self.change = change
77 if diff is not None:
78 self.diff = diff
79 if fact is not None:
80 self.fact = fact
81 if initial_value is not _Variable.NOTHING:
82 self.initial_value = copy.deepcopy(initial_value)
83 if verbosity is not None:
84 self.verbosity = verbosity
85
86 def as_dict(self, meta_only: bool = False) -> dict[str, t.Any]:
87 d = {
88 "diff": self.diff,
89 "change": self.change,
90 "output": self.output,
91 "fact": self.fact,
92 "verbosity": self.verbosity,
93 }
94 if not meta_only:
95 d["initial_value"] = copy.deepcopy(self.initial_value)
96 d["value"] = self.value
97 return d
98
99 def set_value(self, value: t.Any) -> t.Self:
100 if not self.init:
101 self.initial_value = copy.deepcopy(value)
102 self.init = True
103 self.value = value
104 return self
105
106 def is_visible(self, verbosity: int) -> bool:
107 return self.verbosity <= verbosity
108
109 @property
110 def has_changed(self) -> bool:
111 return self.change and (self.initial_value != self.value)
112
113 @property
114 def diff_result(self) -> dict[str, t.Any] | None:
115 if self.diff and self.has_changed:
116 return {"before": self.initial_value, "after": self.value}
117 return None
118
119 def __str__(self) -> str:
120 return (
121 f"<Variable: value={self.value!r}, initial={self.initial_value!r}, diff={self.diff}, "
122 f"output={self.output}, change={self.change}, verbosity={self.verbosity}>"
123 )
124
125
126 class VarDict:
127 reserved_names = (
128 "__vars__",
129 "_var",
130 "var",
131 "set_meta",
132 "get_meta",
133 "set",
134 "output",
135 "diff",
136 "facts",
137 "has_changed",
138 "as_dict",
139 )
140
141 def __init__(self) -> None:
142 self.__vars__: dict[str, _Variable] = dict()
143
144 def __getitem__(self, item: str):
145 return self.__vars__[item].value
146
147 def __setitem__(self, key: str, value) -> None:
148 self.set(key, value)
149
150 def __getattr__(self, item: str):
151 try:
152 return self.__vars__[item].value
153 except KeyError:
154 return getattr(super(), item)
155
156 def __setattr__(self, key: str, value) -> None:
157 if key == "__vars__":
158 super().__setattr__(key, value)
159 else:
160 self.set(key, value)
161
162 def _var(self, name: str) -> _Variable:
163 return self.__vars__[name]
164
165 def var(self, name: str) -> dict[str, t.Any]:
166 return self._var(name).as_dict()
167
168 def set_meta(self, name: str, **kwargs):
169 """Set the metadata for the variable
170
171 Args:
172 name (str): name of the variable having its metadata changed
173 output (bool, optional): flag indicating whether the variable should be in the output of the module. Defaults to None.
174 diff (bool, optional): flag indicating whether to generate diff mode output for this variable. Defaults to None.
175 change (bool, optional): flag indicating whether to track if changes happened to this variable. Defaults to None.
176 fact (bool, optional): flag indicating whether the variable should be exposed as a fact of the module. Defaults to None.
177 initial_value (any, optional): initial value of the variable, to be used with `change`. Defaults to NOTHING.
178 verbosity (int, optional): level of verbosity in which this variable is reported by the module as `output`, `fact` or `diff`. Defaults to None.
179 """
180 self._var(name).set_meta(**kwargs)
181
182 def get_meta(self, name: str) -> dict[str, t.Any]:
183 return self._var(name).as_dict(meta_only=True)
184
185 def set(self, name: str, value, **kwargs) -> None:
186 """Set the value and optionally metadata for a variable. The variable is not required to exist prior to calling `set`.
187
188 For details on the accepted metada see the documentation for method `set_meta`.
189
190 Args:
191 name (str): name of the variable being changed
192 value (any): the value of the variable, it can be of any type
193
194 Raises:
195 ValueError: Raised if trying to set a variable with a reserved name.
196 """
197 if name in self.reserved_names:
198 raise ValueError(f"Name {name} is reserved")
199 if name in self.__vars__:
200 var = self._var(name)
201 var.set_meta(**kwargs)
202 else:
203 var = _Variable(**kwargs)
204 var.set_value(value)
205 self.__vars__[name] = var
206
207 def output(self, verbosity: int = 0) -> dict[str, t.Any]:
208 return {n: v.value for n, v in self.__vars__.items() if v.output and v.is_visible(verbosity)}
209
210 def diff(self, verbosity: int = 0) -> dict[str, dict[str, t.Any]] | None:
211 diff_results = [
212 (n, v.diff_result) for n, v in self.__vars__.items() if v.diff_result and v.is_visible(verbosity)
213 ]
214 if diff_results:
215 before = {n: dr["before"] for n, dr in diff_results}
216 after = {n: dr["after"] for n, dr in diff_results}
217 return {"before": before, "after": after}
218 return None
219
220 def facts(self, verbosity: int = 0) -> dict[str, t.Any] | None:
221 facts_result = {n: v.value for n, v in self.__vars__.items() if v.fact and v.is_visible(verbosity)}
222 return facts_result if facts_result else None
223
224 @property
225 def has_changed(self) -> bool:
226 return any(var.has_changed for var in self.__vars__.values())
227
228 def as_dict(self) -> dict[str, t.Any]:
229 return {name: var.value for name, var in self.__vars__.items()}