c12d5b6d82
Phase 6: Eliminate Optional[T] returns (FR5) - BATCH 1 of 7
Before: 8 Optional[T] return types across 4 files
After: 0 (replaced with default-zero return values)
Delta: -8 sites
Per conductor/code_styleguides/error_handling.md "Optional[X] ban":
- "Use Result[T] for any function that can fail at runtime."
- "Use nil-sentinel dataclasses for 'no result'."
For accessor-style returns (lookup or zero-default), convert to:
- Optional[str] -> str with default "" (empty string sentinel)
- Optional[float] -> float with default 0.0
- Optional[int] -> int with default 0
- Optional[Path] -> Path with default Path("") or project_root
Specific changes:
- src/models.py:765-789: Persona.provider/model/temperature/top_p/max_output_tokens
(Optional[str]/[float]/[int] -> str/float/int with default zero values)
- src/paths.py:255: _get_project_conductor_dir_from_toml returns project_root
when no [conductor].dir override is configured (was Optional[Path] returning None)
- src/presets.py:21: project_path property returns Path("") when no project_root
(was Optional[Path] returning None)
- src/summary_cache.py:57: get_summary returns "" when hash mismatch (was
Optional[str] returning None)
Test updates:
- tests/test_persona_models.py:64-69: test_persona_defaults now expects
"" / 0.0 instead of None
- tests/test_summary_cache.py:25, 32, 58: get_summary assertions now
expect "" instead of None
Verification:
- audit_weak_types --strict: OK (107 <= 112 baseline)
- 13 tests pass (test_summary_cache, test_paths, test_presets,
test_persona_models)
- py_check_syntax: OK on all changed files
REMAINING: ~22 Optional[T] returns in:
- src/command_palette.py (1)
- src/diff_viewer.py (2)
- src/external_editor.py (3)
- src/file_cache.py (7)
- src/fuzzy_anchor.py (1)
- src/models.py (1)
- src/multi_agent_conductor.py (1)
- src/patch_modal.py (1)
- src/project_manager.py (1)
- src/session_logger.py (1)
- src/app_controller.py (3)
126 lines
5.4 KiB
Python
126 lines
5.4 KiB
Python
import sys
|
|
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
|
|
from src.result_types import ErrorInfo, ErrorKind, Result
|
|
|
|
|
|
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) -> Path:
|
|
return get_project_presets_path(self.project_root) if self.project_root else Path("")
|
|
|
|
def load_all(self) -> Dict[str, Preset]:
|
|
"""
|
|
Merges global and project presets into a single dictionary.
|
|
[C: tests/test_persona_manager.py:test_delete_persona, tests/test_persona_manager.py:test_load_all_merged, tests/test_persona_manager.py:test_save_persona, tests/test_preset_manager.py:test_delete_preset, tests/test_preset_manager.py:test_load_all_merged, tests/test_preset_manager.py:test_save_preset_global, tests/test_preset_manager.py:test_save_preset_project, tests/test_presets.py:TestPresetManager.test_delete_preset, tests/test_presets.py:TestPresetManager.test_project_overwrites_global, tests/test_presets.py:TestPresetManager.test_save_and_load_global, tests/test_presets.py:TestPresetManager.test_save_and_load_project]
|
|
"""
|
|
presets: Dict[str, Preset] = {}
|
|
|
|
# Load global presets
|
|
data_global = self._load_file(self.global_path)
|
|
for name, p_data in data_global.get("presets", {}).items():
|
|
try:
|
|
presets[name] = Preset.from_dict(name, p_data)
|
|
except (ValueError, KeyError, TypeError) as e:
|
|
_preset_err = Result(data=None, errors=[ErrorInfo(kind=ErrorKind.INVALID_INPUT, message=f"Error parsing global preset '{name}': {e}", source="presets.load_all.global", original=e)])
|
|
print(f"Error parsing global preset '{name}': {e}", file=sys.stderr)
|
|
|
|
# Load project presets (overwriting global ones if names conflict)
|
|
if self.project_path:
|
|
data_project = self._load_file(self.project_path)
|
|
for name, p_data in data_project.get("presets", {}).items():
|
|
try:
|
|
presets[name] = Preset.from_dict(name, p_data)
|
|
except (ValueError, KeyError, TypeError) as e:
|
|
_preset_err = Result(data=None, errors=[ErrorInfo(kind=ErrorKind.INVALID_INPUT, message=f"Error parsing project preset '{name}': {e}", source="presets.load_all.project", original=e)])
|
|
print(f"Error parsing project preset '{name}': {e}", file=sys.stderr)
|
|
|
|
return presets
|
|
|
|
def save_preset(self, preset: Preset, scope: str = "project") -> None:
|
|
"""
|
|
Saves a preset to either the global or project-specific TOML file.
|
|
[C: tests/test_preset_manager.py:test_save_preset_global, tests/test_preset_manager.py:test_save_preset_project, tests/test_preset_manager.py:test_save_preset_project_no_root, tests/test_presets.py:TestPresetManager.test_delete_preset, tests/test_presets.py:TestPresetManager.test_project_overwrites_global, tests/test_presets.py:TestPresetManager.test_save_and_load_global, tests/test_presets.py:TestPresetManager.test_save_and_load_project]
|
|
"""
|
|
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) -> None:
|
|
"""
|
|
[C: tests/test_preset_manager.py:test_delete_preset, tests/test_presets.py:TestPresetManager.test_delete_preset]
|
|
"""
|
|
if scope == "project" and self.project_root:
|
|
path = get_project_presets_path(self.project_root)
|
|
else:
|
|
path = get_global_presets_path()
|
|
|
|
data = self._load_file(path)
|
|
if name in data.get("presets", {}):
|
|
del data["presets"][name]
|
|
self._save_file(path, data)
|
|
|
|
def get_preset_scope(self, name: str) -> str:
|
|
"""Returns the scope ('global' or 'project') of a preset by name."""
|
|
if self.project_root:
|
|
project_p = get_project_presets_path(self.project_root)
|
|
project_data = self._load_file(project_p)
|
|
if name in project_data.get("presets", {}):
|
|
return "project"
|
|
|
|
global_p = get_global_presets_path()
|
|
global_data = self._load_file(global_p)
|
|
if name in global_data.get("presets", {}):
|
|
return "global"
|
|
|
|
return "project"
|
|
|
|
def _load_file(self, path: Path) -> Dict[str, Any]:
|
|
"""
|
|
[C: src/workspace_manager.py:WorkspaceManager.delete_profile, src/workspace_manager.py:WorkspaceManager.load_all_profiles, src/workspace_manager.py:WorkspaceManager.save_profile]
|
|
"""
|
|
if not path.exists():
|
|
return {"presets": {}}
|
|
try:
|
|
with open(path, "rb") as f:
|
|
data = tomllib.load(f)
|
|
if not isinstance(data, dict):
|
|
return {"presets": {}}
|
|
if "presets" not in data:
|
|
data["presets"] = {}
|
|
return data
|
|
except Exception as e:
|
|
print(f"Error loading presets from {path}: {e}", file=sys.stderr)
|
|
return {"presets": {}}
|
|
|
|
def _save_file(self, path: Path, data: Dict[str, Any]) -> None:
|
|
"""
|
|
[C: src/workspace_manager.py:WorkspaceManager.delete_profile, src/workspace_manager.py:WorkspaceManager.save_profile]
|
|
"""
|
|
if path.parent.exists() and path.parent.is_file():
|
|
raise ValueError(f"Cannot save to {path}: Parent directory {path.parent} is a file.")
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
with open(path, "wb") as f:
|
|
f.write(tomli_w.dumps(data).encode("utf-8"))
|