feat(p1-2): Plugin-State-Datei — atomare Hilfsfunktionen (_get_plugin_state_path, _read_plugin_state, _write_plugin_state)

This commit is contained in:
Bernd (Hermes)
2026-07-26 05:55:28 +02:00
parent 7523c41daa
commit 56badac990
2 changed files with 125 additions and 0 deletions
+69
View File
@@ -14,10 +14,12 @@ import json
import logging
import os
import subprocess
import tempfile
import threading
import time
import urllib.request
import urllib.error
from datetime import datetime, timezone
from typing import Optional, Dict, Callable
logger = logging.getLogger(__name__)
@@ -30,6 +32,73 @@ if not logger.handlers:
logger.propagate = False # Don't double-log to root
# ═══════════════════════════════════════════════════════════════════════════
# P1-2: Plugin-State-Datei — atomare Hilfsfunktionen
# ═══════════════════════════════════════════════════════════════════════════
PLUGIN_STATE_DIR = os.path.expanduser("~/.hermes/plugin_state")
PLUGIN_STATE_FILENAME = "hermes_rocket_plugin.json"
PLUGIN_STATE_SCHEMA_VERSION = 1
def _get_plugin_state_path() -> str:
"""Return the path to the plugin state file.
Returns:
Absolute path to ~/.hermes/plugin_state/hermes_rocket_plugin.json
"""
return os.path.join(PLUGIN_STATE_DIR, PLUGIN_STATE_FILENAME)
def _read_plugin_state(path: str) -> dict:
"""Read the plugin state file, returning {} if missing or corrupt.
Args:
path: Absolute path to the plugin state JSON file.
Returns:
Parsed dict, or empty dict on any error.
"""
try:
if not os.path.exists(path):
return {}
with open(path, 'r') as f:
return json.load(f)
except (json.JSONDecodeError, IOError, OSError) as e:
logger.debug("[plugin_state] read failed: %s", e)
return {}
def _write_plugin_state(path: str, data: dict) -> None:
"""Atomically write the plugin state file (write-temp + rename).
Args:
path: Absolute path to the plugin state JSON file.
data: Dict to serialize as JSON.
"""
try:
os.makedirs(os.path.dirname(path), exist_ok=True)
# Write to temp file in same directory (same filesystem → atomic rename)
fd, tmp_path = tempfile.mkstemp(
suffix=".tmp",
prefix="plugin_state_",
dir=os.path.dirname(path),
)
try:
with os.fdopen(fd, 'w') as f:
json.dump(data, f, ensure_ascii=False)
os.replace(tmp_path, path) # atomic on POSIX
except Exception:
# Clean up temp file on write failure
try:
os.unlink(tmp_path)
except OSError:
pass
raise
except Exception as e:
logger.debug("[plugin_state] write failed: %s", e)
# ═══════════════════════════════════════════════════════════════════════════
# Pure Function: _format_presence_message
# ═══════════════════════════════════════════════════════════════════════════