Skip to content
Draft
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
26 changes: 26 additions & 0 deletions syntax/encoding/yaml.go
Original file line number Diff line number Diff line change
Expand Up @@ -629,8 +629,34 @@ func DecodeYAML(filename string, d *yaml.Decoder, tags TagDecoder) (syntax.Node,
// encoding process.
func EncodeYAML(e *yaml.Encoder, n syntax.Node) syntax.Diagnostics {
yamlNode, diags := MarshalYAML(n)
fixFlowStyles(yamlNode)

if err := e.Encode(yamlNode); err != nil {
diags.Extend(syntax.Error(nil, err.Error(), ""))
}
return diags
}

// fixFlowStyles converts flow-style mappings/sequences to block style when they contain comments,
// which can cause ambiguous YAML that stricter parsers reject.
func fixFlowStyles(node *yaml.Node) {
if node == nil {
return
}
if (node.Kind == yaml.MappingNode || node.Kind == yaml.SequenceNode) &&
node.Style&yaml.FlowStyle != 0 && hasChildWithComment(node) {
node.Style = 0
}
for _, child := range node.Content {
fixFlowStyles(child)
}
}

func hasChildWithComment(node *yaml.Node) bool {
for _, child := range node.Content {
if child.LineComment != "" || child.HeadComment != "" || child.FootComment != "" {
return true
}
}
return false
}
28 changes: 28 additions & 0 deletions syntax/encoding/yaml_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,34 @@ baz: qux
assert.Equal(t, expected, b.String())
}

func TestYAMLFlowWithChildCommentReEmitsAsBlock(t *testing.T) {
// A flow-style sequence whose child carries a comment produces ambiguous YAML
// when re-emitted as flow (e.g. `items: [one, # first\n two, three]`), which
// stricter parsers reject. EncodeYAML should convert such nodes to block style.
const doc = `items: [
one, # first
two,
three,
]
`
const expected = `items:
- one # first
- two
- three
`

rootNode, diags := DecodeYAML("yaml", yaml.NewDecoder(strings.NewReader(doc)), nil)
require.Empty(t, diags)

var b bytes.Buffer
enc := yaml.NewEncoder(&b)
enc.SetIndent(2)
diags = EncodeYAML(enc, rootNode)

assert.Empty(t, diags)
assert.Equal(t, expected, b.String())
}

func TestYAMLDeleteAllValuesThenAdd(t *testing.T) {
const doc = `values:
example1: abc`
Expand Down
Loading