Skip to content

Commit

Permalink
fix: Stringify flow collection comments in parent (fixes #528)
Browse files Browse the repository at this point in the history
  • Loading branch information
eemeli committed Mar 5, 2024
1 parent e07998c commit 750adbe
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 13 deletions.
19 changes: 6 additions & 13 deletions src/stringify/stringifyCollection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,9 @@ function stringifyBlockCollection(
}

function stringifyFlowCollection(
{ comment, items }: Readonly<Collection>,
{ items }: Readonly<Collection>,
ctx: StringifyContext,
{ flowChars, itemIndent, onComment }: StringifyCollectionOptions
{ flowChars, itemIndent }: StringifyCollectionOptions
) {
const {
indent,
Expand Down Expand Up @@ -141,30 +141,23 @@ function stringifyFlowCollection(
linesAtValue = lines.length
}

let str: string
const { start, end } = flowChars
if (lines.length === 0) {
str = start + end
return start + end
} else {
if (!reqNewline) {
const len = lines.reduce((sum, line) => sum + line.length + 2, 2)
reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth
}
if (reqNewline) {
str = start
let str = start
for (const line of lines)
str += line ? `\n${indentStep}${indent}${line}` : '\n'
str += `\n${indent}${end}`
return `${str}\n${indent}${end}`
} else {
str = `${start}${fcPadding}${lines.join(' ')}${fcPadding}${end}`
return `${start}${fcPadding}${lines.join(' ')}${fcPadding}${end}`
}
}

if (comment) {
str += lineComment(str, indent, commentString(comment))
if (onComment) onComment()
}
return str
}

function addCommentBefore(
Expand Down
28 changes: 28 additions & 0 deletions tests/doc/comments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,19 @@ describe('stringify comments', () => {
`)
})

test('line comment after [], in seq', () => {
const doc = YAML.parseDocument(source`
[ [a], #c0
[b] #c1
]`)
expect(String(doc)).toBe(source`
[
[ a ], #c0
[ b ] #c1
]
`)
})

test('line comment after , in map', () => {
const doc = YAML.parseDocument(source`
{ a, #c0
Expand All @@ -555,6 +568,21 @@ describe('stringify comments', () => {
`)
})

test('line comment after {}, in map', () => {
const doc = YAML.parseDocument(source`
{ {a: 1}, #c0
b: {c: 2}, #c1
d #c2
}`)
expect(String(doc)).toBe(source`
{
? { a: 1 }, #c0
b: { c: 2 }, #c1
d #c2
}
`)
})

test('line comment after flow collection (eemeli/yaml#443)', () => {
const doc = YAML.parseDocument(source`
[ value1, value2 ] # comment
Expand Down

0 comments on commit 750adbe

Please sign in to comment.