Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
7 changes: 6 additions & 1 deletion src/stringify/stringifyDocument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,12 @@ export function stringifyDocument(
let dc = doc.comment
if (dc && chompKeep) dc = dc.replace(/^\n+/, '')
if (dc) {
if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '')
const last = lines[lines.length - 1]
if (
(!chompKeep || contentComment) &&
last !== '' &&
!last?.endsWith('\n')
)
lines.push('')
lines.push(indentComment(commentString(dc), ''))
}
Expand Down
9 changes: 8 additions & 1 deletion src/stringify/stringifyString.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,14 @@ function blockString(
: type === Scalar.BLOCK_LITERAL
? true
: !lineLengthOverLimit(value, lineWidth, indent.length)
if (!value) return literal ? '|\n' : '>\n'
if (!value) {
let header = ctx.forceBlockIndent ? (indent ? '2' : '1') : ''
if (comment) {
header += ' ' + commentString(comment.replace(/ ?[\r\n]+/g, ' '))
if (onComment) onComment()
}
return `${literal ? '|' : '>'}${header}\n`
}

// determine chomping from whitespace at value end
let chomp: '' | '-' | '+'
Expand Down
38 changes: 38 additions & 0 deletions tests/doc/comments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1293,3 +1293,41 @@ a:
expect(String(doc)).toBe(src)
})
})

describe('empty block scalar with comments (#687)', () => {
test('top-level empty block literal followed by comment', () => {
const doc = YAML.parseDocument<YAML.Scalar>('|5\n#comment\n')
expect(doc.value).toMatchObject({ value: '' })
expect(doc.comment).toBe('comment')

const str = doc.toString()
expect(str).toBe('|2\n\n#comment\n')

const reparsed = YAML.parseDocument<YAML.Scalar>(str)
expect(reparsed.value).toMatchObject({ value: '' })
expect(reparsed.comment).toBe('comment')
})

test('top-level empty block folded with header and trailing comments', () => {
const doc = YAML.parseDocument<YAML.Scalar>('>5 #c1\n#c2\n')
expect(doc.value).toMatchObject({ value: '', comment: 'c1' })
expect(doc.comment).toBe('c2')

const str = doc.toString()
expect(str).toBe('>2 #c1\n\n#c2\n')

const reparsed = YAML.parseDocument<YAML.Scalar>(str)
expect(reparsed.value).toMatchObject({ value: '', comment: 'c1' })
expect(reparsed.comment).toBe('c2')
})

test('map value empty block scalar with header comment', () => {
const doc = YAML.parseDocument<YAML.YAMLMap>('a: |5 #c1\n')
const str = doc.toString()
expect(str).toBe('a: | #c1\n\n')

const reparsed = YAML.parseDocument<YAML.YAMLMap>(str)
expect(reparsed.toJS()).toEqual({ a: '' })
expect(reparsed.get('a')).toMatchObject({ comment: 'c1' })
})
})