Skip to content

Commit

Permalink
fix: Default to literal block scalar if folded would overflow (fixes #…
Browse files Browse the repository at this point in the history
  • Loading branch information
eemeli committed Nov 19, 2024
1 parent 108f699 commit 6be0a91
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 17 deletions.
42 changes: 25 additions & 17 deletions src/stringify/stringifyString.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,29 +246,37 @@ function blockString(
}

const indentSize = indent ? '2' : '1' // root is at -1
let header =
(literal ? '|' : '>') + (startWithSpace ? indentSize : '') + chomp
// Leading | or > is added later
let header = (startWithSpace ? indentSize : '') + chomp
if (comment) {
header += ' ' + commentString(comment.replace(/ ?[\r\n]+/g, ' '))
if (onComment) onComment()
}

if (literal) {
value = value.replace(/\n+/g, `$&${indent}`)
return `${header}\n${indent}${start}${value}${end}`
if (!literal) {
const foldedValue = value
.replace(/\n+/g, '\n$&')
.replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded
// ^ more-ind. ^ empty ^ capture next empty lines only at end of indent
.replace(/\n+/g, `$&${indent}`)
let literalFallback = false
const foldOptions = getFoldOptions(ctx, true)
if (blockQuote !== 'folded' && type !== Scalar.BLOCK_FOLDED) {
foldOptions.onOverflow = () => {
literalFallback = true
}
}
const body = foldFlowLines(
`${start}${foldedValue}${end}`,
indent,
FOLD_BLOCK,
foldOptions
)
if (!literalFallback) return `>${header}\n${indent}${body}`
}
value = value
.replace(/\n+/g, '\n$&')
.replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded
// ^ more-ind. ^ empty ^ capture next empty lines only at end of indent
.replace(/\n+/g, `$&${indent}`)
const body = foldFlowLines(
`${start}${value}${end}`,
indent,
FOLD_BLOCK,
getFoldOptions(ctx, true)
)
return `${header}\n${indent}${body}`

value = value.replace(/\n+/g, `$&${indent}`)
return `|${header}\n${indent}${start}${value}${end}`
}

function plainString(
Expand Down
10 changes: 10 additions & 0 deletions tests/doc/foldFlowLines.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,16 @@ describe('block scalar', () => {
}
`)
})

test('block scalar with very long lines (#585)', () => {
const str = ('a'.repeat(30) + '\n').repeat(3)
expect(YAML.stringify(str, { lineWidth: 20 })).toBe(source`
|
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
`)
})
})

describe('end-to-end', () => {
Expand Down

0 comments on commit 6be0a91

Please sign in to comment.