mirror of
https://github.com/spf13/viper
synced 2024-12-22 19:47:01 +00:00
Added BindPFlags function which binds all flags in a given flag set to the pflags register
This commit is contained in:
parent
9a0a6692b7
commit
24dd877ad7
2 changed files with 50 additions and 0 deletions
15
viper.go
15
viper.go
|
@ -418,6 +418,21 @@ func (v *Viper) Marshal(rawVal interface{}) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Bind a full flag set to the configuration, using each flag's long
|
||||||
|
// name as the config key.
|
||||||
|
func BindPFlags(flags *pflag.FlagSet) (err error) { return v.BindPFlags(flags) }
|
||||||
|
func (v *Viper) BindPFlags(flags *pflag.FlagSet) (err error) {
|
||||||
|
flags.VisitAll(func(flag *pflag.Flag) {
|
||||||
|
if err != nil {
|
||||||
|
// an error has been encountered in one of the previous flags
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = v.BindPFlag(flag.Name, flag)
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// Bind a specific key to a flag (as used by cobra)
|
// Bind a specific key to a flag (as used by cobra)
|
||||||
// Example(where serverCmd is a Cobra instance):
|
// Example(where serverCmd is a Cobra instance):
|
||||||
//
|
//
|
||||||
|
|
|
@ -333,6 +333,41 @@ func TestMarshal(t *testing.T) {
|
||||||
assert.Equal(t, &C, &config{Name: "Steve", Port: 1234})
|
assert.Equal(t, &C, &config{Name: "Steve", Port: 1234})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestBindPFlags(t *testing.T) {
|
||||||
|
flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
|
||||||
|
|
||||||
|
var testValues = map[string]*string{
|
||||||
|
"host": nil,
|
||||||
|
"port": nil,
|
||||||
|
"endpoint": nil,
|
||||||
|
}
|
||||||
|
|
||||||
|
var mutatedTestValues = map[string]string{
|
||||||
|
"host": "localhost",
|
||||||
|
"port": "6060",
|
||||||
|
"endpoint": "/public",
|
||||||
|
}
|
||||||
|
|
||||||
|
for name, _ := range testValues {
|
||||||
|
testValues[name] = flagSet.String(name, "", "test")
|
||||||
|
}
|
||||||
|
|
||||||
|
err := BindPFlags(flagSet)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("error binding flag set, %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
flagSet.VisitAll(func(flag *pflag.Flag) {
|
||||||
|
flag.Value.Set(mutatedTestValues[flag.Name])
|
||||||
|
flag.Changed = true
|
||||||
|
})
|
||||||
|
|
||||||
|
for name, expected := range mutatedTestValues {
|
||||||
|
assert.Equal(t, Get(name), expected)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
func TestBindPFlag(t *testing.T) {
|
func TestBindPFlag(t *testing.T) {
|
||||||
var testString = "testing"
|
var testString = "testing"
|
||||||
var testValue = newStringValue(testString, &testString)
|
var testValue = newStringValue(testString, &testString)
|
||||||
|
|
Loading…
Reference in a new issue