[tmpfile] delete the temporary file if an error occurs

This commit is contained in:
Jan Petykiewicz 2026-04-01 20:12:24 -07:00
commit ce46cc18dc

View file

@ -145,7 +145,11 @@ def tmpfile(path: str | pathlib.Path) -> Iterator[IO[bytes]]:
path = pathlib.Path(path)
suffixes = ''.join(path.suffixes)
with tempfile.NamedTemporaryFile(suffix=suffixes, delete=False) as tmp_stream:
yield tmp_stream
try:
yield tmp_stream
except Exception:
pathlib.Path(tmp_stream.name).unlink(missing_ok=True)
raise
try:
shutil.move(tmp_stream.name, path)