bvh_match: restore write mode before unlink on replace failure and publish mode on Windows (BVH-MATCH-STAGE-CLEANUP)

This commit is contained in:
Andrey
2026-11-24 16:32:23 +03:00
parent 9600cf0c64
commit 4f7261bef4
2 changed files with 43 additions and 3 deletions

View File

@ -521,6 +521,43 @@ class TestPieces(unittest.TestCase):
with open(path, encoding="utf-8") as f:
self.assertEqual(f.read(), previous)
def test_publish_cleans_up_staged_file_when_replace_fails_even_if_readonly(self):
with tempfile.TemporaryDirectory() as directory:
path = os.path.join(directory, "report.json")
with open(path, "w", encoding="utf-8") as f:
f.write('{"initial": 1}\n')
os.chmod(path, 0o444)
real_unlink = os.unlink
def windows_strict_unlink(p):
mode = os.stat(p).st_mode
if not (mode & 0o200):
raise PermissionError(13, f"Access is denied: {p}")
return real_unlink(p)
with mock.patch.object(M, "replace_retry", side_effect=OSError(13, "Permission denied")), \
mock.patch("os.unlink", side_effect=windows_strict_unlink):
with self.assertRaises(OSError):
M.write_json_report(path, {"signature": [], "consistent": False})
leftover = [f for f in os.listdir(directory) if f.startswith(".bvh_match-")]
self.assertEqual(leftover, [])
def test_publish_applies_published_mode_on_windows(self):
with tempfile.TemporaryDirectory() as directory:
path = os.path.join(directory, "report_win.json")
chmod_calls = []
real_chmod = os.chmod
def track_chmod(p, mode):
chmod_calls.append((p, mode))
real_chmod(p, mode)
with mock.patch("os.name", "nt"), mock.patch("os.chmod", side_effect=track_chmod):
M.write_json_report(path, {"signature": [], "consistent": False})
self.assertTrue(len(chmod_calls) > 0)
if __name__ == "__main__":
unittest.main()

View File

@ -309,13 +309,16 @@ def write_json_report(path, report):
try:
with staged:
json.dump(report, staged, indent=1)
if os.name != "nt":
os.chmod(staged.name, published_mode(destination))
os.chmod(staged.name, published_mode(destination))
replace_retry(staged.name, destination)
finally:
try:
os.chmod(staged.name, 0o600)
except OSError:
pass
try:
os.unlink(staged.name)
except FileNotFoundError:
except OSError:
pass