Adding the ability to bind a flag to a key. Will set the default & override automatically. - viper - [fork] go viper port for 9front
(HTM) git clone git@git.drkhsh.at/viper.git
(DIR) Log
(DIR) Files
(DIR) Refs
(DIR) README
(DIR) LICENSE
---
(DIR) commit 7c42740ea622bc885e5faac3757a8bd906224a13
(DIR) parent af373af72c16a023e39cee8a68f9fa9c7f9c2512
(HTM) Author: spf13 <steve.francia@gmail.com>
Date: Fri, 27 Jun 2014 12:29:37 -0400
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"))
Diffstat:
M viper.go | 20 ++++++++++++++++++++
1 file changed, 20 insertions(+), 0 deletions(-)
---
(DIR) diff --git a/viper.go b/viper.go
@@ -23,6 +23,7 @@ import (
"github.com/mitchellh/mapstructure"
"github.com/spf13/cast"
jww "github.com/spf13/jwalterweatherman"
+ "github.com/spf13/pflag"
"gopkg.in/yaml.v1"
)
@@ -40,6 +41,7 @@ var configType string
var config 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 pflags map[string]*pflag.Flag = make(map[string]*pflag.Flag)
var aliases map[string]string = make(map[string]string)
func SetConfigFile(in string) {
@@ -116,6 +118,15 @@ func GetAllIntoStruct(rawVal interface{}) (err error) {
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{} {
var val interface{}
var exists bool
@@ -123,6 +134,15 @@ func find(key string) interface{} {
// if the requested key is an alias, then return the proper 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]
if exists {
jww.TRACE.Println(key, "found in override:", val)