dynamic-settings-widget 2.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dynamic_settings_widget/__init__.py +56 -0
- dynamic_settings_widget/adapters/__init__.py +42 -0
- dynamic_settings_widget/adapters/base.py +179 -0
- dynamic_settings_widget/adapters/memory.py +201 -0
- dynamic_settings_widget/adapters/runner.py +63 -0
- dynamic_settings_widget/core/__init__.py +1 -0
- dynamic_settings_widget/core/catalog.py +201 -0
- dynamic_settings_widget/core/common.py +214 -0
- dynamic_settings_widget/core/conditions.py +146 -0
- dynamic_settings_widget/core/datatypes.py +414 -0
- dynamic_settings_widget/core/diagnostics.py +69 -0
- dynamic_settings_widget/core/loader.py +101 -0
- dynamic_settings_widget/core/model.py +245 -0
- dynamic_settings_widget/core/overrides.py +353 -0
- dynamic_settings_widget/core/parser.py +552 -0
- dynamic_settings_widget/core/presentation.py +68 -0
- dynamic_settings_widget/core/registry.py +258 -0
- dynamic_settings_widget/core/state.py +314 -0
- dynamic_settings_widget/data/example_catalog.json +23 -0
- dynamic_settings_widget/data/example_layout.json +23 -0
- dynamic_settings_widget/data/settings_catalog.schema.json +388 -0
- dynamic_settings_widget/data/settings_definition.schema.json +1041 -0
- dynamic_settings_widget/data/settings_layout.schema.json +701 -0
- dynamic_settings_widget/data/settings_override.schema.json +406 -0
- dynamic_settings_widget/py.typed +0 -0
- dynamic_settings_widget/session.py +1537 -0
- dynamic_settings_widget/standalone/__init__.py +67 -0
- dynamic_settings_widget/standalone/action_button.py +200 -0
- dynamic_settings_widget/standalone/auth_widget.py +377 -0
- dynamic_settings_widget/standalone/check_box_editor.py +233 -0
- dynamic_settings_widget/standalone/choice_buttons_editor.py +394 -0
- dynamic_settings_widget/standalone/color_editor.py +316 -0
- dynamic_settings_widget/standalone/dropdown_editor.py +356 -0
- dynamic_settings_widget/standalone/editable_label.py +428 -0
- dynamic_settings_widget/standalone/float_spin_box.py +621 -0
- dynamic_settings_widget/standalone/font_editor.py +348 -0
- dynamic_settings_widget/standalone/hotkey_editor.py +681 -0
- dynamic_settings_widget/standalone/info_label.py +190 -0
- dynamic_settings_widget/standalone/int_spin_box.py +627 -0
- dynamic_settings_widget/standalone/multi_choice_editor.py +428 -0
- dynamic_settings_widget/standalone/password_editor.py +348 -0
- dynamic_settings_widget/standalone/path_editor.py +615 -0
- dynamic_settings_widget/standalone/protected_group_box.py +287 -0
- dynamic_settings_widget/standalone/server_connection_editor.py +642 -0
- dynamic_settings_widget/standalone/slider_spin_box.py +840 -0
- dynamic_settings_widget/standalone/sound_selection_widget.py +710 -0
- dynamic_settings_widget/standalone/status_label.py +148 -0
- dynamic_settings_widget/standalone/switch_editor.py +293 -0
- dynamic_settings_widget/standalone/text_editor.py +265 -0
- dynamic_settings_widget/testlab/__init__.py +1 -0
- dynamic_settings_widget/testlab/__main__.py +5 -0
- dynamic_settings_widget/testlab/app.py +699 -0
- dynamic_settings_widget/testlab/assets/extra_sounds/Signal.wav +0 -0
- dynamic_settings_widget/testlab/assets/sounds/Benachrichtigung.wav +0 -0
- dynamic_settings_widget/testlab/assets/sounds/feedback/Signal.wav +0 -0
- dynamic_settings_widget/testlab/definitions/broken_base.json +25 -0
- dynamic_settings_widget/testlab/definitions/demo.json +634 -0
- dynamic_settings_widget/testlab/definitions/gallery.json +255 -0
- dynamic_settings_widget/testlab/definitions/override_example.json +41 -0
- dynamic_settings_widget/testlab/definitions/override_invalid.json +11 -0
- dynamic_settings_widget/testlab/definitions/override_syntax_error.json +5 -0
- dynamic_settings_widget/testlab/definitions/override_weaken.json +10 -0
- dynamic_settings_widget/testlab/definitions/voice_v2/01_left_top.json +1190 -0
- dynamic_settings_widget/testlab/definitions/voice_v2/catalog.json +1930 -0
- dynamic_settings_widget/testlab/definitions/voice_v2/models.json +141 -0
- dynamic_settings_widget/testlab/definitions/voice_v2/wakewords.json +161 -0
- dynamic_settings_widget/testlab/dummy.py +353 -0
- dynamic_settings_widget/testlab/extensions.py +149 -0
- dynamic_settings_widget/testlab/gallery.py +223 -0
- dynamic_settings_widget/testlab/http_adapter.py +430 -0
- dynamic_settings_widget/testlab/http_server.py +493 -0
- dynamic_settings_widget/testlab/voice_v2.py +251 -0
- dynamic_settings_widget/ui/__init__.py +23 -0
- dynamic_settings_widget/ui/base.py +63 -0
- dynamic_settings_widget/ui/builders.py +226 -0
- dynamic_settings_widget/ui/containers.py +441 -0
- dynamic_settings_widget/ui/dialog.py +231 -0
- dynamic_settings_widget/ui/editing.py +51 -0
- dynamic_settings_widget/ui/row.py +810 -0
- dynamic_settings_widget/ui/view.py +248 -0
- dynamic_settings_widget/widgets/__init__.py +74 -0
- dynamic_settings_widget/widgets/base.py +145 -0
- dynamic_settings_widget/widgets/bridge.py +222 -0
- dynamic_settings_widget/widgets/theme.py +107 -0
- dynamic_settings_widget-2.0.0.dist-info/METADATA +237 -0
- dynamic_settings_widget-2.0.0.dist-info/RECORD +90 -0
- dynamic_settings_widget-2.0.0.dist-info/WHEEL +5 -0
- dynamic_settings_widget-2.0.0.dist-info/entry_points.txt +5 -0
- dynamic_settings_widget-2.0.0.dist-info/licenses/LICENSE +21 -0
- dynamic_settings_widget-2.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
"""Datentypen, Wertegrenzen und strikte Validierung.
|
|
2
|
+
|
|
3
|
+
Datentyp (was ist der Wert?) und Widget (wie wird er bearbeitet?) sind getrennt.
|
|
4
|
+
Werte werden nie stillschweigend umgewandelt oder auf Grenzen gekappt.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
import re
|
|
11
|
+
from collections.abc import Callable, Sequence
|
|
12
|
+
from dataclasses import dataclass, fields, replace
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from .common import SECRET_SET, UNSET, SecretValue
|
|
16
|
+
|
|
17
|
+
#: Größter in Qt-Spinboxen exakt darstellbarer Ganzzahlbetrag.
|
|
18
|
+
MAX_SAFE_INT = 2**53
|
|
19
|
+
|
|
20
|
+
DEFAULT_WIDGETS: dict[str, str] = {
|
|
21
|
+
"bool": "checkbox",
|
|
22
|
+
"int": "int_spin",
|
|
23
|
+
"float": "float_spin",
|
|
24
|
+
"string": "text",
|
|
25
|
+
"secret": "password",
|
|
26
|
+
"color": "color",
|
|
27
|
+
"font": "font",
|
|
28
|
+
"path": "path",
|
|
29
|
+
"hotkey": "hotkey",
|
|
30
|
+
"choice": "dropdown",
|
|
31
|
+
"multi_choice": "multi_choice",
|
|
32
|
+
"connection": "server_connection",
|
|
33
|
+
}
|
|
34
|
+
DATATYPES = frozenset(DEFAULT_WIDGETS)
|
|
35
|
+
|
|
36
|
+
#: Metadaten-Datentyp → lokal zulässige, gleich strenge oder strengere Datentypen.
|
|
37
|
+
_COMPATIBLE: dict[str, frozenset[str]] = {
|
|
38
|
+
"string": frozenset({"string", "secret", "color", "font", "path", "hotkey", "choice"}),
|
|
39
|
+
"int": frozenset({"int", "choice"}),
|
|
40
|
+
"float": frozenset({"float", "choice"}),
|
|
41
|
+
"bool": frozenset({"bool", "choice"}),
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
_TEXT_TYPES = frozenset({"string", "secret", "font", "path", "hotkey"})
|
|
45
|
+
_COLOR = re.compile(r"#[0-9A-Fa-f]{6}")
|
|
46
|
+
_COLOR_ALPHA = re.compile(r"#(?:[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _is_number(value: Any) -> bool:
|
|
50
|
+
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _not_finite(value: Any) -> bool:
|
|
54
|
+
return isinstance(value, float) and not math.isfinite(value)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _is_scalar(value: Any) -> bool:
|
|
58
|
+
return isinstance(value, (str, int, float, bool)) and not _not_finite(value)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass(frozen=True)
|
|
62
|
+
class Option:
|
|
63
|
+
"""Ein auswählbarer, beschrifteter Wert."""
|
|
64
|
+
|
|
65
|
+
value: Any
|
|
66
|
+
label: str
|
|
67
|
+
description: str = ""
|
|
68
|
+
available: bool = True
|
|
69
|
+
unavailable_reason: str = ""
|
|
70
|
+
|
|
71
|
+
@classmethod
|
|
72
|
+
def parse(cls, raw: Any) -> "Option":
|
|
73
|
+
"""Akzeptiert einen Skalar oder ``{"value", "label", "description"}``."""
|
|
74
|
+
if isinstance(raw, Option):
|
|
75
|
+
if type(raw.available) is not bool or not isinstance(raw.unavailable_reason, str):
|
|
76
|
+
raise ValueError("Auswahloption: available muss boolesch und unavailable_reason Text sein")
|
|
77
|
+
return raw
|
|
78
|
+
available, reason = True, ""
|
|
79
|
+
if isinstance(raw, dict):
|
|
80
|
+
if set(raw) - {"value", "label", "description", "available", "unavailable_reason"} or "value" not in raw:
|
|
81
|
+
raise ValueError("Auswahloption: erwartet value, label, description, available, unavailable_reason")
|
|
82
|
+
value = raw["value"]
|
|
83
|
+
label = raw.get("label", str(value))
|
|
84
|
+
description = raw.get("description", "")
|
|
85
|
+
available = raw.get("available", True)
|
|
86
|
+
reason = raw.get("unavailable_reason", "")
|
|
87
|
+
else:
|
|
88
|
+
value, label, description = raw, str(raw), ""
|
|
89
|
+
if not _is_scalar(value):
|
|
90
|
+
raise ValueError(f"Auswahlwert {value!r} muss Text, Zahl oder Wahrheitswert sein")
|
|
91
|
+
if not isinstance(label, str) or not isinstance(description, str):
|
|
92
|
+
raise ValueError(f"Auswahloption {value!r}: label/description müssen Text sein")
|
|
93
|
+
if type(available) is not bool or not isinstance(reason, str):
|
|
94
|
+
raise ValueError("Auswahloption: available muss boolesch und unavailable_reason Text sein")
|
|
95
|
+
return cls(value, label, description, available, reason)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass(frozen=True)
|
|
99
|
+
class Constraints:
|
|
100
|
+
"""Fachliche Grenzen eines Werts."""
|
|
101
|
+
|
|
102
|
+
optional: bool = False
|
|
103
|
+
min: float | int | None = None
|
|
104
|
+
max: float | int | None = None
|
|
105
|
+
step: float | int | None = None
|
|
106
|
+
precision: int | None = None
|
|
107
|
+
unit: str = ""
|
|
108
|
+
min_length: int | None = None
|
|
109
|
+
max_length: int | None = None
|
|
110
|
+
pattern: str | None = None
|
|
111
|
+
min_items: int | None = None
|
|
112
|
+
max_items: int | None = None
|
|
113
|
+
alpha: bool = False
|
|
114
|
+
choices: tuple[Option, ...] | None = None
|
|
115
|
+
|
|
116
|
+
def merged(self, **changes: Any) -> "Constraints":
|
|
117
|
+
return replace(self, **changes)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
CONSTRAINT_FIELDS = frozenset(f.name for f in fields(Constraints))
|
|
121
|
+
|
|
122
|
+
#: Welche Grenzen zu welchem Datentyp passen (``optional`` passt immer).
|
|
123
|
+
APPLICABLE: dict[str, frozenset[str]] = {
|
|
124
|
+
"bool": frozenset(),
|
|
125
|
+
"int": frozenset({"min", "max", "step", "unit"}),
|
|
126
|
+
"float": frozenset({"min", "max", "step", "unit", "precision"}),
|
|
127
|
+
"string": frozenset({"min_length", "max_length", "pattern"}),
|
|
128
|
+
"secret": frozenset({"min_length", "max_length", "pattern"}),
|
|
129
|
+
"path": frozenset({"min_length", "max_length", "pattern"}),
|
|
130
|
+
"font": frozenset(),
|
|
131
|
+
"hotkey": frozenset(),
|
|
132
|
+
"color": frozenset({"alpha"}),
|
|
133
|
+
"choice": frozenset({"choices"}),
|
|
134
|
+
"multi_choice": frozenset({"choices", "min_items", "max_items"}),
|
|
135
|
+
"connection": frozenset(),
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
_RANGES = (("min", "max"), ("min_length", "max_length"), ("min_items", "max_items"))
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def same(a: Any, b: Any) -> bool:
|
|
142
|
+
"""Gleichheit ohne Pythons ``True == 1``-Vermischung."""
|
|
143
|
+
if a is b:
|
|
144
|
+
return True
|
|
145
|
+
if a is UNSET or b is UNSET or isinstance(a, bool) != isinstance(b, bool):
|
|
146
|
+
return False
|
|
147
|
+
if isinstance(a, list) and isinstance(b, list):
|
|
148
|
+
return len(a) == len(b) and all(same(x, y) for x, y in zip(a, b))
|
|
149
|
+
if isinstance(a, dict) and isinstance(b, dict):
|
|
150
|
+
return a.keys() == b.keys() and all(same(a[k], b[k]) for k in a)
|
|
151
|
+
return bool(a == b)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def values_equal(datatype: str, a: Any, b: Any) -> bool:
|
|
155
|
+
if datatype == "color" and isinstance(a, str) and isinstance(b, str):
|
|
156
|
+
return a.casefold() == b.casefold()
|
|
157
|
+
if datatype == "multi_choice" and isinstance(a, list) and isinstance(b, list):
|
|
158
|
+
return len(a) == len(b) and all(any(same(x, y) for y in b) for x in a)
|
|
159
|
+
return same(a, b)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def format_number(value: float | int) -> str:
|
|
163
|
+
return str(value) if isinstance(value, int) else f"{value:.12g}"
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def validate_value(datatype: str, constraints: Constraints, value: Any) -> str | None:
|
|
167
|
+
"""Prüft strikt; liefert eine Fehlermeldung oder ``None``."""
|
|
168
|
+
c = constraints
|
|
169
|
+
if value is UNSET:
|
|
170
|
+
return "Kein Wert vorhanden"
|
|
171
|
+
if value is None:
|
|
172
|
+
return None if c.optional else "Ein Wert ist erforderlich"
|
|
173
|
+
|
|
174
|
+
if datatype == "bool":
|
|
175
|
+
return None if isinstance(value, bool) else "Wahrheitswert (true/false) erwartet"
|
|
176
|
+
|
|
177
|
+
if datatype in ("int", "float"):
|
|
178
|
+
if datatype == "int" and (not isinstance(value, int) or isinstance(value, bool)):
|
|
179
|
+
return "Ganzzahl erwartet"
|
|
180
|
+
if datatype == "float" and not _is_number(value):
|
|
181
|
+
return "Zahl erwartet"
|
|
182
|
+
if _not_finite(value):
|
|
183
|
+
return "Endliche Zahl erwartet"
|
|
184
|
+
if datatype == "int" and abs(value) > MAX_SAFE_INT:
|
|
185
|
+
return "Ganzzahl außerhalb des darstellbaren Bereichs (±2^53)"
|
|
186
|
+
if c.min is not None and value < c.min:
|
|
187
|
+
return f"Wert {format_number(value)} unterschreitet das Minimum {format_number(c.min)}"
|
|
188
|
+
if c.max is not None and value > c.max:
|
|
189
|
+
return f"Wert {format_number(value)} überschreitet das Maximum {format_number(c.max)}"
|
|
190
|
+
return None
|
|
191
|
+
|
|
192
|
+
if datatype in _TEXT_TYPES:
|
|
193
|
+
if value is SECRET_SET:
|
|
194
|
+
return None if datatype == "secret" else "Text erwartet"
|
|
195
|
+
if datatype == "secret" and isinstance(value, SecretValue):
|
|
196
|
+
value = value.reveal()
|
|
197
|
+
if not isinstance(value, str):
|
|
198
|
+
return "Text erwartet"
|
|
199
|
+
if c.min_length is not None and len(value) < c.min_length:
|
|
200
|
+
return "Eingabe erforderlich" if c.min_length == 1 else f"Mindestens {c.min_length} Zeichen erforderlich"
|
|
201
|
+
if c.max_length is not None and len(value) > c.max_length:
|
|
202
|
+
return f"Höchstens {c.max_length} Zeichen erlaubt"
|
|
203
|
+
if c.pattern is not None and re.fullmatch(c.pattern, value) is None:
|
|
204
|
+
return "Eingabe entspricht nicht dem erlaubten Format"
|
|
205
|
+
if datatype == "hotkey" and not value:
|
|
206
|
+
return "Eine Tastenkombination ist erforderlich"
|
|
207
|
+
return None
|
|
208
|
+
|
|
209
|
+
if datatype == "color":
|
|
210
|
+
if isinstance(value, str) and (_COLOR_ALPHA if c.alpha else _COLOR).fullmatch(value):
|
|
211
|
+
return None
|
|
212
|
+
return "Farbe im Format #RRGGBB" + (" oder #AARRGGBB" if c.alpha else "") + " erwartet"
|
|
213
|
+
|
|
214
|
+
if datatype == "choice":
|
|
215
|
+
if not _is_scalar(value):
|
|
216
|
+
return "Skalarer Auswahlwert erwartet"
|
|
217
|
+
if c.choices is not None and not any(same(value, o.value) for o in c.choices):
|
|
218
|
+
return f"{value!r} ist keine erlaubte Auswahl"
|
|
219
|
+
return None
|
|
220
|
+
|
|
221
|
+
if datatype == "multi_choice":
|
|
222
|
+
if not isinstance(value, list):
|
|
223
|
+
return "Liste erwartet"
|
|
224
|
+
seen: list[Any] = []
|
|
225
|
+
for item in value:
|
|
226
|
+
if not _is_scalar(item):
|
|
227
|
+
return "Liste skalarer Werte erwartet"
|
|
228
|
+
if any(same(item, s) for s in seen):
|
|
229
|
+
return f"{item!r} ist mehrfach enthalten"
|
|
230
|
+
seen.append(item)
|
|
231
|
+
if c.choices is not None and not any(same(item, o.value) for o in c.choices):
|
|
232
|
+
return f"{item!r} ist keine erlaubte Auswahl"
|
|
233
|
+
if c.min_items is not None and len(value) < c.min_items:
|
|
234
|
+
return f"Mindestens {c.min_items} auswählen"
|
|
235
|
+
if c.max_items is not None and len(value) > c.max_items:
|
|
236
|
+
return f"Höchstens {c.max_items} auswählen"
|
|
237
|
+
return None
|
|
238
|
+
|
|
239
|
+
if datatype == "connection":
|
|
240
|
+
if (
|
|
241
|
+
isinstance(value, dict)
|
|
242
|
+
and set(value) == {"address", "endpoint"}
|
|
243
|
+
and all(isinstance(v, str) for v in value.values())
|
|
244
|
+
):
|
|
245
|
+
return None
|
|
246
|
+
return "Verbindung mit address und endpoint erwartet"
|
|
247
|
+
|
|
248
|
+
return f"Unbekannter Datentyp {datatype!r}"
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def parse_options(raw: Any) -> tuple[tuple[Option, ...], str | None]:
|
|
252
|
+
"""Liest eine Optionsliste; liefert Optionen und ggf. eine Fehlermeldung."""
|
|
253
|
+
if not isinstance(raw, Sequence) or isinstance(raw, str):
|
|
254
|
+
return (), "„choices“ muss eine Liste sein"
|
|
255
|
+
options: list[Option] = []
|
|
256
|
+
for item in raw:
|
|
257
|
+
try:
|
|
258
|
+
option = Option.parse(item)
|
|
259
|
+
except ValueError as exc:
|
|
260
|
+
return (), str(exc)
|
|
261
|
+
if any(same(option.value, o.value) for o in options):
|
|
262
|
+
return (), f"Auswahlwert {option.value!r} ist mehrfach vorhanden"
|
|
263
|
+
options.append(option)
|
|
264
|
+
return tuple(options), None
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def validate_selection_change(datatype: str, constraints: Constraints, value: Any, previous: Any) -> str | None:
|
|
268
|
+
"""Prüft eine neue Auswahl und lässt bisherige, veraltete Listeneinträge stehen."""
|
|
269
|
+
choices = constraints.choices
|
|
270
|
+
if choices is None or value is None or datatype not in ("choice", "multi_choice"):
|
|
271
|
+
return validate_value(datatype, constraints, value)
|
|
272
|
+
if datatype == "multi_choice" and isinstance(previous, list):
|
|
273
|
+
choices += tuple(Option(item, str(item), available=False) for item in previous
|
|
274
|
+
if _is_scalar(item) and not any(same(item, option.value) for option in choices))
|
|
275
|
+
error = validate_value(datatype, constraints.merged(choices=choices), value)
|
|
276
|
+
if error:
|
|
277
|
+
return error
|
|
278
|
+
selected = value if datatype == "multi_choice" else [value]
|
|
279
|
+
retained = previous if datatype == "multi_choice" and isinstance(previous, list) else [previous]
|
|
280
|
+
for item in selected:
|
|
281
|
+
option = next(option for option in choices if same(item, option.value))
|
|
282
|
+
if not option.available and not any(same(item, before) for before in retained):
|
|
283
|
+
return option.unavailable_reason or "Auswahlwert ist derzeit nicht verfügbar"
|
|
284
|
+
return None
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _check_field(datatype: str, name: str, value: Any) -> str | None:
|
|
288
|
+
"""Liefert die verletzte Erwartung oder ``None``."""
|
|
289
|
+
if name in ("optional", "alpha"):
|
|
290
|
+
return None if isinstance(value, bool) else "true oder false"
|
|
291
|
+
if name in ("min", "max", "step"):
|
|
292
|
+
if datatype == "int":
|
|
293
|
+
if not isinstance(value, int) or isinstance(value, bool) or abs(value) > MAX_SAFE_INT:
|
|
294
|
+
return "eine Ganzzahl (±2^53)"
|
|
295
|
+
elif not _is_number(value) or _not_finite(value):
|
|
296
|
+
return "eine endliche Zahl"
|
|
297
|
+
return "größer als 0" if name == "step" and value <= 0 else None
|
|
298
|
+
if name == "precision":
|
|
299
|
+
ok = isinstance(value, int) and not isinstance(value, bool) and 0 <= value <= 12
|
|
300
|
+
return None if ok else "eine Ganzzahl von 0 bis 12"
|
|
301
|
+
if name in ("min_length", "max_length", "min_items", "max_items"):
|
|
302
|
+
ok = isinstance(value, int) and not isinstance(value, bool) and value >= 0
|
|
303
|
+
return None if ok else "eine Ganzzahl ab 0"
|
|
304
|
+
if not isinstance(value, str):
|
|
305
|
+
return "Text"
|
|
306
|
+
if name == "pattern":
|
|
307
|
+
try:
|
|
308
|
+
re.compile(value)
|
|
309
|
+
except re.error as exc:
|
|
310
|
+
return f"ein gültiger regulärer Ausdruck ({exc})"
|
|
311
|
+
return None
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def check_constraints(datatype: str, raw: dict[str, Any]) -> tuple[Constraints, list[str]]:
|
|
315
|
+
"""Liest Grenzen aus Rohdaten; liefert sie zusammen mit Fehlermeldungen."""
|
|
316
|
+
errors: list[str] = []
|
|
317
|
+
values: dict[str, Any] = {}
|
|
318
|
+
allowed = APPLICABLE.get(datatype, frozenset()) | {"optional"}
|
|
319
|
+
for name in sorted(CONSTRAINT_FIELDS & raw.keys()):
|
|
320
|
+
value = raw[name]
|
|
321
|
+
if value is None:
|
|
322
|
+
continue
|
|
323
|
+
if name not in allowed:
|
|
324
|
+
errors.append(f"„{name}“ ist für Datentyp {datatype!r} nicht zulässig")
|
|
325
|
+
elif name == "choices":
|
|
326
|
+
values[name], problem = parse_options(value)
|
|
327
|
+
if problem:
|
|
328
|
+
errors.append(problem)
|
|
329
|
+
elif expected := _check_field(datatype, name, value):
|
|
330
|
+
errors.append(f"„{name}“ muss {expected} sein, ist aber {value!r}")
|
|
331
|
+
else:
|
|
332
|
+
values[name] = value
|
|
333
|
+
result = Constraints(**values)
|
|
334
|
+
for low, high in _RANGES:
|
|
335
|
+
a, b = getattr(result, low), getattr(result, high)
|
|
336
|
+
if a is not None and b is not None and a > b:
|
|
337
|
+
errors.append(f"„{low}“ ({a}) ist größer als „{high}“ ({b})")
|
|
338
|
+
return result, errors
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def datatype_compatible(local: str, remote: str) -> bool:
|
|
342
|
+
"""Darf ein lokal als ``local`` beschriebener Wert einen ``remote``-Parameter darstellen?"""
|
|
343
|
+
return local == remote or local in _COMPATIBLE.get(remote, ())
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def _tighter(a: Any, b: Any, pick: Callable[[Any, Any], Any]) -> Any:
|
|
347
|
+
return b if a is None else a if b is None else pick(a, b)
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def intersect(local: Constraints, trusted: Constraints) -> tuple[Constraints, str | None]:
|
|
351
|
+
"""Schnittmenge aus lokalen und verbindlichen Grenzen – es gilt stets die strengere.
|
|
352
|
+
|
|
353
|
+
Darstellungsangaben (Einheit, Schrittweite, Präzision) gewinnen lokal.
|
|
354
|
+
"""
|
|
355
|
+
choices = local.choices
|
|
356
|
+
if trusted.choices is not None:
|
|
357
|
+
if choices is None:
|
|
358
|
+
choices = trusted.choices
|
|
359
|
+
else:
|
|
360
|
+
choices = tuple(
|
|
361
|
+
replace(o, available=False, unavailable_reason=t.unavailable_reason or o.unavailable_reason)
|
|
362
|
+
if not t.available else o
|
|
363
|
+
for o in choices for t in trusted.choices if same(o.value, t.value)
|
|
364
|
+
)
|
|
365
|
+
if not choices:
|
|
366
|
+
return local, "Lokale und vom Adapter erlaubte Auswahlwerte überschneiden sich nicht"
|
|
367
|
+
pattern = local.pattern
|
|
368
|
+
if trusted.pattern is not None and pattern != trusted.pattern:
|
|
369
|
+
pattern = trusted.pattern if pattern is None else f"(?=(?:{trusted.pattern})\\Z)(?:{pattern})"
|
|
370
|
+
result = Constraints(
|
|
371
|
+
optional=local.optional and trusted.optional,
|
|
372
|
+
min=_tighter(local.min, trusted.min, max),
|
|
373
|
+
max=_tighter(local.max, trusted.max, min),
|
|
374
|
+
step=local.step if local.step is not None else trusted.step,
|
|
375
|
+
precision=local.precision if local.precision is not None else trusted.precision,
|
|
376
|
+
unit=local.unit or trusted.unit,
|
|
377
|
+
min_length=_tighter(local.min_length, trusted.min_length, max),
|
|
378
|
+
max_length=_tighter(local.max_length, trusted.max_length, min),
|
|
379
|
+
pattern=pattern,
|
|
380
|
+
min_items=_tighter(local.min_items, trusted.min_items, max),
|
|
381
|
+
max_items=_tighter(local.max_items, trusted.max_items, min),
|
|
382
|
+
alpha=local.alpha and trusted.alpha,
|
|
383
|
+
choices=choices,
|
|
384
|
+
)
|
|
385
|
+
for low, high in _RANGES:
|
|
386
|
+
a, b = getattr(result, low), getattr(result, high)
|
|
387
|
+
if a is not None and b is not None and a > b:
|
|
388
|
+
return local, f"Lokale und vom Adapter gelieferte Grenzen ({low}/{high}) schließen sich aus"
|
|
389
|
+
return result, None
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def weakened(base: Constraints, changed: Constraints) -> list[str]:
|
|
393
|
+
"""Nennt alle Grenzen, die ``changed`` gegenüber ``base`` lockert."""
|
|
394
|
+
out: list[str] = []
|
|
395
|
+
if changed.optional and not base.optional:
|
|
396
|
+
out.append("optional")
|
|
397
|
+
if changed.alpha and not base.alpha:
|
|
398
|
+
out.append("alpha")
|
|
399
|
+
for low, high in _RANGES:
|
|
400
|
+
a, b = getattr(base, low), getattr(changed, low)
|
|
401
|
+
if a is not None and (b is None or b < a):
|
|
402
|
+
out.append(low)
|
|
403
|
+
a, b = getattr(base, high), getattr(changed, high)
|
|
404
|
+
if a is not None and (b is None or b > a):
|
|
405
|
+
out.append(high)
|
|
406
|
+
if base.pattern is not None and changed.pattern != base.pattern:
|
|
407
|
+
out.append("pattern")
|
|
408
|
+
if base.choices is not None and (
|
|
409
|
+
changed.choices is None
|
|
410
|
+
or any(not any(same(o.value, b.value) and (b.available or not o.available) for b in base.choices)
|
|
411
|
+
for o in changed.choices)
|
|
412
|
+
):
|
|
413
|
+
out.append("choices")
|
|
414
|
+
return out
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Verständliche Diagnosen für Definitionen, Overrides und Metadaten."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from enum import Enum
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Severity(str, Enum):
|
|
11
|
+
ERROR = "error"
|
|
12
|
+
WARNING = "warning"
|
|
13
|
+
INFO = "info"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class Diagnostic:
|
|
18
|
+
severity: Severity
|
|
19
|
+
code: str
|
|
20
|
+
message: str
|
|
21
|
+
source: str = ""
|
|
22
|
+
location: str = ""
|
|
23
|
+
|
|
24
|
+
def __str__(self) -> str:
|
|
25
|
+
label = {"error": "Fehler", "warning": "Warnung", "info": "Hinweis"}[self.severity.value]
|
|
26
|
+
where = " · ".join(part for part in (self.source, self.location) if part)
|
|
27
|
+
return f"{label} [{self.code}]{' ' + where if where else ''}: {self.message}"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Diagnostics:
|
|
31
|
+
"""Sammelt Diagnosen, damit alle Fehler einer Datei gemeinsam gemeldet werden."""
|
|
32
|
+
|
|
33
|
+
def __init__(self, source: str = "") -> None:
|
|
34
|
+
self.source = source
|
|
35
|
+
self.items: list[Diagnostic] = []
|
|
36
|
+
|
|
37
|
+
def _add(self, severity: Severity, code: str, message: str, location: str) -> None:
|
|
38
|
+
item = Diagnostic(severity, code, message, self.source, location)
|
|
39
|
+
if item not in self.items:
|
|
40
|
+
self.items.append(item)
|
|
41
|
+
|
|
42
|
+
def error(self, code: str, message: str, location: str = "") -> None:
|
|
43
|
+
self._add(Severity.ERROR, code, message, location)
|
|
44
|
+
|
|
45
|
+
def warning(self, code: str, message: str, location: str = "") -> None:
|
|
46
|
+
self._add(Severity.WARNING, code, message, location)
|
|
47
|
+
|
|
48
|
+
def info(self, code: str, message: str, location: str = "") -> None:
|
|
49
|
+
self._add(Severity.INFO, code, message, location)
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def errors(self) -> list[Diagnostic]:
|
|
53
|
+
return [item for item in self.items if item.severity is Severity.ERROR]
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def has_errors(self) -> bool:
|
|
57
|
+
return bool(self.errors)
|
|
58
|
+
|
|
59
|
+
def raise_if_errors(self) -> None:
|
|
60
|
+
if self.has_errors:
|
|
61
|
+
raise DefinitionError(self.items)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class DefinitionError(ValueError):
|
|
65
|
+
"""Eine Definition oder ein Override ist nicht verwendbar."""
|
|
66
|
+
|
|
67
|
+
def __init__(self, diagnostics: Iterable[Diagnostic]) -> None:
|
|
68
|
+
self.diagnostics = list(diagnostics)
|
|
69
|
+
super().__init__("\n".join(str(d) for d in self.diagnostics) or "Ungültige Definition")
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Laden von Basisdefinition und Overrides mit sicherem Rückfall auf die Basis."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from .diagnostics import DefinitionError, Diagnostic, Diagnostics, Severity
|
|
12
|
+
from .model import SettingsTree
|
|
13
|
+
from .overrides import apply_override
|
|
14
|
+
from .parser import load_json, parse_document
|
|
15
|
+
from .registry import TypeRegistry
|
|
16
|
+
|
|
17
|
+
#: Umgebungsvariable mit dem Pfad einer optionalen Override-Datei.
|
|
18
|
+
OVERRIDE_ENV = "DYNAMIC_SETTINGS_OVERRIDE"
|
|
19
|
+
|
|
20
|
+
Source = str | Path | Mapping[str, Any]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class LoadResult:
|
|
25
|
+
"""Ergebnis eines Ladevorgangs.
|
|
26
|
+
|
|
27
|
+
``tree`` ist stets vollständig und gültig: Schlägt der Override fehl, gilt
|
|
28
|
+
unverändert die Basisdefinition und ``override_error`` ist gesetzt.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
tree: SettingsTree
|
|
32
|
+
raw: dict[str, Any]
|
|
33
|
+
base_source: str
|
|
34
|
+
override_sources: list[str] = field(default_factory=list)
|
|
35
|
+
override_applied: bool = False
|
|
36
|
+
override_error: DefinitionError | None = None
|
|
37
|
+
diagnostics: list[Diagnostic] = field(default_factory=list)
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def errors(self) -> list[Diagnostic]:
|
|
41
|
+
return [d for d in self.diagnostics if d.severity is Severity.ERROR]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _read(source: Source) -> tuple[Any, str]:
|
|
45
|
+
if isinstance(source, Mapping):
|
|
46
|
+
return dict(source), "<Daten>"
|
|
47
|
+
return load_json(source), str(source)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def load_definitions(
|
|
51
|
+
base: Source,
|
|
52
|
+
override: Source | Sequence[Source] | None = None,
|
|
53
|
+
*,
|
|
54
|
+
registry: TypeRegistry,
|
|
55
|
+
use_env: bool = True,
|
|
56
|
+
environ: Mapping[str, str] | None = None,
|
|
57
|
+
_validate_override: Callable[[SettingsTree, Diagnostics], None] | None = None,
|
|
58
|
+
) -> LoadResult:
|
|
59
|
+
"""Lädt eine Definition und wendet optional Overrides an.
|
|
60
|
+
|
|
61
|
+
Vorrang: Ein ausdrücklich übergebener ``override`` (auch als Liste, spätere
|
|
62
|
+
gewinnen) ersetzt die Angabe in :data:`OVERRIDE_ENV`. Fehler in der Basis
|
|
63
|
+
werden als :class:`DefinitionError` gemeldet, Fehler im Override führen zum
|
|
64
|
+
vollständigen Rückfall auf die Basis.
|
|
65
|
+
"""
|
|
66
|
+
base_raw, base_name = _read(base)
|
|
67
|
+
tree, diag = parse_document(base_raw, registry, base_name)
|
|
68
|
+
result = LoadResult(tree, base_raw, base_name, diagnostics=list(diag.items))
|
|
69
|
+
|
|
70
|
+
sources: list[Source] = []
|
|
71
|
+
if override is not None:
|
|
72
|
+
sources = [override] if isinstance(override, (str, Path, Mapping)) else list(override)
|
|
73
|
+
elif use_env:
|
|
74
|
+
path = (environ if environ is not None else os.environ).get(OVERRIDE_ENV, "").strip()
|
|
75
|
+
if path:
|
|
76
|
+
sources = [path]
|
|
77
|
+
if not sources:
|
|
78
|
+
return result
|
|
79
|
+
|
|
80
|
+
current_raw, merged = base_raw, tree
|
|
81
|
+
collected: list[Diagnostic] = []
|
|
82
|
+
result.override_sources = [s if isinstance(s, str) else "<Daten>" if isinstance(s, Mapping) else str(s) for s in sources]
|
|
83
|
+
try:
|
|
84
|
+
for source in sources:
|
|
85
|
+
override_raw, name = _read(source)
|
|
86
|
+
# Geprüft wird immer gegen die ursprüngliche, vertrauenswürdige Basis.
|
|
87
|
+
current_raw, merged, override_diag = apply_override(current_raw, override_raw, tree, registry, name)
|
|
88
|
+
if _validate_override is not None:
|
|
89
|
+
_validate_override(merged, override_diag)
|
|
90
|
+
override_diag.raise_if_errors()
|
|
91
|
+
collected = override_diag.items
|
|
92
|
+
except DefinitionError as exc:
|
|
93
|
+
result.override_error = exc
|
|
94
|
+
result.diagnostics.extend(exc.diagnostics)
|
|
95
|
+
notice = Diagnostics("Override")
|
|
96
|
+
notice.warning("override-rejected", "Der Override wurde vollständig verworfen; es gilt die Basisdefinition.")
|
|
97
|
+
result.diagnostics.extend(notice.items)
|
|
98
|
+
return result
|
|
99
|
+
result.tree, result.raw, result.override_applied = merged, current_raw, True
|
|
100
|
+
result.diagnostics.extend(d for d in collected if d not in result.diagnostics)
|
|
101
|
+
return result
|