Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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 lib/stringify.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ const escape = str =>
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\t/g, '\\t')
const escapeKey = key => escape(key).replace(/[ =:]/g, '\\$&')
const escapeKey = key =>
escape(key).replace(/[ =:]/g, '\\$&').replace(/^[#!]/, '\\$&')

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should work as well?

Suggested change
const escapeKey = key =>
escape(key).replace(/[ =:]/g, '\\$&').replace(/^[#!]/, '\\$&')
const escapeKey = key => escape(key).replace(/^[#!]|[ =:]/g, '\\$&')

const escapeValue = value => escape(value).replace(/^ /, '\\ ')

const prefixComment = (str, prefix) =>
Expand Down
12 changes: 12 additions & 0 deletions tests/corner-cases.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,18 @@ deserunt mollit anim id est laborum.`
expect(stringify(lines)).toBe('key1 = value1\n# \n# \nkey2 = value2')
})

test('escape leading # and ! in keys so they round-trip', () => {
expect(stringify([['#key', 'v']])).toBe('\\#key = v')
expect(stringify([['!key', 'v']])).toBe('\\!key = v')
expect(parse(stringify({ '#key': 'v', '!key': 'w' }))).toEqual({
'#key': 'v',
'!key': 'w'
})
// # and ! are only comment markers at the start of a line, so they stay
// unescaped elsewhere in the key
expect(stringify([['a#b!c', 'v']])).toBe('a#b!c = v')
})

test('Negative linewidth', () => {
const foo = 'foo '.repeat(200)
expect(stringify([foo], { lineWidth: -1 })).toBe(`# ${foo}`)
Expand Down
Loading