key: deduplicate shadows while adding (#207)

This commit is contained in:
unknwon
2019-09-22 22:54:29 -07:00
parent 6ba806069d
commit 86335412cb
2 changed files with 29 additions and 0 deletions
+19
View File
@@ -305,3 +305,22 @@ func TestFile_SaveTo(t *testing.T) {
So(f.SaveToIndent("testdata/conf_out.ini", "\t"), ShouldBeNil) So(f.SaveToIndent("testdata/conf_out.ini", "\t"), ShouldBeNil)
}) })
} }
// Inspired by https://github.com/go-ini/ini/issues/207
func TestReloadAfterShadowLoad(t *testing.T) {
Convey("Reload file after ShadowLoad", t, func() {
f, err := ini.ShadowLoad([]byte(`
[slice]
v = 1
v = 2
v = 3
`))
So(err, ShouldBeNil)
So(f, ShouldNotBeNil)
So(f.Section("slice").Key("v").ValueWithShadows(), ShouldResemble, []string{"1", "2", "3"})
So(f.Reload(), ShouldBeNil)
So(f.Section("slice").Key("v").ValueWithShadows(), ShouldResemble, []string{"1", "2", "3"})
})
}
+10
View File
@@ -54,6 +54,16 @@ func (k *Key) addShadow(val string) error {
return errors.New("cannot add shadow to auto-increment or boolean key") return errors.New("cannot add shadow to auto-increment or boolean key")
} }
// Deduplicate shadows based on their values.
if k.value == val {
return nil
}
for i := range k.shadows {
if k.shadows[i].value == val {
return nil
}
}
shadow := newKey(k.s, k.name, val) shadow := newKey(k.s, k.name, val)
shadow.isShadow = true shadow.isShadow = true
k.shadows = append(k.shadows, shadow) k.shadows = append(k.shadows, shadow)