gopkg.in/necryin/viper.v1@v1.0.2/viper.go (about)

     1  // Copyright © 2014 Steve Francia <spf@spf13.com>.
     2  //
     3  // Use of this source code is governed by an MIT-style
     4  // license that can be found in the LICENSE file.
     5  
     6  // Viper is a application configuration system.
     7  // It believes that applications can be configured a variety of ways
     8  // via flags, ENVIRONMENT variables, configuration files retrieved
     9  // from the file system, or a remote key/value store.
    10  
    11  // Each item takes precedence over the item below it:
    12  
    13  // overrides
    14  // flag
    15  // env
    16  // config
    17  // key/value store
    18  // default
    19  
    20  package viper
    21  
    22  import (
    23  	"bytes"
    24  	"encoding/csv"
    25  	"fmt"
    26  	"io"
    27  	"log"
    28  	"os"
    29  	"path/filepath"
    30  	"reflect"
    31  	"strings"
    32  	"time"
    33  
    34  	"github.com/fsnotify/fsnotify"
    35  	"github.com/mitchellh/mapstructure"
    36  	"github.com/spf13/afero"
    37  	"github.com/spf13/cast"
    38  	jww "github.com/spf13/jwalterweatherman"
    39  	"github.com/spf13/pflag"
    40  )
    41  
    42  var v *Viper
    43  
    44  type RemoteResponse struct {
    45  	Value []byte
    46  	Error error
    47  }
    48  
    49  func init() {
    50  	v = New()
    51  }
    52  
    53  type remoteConfigFactory interface {
    54  	Get(rp RemoteProvider) (io.Reader, error)
    55  	Watch(rp RemoteProvider) (io.Reader, error)
    56  	WatchChannel(rp RemoteProvider) (<-chan *RemoteResponse, chan bool)
    57  }
    58  
    59  // RemoteConfig is optional, see the remote package
    60  var RemoteConfig remoteConfigFactory
    61  
    62  // UnsupportedConfigError denotes encountering an unsupported
    63  // configuration filetype.
    64  type UnsupportedConfigError string
    65  
    66  // Error returns the formatted configuration error.
    67  func (str UnsupportedConfigError) Error() string {
    68  	return fmt.Sprintf("Unsupported Config Type %q", string(str))
    69  }
    70  
    71  // UnsupportedRemoteProviderError denotes encountering an unsupported remote
    72  // provider. Currently only etcd and Consul are supported.
    73  type UnsupportedRemoteProviderError string
    74  
    75  // Error returns the formatted remote provider error.
    76  func (str UnsupportedRemoteProviderError) Error() string {
    77  	return fmt.Sprintf("Unsupported Remote Provider Type %q", string(str))
    78  }
    79  
    80  // RemoteConfigError denotes encountering an error while trying to
    81  // pull the configuration from the remote provider.
    82  type RemoteConfigError string
    83  
    84  // Error returns the formatted remote provider error
    85  func (rce RemoteConfigError) Error() string {
    86  	return fmt.Sprintf("Remote Configurations Error: %s", string(rce))
    87  }
    88  
    89  // ConfigFileNotFoundError denotes failing to find configuration file.
    90  type ConfigFileNotFoundError struct {
    91  	name, locations string
    92  }
    93  
    94  // Error returns the formatted configuration error.
    95  func (fnfe ConfigFileNotFoundError) Error() string {
    96  	return fmt.Sprintf("Config File %q Not Found in %q", fnfe.name, fnfe.locations)
    97  }
    98  
    99  // Viper is a prioritized configuration registry. It
   100  // maintains a set of configuration sources, fetches
   101  // values to populate those, and provides them according
   102  // to the source's priority.
   103  // The priority of the sources is the following:
   104  // 1. overrides
   105  // 2. flags
   106  // 3. env. variables
   107  // 4. config file
   108  // 5. key/value store
   109  // 6. defaults
   110  //
   111  // For example, if values from the following sources were loaded:
   112  //
   113  //  Defaults : {
   114  //  	"secret": "",
   115  //  	"user": "default",
   116  //  	"endpoint": "https://localhost"
   117  //  }
   118  //  Config : {
   119  //  	"user": "root"
   120  //  	"secret": "defaultsecret"
   121  //  }
   122  //  Env : {
   123  //  	"secret": "somesecretkey"
   124  //  }
   125  //
   126  // The resulting config will have the following values:
   127  //
   128  //	{
   129  //		"secret": "somesecretkey",
   130  //		"user": "root",
   131  //		"endpoint": "https://localhost"
   132  //	}
   133  type Viper struct {
   134  	// Delimiter that separates a list of keys
   135  	// used to access a nested value in one go
   136  	keyDelim string
   137  
   138  	// A set of paths to look for the config file in
   139  	configPaths []string
   140  
   141  	// The filesystem to read config from.
   142  	fs afero.Fs
   143  
   144  	// A set of remote providers to search for the configuration
   145  	remoteProviders []*defaultRemoteProvider
   146  
   147  	// Name of file to look for inside the path
   148  	configName string
   149  	configFile string
   150  	configType string
   151  	envPrefix  string
   152  
   153  	automaticEnvApplied bool
   154  	envKeyReplacer      *strings.Replacer
   155  
   156  	config         map[string]interface{}
   157  	override       map[string]interface{}
   158  	defaults       map[string]interface{}
   159  	kvstore        map[string]interface{}
   160  	pflags         map[string]FlagValue
   161  	env            map[string]string
   162  	aliases        map[string]string
   163  	typeByDefValue bool
   164  
   165  	onConfigChange onConfigChangeFunc
   166  	onConfigRead   OnConfigReadFunc
   167  }
   168  
   169  type onConfigChangeFunc func(fsnotify.Event)
   170  type OnConfigReadFunc func(map[string]interface{}) error
   171  
   172  // New returns an initialized Viper instance.
   173  func New() *Viper {
   174  	v := new(Viper)
   175  	v.keyDelim = "."
   176  	v.configName = "config"
   177  	v.fs = afero.NewOsFs()
   178  	v.config = make(map[string]interface{})
   179  	v.override = make(map[string]interface{})
   180  	v.defaults = make(map[string]interface{})
   181  	v.kvstore = make(map[string]interface{})
   182  	v.pflags = make(map[string]FlagValue)
   183  	v.env = make(map[string]string)
   184  	v.aliases = make(map[string]string)
   185  	v.typeByDefValue = false
   186  
   187  	return v
   188  }
   189  
   190  // Intended for testing, will reset all to default settings.
   191  // In the public interface for the viper package so applications
   192  // can use it in their testing as well.
   193  func Reset() {
   194  	v = New()
   195  	SupportedExts = []string{"json", "toml", "yaml", "yml", "hcl"}
   196  	SupportedRemoteProviders = []string{"etcd", "consul"}
   197  }
   198  
   199  type defaultRemoteProvider struct {
   200  	provider      string
   201  	endpoint      string
   202  	path          string
   203  	secretKeyring string
   204  }
   205  
   206  func (rp defaultRemoteProvider) Provider() string {
   207  	return rp.provider
   208  }
   209  
   210  func (rp defaultRemoteProvider) Endpoint() string {
   211  	return rp.endpoint
   212  }
   213  
   214  func (rp defaultRemoteProvider) Path() string {
   215  	return rp.path
   216  }
   217  
   218  func (rp defaultRemoteProvider) SecretKeyring() string {
   219  	return rp.secretKeyring
   220  }
   221  
   222  // RemoteProvider stores the configuration necessary
   223  // to connect to a remote key/value store.
   224  // Optional secretKeyring to unencrypt encrypted values
   225  // can be provided.
   226  type RemoteProvider interface {
   227  	Provider() string
   228  	Endpoint() string
   229  	Path() string
   230  	SecretKeyring() string
   231  }
   232  
   233  // SupportedExts are universally supported extensions.
   234  var SupportedExts = []string{"json", "toml", "yaml", "yml", "properties", "props", "prop", "hcl"}
   235  
   236  // SupportedRemoteProviders are universally supported remote providers.
   237  var SupportedRemoteProviders = []string{"etcd", "consul"}
   238  
   239  func OnConfigChange(run onConfigChangeFunc) { v.OnConfigChange(run) }
   240  func (v *Viper) OnConfigChange(run onConfigChangeFunc) {
   241  	v.onConfigChange = run
   242  }
   243  
   244  func OnConfigRead(run OnConfigReadFunc) { v.OnConfigRead(run) }
   245  func (v *Viper) OnConfigRead(run OnConfigReadFunc) {
   246  	v.onConfigRead = run
   247  }
   248  
   249  func WatchConfig() { v.WatchConfig() }
   250  func (v *Viper) WatchConfig() {
   251  	go func() {
   252  		watcher, err := fsnotify.NewWatcher()
   253  		if err != nil {
   254  			log.Fatal(err)
   255  		}
   256  		defer watcher.Close()
   257  
   258  		// we have to watch the entire directory to pick up renames/atomic saves in a cross-platform way
   259  		filename, err := v.getConfigFile()
   260  		if err != nil {
   261  			log.Println("error:", err)
   262  			return
   263  		}
   264  
   265  		configFile := filepath.Clean(filename)
   266  		configDir, _ := filepath.Split(configFile)
   267  
   268  		done := make(chan bool)
   269  		go func() {
   270  			for {
   271  				select {
   272  				case event := <-watcher.Events:
   273  					// we only care about the config file
   274  					if filepath.Clean(event.Name) == configFile {
   275  						if event.Op&fsnotify.Write == fsnotify.Write || event.Op&fsnotify.Create == fsnotify.Create {
   276  							if err := v.ReadInConfig(); err != nil {
   277  								log.Println("error:", err)
   278  							} else {
   279  								if v.onConfigChange != nil {
   280  									pInfo := fmt.Sprintf("provider: fs, path: %s", event.Name)
   281  									v.onConfigChange(fsnotify.Event{Op: event.Op, Name: pInfo})
   282  								}
   283  							}
   284  						}
   285  					}
   286  				case err := <-watcher.Errors:
   287  					log.Println("error:", err)
   288  				}
   289  			}
   290  		}()
   291  
   292  		watcher.Add(configDir)
   293  		<-done
   294  	}()
   295  }
   296  
   297  // SetConfigFile explicitly defines the path, name and extension of the config file.
   298  // Viper will use this and not check any of the config paths.
   299  func SetConfigFile(in string) { v.SetConfigFile(in) }
   300  func (v *Viper) SetConfigFile(in string) {
   301  	if in != "" {
   302  		v.configFile = in
   303  	}
   304  }
   305  
   306  // SetEnvPrefix defines a prefix that ENVIRONMENT variables will use.
   307  // E.g. if your prefix is "spf", the env registry will look for env
   308  // variables that start with "SPF_".
   309  func SetEnvPrefix(in string) { v.SetEnvPrefix(in) }
   310  func (v *Viper) SetEnvPrefix(in string) {
   311  	if in != "" {
   312  		v.envPrefix = in
   313  	}
   314  }
   315  
   316  func (v *Viper) mergeWithEnvPrefix(in string) string {
   317  	if v.envPrefix != "" {
   318  		return strings.ToUpper(v.envPrefix + "_" + in)
   319  	}
   320  
   321  	return strings.ToUpper(in)
   322  }
   323  
   324  // TODO: should getEnv logic be moved into find(). Can generalize the use of
   325  // rewriting keys many things, Ex: Get('someKey') -> some_key
   326  // (camel case to snake case for JSON keys perhaps)
   327  
   328  // getEnv is a wrapper around os.Getenv which replaces characters in the original
   329  // key. This allows env vars which have different keys than the config object
   330  // keys.
   331  func (v *Viper) getEnv(key string) string {
   332  	if v.envKeyReplacer != nil {
   333  		key = v.envKeyReplacer.Replace(key)
   334  	}
   335  	return os.Getenv(key)
   336  }
   337  
   338  // ConfigFileUsed returns the file used to populate the config registry.
   339  func ConfigFileUsed() string            { return v.ConfigFileUsed() }
   340  func (v *Viper) ConfigFileUsed() string { return v.configFile }
   341  
   342  // AddConfigPath adds a path for Viper to search for the config file in.
   343  // Can be called multiple times to define multiple search paths.
   344  func AddConfigPath(in string) { v.AddConfigPath(in) }
   345  func (v *Viper) AddConfigPath(in string) {
   346  	if in != "" {
   347  		absin := absPathify(in)
   348  		jww.INFO.Println("adding", absin, "to paths to search")
   349  		if !stringInSlice(absin, v.configPaths) {
   350  			v.configPaths = append(v.configPaths, absin)
   351  		}
   352  	}
   353  }
   354  
   355  // AddRemoteProvider adds a remote configuration source.
   356  // Remote Providers are searched in the order they are added.
   357  // provider is a string value, "etcd" or "consul" are currently supported.
   358  // endpoint is the url.  etcd requires http://ip:port  consul requires ip:port
   359  // path is the path in the k/v store to retrieve configuration
   360  // To retrieve a config file called myapp.json from /configs/myapp.json
   361  // you should set path to /configs and set config name (SetConfigName()) to
   362  // "myapp"
   363  func AddRemoteProvider(provider, endpoint, path string) error {
   364  	return v.AddRemoteProvider(provider, endpoint, path)
   365  }
   366  func (v *Viper) AddRemoteProvider(provider, endpoint, path string) error {
   367  	if !stringInSlice(provider, SupportedRemoteProviders) {
   368  		return UnsupportedRemoteProviderError(provider)
   369  	}
   370  	if provider != "" && endpoint != "" {
   371  		jww.INFO.Printf("adding %s:%s to remote provider list", provider, endpoint)
   372  		rp := &defaultRemoteProvider{
   373  			endpoint: endpoint,
   374  			provider: provider,
   375  			path:     path,
   376  		}
   377  		if !v.providerPathExists(rp) {
   378  			v.remoteProviders = append(v.remoteProviders, rp)
   379  		}
   380  	}
   381  	return nil
   382  }
   383  
   384  // AddSecureRemoteProvider adds a remote configuration source.
   385  // Secure Remote Providers are searched in the order they are added.
   386  // provider is a string value, "etcd" or "consul" are currently supported.
   387  // endpoint is the url.  etcd requires http://ip:port  consul requires ip:port
   388  // secretkeyring is the filepath to your openpgp secret keyring.  e.g. /etc/secrets/myring.gpg
   389  // path is the path in the k/v store to retrieve configuration
   390  // To retrieve a config file called myapp.json from /configs/myapp.json
   391  // you should set path to /configs and set config name (SetConfigName()) to
   392  // "myapp"
   393  // Secure Remote Providers are implemented with github.com/xordataexchange/crypt
   394  func AddSecureRemoteProvider(provider, endpoint, path, secretkeyring string) error {
   395  	return v.AddSecureRemoteProvider(provider, endpoint, path, secretkeyring)
   396  }
   397  
   398  func (v *Viper) AddSecureRemoteProvider(provider, endpoint, path, secretkeyring string) error {
   399  	if !stringInSlice(provider, SupportedRemoteProviders) {
   400  		return UnsupportedRemoteProviderError(provider)
   401  	}
   402  	if provider != "" && endpoint != "" {
   403  		jww.INFO.Printf("adding %s:%s to remote provider list", provider, endpoint)
   404  		rp := &defaultRemoteProvider{
   405  			endpoint:      endpoint,
   406  			provider:      provider,
   407  			path:          path,
   408  			secretKeyring: secretkeyring,
   409  		}
   410  		if !v.providerPathExists(rp) {
   411  			v.remoteProviders = append(v.remoteProviders, rp)
   412  		}
   413  	}
   414  	return nil
   415  }
   416  
   417  func (v *Viper) providerPathExists(p *defaultRemoteProvider) bool {
   418  	for _, y := range v.remoteProviders {
   419  		if reflect.DeepEqual(y, p) {
   420  			return true
   421  		}
   422  	}
   423  	return false
   424  }
   425  
   426  // searchMap recursively searches for a value for path in source map.
   427  // Returns nil if not found.
   428  // Note: This assumes that the path entries and map keys are lower cased.
   429  func (v *Viper) searchMap(source map[string]interface{}, path []string) interface{} {
   430  	if len(path) == 0 {
   431  		return source
   432  	}
   433  
   434  	next, ok := source[path[0]]
   435  	if ok {
   436  		// Fast path
   437  		if len(path) == 1 {
   438  			return next
   439  		}
   440  
   441  		// Nested case
   442  		switch next.(type) {
   443  		case map[interface{}]interface{}:
   444  			return v.searchMap(cast.ToStringMap(next), path[1:])
   445  		case map[string]interface{}:
   446  			// Type assertion is safe here since it is only reached
   447  			// if the type of `next` is the same as the type being asserted
   448  			return v.searchMap(next.(map[string]interface{}), path[1:])
   449  		default:
   450  			// got a value but nested key expected, return "nil" for not found
   451  			return nil
   452  		}
   453  	}
   454  	return nil
   455  }
   456  
   457  // searchMapWithPathPrefixes recursively searches for a value for path in source map.
   458  //
   459  // While searchMap() considers each path element as a single map key, this
   460  // function searches for, and prioritizes, merged path elements.
   461  // e.g., if in the source, "foo" is defined with a sub-key "bar", and "foo.bar"
   462  // is also defined, this latter value is returned for path ["foo", "bar"].
   463  //
   464  // This should be useful only at config level (other maps may not contain dots
   465  // in their keys).
   466  //
   467  // Note: This assumes that the path entries and map keys are lower cased.
   468  func (v *Viper) searchMapWithPathPrefixes(source map[string]interface{}, path []string) interface{} {
   469  	if len(path) == 0 {
   470  		return source
   471  	}
   472  
   473  	// search for path prefixes, starting from the longest one
   474  	for i := len(path); i > 0; i-- {
   475  		prefixKey := strings.ToLower(strings.Join(path[0:i], v.keyDelim))
   476  
   477  		next, ok := source[prefixKey]
   478  		if ok {
   479  			// Fast path
   480  			if i == len(path) {
   481  				return next
   482  			}
   483  
   484  			// Nested case
   485  			var val interface{}
   486  			switch next.(type) {
   487  			case map[interface{}]interface{}:
   488  				val = v.searchMapWithPathPrefixes(cast.ToStringMap(next), path[i:])
   489  			case map[string]interface{}:
   490  				// Type assertion is safe here since it is only reached
   491  				// if the type of `next` is the same as the type being asserted
   492  				val = v.searchMapWithPathPrefixes(next.(map[string]interface{}), path[i:])
   493  			default:
   494  				// got a value but nested key expected, do nothing and look for next prefix
   495  			}
   496  			if val != nil {
   497  				return val
   498  			}
   499  		}
   500  	}
   501  
   502  	// not found
   503  	return nil
   504  }
   505  
   506  // isPathShadowedInDeepMap makes sure the given path is not shadowed somewhere
   507  // on its path in the map.
   508  // e.g., if "foo.bar" has a value in the given map, it “shadows”
   509  //       "foo.bar.baz" in a lower-priority map
   510  func (v *Viper) isPathShadowedInDeepMap(path []string, m map[string]interface{}) string {
   511  	var parentVal interface{}
   512  	for i := 1; i < len(path); i++ {
   513  		parentVal = v.searchMap(m, path[0:i])
   514  		if parentVal == nil {
   515  			// not found, no need to add more path elements
   516  			return ""
   517  		}
   518  		switch parentVal.(type) {
   519  		case map[interface{}]interface{}:
   520  			continue
   521  		case map[string]interface{}:
   522  			continue
   523  		default:
   524  			// parentVal is a regular value which shadows "path"
   525  			return strings.Join(path[0:i], v.keyDelim)
   526  		}
   527  	}
   528  	return ""
   529  }
   530  
   531  // isPathShadowedInFlatMap makes sure the given path is not shadowed somewhere
   532  // in a sub-path of the map.
   533  // e.g., if "foo.bar" has a value in the given map, it “shadows”
   534  //       "foo.bar.baz" in a lower-priority map
   535  func (v *Viper) isPathShadowedInFlatMap(path []string, mi interface{}) string {
   536  	// unify input map
   537  	var m map[string]interface{}
   538  	switch mi.(type) {
   539  	case map[string]string, map[string]FlagValue:
   540  		m = cast.ToStringMap(mi)
   541  	default:
   542  		return ""
   543  	}
   544  
   545  	// scan paths
   546  	var parentKey string
   547  	for i := 1; i < len(path); i++ {
   548  		parentKey = strings.Join(path[0:i], v.keyDelim)
   549  		if _, ok := m[parentKey]; ok {
   550  			return parentKey
   551  		}
   552  	}
   553  	return ""
   554  }
   555  
   556  // isPathShadowedInAutoEnv makes sure the given path is not shadowed somewhere
   557  // in the environment, when automatic env is on.
   558  // e.g., if "foo.bar" has a value in the environment, it “shadows”
   559  //       "foo.bar.baz" in a lower-priority map
   560  func (v *Viper) isPathShadowedInAutoEnv(path []string) string {
   561  	var parentKey string
   562  	var val string
   563  	for i := 1; i < len(path); i++ {
   564  		parentKey = strings.Join(path[0:i], v.keyDelim)
   565  		if val = v.getEnv(v.mergeWithEnvPrefix(parentKey)); val != "" {
   566  			return parentKey
   567  		}
   568  	}
   569  	return ""
   570  }
   571  
   572  // SetTypeByDefaultValue enables or disables the inference of a key value's
   573  // type when the Get function is used based upon a key's default value as
   574  // opposed to the value returned based on the normal fetch logic.
   575  //
   576  // For example, if a key has a default value of []string{} and the same key
   577  // is set via an environment variable to "a b c", a call to the Get function
   578  // would return a string slice for the key if the key's type is inferred by
   579  // the default value and the Get function would return:
   580  //
   581  //   []string {"a", "b", "c"}
   582  //
   583  // Otherwise the Get function would return:
   584  //
   585  //   "a b c"
   586  func SetTypeByDefaultValue(enable bool) { v.SetTypeByDefaultValue(enable) }
   587  func (v *Viper) SetTypeByDefaultValue(enable bool) {
   588  	v.typeByDefValue = enable
   589  }
   590  
   591  // GetViper gets the global Viper instance.
   592  func GetViper() *Viper {
   593  	return v
   594  }
   595  
   596  // Get can retrieve any value given the key to use.
   597  // Get is case-insensitive for a key.
   598  // Get has the behavior of returning the value associated with the first
   599  // place from where it is set. Viper will check in the following order:
   600  // override, flag, env, config file, key/value store, default
   601  //
   602  // Get returns an interface. For a specific value use one of the Get____ methods.
   603  func Get(key string) interface{} { return v.Get(key) }
   604  func (v *Viper) Get(key string) interface{} {
   605  	lcaseKey := strings.ToLower(key)
   606  	val := v.find(lcaseKey)
   607  	if val == nil {
   608  		return nil
   609  	}
   610  
   611  	if v.typeByDefValue {
   612  		// TODO(bep) this branch isn't covered by a single test.
   613  		valType := val
   614  		path := strings.Split(lcaseKey, v.keyDelim)
   615  		defVal := v.searchMap(v.defaults, path)
   616  		if defVal != nil {
   617  			valType = defVal
   618  		}
   619  
   620  		switch valType.(type) {
   621  		case bool:
   622  			return cast.ToBool(val)
   623  		case string:
   624  			return cast.ToString(val)
   625  		case int64, int32, int16, int8, int:
   626  			return cast.ToInt(val)
   627  		case float64, float32:
   628  			return cast.ToFloat64(val)
   629  		case time.Time:
   630  			return cast.ToTime(val)
   631  		case time.Duration:
   632  			return cast.ToDuration(val)
   633  		case []string:
   634  			return cast.ToStringSlice(val)
   635  		}
   636  	}
   637  
   638  	return val
   639  }
   640  
   641  // Sub returns new Viper instance representing a sub tree of this instance.
   642  // Sub is case-insensitive for a key.
   643  func Sub(key string) *Viper { return v.Sub(key) }
   644  func (v *Viper) Sub(key string) *Viper {
   645  	subv := New()
   646  	data := v.Get(key)
   647  	if data == nil {
   648  		return nil
   649  	}
   650  
   651  	if reflect.TypeOf(data).Kind() == reflect.Map {
   652  		subv.config = cast.ToStringMap(data)
   653  		return subv
   654  	}
   655  	return nil
   656  }
   657  
   658  // GetString returns the value associated with the key as a string.
   659  func GetString(key string) string { return v.GetString(key) }
   660  func (v *Viper) GetString(key string) string {
   661  	return cast.ToString(v.Get(key))
   662  }
   663  
   664  // GetBool returns the value associated with the key as a boolean.
   665  func GetBool(key string) bool { return v.GetBool(key) }
   666  func (v *Viper) GetBool(key string) bool {
   667  	return cast.ToBool(v.Get(key))
   668  }
   669  
   670  // GetInt returns the value associated with the key as an integer.
   671  func GetInt(key string) int { return v.GetInt(key) }
   672  func (v *Viper) GetInt(key string) int {
   673  	return cast.ToInt(v.Get(key))
   674  }
   675  
   676  // GetInt64 returns the value associated with the key as an integer.
   677  func GetInt64(key string) int64 { return v.GetInt64(key) }
   678  func (v *Viper) GetInt64(key string) int64 {
   679  	return cast.ToInt64(v.Get(key))
   680  }
   681  
   682  // GetFloat64 returns the value associated with the key as a float64.
   683  func GetFloat64(key string) float64 { return v.GetFloat64(key) }
   684  func (v *Viper) GetFloat64(key string) float64 {
   685  	return cast.ToFloat64(v.Get(key))
   686  }
   687  
   688  // GetTime returns the value associated with the key as time.
   689  func GetTime(key string) time.Time { return v.GetTime(key) }
   690  func (v *Viper) GetTime(key string) time.Time {
   691  	return cast.ToTime(v.Get(key))
   692  }
   693  
   694  // GetDuration returns the value associated with the key as a duration.
   695  func GetDuration(key string) time.Duration { return v.GetDuration(key) }
   696  func (v *Viper) GetDuration(key string) time.Duration {
   697  	return cast.ToDuration(v.Get(key))
   698  }
   699  
   700  // GetStringSlice returns the value associated with the key as a slice of strings.
   701  func GetStringSlice(key string) []string { return v.GetStringSlice(key) }
   702  func (v *Viper) GetStringSlice(key string) []string {
   703  	return cast.ToStringSlice(v.Get(key))
   704  }
   705  
   706  // GetStringMap returns the value associated with the key as a map of interfaces.
   707  func GetStringMap(key string) map[string]interface{} { return v.GetStringMap(key) }
   708  func (v *Viper) GetStringMap(key string) map[string]interface{} {
   709  	return cast.ToStringMap(v.Get(key))
   710  }
   711  
   712  // GetStringMapString returns the value associated with the key as a map of strings.
   713  func GetStringMapString(key string) map[string]string { return v.GetStringMapString(key) }
   714  func (v *Viper) GetStringMapString(key string) map[string]string {
   715  	return cast.ToStringMapString(v.Get(key))
   716  }
   717  
   718  // GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.
   719  func GetStringMapStringSlice(key string) map[string][]string { return v.GetStringMapStringSlice(key) }
   720  func (v *Viper) GetStringMapStringSlice(key string) map[string][]string {
   721  	return cast.ToStringMapStringSlice(v.Get(key))
   722  }
   723  
   724  // GetSizeInBytes returns the size of the value associated with the given key
   725  // in bytes.
   726  func GetSizeInBytes(key string) uint { return v.GetSizeInBytes(key) }
   727  func (v *Viper) GetSizeInBytes(key string) uint {
   728  	sizeStr := cast.ToString(v.Get(key))
   729  	return parseSizeInBytes(sizeStr)
   730  }
   731  
   732  // UnmarshalKey takes a single key and unmarshals it into a Struct.
   733  func UnmarshalKey(key string, rawVal interface{}) error { return v.UnmarshalKey(key, rawVal) }
   734  func (v *Viper) UnmarshalKey(key string, rawVal interface{}) error {
   735  	err := decode(v.Get(key), defaultDecoderConfig(rawVal))
   736  
   737  	if err != nil {
   738  		return err
   739  	}
   740  
   741  	v.insensitiviseMaps()
   742  
   743  	return nil
   744  }
   745  
   746  // Unmarshal unmarshals the config into a Struct. Make sure that the tags
   747  // on the fields of the structure are properly set.
   748  func Unmarshal(rawVal interface{}) error { return v.Unmarshal(rawVal) }
   749  func (v *Viper) Unmarshal(rawVal interface{}) error {
   750  	err := decode(v.AllSettings(), defaultDecoderConfig(rawVal))
   751  
   752  	if err != nil {
   753  		return err
   754  	}
   755  
   756  	v.insensitiviseMaps()
   757  
   758  	return nil
   759  }
   760  
   761  // defaultDecoderConfig returns default mapsstructure.DecoderConfig with suppot
   762  // of time.Duration values & string slices
   763  func defaultDecoderConfig(output interface{}) *mapstructure.DecoderConfig {
   764  	return &mapstructure.DecoderConfig{
   765  		Metadata:         nil,
   766  		Result:           output,
   767  		WeaklyTypedInput: true,
   768  		DecodeHook: mapstructure.ComposeDecodeHookFunc(
   769  			mapstructure.StringToTimeDurationHookFunc(),
   770  			mapstructure.StringToSliceHookFunc(","),
   771  		),
   772  	}
   773  }
   774  
   775  // A wrapper around mapstructure.Decode that mimics the WeakDecode functionality
   776  func decode(input interface{}, config *mapstructure.DecoderConfig) error {
   777  	decoder, err := mapstructure.NewDecoder(config)
   778  	if err != nil {
   779  		return err
   780  	}
   781  	return decoder.Decode(input)
   782  }
   783  
   784  // UnmarshalExact unmarshals the config into a Struct, erroring if a field is nonexistent
   785  // in the destination struct.
   786  func (v *Viper) UnmarshalExact(rawVal interface{}) error {
   787  	config := defaultDecoderConfig(rawVal)
   788  	config.ErrorUnused = true
   789  
   790  	err := decode(v.AllSettings(), config)
   791  
   792  	if err != nil {
   793  		return err
   794  	}
   795  
   796  	v.insensitiviseMaps()
   797  
   798  	return nil
   799  }
   800  
   801  // BindPFlags binds a full flag set to the configuration, using each flag's long
   802  // name as the config key.
   803  func BindPFlags(flags *pflag.FlagSet) error { return v.BindPFlags(flags) }
   804  func (v *Viper) BindPFlags(flags *pflag.FlagSet) error {
   805  	return v.BindFlagValues(pflagValueSet{flags})
   806  }
   807  
   808  // BindPFlag binds a specific key to a pflag (as used by cobra).
   809  // Example (where serverCmd is a Cobra instance):
   810  //
   811  //	 serverCmd.Flags().Int("port", 1138, "Port to run Application server on")
   812  //	 Viper.BindPFlag("port", serverCmd.Flags().Lookup("port"))
   813  //
   814  func BindPFlag(key string, flag *pflag.Flag) error { return v.BindPFlag(key, flag) }
   815  func (v *Viper) BindPFlag(key string, flag *pflag.Flag) error {
   816  	return v.BindFlagValue(key, pflagValue{flag})
   817  }
   818  
   819  // BindFlagValues binds a full FlagValue set to the configuration, using each flag's long
   820  // name as the config key.
   821  func BindFlagValues(flags FlagValueSet) error { return v.BindFlagValues(flags) }
   822  func (v *Viper) BindFlagValues(flags FlagValueSet) (err error) {
   823  	flags.VisitAll(func(flag FlagValue) {
   824  		if err = v.BindFlagValue(flag.Name(), flag); err != nil {
   825  			return
   826  		}
   827  	})
   828  	return nil
   829  }
   830  
   831  // BindFlagValue binds a specific key to a FlagValue.
   832  // Example (where serverCmd is a Cobra instance):
   833  //
   834  //	 serverCmd.Flags().Int("port", 1138, "Port to run Application server on")
   835  //	 Viper.BindFlagValue("port", serverCmd.Flags().Lookup("port"))
   836  //
   837  func BindFlagValue(key string, flag FlagValue) error { return v.BindFlagValue(key, flag) }
   838  func (v *Viper) BindFlagValue(key string, flag FlagValue) error {
   839  	if flag == nil {
   840  		return fmt.Errorf("flag for %q is nil", key)
   841  	}
   842  	v.pflags[strings.ToLower(key)] = flag
   843  	return nil
   844  }
   845  
   846  // BindEnv binds a Viper key to a ENV variable.
   847  // ENV variables are case sensitive.
   848  // If only a key is provided, it will use the env key matching the key, uppercased.
   849  // EnvPrefix will be used when set when env name is not provided.
   850  func BindEnv(input ...string) error { return v.BindEnv(input...) }
   851  func (v *Viper) BindEnv(input ...string) error {
   852  	var key, envkey string
   853  	if len(input) == 0 {
   854  		return fmt.Errorf("BindEnv missing key to bind to")
   855  	}
   856  
   857  	key = strings.ToLower(input[0])
   858  
   859  	if len(input) == 1 {
   860  		envkey = v.mergeWithEnvPrefix(key)
   861  	} else {
   862  		envkey = input[1]
   863  	}
   864  
   865  	v.env[key] = envkey
   866  
   867  	return nil
   868  }
   869  
   870  // Given a key, find the value.
   871  // Viper will check in the following order:
   872  // flag, env, config file, key/value store, default.
   873  // Viper will check to see if an alias exists first.
   874  // Note: this assumes a lower-cased key given.
   875  func (v *Viper) find(lcaseKey string) interface{} {
   876  
   877  	var (
   878  		val    interface{}
   879  		exists bool
   880  		path   = strings.Split(lcaseKey, v.keyDelim)
   881  		nested = len(path) > 1
   882  	)
   883  
   884  	// compute the path through the nested maps to the nested value
   885  	if nested && v.isPathShadowedInDeepMap(path, castMapStringToMapInterface(v.aliases)) != "" {
   886  		return nil
   887  	}
   888  
   889  	// if the requested key is an alias, then return the proper key
   890  	lcaseKey = v.realKey(lcaseKey)
   891  	path = strings.Split(lcaseKey, v.keyDelim)
   892  	nested = len(path) > 1
   893  
   894  	// Set() override first
   895  	val = v.searchMap(v.override, path)
   896  	if val != nil {
   897  		return val
   898  	}
   899  	if nested && v.isPathShadowedInDeepMap(path, v.override) != "" {
   900  		return nil
   901  	}
   902  
   903  	// PFlag override next
   904  	flag, exists := v.pflags[lcaseKey]
   905  	if exists && flag.HasChanged() {
   906  		switch flag.ValueType() {
   907  		case "int", "int8", "int16", "int32", "int64":
   908  			return cast.ToInt(flag.ValueString())
   909  		case "bool":
   910  			return cast.ToBool(flag.ValueString())
   911  		case "stringSlice":
   912  			s := strings.TrimPrefix(flag.ValueString(), "[")
   913  			s = strings.TrimSuffix(s, "]")
   914  			res, _ := readAsCSV(s)
   915  			return res
   916  		default:
   917  			return flag.ValueString()
   918  		}
   919  	}
   920  	if nested && v.isPathShadowedInFlatMap(path, v.pflags) != "" {
   921  		return nil
   922  	}
   923  
   924  	// Env override next
   925  	if v.automaticEnvApplied {
   926  		// even if it hasn't been registered, if automaticEnv is used,
   927  		// check any Get request
   928  		if val = v.getEnv(v.mergeWithEnvPrefix(lcaseKey)); val != "" {
   929  			return val
   930  		}
   931  		if nested && v.isPathShadowedInAutoEnv(path) != "" {
   932  			return nil
   933  		}
   934  	}
   935  	envkey, exists := v.env[lcaseKey]
   936  	if exists {
   937  		if val = v.getEnv(envkey); val != "" {
   938  			return val
   939  		}
   940  	}
   941  	if nested && v.isPathShadowedInFlatMap(path, v.env) != "" {
   942  		return nil
   943  	}
   944  
   945  	// Config file next
   946  	val = v.searchMapWithPathPrefixes(v.config, path)
   947  	if val != nil {
   948  		return val
   949  	}
   950  	if nested && v.isPathShadowedInDeepMap(path, v.config) != "" {
   951  		return nil
   952  	}
   953  
   954  	// K/V store next
   955  	val = v.searchMap(v.kvstore, path)
   956  	if val != nil {
   957  		return val
   958  	}
   959  	if nested && v.isPathShadowedInDeepMap(path, v.kvstore) != "" {
   960  		return nil
   961  	}
   962  
   963  	// Default next
   964  	val = v.searchMap(v.defaults, path)
   965  	if val != nil {
   966  		return val
   967  	}
   968  	if nested && v.isPathShadowedInDeepMap(path, v.defaults) != "" {
   969  		return nil
   970  	}
   971  
   972  	// last chance: if no other value is returned and a flag does exist for the value,
   973  	// get the flag's value even if the flag's value has not changed
   974  	if flag, exists := v.pflags[lcaseKey]; exists {
   975  		switch flag.ValueType() {
   976  		case "int", "int8", "int16", "int32", "int64":
   977  			return cast.ToInt(flag.ValueString())
   978  		case "bool":
   979  			return cast.ToBool(flag.ValueString())
   980  		case "stringSlice":
   981  			s := strings.TrimPrefix(flag.ValueString(), "[")
   982  			s = strings.TrimSuffix(s, "]")
   983  			res, _ := readAsCSV(s)
   984  			return res
   985  		default:
   986  			return flag.ValueString()
   987  		}
   988  	}
   989  	// last item, no need to check shadowing
   990  
   991  	return nil
   992  }
   993  
   994  func readAsCSV(val string) ([]string, error) {
   995  	if val == "" {
   996  		return []string{}, nil
   997  	}
   998  	stringReader := strings.NewReader(val)
   999  	csvReader := csv.NewReader(stringReader)
  1000  	return csvReader.Read()
  1001  }
  1002  
  1003  // IsSet checks to see if the key has been set in any of the data locations.
  1004  // IsSet is case-insensitive for a key.
  1005  func IsSet(key string) bool { return v.IsSet(key) }
  1006  func (v *Viper) IsSet(key string) bool {
  1007  	lcaseKey := strings.ToLower(key)
  1008  	val := v.find(lcaseKey)
  1009  	return val != nil
  1010  }
  1011  
  1012  // AutomaticEnv has Viper check ENV variables for all.
  1013  // keys set in config, default & flags
  1014  func AutomaticEnv() { v.AutomaticEnv() }
  1015  func (v *Viper) AutomaticEnv() {
  1016  	v.automaticEnvApplied = true
  1017  }
  1018  
  1019  // SetEnvKeyReplacer sets the strings.Replacer on the viper object
  1020  // Useful for mapping an environmental variable to a key that does
  1021  // not match it.
  1022  func SetEnvKeyReplacer(r *strings.Replacer) { v.SetEnvKeyReplacer(r) }
  1023  func (v *Viper) SetEnvKeyReplacer(r *strings.Replacer) {
  1024  	v.envKeyReplacer = r
  1025  }
  1026  
  1027  // Aliases provide another accessor for the same key.
  1028  // This enables one to change a name without breaking the application
  1029  func RegisterAlias(alias string, key string) { v.RegisterAlias(alias, key) }
  1030  func (v *Viper) RegisterAlias(alias string, key string) {
  1031  	v.registerAlias(alias, strings.ToLower(key))
  1032  }
  1033  
  1034  func (v *Viper) registerAlias(alias string, key string) {
  1035  	alias = strings.ToLower(alias)
  1036  	if alias != key && alias != v.realKey(key) {
  1037  		_, exists := v.aliases[alias]
  1038  
  1039  		if !exists {
  1040  			// if we alias something that exists in one of the maps to another
  1041  			// name, we'll never be able to get that value using the original
  1042  			// name, so move the config value to the new realkey.
  1043  			if val, ok := v.config[alias]; ok {
  1044  				delete(v.config, alias)
  1045  				v.config[key] = val
  1046  			}
  1047  			if val, ok := v.kvstore[alias]; ok {
  1048  				delete(v.kvstore, alias)
  1049  				v.kvstore[key] = val
  1050  			}
  1051  			if val, ok := v.defaults[alias]; ok {
  1052  				delete(v.defaults, alias)
  1053  				v.defaults[key] = val
  1054  			}
  1055  			if val, ok := v.override[alias]; ok {
  1056  				delete(v.override, alias)
  1057  				v.override[key] = val
  1058  			}
  1059  			v.aliases[alias] = key
  1060  		}
  1061  	} else {
  1062  		jww.WARN.Println("Creating circular reference alias", alias, key, v.realKey(key))
  1063  	}
  1064  }
  1065  
  1066  func (v *Viper) realKey(key string) string {
  1067  	newkey, exists := v.aliases[key]
  1068  	if exists {
  1069  		jww.DEBUG.Println("Alias", key, "to", newkey)
  1070  		return v.realKey(newkey)
  1071  	}
  1072  	return key
  1073  }
  1074  
  1075  // InConfig checks to see if the given key (or an alias) is in the config file.
  1076  func InConfig(key string) bool { return v.InConfig(key) }
  1077  func (v *Viper) InConfig(key string) bool {
  1078  	// if the requested key is an alias, then return the proper key
  1079  	key = v.realKey(key)
  1080  
  1081  	_, exists := v.config[key]
  1082  	return exists
  1083  }
  1084  
  1085  // SetDefault sets the default value for this key.
  1086  // SetDefault is case-insensitive for a key.
  1087  // Default only used when no value is provided by the user via flag, config or ENV.
  1088  func SetDefault(key string, value interface{}) { v.SetDefault(key, value) }
  1089  func (v *Viper) SetDefault(key string, value interface{}) {
  1090  	// If alias passed in, then set the proper default
  1091  	key = v.realKey(strings.ToLower(key))
  1092  	value = toCaseInsensitiveValue(value)
  1093  
  1094  	path := strings.Split(key, v.keyDelim)
  1095  	lastKey := strings.ToLower(path[len(path)-1])
  1096  	deepestMap := deepSearch(v.defaults, path[0:len(path)-1])
  1097  
  1098  	// set innermost value
  1099  	deepestMap[lastKey] = value
  1100  }
  1101  
  1102  // Set sets the value for the key in the override regiser.
  1103  // Set is case-insensitive for a key.
  1104  // Will be used instead of values obtained via
  1105  // flags, config file, ENV, default, or key/value store.
  1106  func Set(key string, value interface{}) { v.Set(key, value) }
  1107  func (v *Viper) Set(key string, value interface{}) {
  1108  	// If alias passed in, then set the proper override
  1109  	key = v.realKey(strings.ToLower(key))
  1110  	value = toCaseInsensitiveValue(value)
  1111  
  1112  	path := strings.Split(key, v.keyDelim)
  1113  	lastKey := strings.ToLower(path[len(path)-1])
  1114  	deepestMap := deepSearch(v.override, path[0:len(path)-1])
  1115  
  1116  	// set innermost value
  1117  	deepestMap[lastKey] = value
  1118  }
  1119  
  1120  // ReadInConfig will discover and load the configuration file from disk
  1121  // and key/value stores, searching in one of the defined paths.
  1122  func ReadInConfig() error { return v.ReadInConfig() }
  1123  func (v *Viper) ReadInConfig() error {
  1124  	jww.INFO.Println("Attempting to read in config file")
  1125  	filename, err := v.getConfigFile()
  1126  	if err != nil {
  1127  		return err
  1128  	}
  1129  
  1130  	if !stringInSlice(v.getConfigType(), SupportedExts) {
  1131  		return UnsupportedConfigError(v.getConfigType())
  1132  	}
  1133  
  1134  	file, err := afero.ReadFile(v.fs, filename)
  1135  	if err != nil {
  1136  		return err
  1137  	}
  1138  
  1139  	config, err := v.readConfig(bytes.NewReader(file))
  1140  	if err != nil {
  1141  		return err
  1142  	}
  1143  
  1144  	v.config = config
  1145  	return nil
  1146  }
  1147  
  1148  // MergeInConfig merges a new configuration with an existing config.
  1149  func MergeInConfig() error { return v.MergeInConfig() }
  1150  func (v *Viper) MergeInConfig() error {
  1151  	jww.INFO.Println("Attempting to merge in config file")
  1152  	filename, err := v.getConfigFile()
  1153  	if err != nil {
  1154  		return err
  1155  	}
  1156  
  1157  	if !stringInSlice(v.getConfigType(), SupportedExts) {
  1158  		return UnsupportedConfigError(v.getConfigType())
  1159  	}
  1160  
  1161  	file, err := afero.ReadFile(v.fs, filename)
  1162  	if err != nil {
  1163  		return err
  1164  	}
  1165  
  1166  	return v.MergeConfig(bytes.NewReader(file))
  1167  }
  1168  
  1169  // ReadConfig will read a configuration file, setting existing keys to nil if the
  1170  // key does not exist in the file.
  1171  func ReadConfig(in io.Reader) error { return v.ReadConfig(in) }
  1172  func (v *Viper) ReadConfig(in io.Reader) error {
  1173  	v.config = make(map[string]interface{})
  1174  	return v.unmarshalReader(in, v.config)
  1175  }
  1176  
  1177  // MergeConfig merges a new configuration with an existing config.
  1178  func MergeConfig(in io.Reader) error { return v.MergeConfig(in) }
  1179  func (v *Viper) MergeConfig(in io.Reader) error {
  1180  	if v.config == nil {
  1181  		v.config = make(map[string]interface{})
  1182  	}
  1183  	cfg := make(map[string]interface{})
  1184  	if err := v.unmarshalReader(in, cfg); err != nil {
  1185  		return err
  1186  	}
  1187  	mergeMaps(cfg, v.config, nil)
  1188  	return nil
  1189  }
  1190  
  1191  func keyExists(k string, m map[string]interface{}) string {
  1192  	lk := strings.ToLower(k)
  1193  	for mk := range m {
  1194  		lmk := strings.ToLower(mk)
  1195  		if lmk == lk {
  1196  			return mk
  1197  		}
  1198  	}
  1199  	return ""
  1200  }
  1201  
  1202  func castToMapStringInterface(
  1203  	src map[interface{}]interface{}) map[string]interface{} {
  1204  	tgt := map[string]interface{}{}
  1205  	for k, v := range src {
  1206  		tgt[fmt.Sprintf("%v", k)] = v
  1207  	}
  1208  	return tgt
  1209  }
  1210  
  1211  func castMapStringToMapInterface(src map[string]string) map[string]interface{} {
  1212  	tgt := map[string]interface{}{}
  1213  	for k, v := range src {
  1214  		tgt[k] = v
  1215  	}
  1216  	return tgt
  1217  }
  1218  
  1219  func castMapFlagToMapInterface(src map[string]FlagValue) map[string]interface{} {
  1220  	tgt := map[string]interface{}{}
  1221  	for k, v := range src {
  1222  		tgt[k] = v
  1223  	}
  1224  	return tgt
  1225  }
  1226  
  1227  // mergeMaps merges two maps. The `itgt` parameter is for handling go-yaml's
  1228  // insistence on parsing nested structures as `map[interface{}]interface{}`
  1229  // instead of using a `string` as the key for nest structures beyond one level
  1230  // deep. Both map types are supported as there is a go-yaml fork that uses
  1231  // `map[string]interface{}` instead.
  1232  func mergeMaps(
  1233  	src, tgt map[string]interface{}, itgt map[interface{}]interface{}) {
  1234  	for sk, sv := range src {
  1235  		tk := keyExists(sk, tgt)
  1236  		if tk == "" {
  1237  			jww.TRACE.Printf("tk=\"\", tgt[%s]=%v", sk, sv)
  1238  			tgt[sk] = sv
  1239  			if itgt != nil {
  1240  				itgt[sk] = sv
  1241  			}
  1242  			continue
  1243  		}
  1244  
  1245  		tv, ok := tgt[tk]
  1246  		if !ok {
  1247  			jww.TRACE.Printf("tgt[%s] != ok, tgt[%s]=%v", tk, sk, sv)
  1248  			tgt[sk] = sv
  1249  			if itgt != nil {
  1250  				itgt[sk] = sv
  1251  			}
  1252  			continue
  1253  		}
  1254  
  1255  		svType := reflect.TypeOf(sv)
  1256  		tvType := reflect.TypeOf(tv)
  1257  		if svType != tvType {
  1258  			jww.ERROR.Printf(
  1259  				"svType != tvType; key=%s, st=%v, tt=%v, sv=%v, tv=%v",
  1260  				sk, svType, tvType, sv, tv)
  1261  			continue
  1262  		}
  1263  
  1264  		jww.TRACE.Printf("processing key=%s, st=%v, tt=%v, sv=%v, tv=%v",
  1265  			sk, svType, tvType, sv, tv)
  1266  
  1267  		switch ttv := tv.(type) {
  1268  		case map[interface{}]interface{}:
  1269  			jww.TRACE.Printf("merging maps (must convert)")
  1270  			tsv := sv.(map[interface{}]interface{})
  1271  			ssv := castToMapStringInterface(tsv)
  1272  			stv := castToMapStringInterface(ttv)
  1273  			mergeMaps(ssv, stv, ttv)
  1274  		case map[string]interface{}:
  1275  			jww.TRACE.Printf("merging maps")
  1276  			mergeMaps(sv.(map[string]interface{}), ttv, nil)
  1277  		default:
  1278  			jww.TRACE.Printf("setting value")
  1279  			tgt[tk] = sv
  1280  			if itgt != nil {
  1281  				itgt[tk] = sv
  1282  			}
  1283  		}
  1284  	}
  1285  }
  1286  
  1287  // ReadRemoteConfig attempts to get configuration from a remote source
  1288  // and read it in the remote configuration registry.
  1289  func ReadRemoteConfig() error { return v.ReadRemoteConfig() }
  1290  func (v *Viper) ReadRemoteConfig() error {
  1291  	return v.getKeyValueConfig()
  1292  }
  1293  
  1294  func WatchRemoteConfig() error { return v.WatchRemoteConfig() }
  1295  func (v *Viper) WatchRemoteConfig() error {
  1296  	return v.watchKeyValueConfig()
  1297  }
  1298  
  1299  func (v *Viper) WatchRemoteConfigOnChannel() error {
  1300  	return v.watchKeyValueConfigOnChannel()
  1301  }
  1302  
  1303  // Unmarshal a Reader into a map.
  1304  // Should probably be an unexported function.
  1305  func unmarshalReader(in io.Reader, c map[string]interface{}) error {
  1306  	return v.unmarshalReader(in, c)
  1307  }
  1308  
  1309  func (v *Viper) unmarshalReader(in io.Reader, c map[string]interface{}) error {
  1310  	return unmarshallConfigReader(in, c, v.getConfigType())
  1311  }
  1312  
  1313  func (v *Viper) insensitiviseMaps() {
  1314  	insensitiviseMap(v.config)
  1315  	insensitiviseMap(v.defaults)
  1316  	insensitiviseMap(v.override)
  1317  	insensitiviseMap(v.kvstore)
  1318  }
  1319  
  1320  // Retrieve the first found remote configuration.
  1321  func (v *Viper) getKeyValueConfig() error {
  1322  	if RemoteConfig == nil {
  1323  		return RemoteConfigError("Enable the remote features by doing a blank import of the viper/remote package: '_ github.com/spf13/viper/remote'")
  1324  	}
  1325  
  1326  	for _, rp := range v.remoteProviders {
  1327  		config, err := v.getRemoteConfig(rp)
  1328  		if err != nil {
  1329  			continue
  1330  		}
  1331  		v.kvstore = config
  1332  		return nil
  1333  	}
  1334  	return RemoteConfigError("No Files Found")
  1335  }
  1336  
  1337  func (v *Viper) getRemoteConfig(provider RemoteProvider) (map[string]interface{}, error) {
  1338  	reader, err := RemoteConfig.Get(provider)
  1339  	if err != nil {
  1340  		return nil, err
  1341  	}
  1342  
  1343  	return v.readConfig(reader)
  1344  }
  1345  
  1346  // Retrieve the first found remote configuration.
  1347  func (v *Viper) watchKeyValueConfigOnChannel() error {
  1348  	for _, rp := range v.remoteProviders {
  1349  		respc, _ := RemoteConfig.WatchChannel(rp)
  1350  		//Todo: Add quit channel
  1351  		go func(rc <-chan *RemoteResponse, provider RemoteProvider) {
  1352  			for {
  1353  				b := <-rc
  1354  				reader := bytes.NewReader(b.Value)
  1355  				config, err := v.readConfig(reader)
  1356  				if err != nil {
  1357  					continue
  1358  				}
  1359  
  1360  				v.kvstore = config
  1361  
  1362  				if v.onConfigChange != nil {
  1363  
  1364  					pInfo := fmt.Sprintf("provider: %s, path: %s%s", rp.Provider(), rp.Endpoint(), rp.Path())
  1365  					v.onConfigChange(fsnotify.Event{Op: fsnotify.Create, Name: pInfo})
  1366  				}
  1367  			}
  1368  		}(respc, rp)
  1369  		return nil
  1370  	}
  1371  	return RemoteConfigError("No Files Found")
  1372  }
  1373  
  1374  // Retrieve the first found remote configuration.
  1375  func (v *Viper) watchKeyValueConfig() error {
  1376  	for _, rp := range v.remoteProviders {
  1377  		config, err := v.watchRemoteConfig(rp)
  1378  		if err != nil {
  1379  			continue
  1380  		}
  1381  
  1382  		v.kvstore = config
  1383  
  1384  		if v.onConfigChange != nil {
  1385  
  1386  			pInfo := fmt.Sprintf("provider: %s, path: %s%s", rp.Provider(), rp.Endpoint(), rp.Path())
  1387  			v.onConfigChange(fsnotify.Event{Op: fsnotify.Create, Name: pInfo})
  1388  		}
  1389  
  1390  		return nil
  1391  	}
  1392  	return RemoteConfigError("No Files Found")
  1393  }
  1394  
  1395  func (v *Viper) watchRemoteConfig(provider RemoteProvider) (map[string]interface{}, error) {
  1396  	reader, err := RemoteConfig.Watch(provider)
  1397  	if err != nil {
  1398  		return nil, err
  1399  	}
  1400  
  1401  	return v.readConfig(reader)
  1402  }
  1403  
  1404  func (v *Viper) readConfig(reader io.Reader) (map[string]interface{}, error) {
  1405  	config := make(map[string]interface{})
  1406  	err := v.unmarshalReader(reader, config)
  1407  	if err != nil {
  1408  
  1409  		return nil, err
  1410  	}
  1411  
  1412  	if v.onConfigRead != nil {
  1413  		if err := v.onConfigRead(config); err != nil {
  1414  			return nil, err
  1415  		}
  1416  	}
  1417  
  1418  	return config, err
  1419  }
  1420  
  1421  // AllKeys returns all keys holding a value, regardless of where they are set.
  1422  // Nested keys are returned with a v.keyDelim (= ".") separator
  1423  func AllKeys() []string { return v.AllKeys() }
  1424  func (v *Viper) AllKeys() []string {
  1425  	m := map[string]bool{}
  1426  	// add all paths, by order of descending priority to ensure correct shadowing
  1427  	m = v.flattenAndMergeMap(m, castMapStringToMapInterface(v.aliases), "")
  1428  	m = v.flattenAndMergeMap(m, v.override, "")
  1429  	m = v.mergeFlatMap(m, castMapFlagToMapInterface(v.pflags))
  1430  	m = v.mergeFlatMap(m, castMapStringToMapInterface(v.env))
  1431  	m = v.flattenAndMergeMap(m, v.config, "")
  1432  	m = v.flattenAndMergeMap(m, v.kvstore, "")
  1433  	m = v.flattenAndMergeMap(m, v.defaults, "")
  1434  
  1435  	// convert set of paths to list
  1436  	a := []string{}
  1437  	for x := range m {
  1438  		a = append(a, x)
  1439  	}
  1440  	return a
  1441  }
  1442  
  1443  // flattenAndMergeMap recursively flattens the given map into a map[string]bool
  1444  // of key paths (used as a set, easier to manipulate than a []string):
  1445  // - each path is merged into a single key string, delimited with v.keyDelim (= ".")
  1446  // - if a path is shadowed by an earlier value in the initial shadow map,
  1447  //   it is skipped.
  1448  // The resulting set of paths is merged to the given shadow set at the same time.
  1449  func (v *Viper) flattenAndMergeMap(shadow map[string]bool, m map[string]interface{}, prefix string) map[string]bool {
  1450  	if shadow != nil && prefix != "" && shadow[prefix] {
  1451  		// prefix is shadowed => nothing more to flatten
  1452  		return shadow
  1453  	}
  1454  	if shadow == nil {
  1455  		shadow = make(map[string]bool)
  1456  	}
  1457  
  1458  	var m2 map[string]interface{}
  1459  	if prefix != "" {
  1460  		prefix += v.keyDelim
  1461  	}
  1462  	for k, val := range m {
  1463  		fullKey := prefix + k
  1464  		switch val.(type) {
  1465  		case map[string]interface{}:
  1466  			m2 = val.(map[string]interface{})
  1467  		case map[interface{}]interface{}:
  1468  			m2 = cast.ToStringMap(val)
  1469  		default:
  1470  			// immediate value
  1471  			shadow[strings.ToLower(fullKey)] = true
  1472  			continue
  1473  		}
  1474  		// recursively merge to shadow map
  1475  		shadow = v.flattenAndMergeMap(shadow, m2, fullKey)
  1476  	}
  1477  	return shadow
  1478  }
  1479  
  1480  // mergeFlatMap merges the given maps, excluding values of the second map
  1481  // shadowed by values from the first map.
  1482  func (v *Viper) mergeFlatMap(shadow map[string]bool, m map[string]interface{}) map[string]bool {
  1483  	// scan keys
  1484  outer:
  1485  	for k, _ := range m {
  1486  		path := strings.Split(k, v.keyDelim)
  1487  		// scan intermediate paths
  1488  		var parentKey string
  1489  		for i := 1; i < len(path); i++ {
  1490  			parentKey = strings.Join(path[0:i], v.keyDelim)
  1491  			if shadow[parentKey] {
  1492  				// path is shadowed, continue
  1493  				continue outer
  1494  			}
  1495  		}
  1496  		// add key
  1497  		shadow[strings.ToLower(k)] = true
  1498  	}
  1499  	return shadow
  1500  }
  1501  
  1502  // AllSettings merges all settings and returns them as a map[string]interface{}.
  1503  func AllSettings() map[string]interface{} { return v.AllSettings() }
  1504  func (v *Viper) AllSettings() map[string]interface{} {
  1505  	m := map[string]interface{}{}
  1506  	// start from the list of keys, and construct the map one value at a time
  1507  	for _, k := range v.AllKeys() {
  1508  		value := v.Get(k)
  1509  		if value == nil {
  1510  			// should not happen, since AllKeys() returns only keys holding a value,
  1511  			// check just in case anything changes
  1512  			continue
  1513  		}
  1514  		path := strings.Split(k, v.keyDelim)
  1515  		lastKey := strings.ToLower(path[len(path)-1])
  1516  		deepestMap := deepSearch(m, path[0:len(path)-1])
  1517  		// set innermost value
  1518  		deepestMap[lastKey] = value
  1519  	}
  1520  	return m
  1521  }
  1522  
  1523  // SetFs sets the filesystem to use to read configuration.
  1524  func SetFs(fs afero.Fs) { v.SetFs(fs) }
  1525  func (v *Viper) SetFs(fs afero.Fs) {
  1526  	v.fs = fs
  1527  }
  1528  
  1529  // SetConfigName sets name for the config file.
  1530  // Does not include extension.
  1531  func SetConfigName(in string) { v.SetConfigName(in) }
  1532  func (v *Viper) SetConfigName(in string) {
  1533  	if in != "" {
  1534  		v.configName = in
  1535  		v.configFile = ""
  1536  	}
  1537  }
  1538  
  1539  // SetConfigType sets the type of the configuration returned by the
  1540  // remote source, e.g. "json".
  1541  func SetConfigType(in string) { v.SetConfigType(in) }
  1542  func (v *Viper) SetConfigType(in string) {
  1543  	if in != "" {
  1544  		v.configType = in
  1545  	}
  1546  }
  1547  
  1548  func (v *Viper) getConfigType() string {
  1549  	if v.configType != "" {
  1550  		return v.configType
  1551  	}
  1552  
  1553  	cf, err := v.getConfigFile()
  1554  	if err != nil {
  1555  		return ""
  1556  	}
  1557  
  1558  	ext := filepath.Ext(cf)
  1559  
  1560  	if len(ext) > 1 {
  1561  		return ext[1:]
  1562  	}
  1563  
  1564  	return ""
  1565  }
  1566  
  1567  func (v *Viper) getConfigFile() (string, error) {
  1568  	// if explicitly set, then use it
  1569  	if v.configFile != "" {
  1570  		return v.configFile, nil
  1571  	}
  1572  
  1573  	cf, err := v.findConfigFile()
  1574  	if err != nil {
  1575  		return "", err
  1576  	}
  1577  
  1578  	v.configFile = cf
  1579  	return v.getConfigFile()
  1580  }
  1581  
  1582  func (v *Viper) searchInPath(in string) (filename string) {
  1583  	jww.DEBUG.Println("Searching for config in ", in)
  1584  	for _, ext := range SupportedExts {
  1585  		jww.DEBUG.Println("Checking for", filepath.Join(in, v.configName+"."+ext))
  1586  		if b, _ := exists(filepath.Join(in, v.configName+"."+ext)); b {
  1587  			jww.DEBUG.Println("Found: ", filepath.Join(in, v.configName+"."+ext))
  1588  			return filepath.Join(in, v.configName+"."+ext)
  1589  		}
  1590  	}
  1591  
  1592  	return ""
  1593  }
  1594  
  1595  // Search all configPaths for any config file.
  1596  // Returns the first path that exists (and is a config file).
  1597  func (v *Viper) findConfigFile() (string, error) {
  1598  	jww.INFO.Println("Searching for config in ", v.configPaths)
  1599  
  1600  	for _, cp := range v.configPaths {
  1601  		file := v.searchInPath(cp)
  1602  		if file != "" {
  1603  			return file, nil
  1604  		}
  1605  	}
  1606  	return "", ConfigFileNotFoundError{v.configName, fmt.Sprintf("%s", v.configPaths)}
  1607  }
  1608  
  1609  // Debug prints all configuration registries for debugging
  1610  // purposes.
  1611  func Debug() { v.Debug() }
  1612  func (v *Viper) Debug() {
  1613  	fmt.Printf("Aliases:\n%#v\n", v.aliases)
  1614  	fmt.Printf("Override:\n%#v\n", v.override)
  1615  	fmt.Printf("PFlags:\n%#v\n", v.pflags)
  1616  	fmt.Printf("Env:\n%#v\n", v.env)
  1617  	fmt.Printf("Key/Value Store:\n%#v\n", v.kvstore)
  1618  	fmt.Printf("Config:\n%#v\n", v.config)
  1619  	fmt.Printf("Defaults:\n%#v\n", v.defaults)
  1620  }