85d3bb1312
- Replace DEFAULT_SETTINGS.copy() with copy.deepcopy(DEFAULT_SETTINGS) in load_settings() and save_settings() to prevent mutation of module-level mutable defaults (hidden_sessions list was shared via shallow copy) - Replace except (json.JSONDecodeError, Exception) with except (FileNotFoundError, json.JSONDecodeError) to only suppress expected errors and let unexpected exceptions (PermissionError etc.) propagate - Add two regression tests: test_load_does_not_mutate_default_settings: verifies deepcopy isolation test_load_propagates_non_json_errors: verifies narrow exception handling
66 lines
1.8 KiB
Python
66 lines
1.8 KiB
Python
"""
|
|
Server-side settings management for muxplex.
|
|
|
|
Settings are stored at ~/.config/muxplex/settings.json.
|
|
"""
|
|
|
|
import copy
|
|
import json
|
|
from pathlib import Path
|
|
|
|
SETTINGS_PATH = Path.home() / ".config" / "muxplex" / "settings.json"
|
|
|
|
DEFAULT_SETTINGS: dict = {
|
|
"default_session": None,
|
|
"sort_order": "manual",
|
|
"hidden_sessions": [],
|
|
"window_size_largest": False,
|
|
"auto_open_created": True,
|
|
"new_session_template": "tmux new-session -d -s {name}",
|
|
}
|
|
|
|
|
|
def load_settings() -> dict:
|
|
"""Load settings from disk, merging saved values over defaults.
|
|
|
|
Returns DEFAULT_SETTINGS if the file does not exist or contains corrupt JSON.
|
|
Unknown keys in the file are ignored.
|
|
"""
|
|
result = copy.deepcopy(DEFAULT_SETTINGS)
|
|
try:
|
|
text = SETTINGS_PATH.read_text()
|
|
data = json.loads(text)
|
|
for key in DEFAULT_SETTINGS:
|
|
if key in data:
|
|
result[key] = data[key]
|
|
except (FileNotFoundError, json.JSONDecodeError):
|
|
pass
|
|
return result
|
|
|
|
|
|
def save_settings(data: dict) -> None:
|
|
"""Save settings to disk, merging *data* with defaults first.
|
|
|
|
Creates parent directories as needed. Writes JSON with indent=2 and a
|
|
trailing newline.
|
|
"""
|
|
merged = copy.deepcopy(DEFAULT_SETTINGS)
|
|
for key in DEFAULT_SETTINGS:
|
|
if key in data:
|
|
merged[key] = data[key]
|
|
SETTINGS_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
SETTINGS_PATH.write_text(json.dumps(merged, indent=2) + "\n")
|
|
|
|
|
|
def patch_settings(patch: dict) -> dict:
|
|
"""Merge known keys from *patch* into the current settings, save, and return result.
|
|
|
|
Unknown keys in *patch* are silently ignored.
|
|
"""
|
|
current = load_settings()
|
|
for key in DEFAULT_SETTINGS:
|
|
if key in patch:
|
|
current[key] = patch[key]
|
|
save_settings(current)
|
|
return current
|