github.com/Nothing-no/viper@v0.0.0-20230922064921-68b4373f7378/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 an 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  	"errors"
    26  	"fmt"
    27  	"io"
    28  	"log"
    29  	"os"
    30  	"path/filepath"
    31  	"reflect"
    32  	"strconv"
    33  	"strings"
    34  	"sync"
    35  	"time"
    36  
    37  	"github.com/fsnotify/fsnotify"
    38  	"github.com/mitchellh/mapstructure"
    39  	"github.com/spf13/afero"
    40  	"github.com/spf13/cast"
    41  	"github.com/spf13/pflag"
    42  
    43  	"github.com/spf13/viper/internal/encoding"
    44  	"github.com/spf13/viper/internal/encoding/dotenv"
    45  	"github.com/spf13/viper/internal/encoding/hcl"
    46  	"github.com/spf13/viper/internal/encoding/ini"
    47  	"github.com/spf13/viper/internal/encoding/javaproperties"
    48  	"github.com/spf13/viper/internal/encoding/json"
    49  	"github.com/spf13/viper/internal/encoding/toml"
    50  	"github.com/spf13/viper/internal/encoding/yaml"
    51  	insensitiveopt "github.com/spf13/viper/internal/insensitiveOpt"
    52  )
    53  
    54  // ConfigMarshalError happens when failing to marshal the configuration.
    55  type ConfigMarshalError struct {
    56  	err error
    57  }
    58  
    59  // Error returns the formatted configuration error.
    60  func (e ConfigMarshalError) Error() string {
    61  	return fmt.Sprintf("While marshaling config: %s", e.err.Error())
    62  }
    63  
    64  var v *Viper
    65  
    66  type RemoteResponse struct {
    67  	Value []byte
    68  	Error error
    69  }
    70  
    71  func init() {
    72  	v = New()
    73  }
    74  
    75  type remoteConfigFactory interface {
    76  	Get(rp RemoteProvider) (io.Reader, error)
    77  	Watch(rp RemoteProvider) (io.Reader, error)
    78  	WatchChannel(rp RemoteProvider) (<-chan *RemoteResponse, chan bool)
    79  }
    80  
    81  // RemoteConfig is optional, see the remote package
    82  var RemoteConfig remoteConfigFactory
    83  
    84  // UnsupportedConfigError denotes encountering an unsupported
    85  // configuration filetype.
    86  type UnsupportedConfigError string
    87  
    88  // Error returns the formatted configuration error.
    89  func (str UnsupportedConfigError) Error() string {
    90  	return fmt.Sprintf("Unsupported Config Type %q", string(str))
    91  }
    92  
    93  // UnsupportedRemoteProviderError denotes encountering an unsupported remote
    94  // provider. Currently only etcd and Consul are supported.
    95  type UnsupportedRemoteProviderError string
    96  
    97  // Error returns the formatted remote provider error.
    98  func (str UnsupportedRemoteProviderError) Error() string {
    99  	return fmt.Sprintf("Unsupported Remote Provider Type %q", string(str))
   100  }
   101  
   102  // RemoteConfigError denotes encountering an error while trying to
   103  // pull the configuration from the remote provider.
   104  type RemoteConfigError string
   105  
   106  // Error returns the formatted remote provider error
   107  func (rce RemoteConfigError) Error() string {
   108  	return fmt.Sprintf("Remote Configurations Error: %s", string(rce))
   109  }
   110  
   111  // ConfigFileNotFoundError denotes failing to find configuration file.
   112  type ConfigFileNotFoundError struct {
   113  	name, locations string
   114  }
   115  
   116  // Error returns the formatted configuration error.
   117  func (fnfe ConfigFileNotFoundError) Error() string {
   118  	return fmt.Sprintf("Config File %q Not Found in %q", fnfe.name, fnfe.locations)
   119  }
   120  
   121  // ConfigFileAlreadyExistsError denotes failure to write new configuration file.
   122  type ConfigFileAlreadyExistsError string
   123  
   124  // Error returns the formatted error when configuration already exists.
   125  func (faee ConfigFileAlreadyExistsError) Error() string {
   126  	return fmt.Sprintf("Config File %q Already Exists", string(faee))
   127  }
   128  
   129  // A DecoderConfigOption can be passed to viper.Unmarshal to configure
   130  // mapstructure.DecoderConfig options
   131  type DecoderConfigOption func(*mapstructure.DecoderConfig)
   132  
   133  // DecodeHook returns a DecoderConfigOption which overrides the default
   134  // DecoderConfig.DecodeHook value, the default is:
   135  //
   136  //	 mapstructure.ComposeDecodeHookFunc(
   137  //			mapstructure.StringToTimeDurationHookFunc(),
   138  //			mapstructure.StringToSliceHookFunc(","),
   139  //		)
   140  func DecodeHook(hook mapstructure.DecodeHookFunc) DecoderConfigOption {
   141  	return func(c *mapstructure.DecoderConfig) {
   142  		c.DecodeHook = hook
   143  	}
   144  }
   145  
   146  // Viper is a prioritized configuration registry. It
   147  // maintains a set of configuration sources, fetches
   148  // values to populate those, and provides them according
   149  // to the source's priority.
   150  // The priority of the sources is the following:
   151  // 1. overrides
   152  // 2. flags
   153  // 3. env. variables
   154  // 4. config file
   155  // 5. key/value store
   156  // 6. defaults
   157  //
   158  // For example, if values from the following sources were loaded:
   159  //
   160  //	Defaults : {
   161  //		"secret": "",
   162  //		"user": "default",
   163  //		"endpoint": "https://localhost"
   164  //	}
   165  //	Config : {
   166  //		"user": "root"
   167  //		"secret": "defaultsecret"
   168  //	}
   169  //	Env : {
   170  //		"secret": "somesecretkey"
   171  //	}
   172  //
   173  // The resulting config will have the following values:
   174  //
   175  //	{
   176  //		"secret": "somesecretkey",
   177  //		"user": "root",
   178  //		"endpoint": "https://localhost"
   179  //	}
   180  //
   181  // Note: Vipers are not safe for concurrent Get() and Set() operations.
   182  type Viper struct {
   183  	// Delimiter that separates a list of keys
   184  	// used to access a nested value in one go
   185  	keyDelim string
   186  
   187  	// A set of paths to look for the config file in
   188  	configPaths []string
   189  
   190  	// The filesystem to read config from.
   191  	fs afero.Fs
   192  
   193  	// A set of remote providers to search for the configuration
   194  	remoteProviders []*defaultRemoteProvider
   195  
   196  	// Name of file to look for inside the path
   197  	configName        string
   198  	configFile        string
   199  	configType        string
   200  	configPermissions os.FileMode
   201  	envPrefix         string
   202  
   203  	// Specific commands for ini parsing
   204  	iniLoadOptions ini.LoadOptions
   205  
   206  	automaticEnvApplied bool
   207  	envKeyReplacer      StringReplacer
   208  	allowEmptyEnv       bool
   209  
   210  	parents        []string
   211  	config         map[string]interface{}
   212  	override       map[string]interface{}
   213  	defaults       map[string]interface{}
   214  	kvstore        map[string]interface{}
   215  	pflags         map[string]FlagValue
   216  	env            map[string][]string
   217  	aliases        map[string]string
   218  	typeByDefValue bool
   219  
   220  	onConfigChange func(fsnotify.Event)
   221  
   222  	logger Logger
   223  
   224  	// TODO: should probably be protected with a mutex
   225  	encoderRegistry *encoding.EncoderRegistry
   226  	decoderRegistry *encoding.DecoderRegistry
   227  }
   228  
   229  // New returns an initialized Viper instance.
   230  func New() *Viper {
   231  	v := new(Viper)
   232  	v.keyDelim = "."
   233  	v.configName = "config"
   234  	v.configPermissions = os.FileMode(0o644)
   235  	v.fs = afero.NewOsFs()
   236  	v.config = make(map[string]interface{})
   237  	v.parents = []string{}
   238  	v.override = make(map[string]interface{})
   239  	v.defaults = make(map[string]interface{})
   240  	v.kvstore = make(map[string]interface{})
   241  	v.pflags = make(map[string]FlagValue)
   242  	v.env = make(map[string][]string)
   243  	v.aliases = make(map[string]string)
   244  	v.typeByDefValue = false
   245  	v.logger = jwwLogger{}
   246  
   247  	v.resetEncoding()
   248  
   249  	return v
   250  }
   251  
   252  // Option configures Viper using the functional options paradigm popularized by Rob Pike and Dave Cheney.
   253  // If you're unfamiliar with this style,
   254  // see https://commandcenter.blogspot.com/2014/01/self-referential-functions-and-design.html and
   255  // https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis.
   256  type Option interface {
   257  	apply(v *Viper)
   258  }
   259  
   260  type optionFunc func(v *Viper)
   261  
   262  func (fn optionFunc) apply(v *Viper) {
   263  	fn(v)
   264  }
   265  
   266  // KeyDelimiter sets the delimiter used for determining key parts.
   267  // By default it's value is ".".
   268  func KeyDelimiter(d string) Option {
   269  	return optionFunc(func(v *Viper) {
   270  		v.keyDelim = d
   271  	})
   272  }
   273  
   274  // StringReplacer applies a set of replacements to a string.
   275  type StringReplacer interface {
   276  	// Replace returns a copy of s with all replacements performed.
   277  	Replace(s string) string
   278  }
   279  
   280  // EnvKeyReplacer sets a replacer used for mapping environment variables to internal keys.
   281  func EnvKeyReplacer(r StringReplacer) Option {
   282  	return optionFunc(func(v *Viper) {
   283  		v.envKeyReplacer = r
   284  	})
   285  }
   286  
   287  // NewWithOptions creates a new Viper instance.
   288  func NewWithOptions(opts ...Option) *Viper {
   289  	v := New()
   290  
   291  	for _, opt := range opts {
   292  		opt.apply(v)
   293  	}
   294  
   295  	v.resetEncoding()
   296  
   297  	return v
   298  }
   299  
   300  // Reset is intended for testing, will reset all to default settings.
   301  // In the public interface for the viper package so applications
   302  // can use it in their testing as well.
   303  func Reset() {
   304  	v = New()
   305  	SupportedExts = []string{"json", "toml", "yaml", "yml", "properties", "props", "prop", "hcl", "tfvars", "dotenv", "env", "ini"}
   306  	SupportedRemoteProviders = []string{"etcd", "etcd3", "consul", "firestore"}
   307  }
   308  
   309  func SetCaseSensitive() {
   310  	insensitiveopt.Insensitive(false)
   311  }
   312  
   313  func SetCaseInsensitive() {
   314  	insensitiveopt.Insensitive(true)
   315  }
   316  
   317  // TODO: make this lazy initialization instead
   318  func (v *Viper) resetEncoding() {
   319  	encoderRegistry := encoding.NewEncoderRegistry()
   320  	decoderRegistry := encoding.NewDecoderRegistry()
   321  
   322  	{
   323  		codec := yaml.Codec{}
   324  
   325  		encoderRegistry.RegisterEncoder("yaml", codec)
   326  		decoderRegistry.RegisterDecoder("yaml", codec)
   327  
   328  		encoderRegistry.RegisterEncoder("yml", codec)
   329  		decoderRegistry.RegisterDecoder("yml", codec)
   330  	}
   331  
   332  	{
   333  		codec := json.Codec{}
   334  
   335  		encoderRegistry.RegisterEncoder("json", codec)
   336  		decoderRegistry.RegisterDecoder("json", codec)
   337  	}
   338  
   339  	{
   340  		codec := toml.Codec{}
   341  
   342  		encoderRegistry.RegisterEncoder("toml", codec)
   343  		decoderRegistry.RegisterDecoder("toml", codec)
   344  	}
   345  
   346  	{
   347  		codec := hcl.Codec{}
   348  
   349  		encoderRegistry.RegisterEncoder("hcl", codec)
   350  		decoderRegistry.RegisterDecoder("hcl", codec)
   351  
   352  		encoderRegistry.RegisterEncoder("tfvars", codec)
   353  		decoderRegistry.RegisterDecoder("tfvars", codec)
   354  	}
   355  
   356  	{
   357  		codec := ini.Codec{
   358  			KeyDelimiter: v.keyDelim,
   359  			LoadOptions:  v.iniLoadOptions,
   360  		}
   361  
   362  		encoderRegistry.RegisterEncoder("ini", codec)
   363  		decoderRegistry.RegisterDecoder("ini", codec)
   364  	}
   365  
   366  	{
   367  		codec := &javaproperties.Codec{
   368  			KeyDelimiter: v.keyDelim,
   369  		}
   370  
   371  		encoderRegistry.RegisterEncoder("properties", codec)
   372  		decoderRegistry.RegisterDecoder("properties", codec)
   373  
   374  		encoderRegistry.RegisterEncoder("props", codec)
   375  		decoderRegistry.RegisterDecoder("props", codec)
   376  
   377  		encoderRegistry.RegisterEncoder("prop", codec)
   378  		decoderRegistry.RegisterDecoder("prop", codec)
   379  	}
   380  
   381  	{
   382  		codec := &dotenv.Codec{}
   383  
   384  		encoderRegistry.RegisterEncoder("dotenv", codec)
   385  		decoderRegistry.RegisterDecoder("dotenv", codec)
   386  
   387  		encoderRegistry.RegisterEncoder("env", codec)
   388  		decoderRegistry.RegisterDecoder("env", codec)
   389  	}
   390  
   391  	v.encoderRegistry = encoderRegistry
   392  	v.decoderRegistry = decoderRegistry
   393  }
   394  
   395  type defaultRemoteProvider struct {
   396  	provider      string
   397  	endpoint      string
   398  	path          string
   399  	secretKeyring string
   400  }
   401  
   402  func (rp defaultRemoteProvider) Provider() string {
   403  	return rp.provider
   404  }
   405  
   406  func (rp defaultRemoteProvider) Endpoint() string {
   407  	return rp.endpoint
   408  }
   409  
   410  func (rp defaultRemoteProvider) Path() string {
   411  	return rp.path
   412  }
   413  
   414  func (rp defaultRemoteProvider) SecretKeyring() string {
   415  	return rp.secretKeyring
   416  }
   417  
   418  // RemoteProvider stores the configuration necessary
   419  // to connect to a remote key/value store.
   420  // Optional secretKeyring to unencrypt encrypted values
   421  // can be provided.
   422  type RemoteProvider interface {
   423  	Provider() string
   424  	Endpoint() string
   425  	Path() string
   426  	SecretKeyring() string
   427  }
   428  
   429  // SupportedExts are universally supported extensions.
   430  var SupportedExts = []string{"json", "toml", "yaml", "yml", "properties", "props", "prop", "hcl", "tfvars", "dotenv", "env", "ini"}
   431  
   432  // SupportedRemoteProviders are universally supported remote providers.
   433  var SupportedRemoteProviders = []string{"etcd", "etcd3", "consul", "firestore"}
   434  
   435  // OnConfigChange sets the event handler that is called when a config file changes.
   436  func OnConfigChange(run func(in fsnotify.Event)) { v.OnConfigChange(run) }
   437  
   438  // OnConfigChange sets the event handler that is called when a config file changes.
   439  func (v *Viper) OnConfigChange(run func(in fsnotify.Event)) {
   440  	v.onConfigChange = run
   441  }
   442  
   443  // WatchConfig starts watching a config file for changes.
   444  func WatchConfig() { v.WatchConfig() }
   445  
   446  // WatchConfig starts watching a config file for changes.
   447  func (v *Viper) WatchConfig() {
   448  	initWG := sync.WaitGroup{}
   449  	initWG.Add(1)
   450  	go func() {
   451  		watcher, err := newWatcher()
   452  		if err != nil {
   453  			log.Fatal(err)
   454  		}
   455  		defer watcher.Close()
   456  		// we have to watch the entire directory to pick up renames/atomic saves in a cross-platform way
   457  		filename, err := v.getConfigFile()
   458  		if err != nil {
   459  			log.Printf("error: %v\n", err)
   460  			initWG.Done()
   461  			return
   462  		}
   463  
   464  		configFile := filepath.Clean(filename)
   465  		configDir, _ := filepath.Split(configFile)
   466  		realConfigFile, _ := filepath.EvalSymlinks(filename)
   467  
   468  		eventsWG := sync.WaitGroup{}
   469  		eventsWG.Add(1)
   470  		go func() {
   471  			for {
   472  				select {
   473  				case event, ok := <-watcher.Events:
   474  					if !ok { // 'Events' channel is closed
   475  						eventsWG.Done()
   476  						return
   477  					}
   478  					currentConfigFile, _ := filepath.EvalSymlinks(filename)
   479  					// we only care about the config file with the following cases:
   480  					// 1 - if the config file was modified or created
   481  					// 2 - if the real path to the config file changed (eg: k8s ConfigMap replacement)
   482  					if (filepath.Clean(event.Name) == configFile &&
   483  						(event.Has(fsnotify.Write) || event.Has(fsnotify.Create))) ||
   484  						(currentConfigFile != "" && currentConfigFile != realConfigFile) {
   485  						realConfigFile = currentConfigFile
   486  						err := v.ReadInConfig()
   487  						if err != nil {
   488  							log.Printf("error reading config file: %v\n", err)
   489  						}
   490  						if v.onConfigChange != nil {
   491  							v.onConfigChange(event)
   492  						}
   493  					} else if filepath.Clean(event.Name) == configFile && event.Has(fsnotify.Remove) {
   494  						eventsWG.Done()
   495  						return
   496  					}
   497  
   498  				case err, ok := <-watcher.Errors:
   499  					if ok { // 'Errors' channel is not closed
   500  						log.Printf("watcher error: %v\n", err)
   501  					}
   502  					eventsWG.Done()
   503  					return
   504  				}
   505  			}
   506  		}()
   507  		watcher.Add(configDir)
   508  		initWG.Done()   // done initializing the watch in this go routine, so the parent routine can move on...
   509  		eventsWG.Wait() // now, wait for event loop to end in this go-routine...
   510  	}()
   511  	initWG.Wait() // make sure that the go routine above fully ended before returning
   512  }
   513  
   514  // SetConfigFile explicitly defines the path, name and extension of the config file.
   515  // Viper will use this and not check any of the config paths.
   516  func SetConfigFile(in string) { v.SetConfigFile(in) }
   517  
   518  func (v *Viper) SetConfigFile(in string) {
   519  	if in != "" {
   520  		v.configFile = in
   521  	}
   522  }
   523  
   524  // SetEnvPrefix defines a prefix that ENVIRONMENT variables will use.
   525  // E.g. if your prefix is "spf", the env registry will look for env
   526  // variables that start with "SPF_".
   527  func SetEnvPrefix(in string) { v.SetEnvPrefix(in) }
   528  
   529  func (v *Viper) SetEnvPrefix(in string) {
   530  	if in != "" {
   531  		v.envPrefix = in
   532  	}
   533  }
   534  
   535  func (v *Viper) mergeWithEnvPrefix(in string) string {
   536  	if v.envPrefix != "" {
   537  		return strings.ToUpper(v.envPrefix + "_" + in)
   538  	}
   539  
   540  	return strings.ToUpper(in)
   541  }
   542  
   543  // AllowEmptyEnv tells Viper to consider set,
   544  // but empty environment variables as valid values instead of falling back.
   545  // For backward compatibility reasons this is false by default.
   546  func AllowEmptyEnv(allowEmptyEnv bool) { v.AllowEmptyEnv(allowEmptyEnv) }
   547  
   548  func (v *Viper) AllowEmptyEnv(allowEmptyEnv bool) {
   549  	v.allowEmptyEnv = allowEmptyEnv
   550  }
   551  
   552  // TODO: should getEnv logic be moved into find(). Can generalize the use of
   553  // rewriting keys many things, Ex: Get('someKey') -> some_key
   554  // (camel case to snake case for JSON keys perhaps)
   555  
   556  // getEnv is a wrapper around os.Getenv which replaces characters in the original
   557  // key. This allows env vars which have different keys than the config object
   558  // keys.
   559  func (v *Viper) getEnv(key string) (string, bool) {
   560  	if v.envKeyReplacer != nil {
   561  		key = v.envKeyReplacer.Replace(key)
   562  	}
   563  
   564  	val, ok := os.LookupEnv(key)
   565  
   566  	return val, ok && (v.allowEmptyEnv || val != "")
   567  }
   568  
   569  // ConfigFileUsed returns the file used to populate the config registry.
   570  func ConfigFileUsed() string            { return v.ConfigFileUsed() }
   571  func (v *Viper) ConfigFileUsed() string { return v.configFile }
   572  
   573  // AddConfigPath adds a path for Viper to search for the config file in.
   574  // Can be called multiple times to define multiple search paths.
   575  func AddConfigPath(in string) { v.AddConfigPath(in) }
   576  
   577  func (v *Viper) AddConfigPath(in string) {
   578  	if in != "" {
   579  		absin := absPathify(v.logger, in)
   580  
   581  		v.logger.Info("adding path to search paths", "path", absin)
   582  		if !stringInSlice(absin, v.configPaths) {
   583  			v.configPaths = append(v.configPaths, absin)
   584  		}
   585  	}
   586  }
   587  
   588  // AddRemoteProvider adds a remote configuration source.
   589  // Remote Providers are searched in the order they are added.
   590  // provider is a string value: "etcd", "etcd3", "consul" or "firestore" are currently supported.
   591  // endpoint is the url.  etcd requires http://ip:port  consul requires ip:port
   592  // path is the path in the k/v store to retrieve configuration
   593  // To retrieve a config file called myapp.json from /configs/myapp.json
   594  // you should set path to /configs and set config name (SetConfigName()) to
   595  // "myapp"
   596  func AddRemoteProvider(provider, endpoint, path string) error {
   597  	return v.AddRemoteProvider(provider, endpoint, path)
   598  }
   599  
   600  func (v *Viper) AddRemoteProvider(provider, endpoint, path string) error {
   601  	if !stringInSlice(provider, SupportedRemoteProviders) {
   602  		return UnsupportedRemoteProviderError(provider)
   603  	}
   604  	if provider != "" && endpoint != "" {
   605  		v.logger.Info("adding remote provider", "provider", provider, "endpoint", endpoint)
   606  
   607  		rp := &defaultRemoteProvider{
   608  			endpoint: endpoint,
   609  			provider: provider,
   610  			path:     path,
   611  		}
   612  		if !v.providerPathExists(rp) {
   613  			v.remoteProviders = append(v.remoteProviders, rp)
   614  		}
   615  	}
   616  	return nil
   617  }
   618  
   619  // AddSecureRemoteProvider adds a remote configuration source.
   620  // Secure Remote Providers are searched in the order they are added.
   621  // provider is a string value: "etcd", "etcd3", "consul" or "firestore" are currently supported.
   622  // endpoint is the url.  etcd requires http://ip:port  consul requires ip:port
   623  // secretkeyring is the filepath to your openpgp secret keyring.  e.g. /etc/secrets/myring.gpg
   624  // path is the path in the k/v store to retrieve configuration
   625  // To retrieve a config file called myapp.json from /configs/myapp.json
   626  // you should set path to /configs and set config name (SetConfigName()) to
   627  // "myapp"
   628  // Secure Remote Providers are implemented with github.com/bketelsen/crypt
   629  func AddSecureRemoteProvider(provider, endpoint, path, secretkeyring string) error {
   630  	return v.AddSecureRemoteProvider(provider, endpoint, path, secretkeyring)
   631  }
   632  
   633  func (v *Viper) AddSecureRemoteProvider(provider, endpoint, path, secretkeyring string) error {
   634  	if !stringInSlice(provider, SupportedRemoteProviders) {
   635  		return UnsupportedRemoteProviderError(provider)
   636  	}
   637  	if provider != "" && endpoint != "" {
   638  		v.logger.Info("adding remote provider", "provider", provider, "endpoint", endpoint)
   639  
   640  		rp := &defaultRemoteProvider{
   641  			endpoint:      endpoint,
   642  			provider:      provider,
   643  			path:          path,
   644  			secretKeyring: secretkeyring,
   645  		}
   646  		if !v.providerPathExists(rp) {
   647  			v.remoteProviders = append(v.remoteProviders, rp)
   648  		}
   649  	}
   650  	return nil
   651  }
   652  
   653  func (v *Viper) providerPathExists(p *defaultRemoteProvider) bool {
   654  	for _, y := range v.remoteProviders {
   655  		if reflect.DeepEqual(y, p) {
   656  			return true
   657  		}
   658  	}
   659  	return false
   660  }
   661  
   662  // searchMap recursively searches for a value for path in source map.
   663  // Returns nil if not found.
   664  // Note: This assumes that the path entries and map keys are lower cased.
   665  func (v *Viper) searchMap(source map[string]interface{}, path []string) interface{} {
   666  	if len(path) == 0 {
   667  		return source
   668  	}
   669  
   670  	next, ok := source[path[0]]
   671  	if ok {
   672  		// Fast path
   673  		if len(path) == 1 {
   674  			return next
   675  		}
   676  
   677  		// Nested case
   678  		switch next.(type) {
   679  		case map[interface{}]interface{}:
   680  			return v.searchMap(cast.ToStringMap(next), path[1:])
   681  		case map[string]interface{}:
   682  			// Type assertion is safe here since it is only reached
   683  			// if the type of `next` is the same as the type being asserted
   684  			return v.searchMap(next.(map[string]interface{}), path[1:])
   685  		default:
   686  			// got a value but nested key expected, return "nil" for not found
   687  			return nil
   688  		}
   689  	}
   690  	return nil
   691  }
   692  
   693  // searchIndexableWithPathPrefixes recursively searches for a value for path in source map/slice.
   694  //
   695  // While searchMap() considers each path element as a single map key or slice index, this
   696  // function searches for, and prioritizes, merged path elements.
   697  // e.g., if in the source, "foo" is defined with a sub-key "bar", and "foo.bar"
   698  // is also defined, this latter value is returned for path ["foo", "bar"].
   699  //
   700  // This should be useful only at config level (other maps may not contain dots
   701  // in their keys).
   702  //
   703  // Note: This assumes that the path entries and map keys are lower cased.
   704  func (v *Viper) searchIndexableWithPathPrefixes(source interface{}, path []string) interface{} {
   705  	if len(path) == 0 {
   706  		return source
   707  	}
   708  
   709  	// search for path prefixes, starting from the longest one
   710  	for i := len(path); i > 0; i-- {
   711  		prefixKey := insensitiveopt.ToLower(strings.Join(path[0:i], v.keyDelim))
   712  
   713  		var val interface{}
   714  		switch sourceIndexable := source.(type) {
   715  		case []interface{}:
   716  			val = v.searchSliceWithPathPrefixes(sourceIndexable, prefixKey, i, path)
   717  		case map[string]interface{}:
   718  			val = v.searchMapWithPathPrefixes(sourceIndexable, prefixKey, i, path)
   719  		}
   720  		if val != nil {
   721  			return val
   722  		}
   723  	}
   724  
   725  	// not found
   726  	return nil
   727  }
   728  
   729  // searchSliceWithPathPrefixes searches for a value for path in sourceSlice
   730  //
   731  // This function is part of the searchIndexableWithPathPrefixes recurring search and
   732  // should not be called directly from functions other than searchIndexableWithPathPrefixes.
   733  func (v *Viper) searchSliceWithPathPrefixes(
   734  	sourceSlice []interface{},
   735  	prefixKey string,
   736  	pathIndex int,
   737  	path []string,
   738  ) interface{} {
   739  	// if the prefixKey is not a number or it is out of bounds of the slice
   740  	index, err := strconv.Atoi(prefixKey)
   741  	if err != nil || len(sourceSlice) <= index {
   742  		return nil
   743  	}
   744  
   745  	next := sourceSlice[index]
   746  
   747  	// Fast path
   748  	if pathIndex == len(path) {
   749  		return next
   750  	}
   751  
   752  	switch n := next.(type) {
   753  	case map[interface{}]interface{}:
   754  		return v.searchIndexableWithPathPrefixes(cast.ToStringMap(n), path[pathIndex:])
   755  	case map[string]interface{}, []interface{}:
   756  		return v.searchIndexableWithPathPrefixes(n, path[pathIndex:])
   757  	default:
   758  		// got a value but nested key expected, do nothing and look for next prefix
   759  	}
   760  
   761  	// not found
   762  	return nil
   763  }
   764  
   765  // searchMapWithPathPrefixes searches for a value for path in sourceMap
   766  //
   767  // This function is part of the searchIndexableWithPathPrefixes recurring search and
   768  // should not be called directly from functions other than searchIndexableWithPathPrefixes.
   769  func (v *Viper) searchMapWithPathPrefixes(
   770  	sourceMap map[string]interface{},
   771  	prefixKey string,
   772  	pathIndex int,
   773  	path []string,
   774  ) interface{} {
   775  	next, ok := sourceMap[prefixKey]
   776  	if !ok {
   777  		return nil
   778  	}
   779  
   780  	// Fast path
   781  	if pathIndex == len(path) {
   782  		return next
   783  	}
   784  
   785  	// Nested case
   786  	switch n := next.(type) {
   787  	case map[interface{}]interface{}:
   788  		return v.searchIndexableWithPathPrefixes(cast.ToStringMap(n), path[pathIndex:])
   789  	case map[string]interface{}, []interface{}:
   790  		return v.searchIndexableWithPathPrefixes(n, path[pathIndex:])
   791  	default:
   792  		// got a value but nested key expected, do nothing and look for next prefix
   793  	}
   794  
   795  	// not found
   796  	return nil
   797  }
   798  
   799  // isPathShadowedInDeepMap makes sure the given path is not shadowed somewhere
   800  // on its path in the map.
   801  // e.g., if "foo.bar" has a value in the given map, it “shadows”
   802  //
   803  //	"foo.bar.baz" in a lower-priority map
   804  func (v *Viper) isPathShadowedInDeepMap(path []string, m map[string]interface{}) string {
   805  	var parentVal interface{}
   806  	for i := 1; i < len(path); i++ {
   807  		parentVal = v.searchMap(m, path[0:i])
   808  		if parentVal == nil {
   809  			// not found, no need to add more path elements
   810  			return ""
   811  		}
   812  		switch parentVal.(type) {
   813  		case map[interface{}]interface{}:
   814  			continue
   815  		case map[string]interface{}:
   816  			continue
   817  		default:
   818  			// parentVal is a regular value which shadows "path"
   819  			return strings.Join(path[0:i], v.keyDelim)
   820  		}
   821  	}
   822  	return ""
   823  }
   824  
   825  // isPathShadowedInFlatMap makes sure the given path is not shadowed somewhere
   826  // in a sub-path of the map.
   827  // e.g., if "foo.bar" has a value in the given map, it “shadows”
   828  //
   829  //	"foo.bar.baz" in a lower-priority map
   830  func (v *Viper) isPathShadowedInFlatMap(path []string, mi interface{}) string {
   831  	// unify input map
   832  	var m map[string]interface{}
   833  	switch mi.(type) {
   834  	case map[string]string, map[string]FlagValue:
   835  		m = cast.ToStringMap(mi)
   836  	default:
   837  		return ""
   838  	}
   839  
   840  	// scan paths
   841  	var parentKey string
   842  	for i := 1; i < len(path); i++ {
   843  		parentKey = strings.Join(path[0:i], v.keyDelim)
   844  		if _, ok := m[parentKey]; ok {
   845  			return parentKey
   846  		}
   847  	}
   848  	return ""
   849  }
   850  
   851  // isPathShadowedInAutoEnv makes sure the given path is not shadowed somewhere
   852  // in the environment, when automatic env is on.
   853  // e.g., if "foo.bar" has a value in the environment, it “shadows”
   854  //
   855  //	"foo.bar.baz" in a lower-priority map
   856  func (v *Viper) isPathShadowedInAutoEnv(path []string) string {
   857  	var parentKey string
   858  	for i := 1; i < len(path); i++ {
   859  		parentKey = strings.Join(path[0:i], v.keyDelim)
   860  		if _, ok := v.getEnv(v.mergeWithEnvPrefix(parentKey)); ok {
   861  			return parentKey
   862  		}
   863  	}
   864  	return ""
   865  }
   866  
   867  // SetTypeByDefaultValue enables or disables the inference of a key value's
   868  // type when the Get function is used based upon a key's default value as
   869  // opposed to the value returned based on the normal fetch logic.
   870  //
   871  // For example, if a key has a default value of []string{} and the same key
   872  // is set via an environment variable to "a b c", a call to the Get function
   873  // would return a string slice for the key if the key's type is inferred by
   874  // the default value and the Get function would return:
   875  //
   876  //	[]string {"a", "b", "c"}
   877  //
   878  // Otherwise the Get function would return:
   879  //
   880  //	"a b c"
   881  func SetTypeByDefaultValue(enable bool) { v.SetTypeByDefaultValue(enable) }
   882  
   883  func (v *Viper) SetTypeByDefaultValue(enable bool) {
   884  	v.typeByDefValue = enable
   885  }
   886  
   887  // GetViper gets the global Viper instance.
   888  func GetViper() *Viper {
   889  	return v
   890  }
   891  
   892  // Get can retrieve any value given the key to use.
   893  // Get is case-insensitive for a key.
   894  // Get has the behavior of returning the value associated with the first
   895  // place from where it is set. Viper will check in the following order:
   896  // override, flag, env, config file, key/value store, default
   897  //
   898  // Get returns an interface. For a specific value use one of the Get____ methods.
   899  func Get(key string) interface{} { return v.Get(key) }
   900  
   901  func (v *Viper) Get(key string) interface{} {
   902  	lcaseKey := insensitiveopt.ToLower(key)
   903  	val := v.find(lcaseKey, true)
   904  	if val == nil {
   905  		return nil
   906  	}
   907  
   908  	if v.typeByDefValue {
   909  		// TODO(bep) this branch isn't covered by a single test.
   910  		valType := val
   911  		path := strings.Split(lcaseKey, v.keyDelim)
   912  		defVal := v.searchMap(v.defaults, path)
   913  		if defVal != nil {
   914  			valType = defVal
   915  		}
   916  
   917  		switch valType.(type) {
   918  		case bool:
   919  			return cast.ToBool(val)
   920  		case string:
   921  			return cast.ToString(val)
   922  		case int32, int16, int8, int:
   923  			return cast.ToInt(val)
   924  		case uint:
   925  			return cast.ToUint(val)
   926  		case uint32:
   927  			return cast.ToUint32(val)
   928  		case uint64:
   929  			return cast.ToUint64(val)
   930  		case int64:
   931  			return cast.ToInt64(val)
   932  		case float64, float32:
   933  			return cast.ToFloat64(val)
   934  		case time.Time:
   935  			return cast.ToTime(val)
   936  		case time.Duration:
   937  			return cast.ToDuration(val)
   938  		case []string:
   939  			return cast.ToStringSlice(val)
   940  		case []int:
   941  			return cast.ToIntSlice(val)
   942  		case []time.Duration:
   943  			return cast.ToDurationSlice(val)
   944  		}
   945  	}
   946  
   947  	return val
   948  }
   949  
   950  // Sub returns new Viper instance representing a sub tree of this instance.
   951  // Sub is case-insensitive for a key.
   952  func Sub(key string) *Viper { return v.Sub(key) }
   953  
   954  func (v *Viper) Sub(key string) *Viper {
   955  	subv := New()
   956  	data := v.Get(key)
   957  	if data == nil {
   958  		return nil
   959  	}
   960  
   961  	if reflect.TypeOf(data).Kind() == reflect.Map {
   962  		subv.parents = append(v.parents, insensitiveopt.ToLower(key))
   963  		subv.automaticEnvApplied = v.automaticEnvApplied
   964  		subv.envPrefix = v.envPrefix
   965  		subv.envKeyReplacer = v.envKeyReplacer
   966  		subv.config = cast.ToStringMap(data)
   967  		return subv
   968  	}
   969  	return nil
   970  }
   971  
   972  // GetString returns the value associated with the key as a string.
   973  func GetString(key string) string { return v.GetString(key) }
   974  
   975  func (v *Viper) GetString(key string) string {
   976  	return cast.ToString(v.Get(key))
   977  }
   978  
   979  // GetBool returns the value associated with the key as a boolean.
   980  func GetBool(key string) bool { return v.GetBool(key) }
   981  
   982  func (v *Viper) GetBool(key string) bool {
   983  	return cast.ToBool(v.Get(key))
   984  }
   985  
   986  // GetInt returns the value associated with the key as an integer.
   987  func GetInt(key string) int { return v.GetInt(key) }
   988  
   989  func (v *Viper) GetInt(key string) int {
   990  	return cast.ToInt(v.Get(key))
   991  }
   992  
   993  // GetInt32 returns the value associated with the key as an integer.
   994  func GetInt32(key string) int32 { return v.GetInt32(key) }
   995  
   996  func (v *Viper) GetInt32(key string) int32 {
   997  	return cast.ToInt32(v.Get(key))
   998  }
   999  
  1000  // GetInt64 returns the value associated with the key as an integer.
  1001  func GetInt64(key string) int64 { return v.GetInt64(key) }
  1002  
  1003  func (v *Viper) GetInt64(key string) int64 {
  1004  	return cast.ToInt64(v.Get(key))
  1005  }
  1006  
  1007  // GetUint returns the value associated with the key as an unsigned integer.
  1008  func GetUint(key string) uint { return v.GetUint(key) }
  1009  
  1010  func (v *Viper) GetUint(key string) uint {
  1011  	return cast.ToUint(v.Get(key))
  1012  }
  1013  
  1014  // GetUint16 returns the value associated with the key as an unsigned integer.
  1015  func GetUint16(key string) uint16 { return v.GetUint16(key) }
  1016  
  1017  func (v *Viper) GetUint16(key string) uint16 {
  1018  	return cast.ToUint16(v.Get(key))
  1019  }
  1020  
  1021  // GetUint32 returns the value associated with the key as an unsigned integer.
  1022  func GetUint32(key string) uint32 { return v.GetUint32(key) }
  1023  
  1024  func (v *Viper) GetUint32(key string) uint32 {
  1025  	return cast.ToUint32(v.Get(key))
  1026  }
  1027  
  1028  // GetUint64 returns the value associated with the key as an unsigned integer.
  1029  func GetUint64(key string) uint64 { return v.GetUint64(key) }
  1030  
  1031  func (v *Viper) GetUint64(key string) uint64 {
  1032  	return cast.ToUint64(v.Get(key))
  1033  }
  1034  
  1035  // GetFloat64 returns the value associated with the key as a float64.
  1036  func GetFloat64(key string) float64 { return v.GetFloat64(key) }
  1037  
  1038  func (v *Viper) GetFloat64(key string) float64 {
  1039  	return cast.ToFloat64(v.Get(key))
  1040  }
  1041  
  1042  // GetTime returns the value associated with the key as time.
  1043  func GetTime(key string) time.Time { return v.GetTime(key) }
  1044  
  1045  func (v *Viper) GetTime(key string) time.Time {
  1046  	return cast.ToTime(v.Get(key))
  1047  }
  1048  
  1049  // GetDuration returns the value associated with the key as a duration.
  1050  func GetDuration(key string) time.Duration { return v.GetDuration(key) }
  1051  
  1052  func (v *Viper) GetDuration(key string) time.Duration {
  1053  	return cast.ToDuration(v.Get(key))
  1054  }
  1055  
  1056  // GetIntSlice returns the value associated with the key as a slice of int values.
  1057  func GetIntSlice(key string) []int { return v.GetIntSlice(key) }
  1058  
  1059  func (v *Viper) GetIntSlice(key string) []int {
  1060  	return cast.ToIntSlice(v.Get(key))
  1061  }
  1062  
  1063  // GetStringSlice returns the value associated with the key as a slice of strings.
  1064  func GetStringSlice(key string) []string { return v.GetStringSlice(key) }
  1065  
  1066  func (v *Viper) GetStringSlice(key string) []string {
  1067  	return cast.ToStringSlice(v.Get(key))
  1068  }
  1069  
  1070  // GetStringMap returns the value associated with the key as a map of interfaces.
  1071  func GetStringMap(key string) map[string]interface{} { return v.GetStringMap(key) }
  1072  
  1073  func (v *Viper) GetStringMap(key string) map[string]interface{} {
  1074  	return cast.ToStringMap(v.Get(key))
  1075  }
  1076  
  1077  // GetStringMapString returns the value associated with the key as a map of strings.
  1078  func GetStringMapString(key string) map[string]string { return v.GetStringMapString(key) }
  1079  
  1080  func (v *Viper) GetStringMapString(key string) map[string]string {
  1081  	return cast.ToStringMapString(v.Get(key))
  1082  }
  1083  
  1084  // GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.
  1085  func GetStringMapStringSlice(key string) map[string][]string { return v.GetStringMapStringSlice(key) }
  1086  
  1087  func (v *Viper) GetStringMapStringSlice(key string) map[string][]string {
  1088  	return cast.ToStringMapStringSlice(v.Get(key))
  1089  }
  1090  
  1091  // GetSizeInBytes returns the size of the value associated with the given key
  1092  // in bytes.
  1093  func GetSizeInBytes(key string) uint { return v.GetSizeInBytes(key) }
  1094  
  1095  func (v *Viper) GetSizeInBytes(key string) uint {
  1096  	sizeStr := cast.ToString(v.Get(key))
  1097  	return parseSizeInBytes(sizeStr)
  1098  }
  1099  
  1100  // UnmarshalKey takes a single key and unmarshals it into a Struct.
  1101  func UnmarshalKey(key string, rawVal interface{}, opts ...DecoderConfigOption) error {
  1102  	return v.UnmarshalKey(key, rawVal, opts...)
  1103  }
  1104  
  1105  func (v *Viper) UnmarshalKey(key string, rawVal interface{}, opts ...DecoderConfigOption) error {
  1106  	return decode(v.Get(key), defaultDecoderConfig(rawVal, opts...))
  1107  }
  1108  
  1109  // Unmarshal unmarshals the config into a Struct. Make sure that the tags
  1110  // on the fields of the structure are properly set.
  1111  func Unmarshal(rawVal interface{}, opts ...DecoderConfigOption) error {
  1112  	return v.Unmarshal(rawVal, opts...)
  1113  }
  1114  
  1115  func (v *Viper) Unmarshal(rawVal interface{}, opts ...DecoderConfigOption) error {
  1116  	return decode(v.AllSettings(), defaultDecoderConfig(rawVal, opts...))
  1117  }
  1118  
  1119  // defaultDecoderConfig returns default mapstructure.DecoderConfig with support
  1120  // of time.Duration values & string slices
  1121  func defaultDecoderConfig(output interface{}, opts ...DecoderConfigOption) *mapstructure.DecoderConfig {
  1122  	c := &mapstructure.DecoderConfig{
  1123  		Metadata:         nil,
  1124  		Result:           output,
  1125  		WeaklyTypedInput: true,
  1126  		DecodeHook: mapstructure.ComposeDecodeHookFunc(
  1127  			mapstructure.StringToTimeDurationHookFunc(),
  1128  			mapstructure.StringToSliceHookFunc(","),
  1129  		),
  1130  	}
  1131  	for _, opt := range opts {
  1132  		opt(c)
  1133  	}
  1134  	return c
  1135  }
  1136  
  1137  // A wrapper around mapstructure.Decode that mimics the WeakDecode functionality
  1138  func decode(input interface{}, config *mapstructure.DecoderConfig) error {
  1139  	decoder, err := mapstructure.NewDecoder(config)
  1140  	if err != nil {
  1141  		return err
  1142  	}
  1143  	return decoder.Decode(input)
  1144  }
  1145  
  1146  // UnmarshalExact unmarshals the config into a Struct, erroring if a field is nonexistent
  1147  // in the destination struct.
  1148  func UnmarshalExact(rawVal interface{}, opts ...DecoderConfigOption) error {
  1149  	return v.UnmarshalExact(rawVal, opts...)
  1150  }
  1151  
  1152  func (v *Viper) UnmarshalExact(rawVal interface{}, opts ...DecoderConfigOption) error {
  1153  	config := defaultDecoderConfig(rawVal, opts...)
  1154  	config.ErrorUnused = true
  1155  
  1156  	return decode(v.AllSettings(), config)
  1157  }
  1158  
  1159  // BindPFlags binds a full flag set to the configuration, using each flag's long
  1160  // name as the config key.
  1161  func BindPFlags(flags *pflag.FlagSet) error { return v.BindPFlags(flags) }
  1162  
  1163  func (v *Viper) BindPFlags(flags *pflag.FlagSet) error {
  1164  	return v.BindFlagValues(pflagValueSet{flags})
  1165  }
  1166  
  1167  // BindPFlag binds a specific key to a pflag (as used by cobra).
  1168  // Example (where serverCmd is a Cobra instance):
  1169  //
  1170  //	serverCmd.Flags().Int("port", 1138, "Port to run Application server on")
  1171  //	Viper.BindPFlag("port", serverCmd.Flags().Lookup("port"))
  1172  func BindPFlag(key string, flag *pflag.Flag) error { return v.BindPFlag(key, flag) }
  1173  
  1174  func (v *Viper) BindPFlag(key string, flag *pflag.Flag) error {
  1175  	if flag == nil {
  1176  		return fmt.Errorf("flag for %q is nil", key)
  1177  	}
  1178  	return v.BindFlagValue(key, pflagValue{flag})
  1179  }
  1180  
  1181  // BindFlagValues binds a full FlagValue set to the configuration, using each flag's long
  1182  // name as the config key.
  1183  func BindFlagValues(flags FlagValueSet) error { return v.BindFlagValues(flags) }
  1184  
  1185  func (v *Viper) BindFlagValues(flags FlagValueSet) (err error) {
  1186  	flags.VisitAll(func(flag FlagValue) {
  1187  		if err = v.BindFlagValue(flag.Name(), flag); err != nil {
  1188  			return
  1189  		}
  1190  	})
  1191  	return nil
  1192  }
  1193  
  1194  // BindFlagValue binds a specific key to a FlagValue.
  1195  func BindFlagValue(key string, flag FlagValue) error { return v.BindFlagValue(key, flag) }
  1196  
  1197  func (v *Viper) BindFlagValue(key string, flag FlagValue) error {
  1198  	if flag == nil {
  1199  		return fmt.Errorf("flag for %q is nil", key)
  1200  	}
  1201  	v.pflags[insensitiveopt.ToLower(key)] = flag
  1202  	return nil
  1203  }
  1204  
  1205  // BindEnv binds a Viper key to a ENV variable.
  1206  // ENV variables are case sensitive.
  1207  // If only a key is provided, it will use the env key matching the key, uppercased.
  1208  // If more arguments are provided, they will represent the env variable names that
  1209  // should bind to this key and will be taken in the specified order.
  1210  // EnvPrefix will be used when set when env name is not provided.
  1211  func BindEnv(input ...string) error { return v.BindEnv(input...) }
  1212  
  1213  func (v *Viper) BindEnv(input ...string) error {
  1214  	if len(input) == 0 {
  1215  		return fmt.Errorf("missing key to bind to")
  1216  	}
  1217  
  1218  	key := insensitiveopt.ToLower(input[0])
  1219  
  1220  	if len(input) == 1 {
  1221  		v.env[key] = append(v.env[key], v.mergeWithEnvPrefix(key))
  1222  	} else {
  1223  		v.env[key] = append(v.env[key], input[1:]...)
  1224  	}
  1225  
  1226  	return nil
  1227  }
  1228  
  1229  // MustBindEnv wraps BindEnv in a panic.
  1230  // If there is an error binding an environment variable, MustBindEnv will
  1231  // panic.
  1232  func MustBindEnv(input ...string) { v.MustBindEnv(input...) }
  1233  
  1234  func (v *Viper) MustBindEnv(input ...string) {
  1235  	if err := v.BindEnv(input...); err != nil {
  1236  		panic(fmt.Sprintf("error while binding environment variable: %v", err))
  1237  	}
  1238  }
  1239  
  1240  // Given a key, find the value.
  1241  //
  1242  // Viper will check to see if an alias exists first.
  1243  // Viper will then check in the following order:
  1244  // flag, env, config file, key/value store.
  1245  // Lastly, if no value was found and flagDefault is true, and if the key
  1246  // corresponds to a flag, the flag's default value is returned.
  1247  //
  1248  // Note: this assumes a lower-cased key given.
  1249  func (v *Viper) find(lcaseKey string, flagDefault bool) interface{} {
  1250  	var (
  1251  		val    interface{}
  1252  		exists bool
  1253  		path   = strings.Split(lcaseKey, v.keyDelim)
  1254  		nested = len(path) > 1
  1255  	)
  1256  
  1257  	// compute the path through the nested maps to the nested value
  1258  	if nested && v.isPathShadowedInDeepMap(path, castMapStringToMapInterface(v.aliases)) != "" {
  1259  		return nil
  1260  	}
  1261  
  1262  	// if the requested key is an alias, then return the proper key
  1263  	lcaseKey = v.realKey(lcaseKey)
  1264  	path = strings.Split(lcaseKey, v.keyDelim)
  1265  	nested = len(path) > 1
  1266  
  1267  	// Set() override first
  1268  	val = v.searchMap(v.override, path)
  1269  	if val != nil {
  1270  		return val
  1271  	}
  1272  	if nested && v.isPathShadowedInDeepMap(path, v.override) != "" {
  1273  		return nil
  1274  	}
  1275  
  1276  	// PFlag override next
  1277  	flag, exists := v.pflags[lcaseKey]
  1278  	if exists && flag.HasChanged() {
  1279  		switch flag.ValueType() {
  1280  		case "int", "int8", "int16", "int32", "int64":
  1281  			return cast.ToInt(flag.ValueString())
  1282  		case "bool":
  1283  			return cast.ToBool(flag.ValueString())
  1284  		case "stringSlice", "stringArray":
  1285  			s := strings.TrimPrefix(flag.ValueString(), "[")
  1286  			s = strings.TrimSuffix(s, "]")
  1287  			res, _ := readAsCSV(s)
  1288  			return res
  1289  		case "intSlice":
  1290  			s := strings.TrimPrefix(flag.ValueString(), "[")
  1291  			s = strings.TrimSuffix(s, "]")
  1292  			res, _ := readAsCSV(s)
  1293  			return cast.ToIntSlice(res)
  1294  		case "durationSlice":
  1295  			s := strings.TrimPrefix(flag.ValueString(), "[")
  1296  			s = strings.TrimSuffix(s, "]")
  1297  			slice := strings.Split(s, ",")
  1298  			return cast.ToDurationSlice(slice)
  1299  		case "stringToString":
  1300  			return stringToStringConv(flag.ValueString())
  1301  
  1302  		default:
  1303  			return flag.ValueString()
  1304  		}
  1305  	}
  1306  	if nested && v.isPathShadowedInFlatMap(path, v.pflags) != "" {
  1307  		return nil
  1308  	}
  1309  
  1310  	// Env override next
  1311  	if v.automaticEnvApplied {
  1312  		envKey := strings.Join(append(v.parents, lcaseKey), ".")
  1313  		// even if it hasn't been registered, if automaticEnv is used,
  1314  		// check any Get request
  1315  		if val, ok := v.getEnv(v.mergeWithEnvPrefix(envKey)); ok {
  1316  			return val
  1317  		}
  1318  		if nested && v.isPathShadowedInAutoEnv(path) != "" {
  1319  			return nil
  1320  		}
  1321  	}
  1322  	envkeys, exists := v.env[lcaseKey]
  1323  	if exists {
  1324  		for _, envkey := range envkeys {
  1325  			if val, ok := v.getEnv(envkey); ok {
  1326  				return val
  1327  			}
  1328  		}
  1329  	}
  1330  	if nested && v.isPathShadowedInFlatMap(path, v.env) != "" {
  1331  		return nil
  1332  	}
  1333  
  1334  	// Config file next
  1335  	val = v.searchIndexableWithPathPrefixes(v.config, path)
  1336  	if val != nil {
  1337  		return val
  1338  	}
  1339  	if nested && v.isPathShadowedInDeepMap(path, v.config) != "" {
  1340  		return nil
  1341  	}
  1342  
  1343  	// K/V store next
  1344  	val = v.searchMap(v.kvstore, path)
  1345  	if val != nil {
  1346  		return val
  1347  	}
  1348  	if nested && v.isPathShadowedInDeepMap(path, v.kvstore) != "" {
  1349  		return nil
  1350  	}
  1351  
  1352  	// Default next
  1353  	val = v.searchMap(v.defaults, path)
  1354  	if val != nil {
  1355  		return val
  1356  	}
  1357  	if nested && v.isPathShadowedInDeepMap(path, v.defaults) != "" {
  1358  		return nil
  1359  	}
  1360  
  1361  	if flagDefault {
  1362  		// last chance: if no value is found and a flag does exist for the key,
  1363  		// get the flag's default value even if the flag's value has not been set.
  1364  		if flag, exists := v.pflags[lcaseKey]; exists {
  1365  			switch flag.ValueType() {
  1366  			case "int", "int8", "int16", "int32", "int64":
  1367  				return cast.ToInt(flag.ValueString())
  1368  			case "bool":
  1369  				return cast.ToBool(flag.ValueString())
  1370  			case "stringSlice", "stringArray":
  1371  				s := strings.TrimPrefix(flag.ValueString(), "[")
  1372  				s = strings.TrimSuffix(s, "]")
  1373  				res, _ := readAsCSV(s)
  1374  				return res
  1375  			case "intSlice":
  1376  				s := strings.TrimPrefix(flag.ValueString(), "[")
  1377  				s = strings.TrimSuffix(s, "]")
  1378  				res, _ := readAsCSV(s)
  1379  				return cast.ToIntSlice(res)
  1380  			case "stringToString":
  1381  				return stringToStringConv(flag.ValueString())
  1382  			case "durationSlice":
  1383  				s := strings.TrimPrefix(flag.ValueString(), "[")
  1384  				s = strings.TrimSuffix(s, "]")
  1385  				slice := strings.Split(s, ",")
  1386  				return cast.ToDurationSlice(slice)
  1387  			default:
  1388  				return flag.ValueString()
  1389  			}
  1390  		}
  1391  		// last item, no need to check shadowing
  1392  	}
  1393  
  1394  	return nil
  1395  }
  1396  
  1397  func readAsCSV(val string) ([]string, error) {
  1398  	if val == "" {
  1399  		return []string{}, nil
  1400  	}
  1401  	stringReader := strings.NewReader(val)
  1402  	csvReader := csv.NewReader(stringReader)
  1403  	return csvReader.Read()
  1404  }
  1405  
  1406  // mostly copied from pflag's implementation of this operation here https://github.com/spf13/pflag/blob/master/string_to_string.go#L79
  1407  // alterations are: errors are swallowed, map[string]interface{} is returned in order to enable cast.ToStringMap
  1408  func stringToStringConv(val string) interface{} {
  1409  	val = strings.Trim(val, "[]")
  1410  	// An empty string would cause an empty map
  1411  	if len(val) == 0 {
  1412  		return map[string]interface{}{}
  1413  	}
  1414  	r := csv.NewReader(strings.NewReader(val))
  1415  	ss, err := r.Read()
  1416  	if err != nil {
  1417  		return nil
  1418  	}
  1419  	out := make(map[string]interface{}, len(ss))
  1420  	for _, pair := range ss {
  1421  		kv := strings.SplitN(pair, "=", 2)
  1422  		if len(kv) != 2 {
  1423  			return nil
  1424  		}
  1425  		out[kv[0]] = kv[1]
  1426  	}
  1427  	return out
  1428  }
  1429  
  1430  // IsSet checks to see if the key has been set in any of the data locations.
  1431  // IsSet is case-insensitive for a key.
  1432  func IsSet(key string) bool { return v.IsSet(key) }
  1433  
  1434  func (v *Viper) IsSet(key string) bool {
  1435  	lcaseKey := insensitiveopt.ToLower(key)
  1436  	val := v.find(lcaseKey, false)
  1437  	return val != nil
  1438  }
  1439  
  1440  // AutomaticEnv makes Viper check if environment variables match any of the existing keys
  1441  // (config, default or flags). If matching env vars are found, they are loaded into Viper.
  1442  func AutomaticEnv() { v.AutomaticEnv() }
  1443  
  1444  func (v *Viper) AutomaticEnv() {
  1445  	v.automaticEnvApplied = true
  1446  }
  1447  
  1448  // SetEnvKeyReplacer sets the strings.Replacer on the viper object
  1449  // Useful for mapping an environmental variable to a key that does
  1450  // not match it.
  1451  func SetEnvKeyReplacer(r *strings.Replacer) { v.SetEnvKeyReplacer(r) }
  1452  
  1453  func (v *Viper) SetEnvKeyReplacer(r *strings.Replacer) {
  1454  	v.envKeyReplacer = r
  1455  }
  1456  
  1457  // RegisterAlias creates an alias that provides another accessor for the same key.
  1458  // This enables one to change a name without breaking the application.
  1459  func RegisterAlias(alias string, key string) { v.RegisterAlias(alias, key) }
  1460  
  1461  func (v *Viper) RegisterAlias(alias string, key string) {
  1462  	v.registerAlias(alias, insensitiveopt.ToLower(key))
  1463  }
  1464  
  1465  func (v *Viper) registerAlias(alias string, key string) {
  1466  	alias = insensitiveopt.ToLower(alias)
  1467  	if alias != key && alias != v.realKey(key) {
  1468  		_, exists := v.aliases[alias]
  1469  
  1470  		if !exists {
  1471  			// if we alias something that exists in one of the maps to another
  1472  			// name, we'll never be able to get that value using the original
  1473  			// name, so move the config value to the new realkey.
  1474  			if val, ok := v.config[alias]; ok {
  1475  				delete(v.config, alias)
  1476  				v.config[key] = val
  1477  			}
  1478  			if val, ok := v.kvstore[alias]; ok {
  1479  				delete(v.kvstore, alias)
  1480  				v.kvstore[key] = val
  1481  			}
  1482  			if val, ok := v.defaults[alias]; ok {
  1483  				delete(v.defaults, alias)
  1484  				v.defaults[key] = val
  1485  			}
  1486  			if val, ok := v.override[alias]; ok {
  1487  				delete(v.override, alias)
  1488  				v.override[key] = val
  1489  			}
  1490  			v.aliases[alias] = key
  1491  		}
  1492  	} else {
  1493  		v.logger.Warn("creating circular reference alias", "alias", alias, "key", key, "real_key", v.realKey(key))
  1494  	}
  1495  }
  1496  
  1497  func (v *Viper) realKey(key string) string {
  1498  	newkey, exists := v.aliases[key]
  1499  	if exists {
  1500  		v.logger.Debug("key is an alias", "alias", key, "to", newkey)
  1501  
  1502  		return v.realKey(newkey)
  1503  	}
  1504  	return key
  1505  }
  1506  
  1507  // InConfig checks to see if the given key (or an alias) is in the config file.
  1508  func InConfig(key string) bool { return v.InConfig(key) }
  1509  
  1510  func (v *Viper) InConfig(key string) bool {
  1511  	lcaseKey := insensitiveopt.ToLower(key)
  1512  
  1513  	// if the requested key is an alias, then return the proper key
  1514  	lcaseKey = v.realKey(lcaseKey)
  1515  	path := strings.Split(lcaseKey, v.keyDelim)
  1516  
  1517  	return v.searchIndexableWithPathPrefixes(v.config, path) != nil
  1518  }
  1519  
  1520  // SetDefault sets the default value for this key.
  1521  // SetDefault is case-insensitive for a key.
  1522  // Default only used when no value is provided by the user via flag, config or ENV.
  1523  func SetDefault(key string, value interface{}) { v.SetDefault(key, value) }
  1524  
  1525  func (v *Viper) SetDefault(key string, value interface{}) {
  1526  	// If alias passed in, then set the proper default
  1527  	key = v.realKey(insensitiveopt.ToLower(key))
  1528  	value = toCaseInsensitiveValue(value)
  1529  
  1530  	path := strings.Split(key, v.keyDelim)
  1531  	lastKey := insensitiveopt.ToLower(path[len(path)-1])
  1532  	deepestMap := deepSearch(v.defaults, path[0:len(path)-1])
  1533  
  1534  	// set innermost value
  1535  	deepestMap[lastKey] = value
  1536  }
  1537  
  1538  // Set sets the value for the key in the override register.
  1539  // Set is case-insensitive for a key.
  1540  // Will be used instead of values obtained via
  1541  // flags, config file, ENV, default, or key/value store.
  1542  func Set(key string, value interface{}) { v.Set(key, value) }
  1543  
  1544  func (v *Viper) Set(key string, value interface{}) {
  1545  	// If alias passed in, then set the proper override
  1546  	key = v.realKey(insensitiveopt.ToLower(key))
  1547  	value = toCaseInsensitiveValue(value)
  1548  
  1549  	path := strings.Split(key, v.keyDelim)
  1550  	lastKey := insensitiveopt.ToLower(path[len(path)-1])
  1551  	deepestMap := deepSearch(v.override, path[0:len(path)-1])
  1552  
  1553  	// set innermost value
  1554  	deepestMap[lastKey] = value
  1555  }
  1556  
  1557  // ReadInConfig will discover and load the configuration file from disk
  1558  // and key/value stores, searching in one of the defined paths.
  1559  func ReadInConfig() error { return v.ReadInConfig() }
  1560  
  1561  func (v *Viper) ReadInConfig() error {
  1562  	v.logger.Info("attempting to read in config file")
  1563  	filename, err := v.getConfigFile()
  1564  	if err != nil {
  1565  		return err
  1566  	}
  1567  
  1568  	if !stringInSlice(v.getConfigType(), SupportedExts) {
  1569  		return UnsupportedConfigError(v.getConfigType())
  1570  	}
  1571  
  1572  	v.logger.Debug("reading file", "file", filename)
  1573  	file, err := afero.ReadFile(v.fs, filename)
  1574  	if err != nil {
  1575  		return err
  1576  	}
  1577  
  1578  	config := make(map[string]interface{})
  1579  
  1580  	err = v.unmarshalReader(bytes.NewReader(file), config)
  1581  	if err != nil {
  1582  		return err
  1583  	}
  1584  
  1585  	v.config = config
  1586  	return nil
  1587  }
  1588  
  1589  // MergeInConfig merges a new configuration with an existing config.
  1590  func MergeInConfig() error { return v.MergeInConfig() }
  1591  
  1592  func (v *Viper) MergeInConfig() error {
  1593  	v.logger.Info("attempting to merge in config file")
  1594  	filename, err := v.getConfigFile()
  1595  	if err != nil {
  1596  		return err
  1597  	}
  1598  
  1599  	if !stringInSlice(v.getConfigType(), SupportedExts) {
  1600  		return UnsupportedConfigError(v.getConfigType())
  1601  	}
  1602  
  1603  	file, err := afero.ReadFile(v.fs, filename)
  1604  	if err != nil {
  1605  		return err
  1606  	}
  1607  
  1608  	return v.MergeConfig(bytes.NewReader(file))
  1609  }
  1610  
  1611  // ReadConfig will read a configuration file, setting existing keys to nil if the
  1612  // key does not exist in the file.
  1613  func ReadConfig(in io.Reader) error { return v.ReadConfig(in) }
  1614  
  1615  func (v *Viper) ReadConfig(in io.Reader) error {
  1616  	v.config = make(map[string]interface{})
  1617  	return v.unmarshalReader(in, v.config)
  1618  }
  1619  
  1620  // MergeConfig merges a new configuration with an existing config.
  1621  func MergeConfig(in io.Reader) error { return v.MergeConfig(in) }
  1622  
  1623  func (v *Viper) MergeConfig(in io.Reader) error {
  1624  	cfg := make(map[string]interface{})
  1625  	if err := v.unmarshalReader(in, cfg); err != nil {
  1626  		return err
  1627  	}
  1628  	return v.MergeConfigMap(cfg)
  1629  }
  1630  
  1631  // MergeConfigMap merges the configuration from the map given with an existing config.
  1632  // Note that the map given may be modified.
  1633  func MergeConfigMap(cfg map[string]interface{}) error { return v.MergeConfigMap(cfg) }
  1634  
  1635  func (v *Viper) MergeConfigMap(cfg map[string]interface{}) error {
  1636  	if v.config == nil {
  1637  		v.config = make(map[string]interface{})
  1638  	}
  1639  	insensitiviseMap(cfg)
  1640  	mergeMaps(cfg, v.config, nil)
  1641  	return nil
  1642  }
  1643  
  1644  // WriteConfig writes the current configuration to a file.
  1645  func WriteConfig() error { return v.WriteConfig() }
  1646  
  1647  func (v *Viper) WriteConfig() error {
  1648  	filename, err := v.getConfigFile()
  1649  	if err != nil {
  1650  		return err
  1651  	}
  1652  	return v.writeConfig(filename, true)
  1653  }
  1654  
  1655  // SafeWriteConfig writes current configuration to file only if the file does not exist.
  1656  func SafeWriteConfig() error { return v.SafeWriteConfig() }
  1657  
  1658  func (v *Viper) SafeWriteConfig() error {
  1659  	if len(v.configPaths) < 1 {
  1660  		return errors.New("missing configuration for 'configPath'")
  1661  	}
  1662  	return v.SafeWriteConfigAs(filepath.Join(v.configPaths[0], v.configName+"."+v.configType))
  1663  }
  1664  
  1665  // WriteConfigAs writes current configuration to a given filename.
  1666  func WriteConfigAs(filename string) error { return v.WriteConfigAs(filename) }
  1667  
  1668  func (v *Viper) WriteConfigAs(filename string) error {
  1669  	return v.writeConfig(filename, true)
  1670  }
  1671  
  1672  // SafeWriteConfigAs writes current configuration to a given filename if it does not exist.
  1673  func SafeWriteConfigAs(filename string) error { return v.SafeWriteConfigAs(filename) }
  1674  
  1675  func (v *Viper) SafeWriteConfigAs(filename string) error {
  1676  	alreadyExists, err := afero.Exists(v.fs, filename)
  1677  	if alreadyExists && err == nil {
  1678  		return ConfigFileAlreadyExistsError(filename)
  1679  	}
  1680  	return v.writeConfig(filename, false)
  1681  }
  1682  
  1683  func (v *Viper) writeConfig(filename string, force bool) error {
  1684  	v.logger.Info("attempting to write configuration to file")
  1685  
  1686  	var configType string
  1687  
  1688  	ext := filepath.Ext(filename)
  1689  	if ext != "" && ext != filepath.Base(filename) {
  1690  		configType = ext[1:]
  1691  	} else {
  1692  		configType = v.configType
  1693  	}
  1694  	if configType == "" {
  1695  		return fmt.Errorf("config type could not be determined for %s", filename)
  1696  	}
  1697  
  1698  	if !stringInSlice(configType, SupportedExts) {
  1699  		return UnsupportedConfigError(configType)
  1700  	}
  1701  	if v.config == nil {
  1702  		v.config = make(map[string]interface{})
  1703  	}
  1704  	flags := os.O_CREATE | os.O_TRUNC | os.O_WRONLY
  1705  	if !force {
  1706  		flags |= os.O_EXCL
  1707  	}
  1708  	f, err := v.fs.OpenFile(filename, flags, v.configPermissions)
  1709  	if err != nil {
  1710  		return err
  1711  	}
  1712  	defer f.Close()
  1713  
  1714  	if err := v.marshalWriter(f, configType); err != nil {
  1715  		return err
  1716  	}
  1717  
  1718  	return f.Sync()
  1719  }
  1720  
  1721  // Unmarshal a Reader into a map.
  1722  // Should probably be an unexported function.
  1723  func unmarshalReader(in io.Reader, c map[string]interface{}) error {
  1724  	return v.unmarshalReader(in, c)
  1725  }
  1726  
  1727  func (v *Viper) unmarshalReader(in io.Reader, c map[string]interface{}) error {
  1728  	buf := new(bytes.Buffer)
  1729  	buf.ReadFrom(in)
  1730  
  1731  	switch format := insensitiveopt.ToLower(v.getConfigType()); format {
  1732  	case "yaml", "yml", "json", "toml", "hcl", "tfvars", "ini", "properties", "props", "prop", "dotenv", "env":
  1733  		err := v.decoderRegistry.Decode(format, buf.Bytes(), c)
  1734  		if err != nil {
  1735  			return ConfigParseError{err}
  1736  		}
  1737  	}
  1738  
  1739  	insensitiviseMap(c)
  1740  	return nil
  1741  }
  1742  
  1743  // Marshal a map into Writer.
  1744  func (v *Viper) marshalWriter(f afero.File, configType string) error {
  1745  	c := v.AllSettings()
  1746  	switch configType {
  1747  	case "yaml", "yml", "json", "toml", "hcl", "tfvars", "ini", "prop", "props", "properties", "dotenv", "env":
  1748  		b, err := v.encoderRegistry.Encode(configType, c)
  1749  		if err != nil {
  1750  			return ConfigMarshalError{err}
  1751  		}
  1752  
  1753  		_, err = f.WriteString(string(b))
  1754  		if err != nil {
  1755  			return ConfigMarshalError{err}
  1756  		}
  1757  	}
  1758  	return nil
  1759  }
  1760  
  1761  func keyExists(k string, m map[string]interface{}) string {
  1762  	lk := insensitiveopt.ToLower(k)
  1763  	for mk := range m {
  1764  		lmk := insensitiveopt.ToLower(mk)
  1765  		if lmk == lk {
  1766  			return mk
  1767  		}
  1768  	}
  1769  	return ""
  1770  }
  1771  
  1772  func castToMapStringInterface(
  1773  	src map[interface{}]interface{},
  1774  ) map[string]interface{} {
  1775  	tgt := map[string]interface{}{}
  1776  	for k, v := range src {
  1777  		tgt[fmt.Sprintf("%v", k)] = v
  1778  	}
  1779  	return tgt
  1780  }
  1781  
  1782  func castMapStringSliceToMapInterface(src map[string][]string) map[string]interface{} {
  1783  	tgt := map[string]interface{}{}
  1784  	for k, v := range src {
  1785  		tgt[k] = v
  1786  	}
  1787  	return tgt
  1788  }
  1789  
  1790  func castMapStringToMapInterface(src map[string]string) map[string]interface{} {
  1791  	tgt := map[string]interface{}{}
  1792  	for k, v := range src {
  1793  		tgt[k] = v
  1794  	}
  1795  	return tgt
  1796  }
  1797  
  1798  func castMapFlagToMapInterface(src map[string]FlagValue) map[string]interface{} {
  1799  	tgt := map[string]interface{}{}
  1800  	for k, v := range src {
  1801  		tgt[k] = v
  1802  	}
  1803  	return tgt
  1804  }
  1805  
  1806  // mergeMaps merges two maps. The `itgt` parameter is for handling go-yaml's
  1807  // insistence on parsing nested structures as `map[interface{}]interface{}`
  1808  // instead of using a `string` as the key for nest structures beyond one level
  1809  // deep. Both map types are supported as there is a go-yaml fork that uses
  1810  // `map[string]interface{}` instead.
  1811  func mergeMaps(
  1812  	src, tgt map[string]interface{}, itgt map[interface{}]interface{},
  1813  ) {
  1814  	for sk, sv := range src {
  1815  		tk := keyExists(sk, tgt)
  1816  		if tk == "" {
  1817  			v.logger.Trace("", "tk", "\"\"", fmt.Sprintf("tgt[%s]", sk), sv)
  1818  			tgt[sk] = sv
  1819  			if itgt != nil {
  1820  				itgt[sk] = sv
  1821  			}
  1822  			continue
  1823  		}
  1824  
  1825  		tv, ok := tgt[tk]
  1826  		if !ok {
  1827  			v.logger.Trace("", fmt.Sprintf("ok[%s]", tk), false, fmt.Sprintf("tgt[%s]", sk), sv)
  1828  			tgt[sk] = sv
  1829  			if itgt != nil {
  1830  				itgt[sk] = sv
  1831  			}
  1832  			continue
  1833  		}
  1834  
  1835  		svType := reflect.TypeOf(sv)
  1836  		tvType := reflect.TypeOf(tv)
  1837  
  1838  		v.logger.Trace(
  1839  			"processing",
  1840  			"key", sk,
  1841  			"st", svType,
  1842  			"tt", tvType,
  1843  			"sv", sv,
  1844  			"tv", tv,
  1845  		)
  1846  
  1847  		switch ttv := tv.(type) {
  1848  		case map[interface{}]interface{}:
  1849  			v.logger.Trace("merging maps (must convert)")
  1850  			tsv, ok := sv.(map[interface{}]interface{})
  1851  			if !ok {
  1852  				v.logger.Error(
  1853  					"Could not cast sv to map[interface{}]interface{}",
  1854  					"key", sk,
  1855  					"st", svType,
  1856  					"tt", tvType,
  1857  					"sv", sv,
  1858  					"tv", tv,
  1859  				)
  1860  				continue
  1861  			}
  1862  
  1863  			ssv := castToMapStringInterface(tsv)
  1864  			stv := castToMapStringInterface(ttv)
  1865  			mergeMaps(ssv, stv, ttv)
  1866  		case map[string]interface{}:
  1867  			v.logger.Trace("merging maps")
  1868  			tsv, ok := sv.(map[string]interface{})
  1869  			if !ok {
  1870  				v.logger.Error(
  1871  					"Could not cast sv to map[string]interface{}",
  1872  					"key", sk,
  1873  					"st", svType,
  1874  					"tt", tvType,
  1875  					"sv", sv,
  1876  					"tv", tv,
  1877  				)
  1878  				continue
  1879  			}
  1880  			mergeMaps(tsv, ttv, nil)
  1881  		default:
  1882  			v.logger.Trace("setting value")
  1883  			tgt[tk] = sv
  1884  			if itgt != nil {
  1885  				itgt[tk] = sv
  1886  			}
  1887  		}
  1888  	}
  1889  }
  1890  
  1891  // ReadRemoteConfig attempts to get configuration from a remote source
  1892  // and read it in the remote configuration registry.
  1893  func ReadRemoteConfig() error { return v.ReadRemoteConfig() }
  1894  
  1895  func (v *Viper) ReadRemoteConfig() error {
  1896  	return v.getKeyValueConfig()
  1897  }
  1898  
  1899  func WatchRemoteConfig() error { return v.WatchRemoteConfig() }
  1900  func (v *Viper) WatchRemoteConfig() error {
  1901  	return v.watchKeyValueConfig()
  1902  }
  1903  
  1904  func (v *Viper) WatchRemoteConfigOnChannel() error {
  1905  	return v.watchKeyValueConfigOnChannel()
  1906  }
  1907  
  1908  // Retrieve the first found remote configuration.
  1909  func (v *Viper) getKeyValueConfig() error {
  1910  	if RemoteConfig == nil {
  1911  		return RemoteConfigError("Enable the remote features by doing a blank import of the viper/remote package: '_ github.com/spf13/viper/remote'")
  1912  	}
  1913  
  1914  	if len(v.remoteProviders) == 0 {
  1915  		return RemoteConfigError("No Remote Providers")
  1916  	}
  1917  
  1918  	for _, rp := range v.remoteProviders {
  1919  		val, err := v.getRemoteConfig(rp)
  1920  		if err != nil {
  1921  			v.logger.Error(fmt.Errorf("get remote config: %w", err).Error())
  1922  
  1923  			continue
  1924  		}
  1925  
  1926  		v.kvstore = val
  1927  
  1928  		return nil
  1929  	}
  1930  	return RemoteConfigError("No Files Found")
  1931  }
  1932  
  1933  func (v *Viper) getRemoteConfig(provider RemoteProvider) (map[string]interface{}, error) {
  1934  	reader, err := RemoteConfig.Get(provider)
  1935  	if err != nil {
  1936  		return nil, err
  1937  	}
  1938  	err = v.unmarshalReader(reader, v.kvstore)
  1939  	return v.kvstore, err
  1940  }
  1941  
  1942  // Retrieve the first found remote configuration.
  1943  func (v *Viper) watchKeyValueConfigOnChannel() error {
  1944  	if len(v.remoteProviders) == 0 {
  1945  		return RemoteConfigError("No Remote Providers")
  1946  	}
  1947  
  1948  	for _, rp := range v.remoteProviders {
  1949  		respc, _ := RemoteConfig.WatchChannel(rp)
  1950  		// Todo: Add quit channel
  1951  		go func(rc <-chan *RemoteResponse) {
  1952  			for {
  1953  				b := <-rc
  1954  				reader := bytes.NewReader(b.Value)
  1955  				v.unmarshalReader(reader, v.kvstore)
  1956  			}
  1957  		}(respc)
  1958  		return nil
  1959  	}
  1960  	return RemoteConfigError("No Files Found")
  1961  }
  1962  
  1963  // Retrieve the first found remote configuration.
  1964  func (v *Viper) watchKeyValueConfig() error {
  1965  	if len(v.remoteProviders) == 0 {
  1966  		return RemoteConfigError("No Remote Providers")
  1967  	}
  1968  
  1969  	for _, rp := range v.remoteProviders {
  1970  		val, err := v.watchRemoteConfig(rp)
  1971  		if err != nil {
  1972  			v.logger.Error(fmt.Errorf("watch remote config: %w", err).Error())
  1973  
  1974  			continue
  1975  		}
  1976  		v.kvstore = val
  1977  		return nil
  1978  	}
  1979  	return RemoteConfigError("No Files Found")
  1980  }
  1981  
  1982  func (v *Viper) watchRemoteConfig(provider RemoteProvider) (map[string]interface{}, error) {
  1983  	reader, err := RemoteConfig.Watch(provider)
  1984  	if err != nil {
  1985  		return nil, err
  1986  	}
  1987  	err = v.unmarshalReader(reader, v.kvstore)
  1988  	return v.kvstore, err
  1989  }
  1990  
  1991  // AllKeys returns all keys holding a value, regardless of where they are set.
  1992  // Nested keys are returned with a v.keyDelim separator
  1993  func AllKeys() []string { return v.AllKeys() }
  1994  
  1995  func (v *Viper) AllKeys() []string {
  1996  	m := map[string]bool{}
  1997  	// add all paths, by order of descending priority to ensure correct shadowing
  1998  	m = v.flattenAndMergeMap(m, castMapStringToMapInterface(v.aliases), "")
  1999  	m = v.flattenAndMergeMap(m, v.override, "")
  2000  	m = v.mergeFlatMap(m, castMapFlagToMapInterface(v.pflags))
  2001  	m = v.mergeFlatMap(m, castMapStringSliceToMapInterface(v.env))
  2002  	m = v.flattenAndMergeMap(m, v.config, "")
  2003  	m = v.flattenAndMergeMap(m, v.kvstore, "")
  2004  	m = v.flattenAndMergeMap(m, v.defaults, "")
  2005  
  2006  	// convert set of paths to list
  2007  	a := make([]string, 0, len(m))
  2008  	for x := range m {
  2009  		a = append(a, x)
  2010  	}
  2011  	return a
  2012  }
  2013  
  2014  // flattenAndMergeMap recursively flattens the given map into a map[string]bool
  2015  // of key paths (used as a set, easier to manipulate than a []string):
  2016  //   - each path is merged into a single key string, delimited with v.keyDelim
  2017  //   - if a path is shadowed by an earlier value in the initial shadow map,
  2018  //     it is skipped.
  2019  //
  2020  // The resulting set of paths is merged to the given shadow set at the same time.
  2021  func (v *Viper) flattenAndMergeMap(shadow map[string]bool, m map[string]interface{}, prefix string) map[string]bool {
  2022  	if shadow != nil && prefix != "" && shadow[prefix] {
  2023  		// prefix is shadowed => nothing more to flatten
  2024  		return shadow
  2025  	}
  2026  	if shadow == nil {
  2027  		shadow = make(map[string]bool)
  2028  	}
  2029  
  2030  	var m2 map[string]interface{}
  2031  	if prefix != "" {
  2032  		prefix += v.keyDelim
  2033  	}
  2034  	for k, val := range m {
  2035  		fullKey := prefix + k
  2036  		switch val.(type) {
  2037  		case map[string]interface{}:
  2038  			m2 = val.(map[string]interface{})
  2039  		case map[interface{}]interface{}:
  2040  			m2 = cast.ToStringMap(val)
  2041  		default:
  2042  			// immediate value
  2043  			shadow[insensitiveopt.ToLower(fullKey)] = true
  2044  			continue
  2045  		}
  2046  		// recursively merge to shadow map
  2047  		shadow = v.flattenAndMergeMap(shadow, m2, fullKey)
  2048  	}
  2049  	return shadow
  2050  }
  2051  
  2052  // mergeFlatMap merges the given maps, excluding values of the second map
  2053  // shadowed by values from the first map.
  2054  func (v *Viper) mergeFlatMap(shadow map[string]bool, m map[string]interface{}) map[string]bool {
  2055  	// scan keys
  2056  outer:
  2057  	for k := range m {
  2058  		path := strings.Split(k, v.keyDelim)
  2059  		// scan intermediate paths
  2060  		var parentKey string
  2061  		for i := 1; i < len(path); i++ {
  2062  			parentKey = strings.Join(path[0:i], v.keyDelim)
  2063  			if shadow[parentKey] {
  2064  				// path is shadowed, continue
  2065  				continue outer
  2066  			}
  2067  		}
  2068  		// add key
  2069  		shadow[insensitiveopt.ToLower(k)] = true
  2070  	}
  2071  	return shadow
  2072  }
  2073  
  2074  // AllSettings merges all settings and returns them as a map[string]interface{}.
  2075  func AllSettings() map[string]interface{} { return v.AllSettings() }
  2076  
  2077  func (v *Viper) AllSettings() map[string]interface{} {
  2078  	m := map[string]interface{}{}
  2079  	// start from the list of keys, and construct the map one value at a time
  2080  	for _, k := range v.AllKeys() {
  2081  		value := v.Get(k)
  2082  		if value == nil {
  2083  			// should not happen, since AllKeys() returns only keys holding a value,
  2084  			// check just in case anything changes
  2085  			continue
  2086  		}
  2087  		path := strings.Split(k, v.keyDelim)
  2088  		lastKey := insensitiveopt.ToLower(path[len(path)-1])
  2089  		deepestMap := deepSearch(m, path[0:len(path)-1])
  2090  		// set innermost value
  2091  		deepestMap[lastKey] = value
  2092  	}
  2093  	return m
  2094  }
  2095  
  2096  // SetFs sets the filesystem to use to read configuration.
  2097  func SetFs(fs afero.Fs) { v.SetFs(fs) }
  2098  
  2099  func (v *Viper) SetFs(fs afero.Fs) {
  2100  	v.fs = fs
  2101  }
  2102  
  2103  // SetConfigName sets name for the config file.
  2104  // Does not include extension.
  2105  func SetConfigName(in string) { v.SetConfigName(in) }
  2106  
  2107  func (v *Viper) SetConfigName(in string) {
  2108  	if in != "" {
  2109  		v.configName = in
  2110  		v.configFile = ""
  2111  	}
  2112  }
  2113  
  2114  // SetConfigType sets the type of the configuration returned by the
  2115  // remote source, e.g. "json".
  2116  func SetConfigType(in string) { v.SetConfigType(in) }
  2117  
  2118  func (v *Viper) SetConfigType(in string) {
  2119  	if in != "" {
  2120  		v.configType = in
  2121  	}
  2122  }
  2123  
  2124  // SetConfigPermissions sets the permissions for the config file.
  2125  func SetConfigPermissions(perm os.FileMode) { v.SetConfigPermissions(perm) }
  2126  
  2127  func (v *Viper) SetConfigPermissions(perm os.FileMode) {
  2128  	v.configPermissions = perm.Perm()
  2129  }
  2130  
  2131  // IniLoadOptions sets the load options for ini parsing.
  2132  func IniLoadOptions(in ini.LoadOptions) Option {
  2133  	return optionFunc(func(v *Viper) {
  2134  		v.iniLoadOptions = in
  2135  	})
  2136  }
  2137  
  2138  func (v *Viper) getConfigType() string {
  2139  	if v.configType != "" {
  2140  		return v.configType
  2141  	}
  2142  
  2143  	cf, err := v.getConfigFile()
  2144  	if err != nil {
  2145  		return ""
  2146  	}
  2147  
  2148  	ext := filepath.Ext(cf)
  2149  
  2150  	if len(ext) > 1 {
  2151  		return ext[1:]
  2152  	}
  2153  
  2154  	return ""
  2155  }
  2156  
  2157  func (v *Viper) getConfigFile() (string, error) {
  2158  	if v.configFile == "" {
  2159  		cf, err := v.findConfigFile()
  2160  		if err != nil {
  2161  			return "", err
  2162  		}
  2163  		v.configFile = cf
  2164  	}
  2165  	return v.configFile, nil
  2166  }
  2167  
  2168  // Debug prints all configuration registries for debugging
  2169  // purposes.
  2170  func Debug()              { v.Debug() }
  2171  func DebugTo(w io.Writer) { v.DebugTo(w) }
  2172  
  2173  func (v *Viper) Debug() { v.DebugTo(os.Stdout) }
  2174  
  2175  func (v *Viper) DebugTo(w io.Writer) {
  2176  	fmt.Fprintf(w, "Aliases:\n%#v\n", v.aliases)
  2177  	fmt.Fprintf(w, "Override:\n%#v\n", v.override)
  2178  	fmt.Fprintf(w, "PFlags:\n%#v\n", v.pflags)
  2179  	fmt.Fprintf(w, "Env:\n%#v\n", v.env)
  2180  	fmt.Fprintf(w, "Key/Value Store:\n%#v\n", v.kvstore)
  2181  	fmt.Fprintf(w, "Config:\n%#v\n", v.config)
  2182  	fmt.Fprintf(w, "Defaults:\n%#v\n", v.defaults)
  2183  }