chore: push all design docs, V2 plan specs, and current working state
Includes AirPlan design documents, AircOding-alpha1-plan, AirPlanV2, AirPlan-ParaV2, AirPlan-Para V1 reference docs, and all working code changes across packages. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
53
AirPlan/docs/spec/AirPlanV2/lib/air_runtime/io.py
Executable file
53
AirPlan/docs/spec/AirPlanV2/lib/air_runtime/io.py
Executable file
@@ -0,0 +1,53 @@
|
||||
"""
|
||||
原子 I/O 模块 — 消除 V1 5 份 _json_dump/_json_load 重复。
|
||||
每次写入使用 tempfile + os.replace() 保证原子性,写入前自动备份。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def atomic_json_write(path: Path, data: dict | list, indent: int = 2) -> None:
|
||||
"""POSIX 原子写入:tempfile + os.replace()。写入前自动备份旧文件为 .bak(单级轮转)。"""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 备份旧文件
|
||||
if path.exists():
|
||||
bak = path.with_suffix(path.suffix + ".bak")
|
||||
try:
|
||||
os.replace(str(path), str(bak))
|
||||
except OSError as exc:
|
||||
logger.warning("backup %s -> %s failed: %s", path, bak, exc)
|
||||
|
||||
fd, tmp = tempfile.mkstemp(dir=path.parent, suffix=".tmp")
|
||||
try:
|
||||
os.write(fd, json.dumps(data, indent=indent, ensure_ascii=False).encode("utf-8"))
|
||||
os.close(fd)
|
||||
os.replace(tmp, path)
|
||||
except BaseException:
|
||||
with contextlib.suppress(OSError):
|
||||
os.unlink(tmp)
|
||||
raise
|
||||
|
||||
|
||||
def safe_json_load(path: Path) -> dict | list | None:
|
||||
"""安全加载:处理损坏文件,自动从 .bak 恢复。文件不存在返回 None。"""
|
||||
try:
|
||||
return json.loads(path.read_text("utf-8"))
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
except (json.JSONDecodeError, UnicodeDecodeError):
|
||||
bak = path.with_suffix(path.suffix + ".bak")
|
||||
if bak.exists():
|
||||
logger.warning("corrupt %s, restoring from %s", path, bak)
|
||||
return json.loads(bak.read_text("utf-8"))
|
||||
logger.error("corrupt %s with no backup", path)
|
||||
return None
|
||||
Reference in New Issue
Block a user