41 lines
1.2 KiB
Python
41 lines
1.2 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from pydantic import BaseModel, Field, ValidationError
|
|
|
|
|
|
class Settings(BaseModel):
|
|
allow_draw_resign: bool = True
|
|
allow_illegal_moves: bool = False
|
|
theme_mode: str = Field(default="by_side") # by_side | both_dark | both_light
|
|
watchdog_seconds: int = 180
|
|
watchdog_max_nudges: int = 3
|
|
stockfish_depth: int = 15
|
|
|
|
|
|
DEFAULTS: dict[str, Any] = Settings().model_dump()
|
|
|
|
|
|
def load_settings(path: Path) -> Settings:
|
|
path = Path(path)
|
|
if not path.exists():
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_text(json.dumps(DEFAULTS, indent=2))
|
|
return Settings()
|
|
data = json.loads(path.read_text())
|
|
return Settings(**data)
|
|
|
|
|
|
def save_settings(path: Path, current: Settings, patch: dict[str, Any]) -> Settings:
|
|
allowed = set(Settings.model_fields.keys())
|
|
unknown = set(patch) - allowed
|
|
if unknown:
|
|
raise ValueError(f"unknown setting keys: {sorted(unknown)}")
|
|
merged = {**current.model_dump(), **patch}
|
|
new = Settings(**merged)
|
|
Path(path).write_text(json.dumps(new.model_dump(), indent=2))
|
|
return new
|