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