Skip to content

Commit

Permalink
Fix temporary file is deleted before closing, in the rewrite function (
Browse files Browse the repository at this point in the history
…#468)

Currently, if an error is raised while using files from the rewrite function, then the temporary file is deleted before closing it.

This is okay on unix, but unlinking open files causes an error on Windows.
  • Loading branch information
Qwerty-133 committed Jan 23, 2024
1 parent 0b94ac0 commit 6ff1391
Showing 1 changed file with 12 additions and 7 deletions.
19 changes: 12 additions & 7 deletions src/dotenv/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import io
import logging
import os
import pathlib
import shutil
import sys
import tempfile
Expand Down Expand Up @@ -131,17 +132,21 @@ def rewrite(
path: StrPath,
encoding: Optional[str],
) -> Iterator[Tuple[IO[str], IO[str]]]:
if not os.path.isfile(path):
with open(path, mode="w", encoding=encoding) as source:
source.write("")
pathlib.Path(path).touch()

with tempfile.NamedTemporaryFile(mode="w", encoding=encoding, delete=False) as dest:
error = None
try:
with open(path, encoding=encoding) as source:
yield (source, dest)
except BaseException:
os.unlink(dest.name)
raise
shutil.move(dest.name, path)
except BaseException as err:
error = err

if error is None:
shutil.move(dest.name, path)
else:
os.unlink(dest.name)
raise error from None


def set_key(
Expand Down

0 comments on commit 6ff1391

Please sign in to comment.