diff --git a/artifactManifest/artifact_manifest.py b/artifactManifest/artifact_manifest.py index 60e84c3..45cc8cd 100644 --- a/artifactManifest/artifact_manifest.py +++ b/artifactManifest/artifact_manifest.py @@ -10,6 +10,7 @@ import re import stat import sys +import tempfile from dataclasses import dataclass from pathlib import Path, PurePosixPath from typing import Iterable, Sequence @@ -193,9 +194,20 @@ def create_manifest( "files": [item.as_dict() for item in files], } output_path.parent.mkdir(parents=True, exist_ok=True) - output_path.write_text( - json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" - ) + temporary_path: Path | None = None + try: + with tempfile.NamedTemporaryFile( + mode="w", encoding="utf-8", dir=output_path.parent, + prefix=f".{output_path.name}.", suffix=".tmp", delete=False, + ) as temporary: + temporary_path = Path(temporary.name) + temporary.write(json.dumps(payload, ensure_ascii=False, indent=2) + "\n") + if output_path.exists(): + os.chmod(temporary_path, stat.S_IMODE(output_path.stat().st_mode)) + os.replace(temporary_path, output_path) + finally: + if temporary_path is not None: + temporary_path.unlink(missing_ok=True) return payload diff --git a/artifactManifest/tests/test_artifact_manifest.py b/artifactManifest/tests/test_artifact_manifest.py index 82b4296..d5a0257 100644 --- a/artifactManifest/tests/test_artifact_manifest.py +++ b/artifactManifest/tests/test_artifact_manifest.py @@ -234,3 +234,20 @@ def test_manifest_rejects_duplicate_json_keys(tmp_path: Path, content: str) -> N manifest.write_text(content, encoding="utf-8") with pytest.raises(artifact_manifest.ManifestError, match="duplicate JSON key"): artifact_manifest.verify_manifest(root, manifest) + + +def test_failed_manifest_replace_preserves_previous_output(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + root = tmp_path / "artifact" + root.mkdir() + (root / "data.txt").write_text("new data", encoding="utf-8") + output = tmp_path / "manifest.json" + output.write_text("previous manifest", encoding="utf-8") + + def fail_replace(src, dst): + raise OSError("simulated replace failure") + + monkeypatch.setattr(artifact_manifest.os, "replace", fail_replace) + with pytest.raises(OSError, match="simulated replace failure"): + artifact_manifest.create_manifest(root, output) + assert output.read_text(encoding="utf-8") == "previous manifest" + assert list(tmp_path.glob(".manifest.json.*.tmp")) == []