Skip to content

Commit

Permalink
add node formatter (#644)
Browse files Browse the repository at this point in the history
  • Loading branch information
goccy authored Feb 9, 2025
1 parent 8d4b192 commit 0653c80
Show file tree
Hide file tree
Showing 3 changed files with 373 additions and 27 deletions.
23 changes: 2 additions & 21 deletions decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (

"github.com/goccy/go-yaml/ast"
"github.com/goccy/go-yaml/internal/errors"
"github.com/goccy/go-yaml/internal/format"
"github.com/goccy/go-yaml/parser"
"github.com/goccy/go-yaml/token"
)
Expand Down Expand Up @@ -756,33 +757,13 @@ 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) unmarshalableDocument(node ast.Node) ([]byte, error) {
var err error
node, err = d.resolveAlias(node)
if err != nil {
return nil, err
}
doc := node.String()
last := d.lastNode(node)
if last != nil && last.Type() == ast.LiteralType {
doc += "\n"
}
doc := format.FormatNode(node, d.toCommentMap != nil)
return []byte(doc), nil
}

Expand Down
61 changes: 55 additions & 6 deletions decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2757,13 +2757,13 @@ type unmarshalList struct {

func (u *unmarshalList) UnmarshalYAML(b []byte) error {
expected := `
- b: c
d: |
hello
- b: c
d: |
hello
hello
f: g
- h: i`
hello
f: g
- h: i`
actual := "\n" + string(b)
if expected != actual {
return fmt.Errorf("unexpected bytes: expected [%q] but got [%q]", expected, actual)
Expand Down Expand Up @@ -3207,3 +3207,52 @@ a: !Not [!Equals [!Ref foo, 'bar']]
t.Fatalf("found unexpected value: %v", v)
}
}

type issue337Template struct{}

func (i *issue337Template) UnmarshalYAML(b []byte) error {
expected := strings.TrimPrefix(`
|
apiVersion: v1
kind: ConfigMap
metadata:
name: "abc"
namespace: "abc"
data:
foo: FOO
`, "\n")
if !bytes.Equal(b, []byte(expected)) {
return fmt.Errorf("expected:\n%s\nbut got:\n%s\n", expected, string(b))
}
return nil
}

func TestIssue337(t *testing.T) {
yml := `
releases:
- name: foo
chart: ./raw
values:
- templates:
- |
apiVersion: v1
kind: ConfigMap
metadata:
name: "abc"
namespace: "abc"
data:
foo: FOO
`
type Value struct {
Templates []*issue337Template `yaml:"templates"`
}
type Release struct {
Values []*Value `yaml:"values"`
}
var v struct {
Releases []*Release `yaml:"releases"`
}
if err := yaml.Unmarshal([]byte(yml), &v); err != nil {
t.Fatal(err)
}
}
Loading

0 comments on commit 0653c80

Please sign in to comment.