Skip to content

fix: escape backslashes in values and keys so they round-trip#307

Open
greymoth-jp wants to merge 1 commit into
npm:mainfrom
greymoth-jp:fix/escape-backslash-roundtrip
Open

fix: escape backslashes in values and keys so they round-trip#307
greymoth-jp wants to merge 1 commit into
npm:mainfrom
greymoth-jp:fix/escape-backslash-roundtrip

Conversation

@greymoth-jp

Copy link
Copy Markdown

ini.parse(ini.stringify(x)) is not stable when a value or key contains a backslash.

unsafe treats \ as an escape character: in the unquoted branch it unescapes \\, \; and \#. safe only escaped ; and #, never the backslash itself, so a backslash that is written verbatim is read back as an escape sequence. Two backslashes collapse to one, and a backslash placed before ; or # gets swallowed.

const ini = require('ini')

// a value of two backslashes comes back as one
ini.parse(ini.stringify({ k: '\\\\' }))      // { k: '\\' }
ini.parse(ini.stringify({ p: 'C:\\\\tmp' })) // { p: 'C:\\tmp' }

This makes safe escape the backslash as well, so it is the inverse of unsafe. Section names are left unchanged: they use \. to escape literal dots in key paths, so safe is called with escapeBackslash = false for the section to avoid doubling those structural backslashes. The existing snapshots are byte-identical.

Round-trip tests are added in test/bar.js (two backslashes, a Windows-style path, \;/\#, and a backslash in a key). npm test passes at 100% coverage, and reverting the one-line change makes the new cases fail.

This is the behaviour #9 had in mind: "a \\ needs to be a \ and not an escape".

`unsafe` treats `\` as an escape character and unescapes `\\`, `\;` and
`\#`, but `safe` only escaped `;` and `#`. A value or key containing a
backslash therefore did not survive stringify -> parse: a value of two
backslashes was written as `k=\\` and read back as a single backslash.

`safe` now escapes the backslash as well. Section names are left
unchanged because they rely on `\.` to escape literal dots in key paths.
@greymoth-jp greymoth-jp requested a review from a team as a code owner June 29, 2026 23:29
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.

1 participant