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
3 changes: 2 additions & 1 deletion src/dotenv/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,8 @@ def set_key(
)

if quote:
value_out = "'{}'".format(value_to_set.replace("'", "\\'"))
escaped_value = value_to_set.replace("\\", "\\\\").replace("'", "\\'")
value_out = f"'{escaped_value}'"
else:
value_out = value_to_set
if export:
Expand Down
15 changes: 15 additions & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,21 @@ def test_set_key_encoding(dotenv_path):
assert dotenv_path.read_text(encoding=encoding) == "a='é'\n"


@pytest.mark.parametrize(
"value",
[
"C:\\Users\\name",
r"\\d+",
r"prefix\\suffix",
"backslash\\'quote",
],
)
def test_set_key_round_trips_backslashes(dotenv_path, value):
dotenv.set_key(dotenv_path, "VALUE", value)

assert dotenv.get_key(dotenv_path, "VALUE") == value


@pytest.mark.skipif(
sys.platform == "win32", reason="file mode bits behave differently on Windows"
)
Expand Down