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