Skip to content

Preserve line breaks across a parse(stringify()) round-trip - #251

Open
mahirhir wants to merge 1 commit into
bevry:masterfrom
mahirhir:fix-newline-round-trip
Open

Preserve line breaks across a parse(stringify()) round-trip#251
mahirhir wants to merge 1 commit into
bevry:masterfrom
mahirhir:fix-newline-round-trip

Conversation

@mahirhir

Copy link
Copy Markdown

stringify escapes a line break to the two characters \n and wraps the value in double quotes, but parse strips the quotes without reversing that escape. A value that contains a line break therefore does not survive a round-trip through the library's own functions:

const { parse, stringify } = require('envfile')

parse(stringify({ greeting: 'hello\nworld' }))
// => { greeting: 'hello\\nworld' }   a literal backslash-n, not a line break

The two existing tests show the intent. "line breaks inside quotes should be preserved on parse" feeds parse an actual line break inside quotes, and "...on stringify" checks that stringify emits the escaped \n form. They were only ever checked in isolation, so composing them silently drops the line break.

parse is the inverse of stringify, so it should reverse what stringify produces. This makes removeQuotes unescape \n back to a line break for double-quoted values, which matches dotenv's double-quote semantics where \n denotes a line break. Single-quoted values are left raw, as in dotenv.

All existing tests still pass unchanged. I added one that runs parse(stringify(value)) for a value with a line break; reverting the one-line change in removeQuotes makes only that new test fail, with the literal backslash-n shown above.

stringify escapes a line break to the two characters \n and wraps the
value in double quotes, but parse stripped the quotes without reversing
that escape, so a value containing a line break did not survive a round
trip through the library's own functions.

removeQuotes now unescapes \n back to a line break for double-quoted
values, matching dotenv's double-quote semantics. Single-quoted values
are left raw. Adds a round-trip regression test.
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