Skip to content
Open
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
10 changes: 5 additions & 5 deletions struct.go
Original file line number Diff line number Diff line change
Expand Up @@ -749,6 +749,11 @@ func (s *Section) encodeStruct(val reflect.Value, path []reflect.Type) error {
continue
}

// A nil pointer has nothing to write, including a StructReflector.
if field.Kind() == reflect.Pointer && field.IsNil() {
continue
}

if r, ok := field.Interface().(StructReflector); ok {
if err := r.ReflectINIStruct(s.f); err != nil {
return err
Expand All @@ -761,11 +766,6 @@ func (s *Section) encodeStruct(val reflect.Value, path []reflect.Type) error {
continue
}

// A nil pointer has nothing to write.
if field.Kind() == reflect.Pointer && field.IsNil() {
continue
}

isStruct := isStructType(tpField.Type)
isStructPtr := tpField.Type.Kind() == reflect.Pointer && isStructType(tpField.Type.Elem())
structType := tpField.Type
Expand Down
45 changes: 45 additions & 0 deletions struct_nil_reflector_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package ini

import (
"bytes"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

type optionalReflector struct {
Value string
}

func (r *optionalReflector) ReflectINIStruct(f *File) error {
f.Section("custom").Key("value").SetValue(r.Value)
return nil
}

func TestReflectFrom_NilStructReflector(t *testing.T) {
for _, tc := range []struct {
name string
reflector *optionalReflector
want string
}{
{name: "nil", want: "After = kept\n"},
{name: "non-nil", reflector: &optionalReflector{Value: "present"},
want: "After = kept\n\n[custom]\nvalue = present\n"},
} {
t.Run(tc.name, func(t *testing.T) {
f := Empty()
in := struct {
Optional *optionalReflector
After string
}{Optional: tc.reflector, After: "kept"}
require.NotPanics(t, func() {
require.NoError(t, f.ReflectFrom(&in))
})
var buf bytes.Buffer
_, err := f.WriteTo(&buf)
require.NoError(t, err)
assert.Equal(t, tc.want, buf.String())
})
}
}