Skip to content

fix: escape backslashes in set_key so values round-trip#662

Open
Noethix55555 wants to merge 1 commit into
theskumar:mainfrom
Noethix55555:fix-set-key-backslash-escaping
Open

fix: escape backslashes in set_key so values round-trip#662
Noethix55555 wants to merge 1 commit into
theskumar:mainfrom
Noethix55555:fix-set-key-backslash-escaping

Conversation

@Noethix55555

Copy link
Copy Markdown

Summary

set_key writes single-quoted values but only escapes single quotes, not backslashes. Because the single-quoted-value parser treats \ as an escape character (decoding \\ -> \ and \' -> '), any value containing a backslash is corrupted on round-trip through get_key.

import dotenv

dotenv.set_key(".env", "PATH", r"C:\Users")
dotenv.get_key(".env", "PATH")   # before: "C:Users"  (backslash lost)

dotenv.set_key(".env", "RE", r"\d+")
dotenv.get_key(".env", "RE")      # before: "d+"

This affects Windows paths and regular expressions in particular.

Fix

Escape backslashes before escaping single quotes in set_key:

value_out = "'{}'".format(
    value_to_set.replace("\\", "\\\\").replace("'", "\\'")
)

This mirrors how the parser unescapes values, so writes round-trip.

Tests

Added a parametrized round-trip regression test (test_set_key_roundtrip_with_backslashes) covering C:\Users, \d+, \, a\b, a\\b, and a backslash+quote combination. Verified it fails on main and passes with the fix. The existing test_set_key cases and the rest of the suite remain green.

Closes #661

set_key wrote single-quoted values escaping only single quotes, but the
single-quoted-value parser treats backslash as an escape character. Values
containing backslashes (Windows paths like C:\Users, regexes like \d+)
were therefore corrupted when read back via get_key. Escape backslashes
before single quotes so the written value round-trips.

Closes theskumar#661
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

set_key corrupts values containing backslashes (Windows paths, regexes) on round-trip

1 participant