Debian Codegraph @

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

raw
1 # (c) 2020, Alexei Znamensky <[email protected]>
2 # Copyright (c) 2020, 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.basic import AnsibleModule
14
15 from ansible_collections.community.general.plugins.module_utils._mh.deco import module_fails_on_exception
16 from ansible_collections.community.general.plugins.module_utils._mh.exceptions import ModuleHelperException as _MHE
17
18
19 class ModuleHelperBase:
20 module: dict[str, t.Any] | None = None # TODO: better spec using t.TypedDict
21 ModuleHelperException = _MHE
22 _delegated_to_module: tuple[str, ...] = (
23 "check_mode",
24 "get_bin_path",
25 "warn",
26 "deprecate",
27 "debug",
28 )
29
30 def __init__(self, module=None):
31 self._changed = False
32
33 if module:
34 self.module = module
35
36 if not isinstance(self.module, AnsibleModule):
37 self.module = AnsibleModule(**self.module)
38
39 @property
40 def diff_mode(self):
41 return self.module._diff
42
43 @property
44 def verbosity(self):
45 return self.module._verbosity
46
47 def do_raise(self, *args, **kwargs) -> t.NoReturn:
48 raise _MHE(*args, **kwargs)
49
50 def __getattr__(self, attr):
51 if attr in self._delegated_to_module:
52 return getattr(self.module, attr)
53 raise AttributeError(f"ModuleHelperBase has no attribute '{attr}'")
54
55 def __init_module__(self):
56 pass
57
58 def __run__(self):
59 raise NotImplementedError()
60
61 def __quit_module__(self):
62 pass
63
64 def __changed__(self):
65 raise NotImplementedError()
66
67 @property
68 def changed(self) -> bool:
69 try:
70 return self.__changed__()
71 except NotImplementedError:
72 return self._changed
73
74 @changed.setter
75 def changed(self, value: bool) -> None:
76 self._changed = value
77
78 def has_changed(self):
79 raise NotImplementedError()
80
81 @property
82 def output(self):
83 raise NotImplementedError()
84
85 @module_fails_on_exception
86 def run(self):
87 self.__init_module__()
88 self.__run__()
89 self.__quit_module__()
90 output = self.output
91 if "failed" not in output:
92 output["failed"] = False
93 self.module.exit_json(changed=self.has_changed(), **output)
94
95 @classmethod
96 def execute(cls, module=None):
97 cls(module).run()