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
15 changes: 14 additions & 1 deletion key.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,10 @@ func (k *Key) NestedValues() []string {

// transformValue takes a raw value and transforms to its final string.
func (k *Key) transformValue(val string) string {
return k.transformValueWithVisited(val, map[*Key]bool{k: true})
}

func (k *Key) transformValueWithVisited(val string, visited map[*Key]bool) string {
if k.s.f.ValueMapper != nil {
val = k.s.f.ValueMapper(val)
}
Expand Down Expand Up @@ -169,8 +173,17 @@ func (k *Key) transformValue(val string) string {
}
}

// A reference back to a key already being resolved is left intact,
// just like a direct self-reference.
if visited[nk] {
break
}
visited[nk] = true
replacement := nk.transformValueWithVisited(nk.value, visited)
delete(visited, nk)

// Substitute by new value and take off leading '%(' and trailing ')s'.
val = strings.ReplaceAll(val, vr, nk.String())
val = strings.ReplaceAll(val, vr, replacement)
}
return val
}
Expand Down
13 changes: 13 additions & 0 deletions key_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -626,6 +626,19 @@ expires = %(expires)s`))
assert.Equal(t, "yes", f.Section("package").Key("expires").String())
})

t.Run("mutually recursive keys remain unresolved", func(t *testing.T) {
f, err := Load([]byte("[s]\na = %(b)s\nb = %(a)s\n"))
require.NoError(t, err)
assert.Equal(t, "%(a)s", f.Section("s").Key("a").String())
assert.Equal(t, "%(b)s", f.Section("s").Key("b").String())
})

t.Run("longer reference cycle remains unresolved", func(t *testing.T) {
f, err := Load([]byte("[s]\na = %(b)s\nb = %(c)s\nc = %(a)s\n"))
require.NoError(t, err)
assert.Equal(t, "%(a)s", f.Section("s").Key("a").String())
})

t.Run("recursive value with no target found", func(t *testing.T) {
f, err := Load([]byte(`
[foo]
Expand Down