Skip to content
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
3 changes: 3 additions & 0 deletions struct.go
Original file line number Diff line number Diff line change
Expand Up @@ -620,6 +620,9 @@ func (s *Section) reflectFrom(val reflect.Value) error {
if err != nil {
// Note: fieldName can never be empty here, ignore error.
sec, _ = s.f.NewSection(fieldName)
} else if sec.name == s.name {
// Keep fields in the current occurrence of a non-unique section.
sec = s
}

// Add comment from comment tag
Expand Down
33 changes: 33 additions & 0 deletions struct_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -628,6 +628,39 @@ name = name
}

func Test_ReflectFromStructNonUniqueSections(t *testing.T) {
t.Run("reflect embedded structs into their own non unique sections", func(t *testing.T) {
type BaseSlot struct {
Id int `ini:",nonunique"`
}
type BigSlot struct {
*BaseSlot `ini:"big_slot,nonunique"`
Color string
}
type IniFile struct {
BigSlots []BigSlot `ini:"big_slot,nonunique"`
}

cfg := Empty(LoadOptions{AllowNonUniqueSections: true})
require.NoError(t, ReflectFrom(cfg, &IniFile{
BigSlots: []BigSlot{
{BaseSlot: &BaseSlot{Id: 3}, Color: "blue"},
{BaseSlot: &BaseSlot{Id: 4}, Color: "red"},
},
}))

var buf bytes.Buffer
_, err := cfg.WriteTo(&buf)
require.NoError(t, err)
assert.Equal(t, `[big_slot]
Id = 3
Color = blue

[big_slot]
Id = 4
Color = red
`, buf.String())
})

t.Run("reflect from struct with non unique sections", func(t *testing.T) {
nonUnique := &testNonUniqueSectionsStruct{
Interface: testInterface{
Expand Down