diff --git a/tests/test_anim_clips.py b/tests/test_anim_clips.py index 02df698a0..978d1eb18 100644 --- a/tests/test_anim_clips.py +++ b/tests/test_anim_clips.py @@ -1458,6 +1458,28 @@ def test_counts_only_ordinary_clips(self): anim_clips.count_clip_windows(clips, stats) self.assertEqual(stats, {"clip_windows": 4, "clip_windows_match_duration": 2, "clip_windows_rate_zero": 1}) + def test_write_json_atomic_and_replace_failure_preserves_existing(self): + import tempfile + from unittest import mock + + with tempfile.TemporaryDirectory() as tmp: + out = os.path.join(tmp, "out.json") + anim_clips._write_json_atomic(out, {"summary": {}, "dictionaries": []}) + self.assertEqual(os.listdir(tmp), ["out.json"]) + with open(out, "rb") as f: + raw = f.read() + self.assertTrue(raw.endswith(b"\n")) + self.assertNotIn(b"\r\n", raw) + + with open(out, "w", encoding="utf-8", newline="\n") as f: + f.write('{"keep": true}\n') + with mock.patch.object(anim_clips, "replace_retry", side_effect=OSError("replace denied")): + with self.assertRaises(OSError): + anim_clips._write_json_atomic(out, {"summary": {}, "dictionaries": [1]}) + self.assertEqual(os.listdir(tmp), ["out.json"]) + with open(out, encoding="utf-8") as f: + self.assertEqual(f.read(), '{"keep": true}\n') + if __name__ == "__main__": unittest.main() diff --git a/tools/anim_clips.py b/tools/anim_clips.py index 14783e0cb..35c235884 100644 --- a/tools/anim_clips.py +++ b/tools/anim_clips.py @@ -34,6 +34,7 @@ import os import struct import sys +import tempfile import time import zlib @@ -41,7 +42,9 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import anim_index # noqa: E402 +from file_mode import published_mode # noqa: E402 from pool_workers import process_workers # noqa: E402 +from replace_retry import replace as replace_retry # noqa: E402 SYSTEM = 0x50000000 CHANNEL_NAMES = ("static_quat", "static_vec3", "static_float", "raw_float", "quantize_float", @@ -1571,11 +1574,7 @@ def progress(n, total): except OSError as e: sys.exit(f"{e.filename or a.archive}: {e.strerror or e}") try: - parent = os.path.dirname(os.path.abspath(a.out)) - if parent: - os.makedirs(parent, exist_ok=True) - with open(a.out, "w", encoding="utf-8", newline="\n") as f: - json.dump({"summary": summary, "dictionaries": rows}, f, indent=1) + _write_json_atomic(a.out, {"summary": summary, "dictionaries": rows}) except OSError as e: sys.exit(f"{a.out}: cannot write: {e.strerror or e}") c = summary["counts"] @@ -1585,6 +1584,36 @@ def progress(n, total): return 0 +def _write_json_atomic(path, payload): + dest = os.path.realpath(path) + parent = os.path.dirname(dest) or "." + os.makedirs(parent, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=parent, prefix=".anim_clips-", suffix=".tmp") + try: + try: + f = os.fdopen(fd, "w", encoding="utf-8", newline="\n") + except BaseException: + os.close(fd) + raise + with f: + json.dump(payload, f, indent=1) + f.write("\n") + f.flush() + os.fsync(f.fileno()) + os.chmod(tmp, published_mode(dest)) + replace_retry(tmp, dest) + except BaseException: + try: + os.chmod(tmp, 0o600) + except OSError: + pass + try: + os.unlink(tmp) + except OSError: + pass + raise + + if __name__ == "__main__": try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode sys.stdout.reconfigure(errors="replace")