Skip to content
Merged
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
5 changes: 4 additions & 1 deletion key.go
Original file line number Diff line number Diff line change
Expand Up @@ -840,5 +840,8 @@ func (k *Key) SetValue(v string) {
}

k.value = v
k.s.keysHash[k.name] = v
// The Key Section.Key returns for an empty name isn't in the section.
if k.name != "" {
k.s.keysHash[k.name] = v
}
}
11 changes: 8 additions & 3 deletions section.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,12 +163,17 @@ func (s *Section) HasValue(value string) bool {
}

// Key assumes named Key exists in section and returns a zero-value when not.
// For an empty name, the returned Key is not part of the section, so setting
// its value changes nothing in the section.
func (s *Section) Key(name string) *Key {
key, err := s.GetKey(name)
if err != nil {
// It's OK here because the only possible error is empty key name,
// but if it's empty, this piece of code won't be executed.
key, _ = s.NewKey(name, "")
key, err = s.NewKey(name, "")
if err != nil {
// NewKey rejects empty names. Still honor the zero-value
// contract so Key("") is not nil.
return newKey(s, name, "")
}
return key
}
return key
Expand Down
13 changes: 13 additions & 0 deletions section_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,19 @@ func TestSection_Key(t *testing.T) {
assert.Equal(t, "404", k.Name())
})

t.Run("empty key name", func(t *testing.T) {
k := f.Section("").Key("")
require.NotNil(t, k)
assert.Equal(t, "", k.Name())
assert.Equal(t, "", k.Value())
assert.False(t, f.Section("").HasKey(""))

before := f.Section("").KeysHash()
k.SetValue("x")
assert.Equal(t, before, f.Section("").KeysHash())
assert.False(t, f.Section("").HasKey(""))
})

t.Run("key exists in parent section", func(t *testing.T) {
k, err := f.Section("parent").NewKey("AGE", "18")
require.NoError(t, err)
Expand Down