to prevent empty sections, the install and header methods return None if the method would just the scetion header

Dieser Commit ist enthalten in:
Sebastian Tobie 2024-03-08 21:57:38 +01:00
Ursprung d03b45d678
Commit 0ba608406e
8 geänderte Dateien mit 56 neuen und 30 gelöschten Zeilen

Datei anzeigen

@ -5,6 +5,16 @@ Sebastian.Base Release Notes
.. contents:: Topics .. contents:: Topics
v0.4.0
======
Release Summary
---------------
to prevent empty sections, the install and header methods return None if the method would just the scetion
header
v0.3.1 v0.3.1
====== ======

Datei anzeigen

@ -16,4 +16,4 @@ plugins:
strategy: {} strategy: {}
test: {} test: {}
vars: {} vars: {}
version: 0.2.0 version: 0.4.0

Datei anzeigen

@ -14,3 +14,9 @@ releases:
changes: changes:
release_summary: removed forgotten print calls release_summary: removed forgotten print calls
release_date: "2024-02-24" release_date: "2024-02-24"
0.4.0:
release_date: "2024-03-08"
changes:
release_summary: |
to prevent empty sections, the install and header methods return None if the method would just the scetion
header

Datei anzeigen

@ -1,7 +1,7 @@
--- ---
namespace: sebastian namespace: sebastian
name: base name: base
version: 0.3.1 version: 0.4.0
readme: README.md readme: README.md
@ -9,7 +9,7 @@ authors:
- Sebastian Tobie - Sebastian Tobie
description: > description: >
The base of my ansible collections. It provides the nessesary tools for my modules The base of my ansible collections. It provides the nessesary tools for my modules
license_file: LICENSE license_file: LICENSE.txt
tags: tags:
- linux - linux
- systemd - systemd

Datei anzeigen

@ -89,7 +89,8 @@ class meta(type):
class Types(metaclass=meta): class Types(metaclass=meta):
def list(
def list( # type: ignore[misc]
elements: Union[Type[object], str, AnsibleParameter], elements: Union[Type[object], str, AnsibleParameter],
required: bool = False, required: bool = False,
help: Optional[str] = None, help: Optional[str] = None,
@ -119,7 +120,7 @@ class Types(metaclass=meta):
option["description"] = help.split("\n") option["description"] = help.split("\n")
return option return option
def dict(required: bool = False, help: Optional[str] = None, **options: AnsibleParameter) -> AnsibleParameter: def dict(required: bool = False, help: Optional[str] = None, **options: AnsibleParameter) -> AnsibleParameter: # type: ignore[misc]
"""Wrapper for the Ansible dict type """Wrapper for the Ansible dict type
Args: Args:

Datei anzeigen

@ -1,7 +1,6 @@
import pathlib import pathlib
from copy import deepcopy from copy import deepcopy
from typing import (Any, Callable, ClassVar, Dict, NoReturn, Optional, Type, from typing import Any, Callable, ClassVar, Dict, NoReturn, Optional, Type, TypeVar, Union, overload
TypeVar, Union, overload)
import ansible.module_utils.basic as basic import ansible.module_utils.basic as basic
@ -229,18 +228,16 @@ class SystemdUnitModule(AnsibleModule):
), ),
) )
#: if defined it will be called after run has changed the unitfile #: if defined it will be called after run has changed the unitfile
post: Optional[Callable[[], None]] post: Optional[Callable[[], None]] = None
#: generates the install section if the unit is installable #: generates the install section if the unit is installable
install: ClassVar[Optional[Callable[["SystemdUnitModule"], str]]] install: ClassVar[Optional[Callable[["SystemdUnitModule"], str | None]]] = None
def unit(self) -> str: # pragma: nocover def unit(self) -> str: # pragma: nocover
raise NotImplementedError() raise NotImplementedError()
def header(self) -> str: def header(self) -> Optional[str]:
header = "[Unit]\n" parts = self.map_param(
header += "".join(
self.map_param(
description="Description", description="Description",
documentation="Documentation", documentation="Documentation",
requires="Requires", requires="Requires",
@ -249,10 +246,19 @@ class SystemdUnitModule(AnsibleModule):
before="Before", before="Before",
after="After", after="After",
) )
) if len(parts) == 0:
return None
header = "[Unit]\n" + "".join(parts)
return header return header
def map_param(self, **parammap: str): def _unit(self, *parts: Optional[str]) -> str:
opart = []
for part in parts:
if part is not None:
opart.append(part)
return "\n".join(opart)
def map_param(self, **parammap: str) -> list[str]:
"""maps an dict with keys for an section with given params. The key of the dictionary is the parameter and the value is the key in the unitfile. If an parameter has multiple values it adds multiple entries""" """maps an dict with keys for an section with given params. The key of the dictionary is the parameter and the value is the key in the unitfile. If an parameter has multiple values it adds multiple entries"""
output: list[str] = [] output: list[str] = []
for param, key in parammap.items(): for param, key in parammap.items():
@ -264,7 +270,7 @@ class SystemdUnitModule(AnsibleModule):
output.append(f"{key}={systemdbool(params)}\n") output.append(f"{key}={systemdbool(params)}\n")
return output return output
def unitfile_gen(self): # pragma: nocover def unitfile_gen(self) -> None: # pragma: nocover
path = self.tmpdir / "newunit" path = self.tmpdir / "newunit"
with open(path, "w") as unit: with open(path, "w") as unit:
unit.write(self.unit()) unit.write(self.unit())
@ -272,7 +278,7 @@ class SystemdUnitModule(AnsibleModule):
self.module.set_group_if_different(path.as_posix(), "root", False) self.module.set_group_if_different(path.as_posix(), "root", False)
self.module.set_mode_if_different(path.as_posix(), "0644", False) self.module.set_mode_if_different(path.as_posix(), "0644", False)
if self.unitfile.exists(): if self.unitfile.exists():
diff = dict() diff: dict[str, str] = dict()
self.changed = self.changed | self.module.set_owner_if_different( self.changed = self.changed | self.module.set_owner_if_different(
self.unitfile.as_posix(), self.unitfile.as_posix(),
"root", "root",
@ -343,13 +349,15 @@ def installable(_class: Type[SystemdUnitModule]): # pragma: nocover
) )
specs["argument_spec"].update(arguments) specs["argument_spec"].update(arguments)
def install(self: SystemdUnitModule) -> str: def install(self: SystemdUnitModule) -> Optional[str]:
output = "[Install]\n" parts = []
for argument, key in _INSTALL_MAPPING.items(): for argument, key in _INSTALL_MAPPING.items():
if self.get(argument, False): if self.get(argument, False):
for unit in self.get(argument): # type: ignore for unit in self.get(argument): # type: ignore
output += "{}={}\n".format(key, unit) parts.append("{}={}\n".format(key, unit))
return output if len(parts) == 0:
return None
return "[Install]\n" + "".join(parts)
_class.install = install _class.install = install
_class.module_spec = specs _class.module_spec = specs

Datei anzeigen

@ -146,10 +146,11 @@ exclude_lines = [
] ]
[tool.mypy] [tool.mypy]
disable_error_code = "import-untyped"
python_version = "3.11" python_version = "3.11"
warn_return_any = true warn_return_any = true
warn_unused_configs = true warn_unused_configs = true
[[tool.mypy.overrides]] [[tool.mypy.overrides]]
module = ["ansible", "ansible.module_utils", "ansible.module_utils.basic"] module = ["ansible", "ansible.module_utils", "ansible.module_utils.basic"]
ignore_missing_imports = true ignore_missing_imports = true

Datei anzeigen

@ -1 +1 @@
__version__ = "0.3.1" __version__ = "0.4.0"