"""Merge the JSON object in SRC into DEST. SRC wins; keys only DEST has are kept.""" import json import os import shutil import sys import tempfile def merge(base, override): if not (isinstance(base, dict) and isinstance(override, dict)): return override merged = dict(base) for key, value in override.items(): merged[key] = merge(base[key], value) if key in base else value return merged def merged_text(src_text, dest): with open(dest, encoding="utf-8") as f: existing = json.load(f) if not isinstance(existing, dict): raise ValueError("top level is not a JSON object") before = json.dumps(existing, indent=2, ensure_ascii=False) after = json.dumps(merge(existing, json.loads(src_text)), indent=2, ensure_ascii=False) return None if after == before else after + "\n" def replace_file(dest, text): # Renaming a complete temporary file over dest means a failure never truncates it. fd, tmp = tempfile.mkstemp(dir=os.path.dirname(dest), prefix=".merge-json.") try: with os.fdopen(fd, "w", encoding="utf-8") as f: f.write(text) f.flush() os.fsync(f.fileno()) if os.path.exists(dest): shutil.copymode(dest, tmp) os.replace(tmp, dest) except BaseException: os.unlink(tmp) raise def main(): src, dest_arg = sys.argv[1:] # Renaming over a symlink would replace the link, so write to its target. dest = os.path.realpath(dest_arg) with open(src, encoding="utf-8") as f: text = f.read() try: if os.path.exists(dest): text = merged_text(text, dest) if text is not None: replace_file(dest, text) except (OSError, ValueError) as error: sys.exit(f"ERROR: cannot merge settings into {dest_arg}, left unchanged: {error}") main()