From da3a163f9ee2f0b6958988a4d46e5d9be98048af Mon Sep 17 00:00:00 2001 From: Joe Chen Date: Sun, 15 Nov 2026 01:30:52 +0000 Subject: [PATCH] Pass the key to ValueMapper ValueMapper is now func(k *Key, value string) string, and Key.Section and Section.File reach the rest of the file, so a mapper can expand references to other sections or keys of its own (#357). --- docs/migrate-v1-to-v2.md | 3 ++- key.go | 14 +++++++++++--- key_test.go | 27 +++++++++++++++++++++++++-- options.go | 4 ++-- section.go | 5 +++++ 5 files changed, 45 insertions(+), 8 deletions(-) diff --git a/docs/migrate-v1-to-v2.md b/docs/migrate-v1-to-v2.md index f3a58a8..9a3d386 100644 --- a/docs/migrate-v1-to-v2.md +++ b/docs/migrate-v1-to-v2.md @@ -104,7 +104,8 @@ For ordinary files, `Write` output is byte-identical to v1's, apart from the par | `LooseLoad`, `InsensitiveLoad`, `ShadowLoad` | `Load` with `ini.IgnoreMissingFiles(true)`, `ini.CaseInsensitive(true)`, `ini.AllowShadows(true)` | | `MapTo(v, a, b)` | `MapTo(v, a, opts...)`, with one source | | `MapToWithMapper(v, m, a)`, `StrictMapToWithMapper` | `MapTo(v, a, ini.NameMapping(m))`, `StrictMapTo(v, a, ini.NameMapping(m))` | -| `f.NameMapper = m`, `f.ValueMapper = fn` | load with `ini.NameMapping(m)`, `ini.ValueMapping(fn)` | +| `f.NameMapper = m` | load with `ini.NameMapping(m)` | +| `f.ValueMapper = fn` | load with `ini.ValueMapping(func(_ *ini.Key, v string) string { return fn(v) })`. The mapper gets the key whose value it maps, and reaches other keys through `k.Section()` and `k.Section().File()`. | | `f.BlockMode = false` | load with `ini.Locking(false)` | | `ini.DefaultSection = "default"` | load with `ini.DefaultSectionName("default")`. `DefaultSection` is now a constant. | diff --git a/key.go b/key.go index 5eeb854..13b30dd 100644 --- a/key.go +++ b/key.go @@ -115,8 +115,16 @@ func (k *Key) AddNestedValue(val string) error { return k.attach().addNestedValue(val) } -// ValueMapper represents a mapping function for values, e.g., os.ExpandEnv -type ValueMapper func(string) string +// ValueMapper maps the raw value of k before %(name)s references in it are +// expanded. It can read other keys through k.Section and k.Section().File, +// for example to expand references of its own. Wrap a func(string) string +// such as os.ExpandEnv as func(_ *Key, v string) string { return os.ExpandEnv(v) }. +type ValueMapper func(k *Key, value string) string + +// Section returns the section of the key. +func (k *Key) Section() *Section { + return k.s +} // Name returns name of key. func (k *Key) Name() string { @@ -214,7 +222,7 @@ type expansion struct { // overflowing the stack or using up time and memory. func (k *Key) expand(val string, depth int, e *expansion) string { if k.s.f.options.ValueMapper != nil { - val = k.s.f.options.ValueMapper(val) + val = k.s.f.options.ValueMapper(k, val) } // Fail-fast if no indicate char found for recursive value diff --git a/key_test.go b/key_test.go index a0cf3ab..79e85a4 100644 --- a/key_test.go +++ b/key_test.go @@ -3,6 +3,7 @@ package ini import ( "bytes" "fmt" + "regexp" "runtime" "strings" "testing" @@ -96,7 +97,7 @@ func TestKey_Helpers(t *testing.T) { assert.Equal(t, "gopkg.in/ini.v1", sec.Key("IMPORT_PATH").String()) t.Run("with ValueMapper", func(t *testing.T) { - f, err := Load(fullConf, ValueMapping(func(in string) string { + f, err := Load(fullConf, ValueMapping(func(_ *Key, in string) string { if in == "gopkg.in/%(NAME)s.%(VERSION)s" { return "github.com/go-ini/ini" } @@ -466,7 +467,7 @@ bar = %(missing)s f, err := Load([]byte(` ACCOUNT_ID = ${LFSD_R2_ACCOUNT_ID} ENDPOINT = https://%(ACCOUNT_ID)s.r2.cloudflarestorage.com -`), ValueMapping(func(in string) string { +`), ValueMapping(func(_ *Key, in string) string { if in == "${LFSD_R2_ACCOUNT_ID}" { return "abc123" } @@ -477,4 +478,26 @@ ENDPOINT = https://%(ACCOUNT_ID)s.r2.cloudflarestorage.com assert.Equal(t, "https://abc123.r2.cloudflarestorage.com", f.Section("").Key("ENDPOINT").String()) }) + + t.Run("ValueMapper gets the key whose value it maps", func(t *testing.T) { + ref := regexp.MustCompile(`\$\{(\w+)\.(\w+)\}`) + f, err := Load([]byte(` +[db] +HOST = localhost +[app] +DSN = postgres://${db.HOST}/${self} +REF = %(DSN)s +`), ValueMapping(func(k *Key, in string) string { + in = strings.ReplaceAll(in, "${self}", k.Section().Name()+"."+k.Name()) + return ref.ReplaceAllStringFunc(in, func(m string) string { + sub := ref.FindStringSubmatch(m) + return k.Section().File().Section(sub[1]).Key(sub[2]).String() + }) + })) + require.NoError(t, err) + + assert.Equal(t, "postgres://localhost/app.DSN", f.Section("app").Key("DSN").String()) + // The referenced value is mapped with its own key, not the referencing one. + assert.Equal(t, "postgres://localhost/app.DSN", f.Section("app").Key("REF").String()) + }) } diff --git a/options.go b/options.go index 5744e25..00e05b2 100644 --- a/options.go +++ b/options.go @@ -68,8 +68,8 @@ func NameMapping(mapper NameMapper) LoadOption { return func(o *loadOptions) { o.NameMapper = mapper } } -// ValueMapping sets the ValueMapper applied to raw values, such as -// os.ExpandEnv, by Key.String and the accessors built on it. +// ValueMapping sets the ValueMapper applied to raw values by Key.String and +// the accessors built on it. func ValueMapping(mapper ValueMapper) LoadOption { return func(o *loadOptions) { o.ValueMapper = mapper } } diff --git a/section.go b/section.go index 6ee54cd..553910c 100644 --- a/section.go +++ b/section.go @@ -41,6 +41,11 @@ func newSection(f *File, name string) *Section { } } +// File returns the file of the section. +func (s *Section) File() *File { + return s.f +} + // current returns the section s reads and changes. That is s, unless s is // missing and its file has since gained a section of its name and index, // other than one added for another index. The caller holds the lock.