Skip to content

Commit

Permalink
Fixes theskumar#413, whereby the NamedTemporaryFile "dest" was out of…
Browse files Browse the repository at this point in the history
… scope in the error handling portion of rewrite.
  • Loading branch information
theGOTOguy committed Jul 27, 2022
1 parent 914c68e commit 532a679
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/dotenv/main.py
Expand Up @@ -125,15 +125,16 @@ def rewrite(
path: Union[str, os.PathLike],
encoding: Optional[str],
) -> Iterator[Tuple[IO[str], IO[str]]]:
dest = None
try:
if not os.path.isfile(path):
with open(path, "w+", encoding=encoding) as source:
source.write("")
with tempfile.NamedTemporaryFile(mode="w+", delete=False, encoding=encoding) as dest:
with open(path, encoding=encoding) as source:
yield (source, dest) # type: ignore
dest = tempfile.NamedTemporaryFile(mode="w+", delete=False, encoding=encoding)
with open(path, encoding=encoding) as source:
yield (source, dest) # type: ignore
except BaseException:
if os.path.isfile(dest.name):
if dest and os.path.isfile(dest.name):
os.unlink(dest.name)
raise
else:
Expand Down
5 changes: 5 additions & 0 deletions tests/test_main.py
Expand Up @@ -22,6 +22,11 @@ def test_set_key_no_file(tmp_path):
assert os.path.exists(nx_file)


def test_set_key_invalid_file():
with pytest.raises(TypeError):
result = dotenv.set_key(None, "foo", "bar")


@pytest.mark.parametrize(
"before,key,value,expected,after",
[
Expand Down

0 comments on commit 532a679

Please sign in to comment.