35 lines
991 B
Python
35 lines
991 B
Python
"""用户设置的 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)
|