Skip to content

Commit

Permalink
fix: Quote top-level map keys containing document markers (fixes #431)
Browse files Browse the repository at this point in the history
  • Loading branch information
eemeli committed Dec 30, 2022
1 parent 3576408 commit c8551eb
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/stringify/stringifyString.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ function plainString(
onChompKeep?: () => void
) {
const { type, value } = item
const { actualString, implicitKey, indent, inFlow } = ctx
const { actualString, implicitKey, indent, indentStep, inFlow } = ctx
if (
(implicitKey && /[\n[\]{},]/.test(value)) ||
(inFlow && /[[\]{},]/.test(value))
Expand Down Expand Up @@ -298,9 +298,13 @@ function plainString(
// Where allowed & type not set explicitly, prefer block style for multiline strings
return blockString(item, ctx, onComment, onChompKeep)
}
if (indent === '' && containsDocumentMarker(value)) {
ctx.forceBlockIndent = true
return blockString(item, ctx, onComment, onChompKeep)
if (containsDocumentMarker(value)) {
if (indent === '') {
ctx.forceBlockIndent = true
return blockString(item, ctx, onComment, onChompKeep)
} else if (implicitKey && indent === indentStep) {
return quotedString(value, ctx)
}
}
const str = value.replace(/\n+/g, `$&\n${indent}`)
// Verify that output will be parsed as a string, as e.g. plain numbers and
Expand Down
14 changes: 14 additions & 0 deletions tests/doc/stringify.js
Original file line number Diff line number Diff line change
Expand Up @@ -1118,6 +1118,20 @@ describe('Document markers in top-level scalars', () => {
})
})

describe('Document markers in top-level map keys (eemeli/yaml#431)', () => {
test('---', () => {
const str = YAML.stringify({ '--- x': 42 })
expect(str).toBe('"--- x": 42\n')
expect(YAML.parse(str)).toEqual({ '--- x': 42 })
})

test('...', () => {
const str = YAML.stringify({ '... x': 42 })
expect(str).toBe('"... x": 42\n')
expect(YAML.parse(str)).toEqual({ '... x': 42 })
})
})

describe('undefined values', () => {
test('undefined', () => {
expect(YAML.stringify(undefined)).toBeUndefined()
Expand Down

0 comments on commit c8551eb

Please sign in to comment.