Skip to content
Open
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
34 changes: 20 additions & 14 deletions src/dotenv/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,11 +147,11 @@ def rewrite(
def set_key(
dotenv_path: StrPath,
key_to_set: str,
value_to_set: str,
value_to_set: Optional[str],
quote_mode: str = "always",
export: bool = False,
encoding: Optional[str] = "utf-8",
) -> Tuple[Optional[bool], str, str]:
) -> Tuple[Optional[bool], str, Optional[str]]:
"""
Adds or Updates a key/value to the given .env

Expand All @@ -161,19 +161,25 @@ def set_key(
if quote_mode not in ("always", "auto", "never"):
raise ValueError(f"Unknown quote_mode: {quote_mode}")

quote = (
quote_mode == "always"
or (quote_mode == "auto" and not value_to_set.isalnum())
)

if quote:
value_out = "'{}'".format(value_to_set.replace("'", "\\'"))
else:
value_out = value_to_set
if export:
line_out = f'export {key_to_set}={value_out}\n'
if value_to_set is None:
if export:
line_out = f'export {key_to_set}\n'
else:
line_out = f"{key_to_set}\n"
else:
line_out = f"{key_to_set}={value_out}\n"
quote = (
quote_mode == "always"
or (quote_mode == "auto" and not value_to_set.isalnum())
)

if quote:
value_out = "'{}'".format(value_to_set.replace("'", "\\'"))
else:
value_out = value_to_set
if export:
line_out = f'export {key_to_set}={value_out}\n'
else:
line_out = f"{key_to_set}={value_out}\n"

with rewrite(dotenv_path, encoding=encoding) as (source, dest):
replaced = False
Expand Down
1 change: 1 addition & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ def test_set_key_no_file(tmp_path):
"before,key,value,expected,after",
[
("", "a", "", (True, "a", ""), "a=''\n"),
("", "a", None, (True, "a", None), "a\n"),
("", "a", "b", (True, "a", "b"), "a='b'\n"),
("", "a", "'b'", (True, "a", "'b'"), "a='\\'b\\''\n"),
("", "a", "\"b\"", (True, "a", '"b"'), "a='\"b\"'\n"),
Expand Down