1
0
Fork 0
ansible-systemd/plugins/module_utils/generic.py

123 Zeilen
3.7 KiB
Python

import pathlib
import warnings
from typing import Any, Callable, Dict, Optional, Sequence, Tuple, Type, Union
__all__ = (
"Types",
"SYSTEMD_SERVICE_CONFIG",
"SYSTEMD_NETWORK_CONFIG",
"SYSTEMD_CONFIG_ROOT",
2023-04-21 18:49:07 +00:00
"systemdbool",
)
SYSTEMD_CONFIG_ROOT = pathlib.Path("/etc/systemd")
SYSTEMD_NETWORK_CONFIG = SYSTEMD_CONFIG_ROOT / "network"
SYSTEMD_SERVICE_CONFIG = SYSTEMD_CONFIG_ROOT / "system"
class _sdict(dict):
_help: Optional[str]
__name__: str
class _Type:
def __dir__(self) -> tuple:
return (
"str",
"bool",
"int",
"float",
"path",
"raw",
"jsonarg",
"json",
"bytes",
"dict",
"list",
"bits",
"__doc__",
)
def list(
self,
elements: Union[Type[object], str, dict],
required: bool = False,
help: Optional[str] = None,
) -> _sdict:
option = _sdict(type="list", required=required)
if not isinstance(elements, (str, _sdict)):
option["elements"] = elements.__name__
elif isinstance(elements, dict):
option["elements"] = elements["type"]
if elements["type"] == "dict":
option["options"] = dict()
for name, value in elements["option"].items():
option["options"][name] = value
if isinstance(value, _sdict) and value._help is not None:
option["options"][name]["description"] = value._help
elif "description" in option["options"][name]:
pass
else:
warnings.warn(
"helptext of option {} is unset. Ansible requires suboptions to have an documentation".format(name),
)
option._help = help
return option
def dict(self, required: bool = False, help: Optional[str] = None, **options: dict) -> _sdict:
option = _sdict(type="dict", required=required)
option["option"] = options
option._help = help
return option
def __getattr__(self, name: str):
def argument(
required: bool = False,
help: Optional[str] = None,
choices: Optional[Sequence] = None,
default: Optional[Any] = None,
):
"""Simple wrapper for Ansible {0} argument dict"""
output = _sdict(type=name, required=required)
if choices is not None:
output["choices"] = choices
if default is not None:
output["default"] = default
output._help = help
return output
argument.__name__ = name
argument.__doc__ = argument.__doc__.format(name) # type: ignore
return argument
2023-04-21 18:49:07 +00:00
Types = _Type()
2023-04-21 18:49:07 +00:00
def systemdbool(b: Union[bool, str]) -> str:
if b is True:
return "yes"
elif b is False:
return "no"
return b
def modspec(
argument_spec: Dict[str, Dict[str, Any]],
mutually_exclusive: Sequence[Tuple[str, ...]] = (),
required_together: Sequence[Tuple[str, ...]] = (),
required_one_of: Sequence[Tuple[str, ...]] = (),
required_if: Sequence[Union[Tuple[str, Any, Tuple[str, ...]], Tuple[str, Any, Tuple[str, ...], bool]]] = (),
required_by: Dict[str, Union[str, Tuple[str, ...]]] = {},
) -> Dict[str, Any]:
return dict(
argument_spec=argument_spec,
mutually_exclusive=mutually_exclusive,
required_together=required_together,
required_one_of=required_one_of,
required_if=required_if,
required_by=required_by,
)