重构:模块化 RRPP Lite 并更新入口
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
"""用户设置的 JSON 存储实现。"""
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
|
||||
class JsonSettingsStore:
|
||||
"""读取与原子写回一个 JSON 对象。
|
||||
|
||||
``path_getter`` 在每次操作时调用,保证测试或运行时切换用户目录后不会
|
||||
意外写到旧目录。
|
||||
"""
|
||||
|
||||
def __init__(self, path_getter):
|
||||
self._path_getter = path_getter
|
||||
|
||||
def load(self):
|
||||
path = self._path_getter()
|
||||
try:
|
||||
if not path.is_file():
|
||||
return {}
|
||||
data = json.loads(path.read_text("utf-8"))
|
||||
return data if isinstance(data, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
def save(self, data):
|
||||
path = self._path_getter()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary_path = path.with_suffix(path.suffix + ".tmp")
|
||||
temporary_path.write_text(
|
||||
json.dumps(data, ensure_ascii=False, indent=2) + "\n", "utf-8"
|
||||
)
|
||||
os.replace(temporary_path, path)
|
||||
Reference in New Issue
Block a user