From 25b5a7c2607bdcc4c2ff52d492d38fa3282b959c Mon Sep 17 00:00:00 2001 From: qianlongzt <1401300561@qq.com> Date: Fri, 20 Sep 2024 22:34:43 +0800 Subject: [PATCH] fix(basicflag): option not apply --- providers/basicflag/basicflag.go | 9 ++++++++- tests/koanf_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/providers/basicflag/basicflag.go b/providers/basicflag/basicflag.go index a5f5a812..10947a20 100644 --- a/providers/basicflag/basicflag.go +++ b/providers/basicflag/basicflag.go @@ -66,11 +66,18 @@ func Provider(f *flag.FlagSet, delim string, opt ...*Opt) *Pflag { // function definition. // See https://github.com/knadh/koanf/issues/255 func ProviderWithValue(f *flag.FlagSet, delim string, cb func(key string, value string) (string, interface{}), ko ...KoanfIntf) *Pflag { - return &Pflag{ + pf := &Pflag{ flagset: f, delim: delim, cb: cb, } + + if len(ko) > 0 { + pf.opt = &Opt{ + KeyMap: ko[0], + } + } + return pf } // Read reads the flag variables and returns a nested conf map. diff --git a/tests/koanf_test.go b/tests/koanf_test.go index 16ab9537..dc549c3f 100644 --- a/tests/koanf_test.go +++ b/tests/koanf_test.go @@ -709,6 +709,30 @@ func TestFlags(t *testing.T) { assert.Equal("custom", k.String("parent2.child2.name"), "basicflag set failed") } + // Override with the basicflag provider. + { + k := def.Copy() + bf := flag.NewFlagSet("test", flag.ContinueOnError) + bf.String("parent1.child1.type", "flag", "") + bf.String("parent2.child2.name", "override-default", "") + bf.Set("parent1.child1.type", "basicflag") + assert.Nil(k.Load(basicflag.ProviderWithValue(bf, ".",nil), nil), "error loading basicflag") + assert.Equal("basicflag", k.String("parent1.child1.type"), "types don't match") + assert.Equal("override-default", k.String("parent2.child2.name"), "basicflag default value override failed") + } + + // No defualt-value override behaviour. + { + k := def.Copy() + bf := flag.NewFlagSet("test", flag.ContinueOnError) + bf.String("parent1.child1.name", "override-default", "") + bf.String("parent2.child2.name", "override-default", "") + bf.Set("parent2.child2.name", "custom") + assert.Nil(k.Load(basicflag.ProviderWithValue(bf, ".",nil, def),nil), "error loading basicflag") + assert.Equal("child1", k.String("parent1.child1.name"), "basicflag default overwrote") + assert.Equal("custom", k.String("parent2.child2.name"), "basicflag set failed") + } + // Override with the basicflag provider. { k := def.Copy()