Skip to content

Commit 65ca806

Browse files
authored
Fix Unmarshaler call when value is missing (#439)
Fixes #431
1 parent 5c94d86 commit 65ca806

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

marshal.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -742,6 +742,10 @@ func (d *Decoder) valueFromTree(mtype reflect.Type, tval *Tree, mval1 *reflect.V
742742
if mvalPtr := reflect.New(mtype); isCustomUnmarshaler(mvalPtr.Type()) {
743743
d.visitor.visitAll()
744744

745+
if tval == nil {
746+
return mvalPtr.Elem(), nil
747+
}
748+
745749
if err := callCustomUnmarshaler(mvalPtr, tval.ToMap()); err != nil {
746750
return reflect.ValueOf(nil), fmt.Errorf("unmarshal toml: %v", err)
747751
}

marshal_test.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3941,3 +3941,38 @@ bar = 42
39413941

39423942
reflect.DeepEqual(x, expected)
39433943
}
3944+
3945+
type Config struct {
3946+
Key string `toml:"key"`
3947+
Obj Custom `toml:"obj"`
3948+
}
3949+
3950+
type Custom struct {
3951+
v string
3952+
}
3953+
3954+
func (c *Custom) UnmarshalTOML(v interface{}) error {
3955+
c.v = "called"
3956+
return nil
3957+
}
3958+
3959+
func TestGithubIssue431(t *testing.T) {
3960+
doc := `key = "value"`
3961+
tree, err := LoadBytes([]byte(doc))
3962+
if err != nil {
3963+
t.Fatalf("unexpected error: %s", err)
3964+
}
3965+
3966+
var c Config
3967+
if err := tree.Unmarshal(&c); err != nil {
3968+
t.Fatalf("unexpected error: %s", err)
3969+
}
3970+
3971+
if c.Key != "value" {
3972+
t.Errorf("expected c.Key='value', not '%s'", c.Key)
3973+
}
3974+
3975+
if c.Obj.v == "called" {
3976+
t.Errorf("UnmarshalTOML should not have been called")
3977+
}
3978+
}

0 commit comments

Comments
 (0)