Skip to content

Commit

Permalink
Merge pull request #137 from goccy/feature/fix-encode-literal
Browse files Browse the repository at this point in the history
Fix encoding when last node is literal
  • Loading branch information
goccy authored Jun 16, 2020
2 parents 60a0cd3 + 80e0e8a commit 0bc342e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
20 changes: 20 additions & 0 deletions decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,22 @@ func (d *Decoder) deleteStructKeys(structType reflect.Type, unknownFields map[st
return nil
}

func (d *Decoder) lastNode(node ast.Node) ast.Node {
switch n := node.(type) {
case *ast.MappingNode:
if len(n.Values) > 0 {
return d.lastNode(n.Values[len(n.Values)-1])
}
case *ast.MappingValueNode:
return d.lastNode(n.Value)
case *ast.SequenceNode:
if len(n.Values) > 0 {
return d.lastNode(n.Values[len(n.Values)-1])
}
}
return node
}

func (d *Decoder) decodeValue(dst reflect.Value, src ast.Node) error {
if src.Type() == ast.AnchorType {
anchorName := src.(*ast.AnchorNode).Name.GetToken().Value
Expand All @@ -435,6 +451,10 @@ func (d *Decoder) decodeValue(dst reflect.Value, src ast.Node) error {
} else {
b = src.String()
}
last := d.lastNode(src)
if last != nil && last.Type() == ast.LiteralType {
b += "\n"
}
if err := unmarshaler.UnmarshalYAML([]byte(b)); err != nil {
return errors.Wrapf(err, "failed to UnmarshalYAML")
}
Expand Down
11 changes: 9 additions & 2 deletions decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1948,8 +1948,15 @@ b:
}
}

type unmarshalString string

func (u *unmarshalString) UnmarshalYAML(b []byte) error {
*u = unmarshalString(string(b))
return nil
}

type unmarshalList struct {
v []map[string]string
v []map[string]unmarshalString
}

func (u *unmarshalList) UnmarshalYAML(b []byte) error {
Expand All @@ -1965,7 +1972,7 @@ func (u *unmarshalList) UnmarshalYAML(b []byte) error {
if expected != actual {
return xerrors.Errorf("unexpected bytes: expected [%q] but got [%q]", expected, actual)
}
var v []map[string]string
var v []map[string]unmarshalString
if err := yaml.Unmarshal(b, &v); err != nil {
return err
}
Expand Down

0 comments on commit 0bc342e

Please sign in to comment.