From b5dd9acbb6de86b17d19be3c3ae5e34601191341 Mon Sep 17 00:00:00 2001 From: Andrey Date: Tue, 24 Nov 2026 17:21:01 +0300 Subject: [PATCH] dds_png: restore write mode before unlink on replace failure in main (DDS-PNG-STAGE-CLEANUP) When previewing/saving PNG in CLI main(), if os.replace fails after shutil.copymode set the destination's permissions, resetting os.chmod to 0o600 ensures TemporaryDirectory cleanup does not fail with PermissionError on Windows if the output was read-only. agent: yes AI-assisted: yes --- tests/test_dds_png.py | 20 ++++++++++++++++++++ tools/dds_png.py | 6 +++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/tests/test_dds_png.py b/tests/test_dds_png.py index 4d800b25b..1e80aa8c9 100644 --- a/tests/test_dds_png.py +++ b/tests/test_dds_png.py @@ -1268,6 +1268,26 @@ class HalfFloatTests(unittest.TestCase): raw = zlib.decompress(b"".join(p for t, p, _ in chunks if t == b"IDAT")) self.assertEqual(raw[1:], bytes((255, 0, 128, 255, 0, 255, 64, 128))) + def test_cli_cleanup_restores_write_mode_on_replace_failure(self): + payload = halves(0x3C00, 0x0000, 0x3800, 0x3C00, 0x7E00, 0x7C00, 0x3400, 0x3800) + with tempfile.TemporaryDirectory() as tmp: + src = os.path.join(tmp, "in.dds") + dst = os.path.join(tmp, "out.png") + with open(src, "wb") as f: + f.write(dds_buffer(2, 1, payload, pitch=16, dxgi=10, **HALF_FLOAT)) + chmod_calls = [] + real_chmod = os.chmod + + def track_chmod(p, mode, **kwargs): + chmod_calls.append((p, mode)) + return real_chmod(p, mode, **kwargs) + + with mock.patch.object(dds.os, "replace", side_effect=OSError("replace failed")), \ + mock.patch.object(dds.os, "chmod", side_effect=track_chmod): + ret = dds.main([src, dst]) + self.assertEqual(ret, 1) + self.assertTrue(any(mode == 0o600 for p, mode in chmod_calls)) + if __name__ == "__main__": unittest.main() diff --git a/tools/dds_png.py b/tools/dds_png.py index dd59d7545..eb5ce48e9 100644 --- a/tools/dds_png.py +++ b/tools/dds_png.py @@ -1538,7 +1538,11 @@ def main(argv: list[str] | None = None) -> int: f.write(png) if os.path.isfile(output): shutil.copymode(output, pending) - os.replace(pending, output) + try: + os.replace(pending, output) + except BaseException: + os.chmod(pending, 0o600) + raise except (DdsError, OSError) as exc: print(f"ERROR: {exc}", file=sys.stderr) return 1