""" sn_basis/functions/sys_wrapper.py – System- und Pfad-Abstraktion """ from pathlib import Path from typing import Union import sys _PathLike = Union[str, Path] # --------------------------------------------------------- # Plugin Root # --------------------------------------------------------- def get_plugin_root() -> Path: """ Liefert das Basisverzeichnis des Plugins. """ return Path(__file__).resolve().parents[2] # --------------------------------------------------------- # Pfad-Utilities # --------------------------------------------------------- def join_path(*parts: _PathLike) -> Path: """ Verbindet Pfadbestandteile OS-sicher. """ path = Path(parts[0]) for part in parts[1:]: path /= part return path def file_exists(path: _PathLike) -> bool: """ Prüft, ob eine Datei existiert. """ try: return Path(path).exists() except Exception: return False def ensure_dir(path: _PathLike) -> Path: """ Stellt sicher, dass ein Verzeichnis existiert. """ p = Path(path) p.mkdir(parents=True, exist_ok=True) return p # --------------------------------------------------------- # Datei-IO # --------------------------------------------------------- def read_text(path: _PathLike, encoding: str = "utf-8") -> str: """ Liest eine Textdatei. """ try: return Path(path).read_text(encoding=encoding) except Exception: return "" def write_text( path: _PathLike, content: str, encoding: str = "utf-8", ) -> bool: """ Schreibt eine Textdatei. """ try: Path(path).write_text(content, encoding=encoding) return True except Exception: return False def add_to_sys_path(path: Union[str, Path]) -> None: """ Fügt einen Pfad zu sys.path hinzu, falls er noch nicht enthalten ist. """ p = str(path) if p not in sys.path: sys.path.insert(0, p) def getattr_safe(obj, attr, default=None): """ Sicherer Zugriff auf ein Attribut. Gibt das Attribut zurück, wenn es existiert, ansonsten den Default-Wert (None, wenn nicht angegeben). """ try: return getattr(obj, attr) except Exception: return default