Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions tests/test_anim_clips.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
39 changes: 34 additions & 5 deletions tools/anim_clips.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,17 @@
import os
import struct
import sys
import tempfile
import time
import zlib

# -I keeps the script directory off sys.path, so add it explicitly before importing the stream walk.
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",
Expand Down Expand Up @@ -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"]
Expand All @@ -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")
Expand Down
Loading