File size: 924 Bytes
0bcd139
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/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