Skip to content

Commit

Permalink
Fix out of scope error when "dest" variable is undefined
Browse files Browse the repository at this point in the history
Fixes theskumar#413 whereby the NamedTemporaryFile "dest" was out of scope in the
error handling portion of rewrite.

The problem was initially fixed in theskumar#414 but it got reverted because of a
linter error. This new commit works around that linter error.
  • Loading branch information
theGOTOguy authored and bbc2 committed Nov 11, 2022
1 parent 718307b commit 5f28ee6
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 11 deletions.
20 changes: 9 additions & 11 deletions src/dotenv/main.py
Expand Up @@ -125,19 +125,17 @@ def rewrite(
path: Union[str, os.PathLike],
encoding: Optional[str],
) -> Iterator[Tuple[IO[str], IO[str]]]:
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:
if not os.path.isfile(path):
with open(path, mode="w", encoding=encoding) as source:
source.write("")
with tempfile.NamedTemporaryFile(mode="w", encoding=encoding, delete=False) as dest:
try:
with open(path, encoding=encoding) as source:
yield (source, dest) # type: ignore
except BaseException:
if os.path.isfile(dest.name):
yield (source, dest)
except BaseException:
os.unlink(dest.name)
raise
else:
shutil.move(dest.name, path)
raise
shutil.move(dest.name, path)


def set_key(
Expand Down
7 changes: 7 additions & 0 deletions tests/test_main.py
Expand Up @@ -178,6 +178,13 @@ def test_unset_encoding(dotenv_file):
assert f.read() == ""


def test_set_key_unauthorized_file(dotenv_file):
os.chmod(dotenv_file, 0o000)

with pytest.raises(PermissionError):
dotenv.set_key(dotenv_file, "a", "x")


def test_unset_non_existent_file(tmp_path):
nx_file = str(tmp_path / "nx")
logger = logging.getLogger("dotenv.main")
Expand Down

0 comments on commit 5f28ee6

Please sign in to comment.