diff --git a/viper.go b/viper.go index 1f25785..1b749a2 100644 --- a/viper.go +++ b/viper.go @@ -418,6 +418,21 @@ func (v *Viper) Marshal(rawVal interface{}) error { 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) // Example(where serverCmd is a Cobra instance): // diff --git a/viper_test.go b/viper_test.go index 78b107b..4d049b6 100644 --- a/viper_test.go +++ b/viper_test.go @@ -333,6 +333,41 @@ func TestMarshal(t *testing.T) { 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) { var testString = "testing" var testValue = newStringValue(testString, &testString)