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 #423

Merged
merged 1 commit into from
Nov 11, 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
20 changes: 9 additions & 11 deletions src/dotenv/main.py
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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