Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Call MarshalYAML on embedded structures #743

Closed
wants to merge 2 commits into from
Closed
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
16 changes: 16 additions & 0 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,22 @@ func (e *encoder) marshal(tag string, in reflect.Value) {
e.nilv()
return
}
// In case of embedded fields, let's get a poiter etc.
if in.CanAddr() {
m, ok := in.Addr().Interface().(Marshaler)
if ok {
v, err := m.MarshalYAML()
if err != nil {
fail(err)
}
if v == nil {
e.nilv()
return
}
in = reflect.ValueOf(v)
}
}

iface := in.Interface()
switch m := iface.(type) {
case jsonNumber:
Expand Down
18 changes: 16 additions & 2 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,24 @@ func (j jsonNumberT) String() string {

var marshalIntTest = 123

type Outer struct {
Inner Inner
}

type Inner struct{}

func (i *Inner) MarshalYAML() (interface{}, error) {
return "foo", nil
}

var marshalTests = []struct {
value interface{}
data string
}{
{
&Outer{},
"inner: foo\n",
},
{
nil,
"null\n",
Expand Down Expand Up @@ -406,8 +420,8 @@ func (s *S) TestLineWrapping(c *C) {
data, err := yaml.Marshal(v)
c.Assert(err, IsNil)
c.Assert(string(data), Equals,
"a: 'abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 abcdefghijklmnopqrstuvwxyz\n" +
" ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 '\n")
"a: 'abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 abcdefghijklmnopqrstuvwxyz\n"+
" ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 '\n")

// The API does not allow this process to be reversed as it's intended
// for migration only. v3 drops this method and instead offers more
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module gopkg.in/yaml.v2
module github.com/sustrik/yaml

go 1.15

Expand Down