forked from mirror/viper
Adding the ability to bind a flag to a key. Will set the default & override automatically.
Use like: fetchCmd.Flags().Int("rsstimeout", 5, "Timeout (in min) for RSS retrival") viper.BindPFlag("rsstimeout", fetchCmd.Flags().Lookup("rsstimeout"))
This commit is contained in:
parent
af373af72c
commit
7c42740ea6
20
viper.go
20
viper.go
|
@ -23,6 +23,7 @@ import (
|
||||||
"github.com/mitchellh/mapstructure"
|
"github.com/mitchellh/mapstructure"
|
||||||
"github.com/spf13/cast"
|
"github.com/spf13/cast"
|
||||||
jww "github.com/spf13/jwalterweatherman"
|
jww "github.com/spf13/jwalterweatherman"
|
||||||
|
"github.com/spf13/pflag"
|
||||||
"gopkg.in/yaml.v1"
|
"gopkg.in/yaml.v1"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -40,6 +41,7 @@ var configType string
|
||||||
var config map[string]interface{} = make(map[string]interface{})
|
var config map[string]interface{} = make(map[string]interface{})
|
||||||
var override map[string]interface{} = make(map[string]interface{})
|
var override map[string]interface{} = make(map[string]interface{})
|
||||||
var defaults map[string]interface{} = make(map[string]interface{})
|
var defaults map[string]interface{} = make(map[string]interface{})
|
||||||
|
var pflags map[string]*pflag.Flag = make(map[string]*pflag.Flag)
|
||||||
var aliases map[string]string = make(map[string]string)
|
var aliases map[string]string = make(map[string]string)
|
||||||
|
|
||||||
func SetConfigFile(in string) {
|
func SetConfigFile(in string) {
|
||||||
|
@ -116,6 +118,15 @@ func GetAllIntoStruct(rawVal interface{}) (err error) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func BindPFlag(key string, flag *pflag.Flag) (err error) {
|
||||||
|
if flag == nil {
|
||||||
|
return fmt.Errorf("flag for %q is nil", key)
|
||||||
|
}
|
||||||
|
pflags[key] = flag
|
||||||
|
SetDefault(key, flag.Value.String())
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func find(key string) interface{} {
|
func find(key string) interface{} {
|
||||||
var val interface{}
|
var val interface{}
|
||||||
var exists bool
|
var exists bool
|
||||||
|
@ -123,6 +134,15 @@ func find(key string) interface{} {
|
||||||
// if the requested key is an alias, then return the proper key
|
// if the requested key is an alias, then return the proper key
|
||||||
key = realKey(key)
|
key = realKey(key)
|
||||||
|
|
||||||
|
// PFlag Override first
|
||||||
|
flag, exists := pflags[key]
|
||||||
|
if exists {
|
||||||
|
if flag.Changed {
|
||||||
|
jww.TRACE.Println(key, "found in override (via pflag):", val)
|
||||||
|
return flag.Value.String()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
val, exists = override[key]
|
val, exists = override[key]
|
||||||
if exists {
|
if exists {
|
||||||
jww.TRACE.Println(key, "found in override:", val)
|
jww.TRACE.Println(key, "found in override:", val)
|
||||||
|
|
Loading…
Reference in New Issue