Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: out of scope error when "dest" variable is undefined #413 #414

Merged
merged 1 commit into from Sep 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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