Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
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