Debian Codegraph @

ansible_collections/community/general/plugins/module_utils/_mh/mixins/state.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
14 class StateMixin:
15 state_param: str = "state"
16 default_state: str | None = None
17
18 def _state(self) -> str:
19 state: str = self.module.params.get(self.state_param) # type: ignore[attr-defined]
20 return self.default_state if state is None else state
21
22 def _method(self, state: str) -> str:
23 return f"{self.state_param}_{state}"
24
25 def __run__(self):
26 state = self._state()
27 self.vars.state = state
28
29 # resolve aliases
30 if state not in self.module.params:
31 aliased = [name for name, param in self.module.argument_spec.items() if state in param.get("aliases", [])]
32 if aliased:
33 state = aliased[0]
34 self.vars.effective_state = state
35
36 method = self._method(state)
37 if not hasattr(self, method):
38 return self.__state_fallback__()
39 func = getattr(self, method)
40 return func()
41
42 def __state_fallback__(self) -> t.NoReturn:
43 raise ValueError(f"Cannot find method: {self._method(self._state())}")