checkpoint(Saved system prompt presets)

This commit is contained in:
2026-03-09 22:27:40 -04:00
parent d8a4ec121d
commit e2a403a187
11 changed files with 649 additions and 35 deletions

85
src/presets.py Normal file
View File

@@ -0,0 +1,85 @@
import tomllib
import tomli_w
from pathlib import Path
from typing import Dict, Any, Optional
from src.models import Preset
from src.paths import get_global_presets_path, get_project_presets_path
class PresetManager:
"""Manages system prompt presets across global and project-specific files."""
def __init__(self, project_root: Optional[Path] = None):
self.project_root = project_root
self.global_path = get_global_presets_path()
@property
def project_path(self) -> Optional[Path]:
return get_project_presets_path(self.project_root) if self.project_root else None
def load_all(self) -> Dict[str, Preset]:
"""Merges global and project presets into a single dictionary."""
presets: Dict[str, Preset] = {}
# Load global presets
if self.global_path.exists():
try:
with open(self.global_path, "rb") as f:
data = tomllib.load(f)
for name, p_data in data.get("presets", {}).items():
presets[name] = Preset.from_dict(name, p_data)
except Exception:
pass
# Load project presets (overwriting global ones if names conflict)
if self.project_path and self.project_path.exists():
try:
with open(self.project_path, "rb") as f:
data = tomllib.load(f)
for name, p_data in data.get("presets", {}).items():
presets[name] = Preset.from_dict(name, p_data)
except Exception:
pass
return presets
def save_preset(self, preset: Preset, scope: str = "project") -> None:
"""Saves a preset to either the global or project-specific TOML file."""
path = self.global_path if scope == "global" else self.project_path
if not path:
if scope == "project":
raise ValueError("Project scope requested but no project_root provided.")
path = self.global_path
data = self._load_file(path)
if "presets" not in data:
data["presets"] = {}
data["presets"][preset.name] = preset.to_dict()
self._save_file(path, data)
def delete_preset(self, name: str, scope: str = "project") -> None:
"""Deletes a preset by name from the specified scope."""
path = self.global_path if scope == "global" else self.project_path
if not path:
if scope == "project":
raise ValueError("Project scope requested but no project_root provided.")
path = self.global_path
data = self._load_file(path)
if "presets" in data and name in data["presets"]:
del data["presets"][name]
self._save_file(path, data)
def _load_file(self, path: Path) -> Dict[str, Any]:
if not path.exists():
return {"presets": {}}
try:
with open(path, "rb") as f:
return tomllib.load(f)
except Exception:
return {"presets": {}}
def _save_file(self, path: Path, data: Dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "wb") as f:
f.write(tomli_w.dumps(data).encode("utf-8"))