Skip to content

Commit c8551eb

Browse files
committedDec 30, 2022
fix: Quote top-level map keys containing document markers (fixes #431)
1 parent 3576408 commit c8551eb

File tree

2 files changed

+22
-4
lines changed

2 files changed

+22
-4
lines changed
 

‎src/stringify/stringifyString.ts

+8-4
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,7 @@ function plainString(
266266
onChompKeep?: () => void
267267
) {
268268
const { type, value } = item
269-
const { actualString, implicitKey, indent, inFlow } = ctx
269+
const { actualString, implicitKey, indent, indentStep, inFlow } = ctx
270270
if (
271271
(implicitKey && /[\n[\]{},]/.test(value)) ||
272272
(inFlow && /[[\]{},]/.test(value))
@@ -298,9 +298,13 @@ function plainString(
298298
// Where allowed & type not set explicitly, prefer block style for multiline strings
299299
return blockString(item, ctx, onComment, onChompKeep)
300300
}
301-
if (indent === '' && containsDocumentMarker(value)) {
302-
ctx.forceBlockIndent = true
303-
return blockString(item, ctx, onComment, onChompKeep)
301+
if (containsDocumentMarker(value)) {
302+
if (indent === '') {
303+
ctx.forceBlockIndent = true
304+
return blockString(item, ctx, onComment, onChompKeep)
305+
} else if (implicitKey && indent === indentStep) {
306+
return quotedString(value, ctx)
307+
}
304308
}
305309
const str = value.replace(/\n+/g, `$&\n${indent}`)
306310
// Verify that output will be parsed as a string, as e.g. plain numbers and

‎tests/doc/stringify.js

+14
Original file line numberDiff line numberDiff line change
@@ -1118,6 +1118,20 @@ describe('Document markers in top-level scalars', () => {
11181118
})
11191119
})
11201120

1121+
describe('Document markers in top-level map keys (eemeli/yaml#431)', () => {
1122+
test('---', () => {
1123+
const str = YAML.stringify({ '--- x': 42 })
1124+
expect(str).toBe('"--- x": 42\n')
1125+
expect(YAML.parse(str)).toEqual({ '--- x': 42 })
1126+
})
1127+
1128+
test('...', () => {
1129+
const str = YAML.stringify({ '... x': 42 })
1130+
expect(str).toBe('"... x": 42\n')
1131+
expect(YAML.parse(str)).toEqual({ '... x': 42 })
1132+
})
1133+
})
1134+
11211135
describe('undefined values', () => {
11221136
test('undefined', () => {
11231137
expect(YAML.stringify(undefined)).toBeUndefined()

0 commit comments

Comments
 (0)
Please sign in to comment.