Write JSON atomically via temp-file + rename, chmod 0600.
(path: Path, data: dict[str, Any])
| 107 | |
| 108 | |
| 109 | def _atomic_write_json(path: Path, data: dict[str, Any]) -> None: |
| 110 | """Write JSON atomically via temp-file + rename, chmod 0600.""" |
| 111 | path.parent.mkdir(parents=True, exist_ok=True) |
| 112 | fd, tmp = tempfile.mkstemp(dir=str(path.parent), suffix=".tmp") |
| 113 | try: |
| 114 | with os.fdopen(fd, "w", encoding="utf-8") as f: |
| 115 | json.dump(data, f, indent=2, ensure_ascii=False) |
| 116 | f.write("\n") |
| 117 | os.replace(tmp, str(path)) |
| 118 | if os.name != "nt": |
| 119 | os.chmod(str(path), 0o600) |
| 120 | except Exception: |
| 121 | try: |
| 122 | os.unlink(tmp) |
| 123 | except OSError: |
| 124 | pass |
| 125 | raise |
| 126 | |
| 127 | |
| 128 | # --------------------------------------------------------------------------- |