Skip to content

Commit

Permalink
fix(basicflag): option not apply (#322)
Browse files Browse the repository at this point in the history
  • Loading branch information
qianlongzt authored Sep 23, 2024
1 parent ec1d17c commit 09fd5db
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
9 changes: 8 additions & 1 deletion providers/basicflag/basicflag.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
24 changes: 24 additions & 0 deletions tests/koanf_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down

0 comments on commit 09fd5db

Please sign in to comment.