Add unknown_whitelist_manager/src/unknown_whitelist_manager/core.py

This commit is contained in:
Mika 2026-02-11 12:51:45 +00:00
parent 137d2c72de
commit ba5080c9c5

View file

@ -0,0 +1,59 @@
import json
from pathlib import Path
from dataclasses import dataclass
from typing import List
@dataclass
class WhitelistEntry:
"""Datenmodell für einen Eintrag in der Whitelist."""
entry: str
def __post_init__(self) -> None:
if not isinstance(self.entry, str) or not self.entry.strip():
raise ValueError("WhitelistEntry 'entry' must be a non-empty string.")
def _load_whitelist(whitelist_path: Path) -> List[dict]:
"""Hilfsfunktion: Lade bestehende Whitelist als Liste von Dicts."""
if not whitelist_path.exists():
return []
try:
with whitelist_path.open('r', encoding='utf-8') as f:
data = json.load(f)
if not isinstance(data, list):
raise ValueError("Whitelist file format invalid: must be a list.")
return data
except json.JSONDecodeError as exc:
raise ValueError(f"Invalid JSON in whitelist file: {exc}") from exc
def _save_whitelist(whitelist_path: Path, data: List[dict]) -> None:
"""Hilfsfunktion: Schreibe aktualisierte Whitelist in Datei."""
with whitelist_path.open('w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
def update_whitelist(whitelist_path: str, entry: WhitelistEntry) -> None:
"""Aktualisiert die bestehende Whitelist-Datei mit einem neuen Eintrag, sofern dieser noch nicht vorhanden ist.
Args:
whitelist_path: Pfad zur JSON-Whitelist-Datei.
entry: WhitelistEntry-Objekt mit Beschreibung des Unknown-Falls.
Raises:
ValueError: Wenn Eingabedaten oder Dateiinhalt ungültig sind.
OSError: Wenn Dateioperationen fehlschlagen.
"""
path = Path(whitelist_path)
whitelist_data = _load_whitelist(path)
# Sicherstellen, dass keine doppelten Einträge eingefügt werden
existing_entries = {item.get('entry') for item in whitelist_data if isinstance(item, dict)}
if entry.entry not in existing_entries:
whitelist_data.append({'entry': entry.entry})
_save_whitelist(path, whitelist_data)
# CI-Integrity Check
assert path.exists(), f"Whitelist file {path} must exist after update."