mission_tables: restore write mode before unlink on replace failure and publish mode on Windows (MISSION-TABLES-STAGE-CLEANUP)

agent: yes
AI-assisted: yes
This commit is contained in:
Andrey
2026-11-24 16:50:09 +03:00
parent 47c6511747
commit 0bb217f6d5
2 changed files with 42 additions and 2 deletions

View File

@ -460,6 +460,43 @@ class TestWriteJson(unittest.TestCase):
self.assertEqual(json.load(handle), payload)
self.assertEqual(os.listdir(folder), ["report.json"])
def test_publish_cleans_up_staged_file_when_replace_fails_even_if_readonly(self):
with tempfile.TemporaryDirectory() as folder:
report = os.path.join(folder, "report.json")
with open(report, "w", encoding="utf-8") as f:
f.write('{"initial": 1}\n')
os.chmod(report, 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, {"updated": True})
leftover = [f for f in os.listdir(folder) if f.startswith(".mission_tables-")]
self.assertEqual(leftover, [])
def test_publish_applies_published_mode_on_windows(self):
with tempfile.TemporaryDirectory() as folder:
report = os.path.join(folder, "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, {"files": []})
self.assertTrue(len(chmod_calls) > 0)
if __name__ == "__main__":
unittest.main()

View File

@ -577,12 +577,15 @@ def write_json(path, payload):
staged_path = staged.name
json.dump(payload, staged, indent=1)
staged.write("\n")
if os.name != "nt":
os.chmod(staged_path, published_mode(destination))
os.chmod(staged_path, published_mode(destination))
replace_retry(staged_path, destination)
staged_path = None
finally:
if staged_path is not None:
try:
os.chmod(staged_path, 0o600)
except OSError:
pass
try:
os.unlink(staged_path)
except OSError: