viper.go 55 KB

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