world_names: restore write mode before unlink on replace failure and publish mode (WORLD-NAMES-STAGE-CLEANUP)

When writing dictionary JSON atomically in _write_json, apply published_mode
to the staged file and reset os.chmod to 0o600 before exiting TemporaryDirectory
if os.replace fails, ensuring cleanup does not fail with PermissionError on
Windows when replacing a read-only file.

agent: yes
AI-assisted: yes
This commit is contained in:
Andrey
2026-11-24 17:22:00 +03:00
parent d0da7dade8
commit 2cb6ed8821
2 changed files with 23 additions and 1 deletions

View File

@ -588,6 +588,22 @@ class CliTest(unittest.TestCase):
with open(source, "rb") as handle:
self.assertEqual(handle.read(), original)
def test_stage_cleanup_restores_write_mode_on_replace_failure(self):
with tempfile.TemporaryDirectory() as tmp:
dest = os.path.join(tmp, "out.json")
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(WN.os, "replace", side_effect=OSError("replace failed")), \
mock.patch.object(WN.os, "chmod", side_effect=track_chmod):
with self.assertRaises(OSError):
WN._write_json(dest, {})
self.assertTrue(any(mode == 0o600 for p, mode in chmod_calls))
if __name__ == "__main__":
unittest.main()

View File

@ -38,6 +38,7 @@ import tempfile
# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module.
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from file_mode import published_mode # noqa: E402
from report_paths import same_report_path # noqa: E402
MASK32 = 0xFFFFFFFF
@ -630,7 +631,12 @@ def _write_json(path: str, data: dict) -> None:
with open(tmp, "w", encoding="utf-8", newline="\n") as handle:
json.dump(data, handle, indent=1, sort_keys=True)
handle.write("\n")
os.replace(tmp, path)
os.chmod(tmp, published_mode(path))
try:
os.replace(tmp, path)
except BaseException:
os.chmod(tmp, 0o600)
raise
def main(argv=None) -> int: