Debian Codegraph @

ansible_collections/community/general/plugins/module_utils/_mh/module_helper.py

raw
1 # (c) 2020-2024, Alexei Znamensky <[email protected]>
2 # Copyright (c) 2020-2024, 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 typing as t
12
13 from ansible.module_utils.common.dict_transformations import dict_merge
14
15 from ansible_collections.community.general.plugins.module_utils._mh.base import ModuleHelperBase
16 from ansible_collections.community.general.plugins.module_utils._mh.mixins.deprecate_attrs import DeprecateAttrsMixin
17 from ansible_collections.community.general.plugins.module_utils._mh.mixins.state import StateMixin
18 from ansible_collections.community.general.plugins.module_utils._vardict import VarDict
19
20 if t.TYPE_CHECKING:
21 from collections.abc import Sequence
22
23 from ansible.module_utils.basic import AnsibleModule
24
25
26 class ModuleHelper(DeprecateAttrsMixin, ModuleHelperBase):
27 facts_name: str | None = None
28 output_params: Sequence[str] = ()
29 diff_params: Sequence[str] = ()
30 change_params: Sequence[str] = ()
31 facts_params: Sequence[str] = ()
32
33 def __init__(self, module: AnsibleModule | dict[str, t.Any] | None = None) -> None:
34 super().__init__(module)
35
36 self.vars = VarDict()
37 for name, value in self.module.params.items(): # type: ignore[union-attr]
38 self.vars.set(
39 name,
40 value,
41 diff=name in self.diff_params,
42 output=name in self.output_params,
43 change=None if not self.change_params else name in self.change_params,
44 fact=name in self.facts_params,
45 )
46
47 def update_vars(self, meta: dict[str, t.Any] | None = None, **kwargs: t.Any) -> None:
48 if meta is None:
49 meta = {}
50 for k, v in kwargs.items():
51 self.vars.set(k, v, **meta)
52
53 def update_output(self, **kwargs: t.Any) -> None:
54 self.update_vars(meta={"output": True}, **kwargs)
55
56 def update_facts(self, **kwargs: t.Any) -> None:
57 self.update_vars(meta={"fact": True}, **kwargs)
58
59 def _vars_changed(self) -> bool:
60 return self.vars.has_changed
61
62 def has_changed(self) -> bool:
63 return self.changed or self._vars_changed()
64
65 @property
66 def output(self) -> dict[str, t.Any]:
67 result = dict(self.vars.output())
68 if self.facts_name:
69 facts = self.vars.facts()
70 if facts is not None:
71 result["ansible_facts"] = {self.facts_name: facts}
72 if self.diff_mode:
73 diff = result.get("diff", {})
74 vars_diff = self.vars.diff() or {}
75 result["diff"] = dict_merge(dict(diff), vars_diff)
76
77 return result
78
79
80 class StateModuleHelper(StateMixin, ModuleHelper):
81 pass