Files
douyi_guaji_main/tools/dev/merge_configs.py
T
CodexandClaude Opus 4.5 a19fa35a0f chore: 整理 tools/ 47 个脚本按功能分组
- diagnostics/ 11 个:环境/配置/依赖诊断
- logs/ 7 个:日志分析与查看
- coords/ 6 个:坐标拾取与区域选择
- cleanup/ 3 个:代码清理工具
- adb/ 2 个:ADB / 输入法相关
- windows/ 4 个:Windows 系统修复(备份)
- dev/ 9 个:开发辅助 / 运行时探测

并更新 tools/README.md 描述新结构。
删除 3 个明显的临时调试脚本 (_dump_lines.py / tmp_*.py)。

tools/ 不被业务代码 import,分组仅为人工浏览方便。

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-20 23:25:28 +08:00

132 lines
3.6 KiB
Python

"""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())