| #!/usr/bin/env python3 | |
| """Write JSON only when semantic content changes (ignore generated_at_utc churn).""" | |
| from __future__ import annotations | |
| import json | |
| from copy import deepcopy | |
| from pathlib import Path | |
| def _strip_volatile(obj: dict) -> dict: | |
| data = deepcopy(obj) | |
| data.pop("generated_at_utc", None) | |
| data.pop("fetched", None) # fetch stamp string can churn; keep in FETCHED_AT.txt | |
| return data | |
| def write_json_stable(path: Path, data: dict, *, indent: int = 2) -> bool: | |
| """Return True if file was written/changed.""" | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| text = json.dumps(data, indent=indent) + "\n" | |
| if path.exists(): | |
| try: | |
| old = json.loads(path.read_text()) | |
| if _strip_volatile(old) == _strip_volatile(data): | |
| return False | |
| except (json.JSONDecodeError, OSError): | |
| pass | |
| path.write_text(text) | |
| return True | |