mirror of https://github.com/spf13/viper.git
Added BindPFlags function which binds all flags in a given flag set to the pflags register
This commit is contained in:
parent
ac722f39d3
commit
2ef7a4a18b
15
viper.go
15
viper.go
|
@ -361,6 +361,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)
|
||||||
//
|
//
|
||||||
// serverCmd.Flags().Int("port", 1138, "Port to run Application server on")
|
// serverCmd.Flags().Int("port", 1138, "Port to run Application server on")
|
||||||
|
|
|
@ -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 New Issue