|
3 | 3 | # This file is part of Checkmk (https://checkmk.com). It is subject to the terms and |
4 | 4 | # conditions defined in the file COPYING, which is part of this source code package. |
5 | 5 | import ipaddress |
6 | | -from collections.abc import Callable |
| 6 | +from collections.abc import Callable, Mapping |
7 | 7 | from dataclasses import dataclass |
8 | 8 | from typing import Literal |
9 | 9 |
|
@@ -49,6 +49,34 @@ def _with_type_check(value: T) -> object: |
49 | 49 | ) |
50 | 50 |
|
51 | 51 |
|
| 52 | +@dataclass(slots=True) |
| 53 | +class RegistryConverter[T]: |
| 54 | + registry_or_getter: Mapping[str, T] | Callable[[], Mapping[str, T]] |
| 55 | + custom_error_message: str | None = None |
| 56 | + |
| 57 | + @property |
| 58 | + def _registry(self) -> Mapping[str, T]: |
| 59 | + if not isinstance(self.registry_or_getter, Mapping): |
| 60 | + self.registry_or_getter = self.registry_or_getter() |
| 61 | + |
| 62 | + return self.registry_or_getter |
| 63 | + |
| 64 | + def validate(self, value: str) -> str: |
| 65 | + """Validates that the given value is in the registry.""" |
| 66 | + if value not in self._registry: |
| 67 | + raise ValueError( |
| 68 | + self.custom_error_message |
| 69 | + or f"Value {value!r} is not allowed, valid options are: {', '.join(sorted(self._registry))}" |
| 70 | + ) |
| 71 | + |
| 72 | + return value |
| 73 | + |
| 74 | + def value(self, value: str) -> T: |
| 75 | + """Returns the value from the registry.""" |
| 76 | + self.validate(value) |
| 77 | + return self._registry[value] |
| 78 | + |
| 79 | + |
52 | 80 | @dataclass(slots=True) |
53 | 81 | class HostConverter: |
54 | 82 | type PermissionType = Literal["setup_write", "setup_read", "monitor"] |
|
0 commit comments