feat: 增加合并配置文件的工具,支持从旧版配置文件合并缺失的键并备份原文件
This commit is contained in:
1 parent
e42e6e6d3b
commit
4620d28364
3 files changed
+179
-3
No files matched your search
@@ -1719,6 +1719,51 @@ def process_reservation_attend_window(
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 回退校验失败:根据映射表尝试再次回退到对应直播间,且不进入锁定期
|
||||
try:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 回退校验失败:尝试根据映射表回退到对应直播间并跳过设置锁定期",
|
||||
target_pos=int(target.get("pos_seen", 0)),
|
||||
target_room_title=(
|
||||
target_room_title[:50]
|
||||
if target_room_title
|
||||
else ""
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 尝试使用回退回调根据映射表定位到目标直播间
|
||||
ok2 = False
|
||||
try:
|
||||
if seek_reservation_room_callback:
|
||||
ok2 = bool(seek_reservation_room_callback(target))
|
||||
except Exception:
|
||||
ok2 = False
|
||||
|
||||
# 清理锁定相关标志,避免进入锁定期
|
||||
try:
|
||||
if reservation_focus_until_ts_ref:
|
||||
reservation_focus_until_ts_ref[0] = 0.0
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if reservation_after_action_pending_ref:
|
||||
reservation_after_action_pending_ref[0] = False
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
write_state_callback()
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 不设置锁定期,回退校验失败视作本次未成功回退,返回 False 以便上层继续处理
|
||||
return False
|
||||
else:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
|
||||
@@ -44,9 +44,9 @@ class ConfigManager:
|
||||
cp_abs = os.path.abspath(str(config_path))
|
||||
root_abs = os.path.abspath(path_config.get_project_root())
|
||||
legacy_abs = os.path.join(root_abs, "config.json")
|
||||
if os.path.normcase(cp_abs) == os.path.normcase(legacy_abs) and os.path.exists(
|
||||
preferred_abs
|
||||
):
|
||||
if os.path.normcase(cp_abs) == os.path.normcase(
|
||||
legacy_abs
|
||||
) and os.path.exists(preferred_abs):
|
||||
config_path = preferred_abs
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Merge legacy root config.json into config/config.json.
|
||||
|
||||
Rules (safe-default):
|
||||
- Primary file is config/config.json (used by runtime via path_config.get_config_path()).
|
||||
- Fill missing keys from root config.json.
|
||||
- For keys existing in both:
|
||||
- If both are dict: deep-merge recursively.
|
||||
- Otherwise keep primary value, unless primary is "empty" and legacy is non-empty.
|
||||
|
||||
"Empty" means: None, "", [], {}.
|
||||
|
||||
Creates backups next to the target files before writing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, Tuple
|
||||
|
||||
|
||||
def _is_empty(value: Any) -> bool:
|
||||
if value is None:
|
||||
return True
|
||||
if value == "":
|
||||
return True
|
||||
if isinstance(value, (list, tuple, dict)) and len(value) == 0:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def deep_merge(primary: Any, legacy: Any) -> Any:
|
||||
if isinstance(primary, dict) and isinstance(legacy, dict):
|
||||
merged: Dict[str, Any] = dict(primary)
|
||||
for k, v in legacy.items():
|
||||
if k not in merged:
|
||||
merged[k] = v
|
||||
continue
|
||||
merged[k] = deep_merge(merged[k], v)
|
||||
return merged
|
||||
|
||||
# scalar/list mismatch: keep primary unless it's empty and legacy is not
|
||||
if _is_empty(primary) and not _is_empty(legacy):
|
||||
return legacy
|
||||
return primary
|
||||
|
||||
|
||||
def read_json(path: str) -> Dict[str, Any]:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
obj = json.load(f)
|
||||
if not isinstance(obj, dict):
|
||||
raise ValueError(f"Config must be a JSON object: {path}")
|
||||
return obj
|
||||
|
||||
|
||||
def backup(path: str) -> str:
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
bak = f"{path}.bak_{ts}"
|
||||
shutil.copy2(path, bak)
|
||||
return bak
|
||||
|
||||
|
||||
def write_json(path: str, data: Dict[str, Any]) -> None:
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=4)
|
||||
f.write("\n")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument(
|
||||
"--primary",
|
||||
default=os.path.join("config", "config.json"),
|
||||
help="Primary config path (default: config/config.json)",
|
||||
)
|
||||
ap.add_argument(
|
||||
"--legacy",
|
||||
default="config.json",
|
||||
help="Legacy config path (default: ./config.json)",
|
||||
)
|
||||
ap.add_argument(
|
||||
"--write-back-legacy",
|
||||
action="store_true",
|
||||
help="Also write merged result back to legacy file (keeps both in sync)",
|
||||
)
|
||||
args = ap.parse_args()
|
||||
|
||||
primary_path = os.path.abspath(args.primary)
|
||||
legacy_path = os.path.abspath(args.legacy)
|
||||
|
||||
if not os.path.exists(primary_path):
|
||||
raise FileNotFoundError(primary_path)
|
||||
if not os.path.exists(legacy_path):
|
||||
raise FileNotFoundError(legacy_path)
|
||||
|
||||
primary_cfg = read_json(primary_path)
|
||||
legacy_cfg = read_json(legacy_path)
|
||||
|
||||
merged = deep_merge(primary_cfg, legacy_cfg)
|
||||
|
||||
# backup first
|
||||
primary_bak = backup(primary_path)
|
||||
write_json(primary_path, merged)
|
||||
|
||||
legacy_bak = None
|
||||
if args.write_back_legacy:
|
||||
legacy_bak = backup(legacy_path)
|
||||
write_json(legacy_path, merged)
|
||||
|
||||
added_keys = sorted(set(legacy_cfg.keys()) - set(primary_cfg.keys()))
|
||||
|
||||
print("Merged config files:")
|
||||
print(f"- primary : {primary_path}")
|
||||
print(f" backup : {primary_bak}")
|
||||
print(f"- legacy : {legacy_path}")
|
||||
if legacy_bak:
|
||||
print(f" backup : {legacy_bak}")
|
||||
print(f"- added top-level keys from legacy -> primary: {len(added_keys)}")
|
||||
if added_keys:
|
||||
print(
|
||||
" " + ", ".join(added_keys[:50]) + (" ..." if len(added_keys) > 50 else "")
|
||||
)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user