-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsettings.py
More file actions
58 lines (46 loc) · 1.72 KB
/
settings.py
File metadata and controls
58 lines (46 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import json
import logging
from typing import Callable, Dict, Hashable
from .utils import get_app_path
SETTINGS_FILE = get_app_path() / "hackablock.json"
VALIDATION_RULES: Dict[str, Callable] = {
"hackatime_api_key": lambda v: isinstance(v, str),
"minutes_required": lambda v: isinstance(v, int) and 1 <= v <= 720
}
DEFAULTS: Dict = {
"hackatime_api_key": "",
"blocked_apps": ["steam.exe"],
"minutes_required": 60,
}
class Settings:
def __init__(self) -> None:
self.data = DEFAULTS.copy()
self._load()
def save(self) -> None:
try:
SETTINGS_FILE.write_text(json.dumps(self.data, indent=2))
except Exception as e:
logging.error(f"Failed to save settings: {e}")
def _load(self) -> None:
if not SETTINGS_FILE.exists():
return
try:
data = json.loads(SETTINGS_FILE.read_text())
if not isinstance(data, dict):
raise ValueError("Settings file is not a dict")
except Exception as e:
logging.warning(f"Failed to load settings: {e}. Using default values.")
self.data = DEFAULTS.copy()
return
validated = {}
for key, default_value in DEFAULTS.items():
value = data.get(key, default_value)
rule = VALIDATION_RULES.get(key, lambda _: True)
if not rule(value):
logging.warning(f"Invalid type for {key}: {value}. Using default {default_value}")
value = default_value
validated[key] = value
self.data = validated
def update_setting(self, key: str, value: Hashable) -> None:
self.data[key] = value
settings = Settings()