Atomically write ``text`` only if it differs from what is already on disk; return ``True`` if a write happened, ``False`` if the file was left untouched. Exporters regenerate their whole page set on every ``graph.json`` change and used to rewrite every file unconditionally — tens of tho
(path: "str | Path", text: str)
| 258 | |
| 259 | |
| 260 | def write_text_atomic_if_changed(path: "str | Path", text: str) -> bool: |
| 261 | """Atomically write ``text`` only if it differs from what is already on disk; |
| 262 | return ``True`` if a write happened, ``False`` if the file was left untouched. |
| 263 | |
| 264 | Exporters regenerate their whole page set on every ``graph.json`` change and |
| 265 | used to rewrite every file unconditionally — tens of thousands of identical |
| 266 | pages per run, which also fires inotify / re-index / sync on unchanged |
| 267 | content (#3060). Skipping the atomic replace when nothing changed avoids the |
| 268 | rename entirely, so mtime and inode are preserved. |
| 269 | |
| 270 | The comparison is on DECODED text, never bytes: :func:`write_text_atomic` |
| 271 | writes in text mode and (on Windows) translates ``\\n`` to ``\\r\\n`` while |
| 272 | :func:`Path.read_text` translates it back, so a byte compare would report |
| 273 | every file as changed. A missing or non-UTF-8 destination counts as changed.""" |
| 274 | try: |
| 275 | if Path(os.path.realpath(str(path))).read_text(encoding="utf-8") == text: |
| 276 | return False |
| 277 | except (OSError, UnicodeDecodeError): |
| 278 | pass |
| 279 | write_text_atomic(path, text) |
| 280 | return True |
| 281 | |
| 282 | |
| 283 | _JSON_STREAM_THRESHOLD = 1024 |