From 6682fda95a4fcc4824cf2513e54197f2d5a7df12 Mon Sep 17 00:00:00 2001 From: Nash Aschenbath Date: Tue, 24 Nov 2026 23:51:12 +0800 Subject: [PATCH] Clear existing values when reflecting an empty slice --- struct.go | 7 ++++++ struct_empty_slice_test.go | 48 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 struct_empty_slice_test.go diff --git a/struct.go b/struct.go index 2fcd025..fdf629c 100644 --- a/struct.go +++ b/struct.go @@ -601,6 +601,13 @@ func StrictMapTo(v, source any, opts ...LoadOption) error { // encodeSlice does the opposite thing as decodeSlice. func encodeSlice(key *Key, field reflect.Value, delim string, allowShadow bool) error { if field.Len() == 0 { + key.s.f.maybeLock() + defer key.s.f.maybeUnlock() + key = key.attach() + key.value = "" + if allowShadow { + key.shadows = nil + } return nil } elemType := field.Type().Elem() diff --git a/struct_empty_slice_test.go b/struct_empty_slice_test.go new file mode 100644 index 0000000..be6c5b2 --- /dev/null +++ b/struct_empty_slice_test.go @@ -0,0 +1,48 @@ +package ini + +import ( + "bytes" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestReflectFrom_EmptySliceOverwritesExistingValues(t *testing.T) { + type config struct { + Plain []string `ini:"plain"` + Shadow []string `ini:"shadow,allowshadow"` + Keep []string `ini:"keep,omitempty"` + KeepShadows []string `ini:"keep_shadows,omitempty,allowshadow"` + } + for _, preserveEmpty := range []bool{false, true} { + for _, tc := range []struct { + name string + in config + }{ + {name: "nil"}, + {name: "empty", in: config{Plain: []string{}, Shadow: []string{}, Keep: []string{}, KeepShadows: []string{}}}, + } { + t.Run(tc.name+map[bool]string{false: "/drop-empty", true: "/preserve-empty"}[preserveEmpty], func(t *testing.T) { + opts := []LoadOption{AllowShadows(true), PreserveEmptyShadowValues(preserveEmpty)} + f, err := Load([]byte("plain = a,b\nshadow = a\nshadow = b\nkeep = x,y\nkeep_shadows = x\nkeep_shadows = y\n"), opts...) + require.NoError(t, err) + require.NoError(t, f.ReflectFrom(&tc.in)) + assert.Empty(t, f.Section("").Key("plain").String()) + assert.Empty(t, f.Section("").Key("shadow").String()) + assert.Equal(t, "x,y", f.Section("").Key("keep").String()) + assert.Equal(t, []string{"x", "y"}, f.Section("").Key("keep_shadows").Values()) + + var buf bytes.Buffer + _, err = f.WriteTo(&buf) + require.NoError(t, err) + var out config + require.NoError(t, MapTo(&out, buf.Bytes(), opts...)) + assert.Empty(t, out.Plain) + assert.Empty(t, out.Shadow) + assert.Equal(t, []string{"x", "y"}, out.Keep) + assert.Equal(t, []string{"x", "y"}, out.KeepShadows) + }) + } + } +}