123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154 |
- package viper
- import (
- "bytes"
- "encoding/csv"
- "errors"
- "fmt"
- "io"
- "log"
- "os"
- "path/filepath"
- "reflect"
- "strconv"
- "strings"
- "sync"
- "time"
- "github.com/fsnotify/fsnotify"
- "github.com/mitchellh/mapstructure"
- "github.com/spf13/afero"
- "github.com/spf13/cast"
- "github.com/spf13/pflag"
- "github.com/spf13/viper/internal/encoding"
- "github.com/spf13/viper/internal/encoding/dotenv"
- "github.com/spf13/viper/internal/encoding/hcl"
- "github.com/spf13/viper/internal/encoding/ini"
- "github.com/spf13/viper/internal/encoding/javaproperties"
- "github.com/spf13/viper/internal/encoding/json"
- "github.com/spf13/viper/internal/encoding/toml"
- "github.com/spf13/viper/internal/encoding/yaml"
- )
- type ConfigMarshalError struct {
- err error
- }
- func (e ConfigMarshalError) Error() string {
- return fmt.Sprintf("While marshaling config: %s", e.err.Error())
- }
- var v *Viper
- type RemoteResponse struct {
- Value []byte
- Error error
- }
- func init() {
- v = New()
- }
- type remoteConfigFactory interface {
- Get(rp RemoteProvider) (io.Reader, error)
- Watch(rp RemoteProvider) (io.Reader, error)
- WatchChannel(rp RemoteProvider) (<-chan *RemoteResponse, chan bool)
- }
- var RemoteConfig remoteConfigFactory
- type UnsupportedConfigError string
- func (str UnsupportedConfigError) Error() string {
- return fmt.Sprintf("Unsupported Config Type %q", string(str))
- }
- type UnsupportedRemoteProviderError string
- func (str UnsupportedRemoteProviderError) Error() string {
- return fmt.Sprintf("Unsupported Remote Provider Type %q", string(str))
- }
- type RemoteConfigError string
- func (rce RemoteConfigError) Error() string {
- return fmt.Sprintf("Remote Configurations Error: %s", string(rce))
- }
- type ConfigFileNotFoundError struct {
- name, locations string
- }
- func (fnfe ConfigFileNotFoundError) Error() string {
- return fmt.Sprintf("Config File %q Not Found in %q", fnfe.name, fnfe.locations)
- }
- type ConfigFileAlreadyExistsError string
- func (faee ConfigFileAlreadyExistsError) Error() string {
- return fmt.Sprintf("Config File %q Already Exists", string(faee))
- }
- type DecoderConfigOption func(*mapstructure.DecoderConfig)
- func DecodeHook(hook mapstructure.DecodeHookFunc) DecoderConfigOption {
- return func(c *mapstructure.DecoderConfig) {
- c.DecodeHook = hook
- }
- }
- type Viper struct {
-
-
- keyDelim string
-
- configPaths []string
-
- fs afero.Fs
-
- remoteProviders []*defaultRemoteProvider
-
- configName string
- configFile string
- configType string
- configPermissions os.FileMode
- envPrefix string
-
- iniLoadOptions ini.LoadOptions
- automaticEnvApplied bool
- envKeyReplacer StringReplacer
- allowEmptyEnv bool
- config map[string]interface{}
- override map[string]interface{}
- defaults map[string]interface{}
- kvstore map[string]interface{}
- pflags map[string]FlagValue
- env map[string][]string
- aliases map[string]string
- typeByDefValue bool
- onConfigChange func(fsnotify.Event)
- logger Logger
-
- encoderRegistry *encoding.EncoderRegistry
- decoderRegistry *encoding.DecoderRegistry
- }
- func New() *Viper {
- v := new(Viper)
- v.keyDelim = "."
- v.configName = "config"
- v.configPermissions = os.FileMode(0o644)
- v.fs = afero.NewOsFs()
- v.config = make(map[string]interface{})
- v.override = make(map[string]interface{})
- v.defaults = make(map[string]interface{})
- v.kvstore = make(map[string]interface{})
- v.pflags = make(map[string]FlagValue)
- v.env = make(map[string][]string)
- v.aliases = make(map[string]string)
- v.typeByDefValue = false
- v.logger = jwwLogger{}
- v.resetEncoding()
- return v
- }
- type Option interface {
- apply(v *Viper)
- }
- type optionFunc func(v *Viper)
- func (fn optionFunc) apply(v *Viper) {
- fn(v)
- }
- func KeyDelimiter(d string) Option {
- return optionFunc(func(v *Viper) {
- v.keyDelim = d
- })
- }
- type StringReplacer interface {
-
- Replace(s string) string
- }
- func EnvKeyReplacer(r StringReplacer) Option {
- return optionFunc(func(v *Viper) {
- v.envKeyReplacer = r
- })
- }
- func NewWithOptions(opts ...Option) *Viper {
- v := New()
- for _, opt := range opts {
- opt.apply(v)
- }
- v.resetEncoding()
- return v
- }
- func Reset() {
- v = New()
- SupportedExts = []string{"json", "toml", "yaml", "yml", "properties", "props", "prop", "hcl", "tfvars", "dotenv", "env", "ini"}
- SupportedRemoteProviders = []string{"etcd", "etcd3", "consul", "firestore"}
- }
- func (v *Viper) resetEncoding() {
- encoderRegistry := encoding.NewEncoderRegistry()
- decoderRegistry := encoding.NewDecoderRegistry()
- {
- codec := yaml.Codec{}
- encoderRegistry.RegisterEncoder("yaml", codec)
- decoderRegistry.RegisterDecoder("yaml", codec)
- encoderRegistry.RegisterEncoder("yml", codec)
- decoderRegistry.RegisterDecoder("yml", codec)
- }
- {
- codec := json.Codec{}
- encoderRegistry.RegisterEncoder("json", codec)
- decoderRegistry.RegisterDecoder("json", codec)
- }
- {
- codec := toml.Codec{}
- encoderRegistry.RegisterEncoder("toml", codec)
- decoderRegistry.RegisterDecoder("toml", codec)
- }
- {
- codec := hcl.Codec{}
- encoderRegistry.RegisterEncoder("hcl", codec)
- decoderRegistry.RegisterDecoder("hcl", codec)
- encoderRegistry.RegisterEncoder("tfvars", codec)
- decoderRegistry.RegisterDecoder("tfvars", codec)
- }
- {
- codec := ini.Codec{
- KeyDelimiter: v.keyDelim,
- LoadOptions: v.iniLoadOptions,
- }
- encoderRegistry.RegisterEncoder("ini", codec)
- decoderRegistry.RegisterDecoder("ini", codec)
- }
- {
- codec := &javaproperties.Codec{
- KeyDelimiter: v.keyDelim,
- }
- encoderRegistry.RegisterEncoder("properties", codec)
- decoderRegistry.RegisterDecoder("properties", codec)
- encoderRegistry.RegisterEncoder("props", codec)
- decoderRegistry.RegisterDecoder("props", codec)
- encoderRegistry.RegisterEncoder("prop", codec)
- decoderRegistry.RegisterDecoder("prop", codec)
- }
- {
- codec := &dotenv.Codec{}
- encoderRegistry.RegisterEncoder("dotenv", codec)
- decoderRegistry.RegisterDecoder("dotenv", codec)
- encoderRegistry.RegisterEncoder("env", codec)
- decoderRegistry.RegisterDecoder("env", codec)
- }
- v.encoderRegistry = encoderRegistry
- v.decoderRegistry = decoderRegistry
- }
- type defaultRemoteProvider struct {
- provider string
- endpoint string
- path string
- secretKeyring string
- }
- func (rp defaultRemoteProvider) Provider() string {
- return rp.provider
- }
- func (rp defaultRemoteProvider) Endpoint() string {
- return rp.endpoint
- }
- func (rp defaultRemoteProvider) Path() string {
- return rp.path
- }
- func (rp defaultRemoteProvider) SecretKeyring() string {
- return rp.secretKeyring
- }
- type RemoteProvider interface {
- Provider() string
- Endpoint() string
- Path() string
- SecretKeyring() string
- }
- var SupportedExts = []string{"json", "toml", "yaml", "yml", "properties", "props", "prop", "hcl", "tfvars", "dotenv", "env", "ini"}
- var SupportedRemoteProviders = []string{"etcd", "etcd3", "consul", "firestore"}
- func OnConfigChange(run func(in fsnotify.Event)) { v.OnConfigChange(run) }
- func (v *Viper) OnConfigChange(run func(in fsnotify.Event)) {
- v.onConfigChange = run
- }
- func WatchConfig() { v.WatchConfig() }
- func (v *Viper) WatchConfig() {
- initWG := sync.WaitGroup{}
- initWG.Add(1)
- go func() {
- watcher, err := newWatcher()
- if err != nil {
- log.Fatal(err)
- }
- defer watcher.Close()
-
- filename, err := v.getConfigFile()
- if err != nil {
- log.Printf("error: %v\n", err)
- initWG.Done()
- return
- }
- configFile := filepath.Clean(filename)
- configDir, _ := filepath.Split(configFile)
- realConfigFile, _ := filepath.EvalSymlinks(filename)
- eventsWG := sync.WaitGroup{}
- eventsWG.Add(1)
- go func() {
- for {
- select {
- case event, ok := <-watcher.Events:
- if !ok {
- eventsWG.Done()
- return
- }
- currentConfigFile, _ := filepath.EvalSymlinks(filename)
-
-
-
- if (filepath.Clean(event.Name) == configFile &&
- (event.Has(fsnotify.Write) || event.Has(fsnotify.Create))) ||
- (currentConfigFile != "" && currentConfigFile != realConfigFile) {
- realConfigFile = currentConfigFile
- err := v.ReadInConfig()
- if err != nil {
- log.Printf("error reading config file: %v\n", err)
- }
- if v.onConfigChange != nil {
- v.onConfigChange(event)
- }
- } else if filepath.Clean(event.Name) == configFile && event.Has(fsnotify.Remove) {
- eventsWG.Done()
- return
- }
- case err, ok := <-watcher.Errors:
- if ok {
- log.Printf("watcher error: %v\n", err)
- }
- eventsWG.Done()
- return
- }
- }
- }()
- watcher.Add(configDir)
- initWG.Done()
- eventsWG.Wait()
- }()
- initWG.Wait()
- }
- func SetConfigFile(in string) { v.SetConfigFile(in) }
- func (v *Viper) SetConfigFile(in string) {
- if in != "" {
- v.configFile = in
- }
- }
- func SetEnvPrefix(in string) { v.SetEnvPrefix(in) }
- func (v *Viper) SetEnvPrefix(in string) {
- if in != "" {
- v.envPrefix = in
- }
- }
- func (v *Viper) mergeWithEnvPrefix(in string) string {
- if v.envPrefix != "" {
- return strings.ToUpper(v.envPrefix + "_" + in)
- }
- return strings.ToUpper(in)
- }
- func AllowEmptyEnv(allowEmptyEnv bool) { v.AllowEmptyEnv(allowEmptyEnv) }
- func (v *Viper) AllowEmptyEnv(allowEmptyEnv bool) {
- v.allowEmptyEnv = allowEmptyEnv
- }
- func (v *Viper) getEnv(key string) (string, bool) {
- if v.envKeyReplacer != nil {
- key = v.envKeyReplacer.Replace(key)
- }
- val, ok := os.LookupEnv(key)
- return val, ok && (v.allowEmptyEnv || val != "")
- }
- func ConfigFileUsed() string { return v.ConfigFileUsed() }
- func (v *Viper) ConfigFileUsed() string { return v.configFile }
- func AddConfigPath(in string) { v.AddConfigPath(in) }
- func (v *Viper) AddConfigPath(in string) {
- if in != "" {
- absin := absPathify(v.logger, in)
- v.logger.Info("adding path to search paths", "path", absin)
- if !stringInSlice(absin, v.configPaths) {
- v.configPaths = append(v.configPaths, absin)
- }
- }
- }
- func AddRemoteProvider(provider, endpoint, path string) error {
- return v.AddRemoteProvider(provider, endpoint, path)
- }
- func (v *Viper) AddRemoteProvider(provider, endpoint, path string) error {
- if !stringInSlice(provider, SupportedRemoteProviders) {
- return UnsupportedRemoteProviderError(provider)
- }
- if provider != "" && endpoint != "" {
- v.logger.Info("adding remote provider", "provider", provider, "endpoint", endpoint)
- rp := &defaultRemoteProvider{
- endpoint: endpoint,
- provider: provider,
- path: path,
- }
- if !v.providerPathExists(rp) {
- v.remoteProviders = append(v.remoteProviders, rp)
- }
- }
- return nil
- }
- func AddSecureRemoteProvider(provider, endpoint, path, secretkeyring string) error {
- return v.AddSecureRemoteProvider(provider, endpoint, path, secretkeyring)
- }
- func (v *Viper) AddSecureRemoteProvider(provider, endpoint, path, secretkeyring string) error {
- if !stringInSlice(provider, SupportedRemoteProviders) {
- return UnsupportedRemoteProviderError(provider)
- }
- if provider != "" && endpoint != "" {
- v.logger.Info("adding remote provider", "provider", provider, "endpoint", endpoint)
- rp := &defaultRemoteProvider{
- endpoint: endpoint,
- provider: provider,
- path: path,
- secretKeyring: secretkeyring,
- }
- if !v.providerPathExists(rp) {
- v.remoteProviders = append(v.remoteProviders, rp)
- }
- }
- return nil
- }
- func (v *Viper) providerPathExists(p *defaultRemoteProvider) bool {
- for _, y := range v.remoteProviders {
- if reflect.DeepEqual(y, p) {
- return true
- }
- }
- return false
- }
- func (v *Viper) searchMap(source map[string]interface{}, path []string) interface{} {
- if len(path) == 0 {
- return source
- }
- next, ok := source[path[0]]
- if ok {
-
- if len(path) == 1 {
- return next
- }
-
- switch next.(type) {
- case map[interface{}]interface{}:
- return v.searchMap(cast.ToStringMap(next), path[1:])
- case map[string]interface{}:
-
-
- return v.searchMap(next.(map[string]interface{}), path[1:])
- default:
-
- return nil
- }
- }
- return nil
- }
- func (v *Viper) searchIndexableWithPathPrefixes(source interface{}, path []string) interface{} {
- if len(path) == 0 {
- return source
- }
-
- for i := len(path); i > 0; i-- {
- prefixKey := strings.ToLower(strings.Join(path[0:i], v.keyDelim))
- var val interface{}
- switch sourceIndexable := source.(type) {
- case []interface{}:
- val = v.searchSliceWithPathPrefixes(sourceIndexable, prefixKey, i, path)
- case map[string]interface{}:
- val = v.searchMapWithPathPrefixes(sourceIndexable, prefixKey, i, path)
- }
- if val != nil {
- return val
- }
- }
-
- return nil
- }
- func (v *Viper) searchSliceWithPathPrefixes(
- sourceSlice []interface{},
- prefixKey string,
- pathIndex int,
- path []string,
- ) interface{} {
-
- index, err := strconv.Atoi(prefixKey)
- if err != nil || len(sourceSlice) <= index {
- return nil
- }
- next := sourceSlice[index]
-
- if pathIndex == len(path) {
- return next
- }
- switch n := next.(type) {
- case map[interface{}]interface{}:
- return v.searchIndexableWithPathPrefixes(cast.ToStringMap(n), path[pathIndex:])
- case map[string]interface{}, []interface{}:
- return v.searchIndexableWithPathPrefixes(n, path[pathIndex:])
- default:
-
- }
-
- return nil
- }
- func (v *Viper) searchMapWithPathPrefixes(
- sourceMap map[string]interface{},
- prefixKey string,
- pathIndex int,
- path []string,
- ) interface{} {
- next, ok := sourceMap[prefixKey]
- if !ok {
- return nil
- }
-
- if pathIndex == len(path) {
- return next
- }
-
- switch n := next.(type) {
- case map[interface{}]interface{}:
- return v.searchIndexableWithPathPrefixes(cast.ToStringMap(n), path[pathIndex:])
- case map[string]interface{}, []interface{}:
- return v.searchIndexableWithPathPrefixes(n, path[pathIndex:])
- default:
-
- }
-
- return nil
- }
- func (v *Viper) isPathShadowedInDeepMap(path []string, m map[string]interface{}) string {
- var parentVal interface{}
- for i := 1; i < len(path); i++ {
- parentVal = v.searchMap(m, path[0:i])
- if parentVal == nil {
-
- return ""
- }
- switch parentVal.(type) {
- case map[interface{}]interface{}:
- continue
- case map[string]interface{}:
- continue
- default:
-
- return strings.Join(path[0:i], v.keyDelim)
- }
- }
- return ""
- }
- func (v *Viper) isPathShadowedInFlatMap(path []string, mi interface{}) string {
-
- var m map[string]interface{}
- switch mi.(type) {
- case map[string]string, map[string]FlagValue:
- m = cast.ToStringMap(mi)
- default:
- return ""
- }
-
- var parentKey string
- for i := 1; i < len(path); i++ {
- parentKey = strings.Join(path[0:i], v.keyDelim)
- if _, ok := m[parentKey]; ok {
- return parentKey
- }
- }
- return ""
- }
- func (v *Viper) isPathShadowedInAutoEnv(path []string) string {
- var parentKey string
- for i := 1; i < len(path); i++ {
- parentKey = strings.Join(path[0:i], v.keyDelim)
- if _, ok := v.getEnv(v.mergeWithEnvPrefix(parentKey)); ok {
- return parentKey
- }
- }
- return ""
- }
- func SetTypeByDefaultValue(enable bool) { v.SetTypeByDefaultValue(enable) }
- func (v *Viper) SetTypeByDefaultValue(enable bool) {
- v.typeByDefValue = enable
- }
- func GetViper() *Viper {
- return v
- }
- func Get(key string) interface{} { return v.Get(key) }
- func (v *Viper) Get(key string) interface{} {
- lcaseKey := strings.ToLower(key)
- val := v.find(lcaseKey, true)
- if val == nil {
- return nil
- }
- if v.typeByDefValue {
-
- valType := val
- path := strings.Split(lcaseKey, v.keyDelim)
- defVal := v.searchMap(v.defaults, path)
- if defVal != nil {
- valType = defVal
- }
- switch valType.(type) {
- case bool:
- return cast.ToBool(val)
- case string:
- return cast.ToString(val)
- case int32, int16, int8, int:
- return cast.ToInt(val)
- case uint:
- return cast.ToUint(val)
- case uint32:
- return cast.ToUint32(val)
- case uint64:
- return cast.ToUint64(val)
- case int64:
- return cast.ToInt64(val)
- case float64, float32:
- return cast.ToFloat64(val)
- case time.Time:
- return cast.ToTime(val)
- case time.Duration:
- return cast.ToDuration(val)
- case []string:
- return cast.ToStringSlice(val)
- case []int:
- return cast.ToIntSlice(val)
- }
- }
- return val
- }
- func Sub(key string) *Viper { return v.Sub(key) }
- func (v *Viper) Sub(key string) *Viper {
- subv := New()
- data := v.Get(key)
- if data == nil {
- return nil
- }
- if reflect.TypeOf(data).Kind() == reflect.Map {
- subv.config = cast.ToStringMap(data)
- return subv
- }
- return nil
- }
- func GetString(key string) string { return v.GetString(key) }
- func (v *Viper) GetString(key string) string {
- return cast.ToString(v.Get(key))
- }
- func GetBool(key string) bool { return v.GetBool(key) }
- func (v *Viper) GetBool(key string) bool {
- return cast.ToBool(v.Get(key))
- }
- func GetInt(key string) int { return v.GetInt(key) }
- func (v *Viper) GetInt(key string) int {
- return cast.ToInt(v.Get(key))
- }
- func GetInt32(key string) int32 { return v.GetInt32(key) }
- func (v *Viper) GetInt32(key string) int32 {
- return cast.ToInt32(v.Get(key))
- }
- func GetInt64(key string) int64 { return v.GetInt64(key) }
- func (v *Viper) GetInt64(key string) int64 {
- return cast.ToInt64(v.Get(key))
- }
- func GetUint(key string) uint { return v.GetUint(key) }
- func (v *Viper) GetUint(key string) uint {
- return cast.ToUint(v.Get(key))
- }
- func GetUint16(key string) uint16 { return v.GetUint16(key) }
- func (v *Viper) GetUint16(key string) uint16 {
- return cast.ToUint16(v.Get(key))
- }
- func GetUint32(key string) uint32 { return v.GetUint32(key) }
- func (v *Viper) GetUint32(key string) uint32 {
- return cast.ToUint32(v.Get(key))
- }
- func GetUint64(key string) uint64 { return v.GetUint64(key) }
- func (v *Viper) GetUint64(key string) uint64 {
- return cast.ToUint64(v.Get(key))
- }
- func GetFloat64(key string) float64 { return v.GetFloat64(key) }
- func (v *Viper) GetFloat64(key string) float64 {
- return cast.ToFloat64(v.Get(key))
- }
- func GetTime(key string) time.Time { return v.GetTime(key) }
- func (v *Viper) GetTime(key string) time.Time {
- return cast.ToTime(v.Get(key))
- }
- func GetDuration(key string) time.Duration { return v.GetDuration(key) }
- func (v *Viper) GetDuration(key string) time.Duration {
- return cast.ToDuration(v.Get(key))
- }
- func GetIntSlice(key string) []int { return v.GetIntSlice(key) }
- func (v *Viper) GetIntSlice(key string) []int {
- return cast.ToIntSlice(v.Get(key))
- }
- func GetStringSlice(key string) []string { return v.GetStringSlice(key) }
- func (v *Viper) GetStringSlice(key string) []string {
- return cast.ToStringSlice(v.Get(key))
- }
- func GetStringMap(key string) map[string]interface{} { return v.GetStringMap(key) }
- func (v *Viper) GetStringMap(key string) map[string]interface{} {
- return cast.ToStringMap(v.Get(key))
- }
- func GetStringMapString(key string) map[string]string { return v.GetStringMapString(key) }
- func (v *Viper) GetStringMapString(key string) map[string]string {
- return cast.ToStringMapString(v.Get(key))
- }
- func GetStringMapStringSlice(key string) map[string][]string { return v.GetStringMapStringSlice(key) }
- func (v *Viper) GetStringMapStringSlice(key string) map[string][]string {
- return cast.ToStringMapStringSlice(v.Get(key))
- }
- func GetSizeInBytes(key string) uint { return v.GetSizeInBytes(key) }
- func (v *Viper) GetSizeInBytes(key string) uint {
- sizeStr := cast.ToString(v.Get(key))
- return parseSizeInBytes(sizeStr)
- }
- func UnmarshalKey(key string, rawVal interface{}, opts ...DecoderConfigOption) error {
- return v.UnmarshalKey(key, rawVal, opts...)
- }
- func (v *Viper) UnmarshalKey(key string, rawVal interface{}, opts ...DecoderConfigOption) error {
- return decode(v.Get(key), defaultDecoderConfig(rawVal, opts...))
- }
- func Unmarshal(rawVal interface{}, opts ...DecoderConfigOption) error {
- return v.Unmarshal(rawVal, opts...)
- }
- func (v *Viper) Unmarshal(rawVal interface{}, opts ...DecoderConfigOption) error {
- return decode(v.AllSettings(), defaultDecoderConfig(rawVal, opts...))
- }
- func defaultDecoderConfig(output interface{}, opts ...DecoderConfigOption) *mapstructure.DecoderConfig {
- c := &mapstructure.DecoderConfig{
- Metadata: nil,
- Result: output,
- WeaklyTypedInput: true,
- DecodeHook: mapstructure.ComposeDecodeHookFunc(
- mapstructure.StringToTimeDurationHookFunc(),
- mapstructure.StringToSliceHookFunc(","),
- ),
- }
- for _, opt := range opts {
- opt(c)
- }
- return c
- }
- func decode(input interface{}, config *mapstructure.DecoderConfig) error {
- decoder, err := mapstructure.NewDecoder(config)
- if err != nil {
- return err
- }
- return decoder.Decode(input)
- }
- func UnmarshalExact(rawVal interface{}, opts ...DecoderConfigOption) error {
- return v.UnmarshalExact(rawVal, opts...)
- }
- func (v *Viper) UnmarshalExact(rawVal interface{}, opts ...DecoderConfigOption) error {
- config := defaultDecoderConfig(rawVal, opts...)
- config.ErrorUnused = true
- return decode(v.AllSettings(), config)
- }
- func BindPFlags(flags *pflag.FlagSet) error { return v.BindPFlags(flags) }
- func (v *Viper) BindPFlags(flags *pflag.FlagSet) error {
- return v.BindFlagValues(pflagValueSet{flags})
- }
- func BindPFlag(key string, flag *pflag.Flag) error { return v.BindPFlag(key, flag) }
- func (v *Viper) BindPFlag(key string, flag *pflag.Flag) error {
- if flag == nil {
- return fmt.Errorf("flag for %q is nil", key)
- }
- return v.BindFlagValue(key, pflagValue{flag})
- }
- func BindFlagValues(flags FlagValueSet) error { return v.BindFlagValues(flags) }
- func (v *Viper) BindFlagValues(flags FlagValueSet) (err error) {
- flags.VisitAll(func(flag FlagValue) {
- if err = v.BindFlagValue(flag.Name(), flag); err != nil {
- return
- }
- })
- return nil
- }
- func BindFlagValue(key string, flag FlagValue) error { return v.BindFlagValue(key, flag) }
- func (v *Viper) BindFlagValue(key string, flag FlagValue) error {
- if flag == nil {
- return fmt.Errorf("flag for %q is nil", key)
- }
- v.pflags[strings.ToLower(key)] = flag
- return nil
- }
- func BindEnv(input ...string) error { return v.BindEnv(input...) }
- func (v *Viper) BindEnv(input ...string) error {
- if len(input) == 0 {
- return fmt.Errorf("missing key to bind to")
- }
- key := strings.ToLower(input[0])
- if len(input) == 1 {
- v.env[key] = append(v.env[key], v.mergeWithEnvPrefix(key))
- } else {
- v.env[key] = append(v.env[key], input[1:]...)
- }
- return nil
- }
- func MustBindEnv(input ...string) { v.MustBindEnv(input...) }
- func (v *Viper) MustBindEnv(input ...string) {
- if err := v.BindEnv(input...); err != nil {
- panic(fmt.Sprintf("error while binding environment variable: %v", err))
- }
- }
- func (v *Viper) find(lcaseKey string, flagDefault bool) interface{} {
- var (
- val interface{}
- exists bool
- path = strings.Split(lcaseKey, v.keyDelim)
- nested = len(path) > 1
- )
-
- if nested && v.isPathShadowedInDeepMap(path, castMapStringToMapInterface(v.aliases)) != "" {
- return nil
- }
-
- lcaseKey = v.realKey(lcaseKey)
- path = strings.Split(lcaseKey, v.keyDelim)
- nested = len(path) > 1
-
- val = v.searchMap(v.override, path)
- if val != nil {
- return val
- }
- if nested && v.isPathShadowedInDeepMap(path, v.override) != "" {
- return nil
- }
-
- flag, exists := v.pflags[lcaseKey]
- if exists && flag.HasChanged() {
- switch flag.ValueType() {
- case "int", "int8", "int16", "int32", "int64":
- return cast.ToInt(flag.ValueString())
- case "bool":
- return cast.ToBool(flag.ValueString())
- case "stringSlice", "stringArray":
- s := strings.TrimPrefix(flag.ValueString(), "[")
- s = strings.TrimSuffix(s, "]")
- res, _ := readAsCSV(s)
- return res
- case "intSlice":
- s := strings.TrimPrefix(flag.ValueString(), "[")
- s = strings.TrimSuffix(s, "]")
- res, _ := readAsCSV(s)
- return cast.ToIntSlice(res)
- case "stringToString":
- return stringToStringConv(flag.ValueString())
- default:
- return flag.ValueString()
- }
- }
- if nested && v.isPathShadowedInFlatMap(path, v.pflags) != "" {
- return nil
- }
-
- if v.automaticEnvApplied {
-
-
- if val, ok := v.getEnv(v.mergeWithEnvPrefix(lcaseKey)); ok {
- return val
- }
- if nested && v.isPathShadowedInAutoEnv(path) != "" {
- return nil
- }
- }
- envkeys, exists := v.env[lcaseKey]
- if exists {
- for _, envkey := range envkeys {
- if val, ok := v.getEnv(envkey); ok {
- return val
- }
- }
- }
- if nested && v.isPathShadowedInFlatMap(path, v.env) != "" {
- return nil
- }
-
- val = v.searchIndexableWithPathPrefixes(v.config, path)
- if val != nil {
- return val
- }
- if nested && v.isPathShadowedInDeepMap(path, v.config) != "" {
- return nil
- }
-
- val = v.searchMap(v.kvstore, path)
- if val != nil {
- return val
- }
- if nested && v.isPathShadowedInDeepMap(path, v.kvstore) != "" {
- return nil
- }
-
- val = v.searchMap(v.defaults, path)
- if val != nil {
- return val
- }
- if nested && v.isPathShadowedInDeepMap(path, v.defaults) != "" {
- return nil
- }
- if flagDefault {
-
-
- if flag, exists := v.pflags[lcaseKey]; exists {
- switch flag.ValueType() {
- case "int", "int8", "int16", "int32", "int64":
- return cast.ToInt(flag.ValueString())
- case "bool":
- return cast.ToBool(flag.ValueString())
- case "stringSlice", "stringArray":
- s := strings.TrimPrefix(flag.ValueString(), "[")
- s = strings.TrimSuffix(s, "]")
- res, _ := readAsCSV(s)
- return res
- case "intSlice":
- s := strings.TrimPrefix(flag.ValueString(), "[")
- s = strings.TrimSuffix(s, "]")
- res, _ := readAsCSV(s)
- return cast.ToIntSlice(res)
- case "stringToString":
- return stringToStringConv(flag.ValueString())
- default:
- return flag.ValueString()
- }
- }
-
- }
- return nil
- }
- func readAsCSV(val string) ([]string, error) {
- if val == "" {
- return []string{}, nil
- }
- stringReader := strings.NewReader(val)
- csvReader := csv.NewReader(stringReader)
- return csvReader.Read()
- }
- func stringToStringConv(val string) interface{} {
- val = strings.Trim(val, "[]")
-
- if len(val) == 0 {
- return map[string]interface{}{}
- }
- r := csv.NewReader(strings.NewReader(val))
- ss, err := r.Read()
- if err != nil {
- return nil
- }
- out := make(map[string]interface{}, len(ss))
- for _, pair := range ss {
- kv := strings.SplitN(pair, "=", 2)
- if len(kv) != 2 {
- return nil
- }
- out[kv[0]] = kv[1]
- }
- return out
- }
- func IsSet(key string) bool { return v.IsSet(key) }
- func (v *Viper) IsSet(key string) bool {
- lcaseKey := strings.ToLower(key)
- val := v.find(lcaseKey, false)
- return val != nil
- }
- func AutomaticEnv() { v.AutomaticEnv() }
- func (v *Viper) AutomaticEnv() {
- v.automaticEnvApplied = true
- }
- func SetEnvKeyReplacer(r *strings.Replacer) { v.SetEnvKeyReplacer(r) }
- func (v *Viper) SetEnvKeyReplacer(r *strings.Replacer) {
- v.envKeyReplacer = r
- }
- func RegisterAlias(alias string, key string) { v.RegisterAlias(alias, key) }
- func (v *Viper) RegisterAlias(alias string, key string) {
- v.registerAlias(alias, strings.ToLower(key))
- }
- func (v *Viper) registerAlias(alias string, key string) {
- alias = strings.ToLower(alias)
- if alias != key && alias != v.realKey(key) {
- _, exists := v.aliases[alias]
- if !exists {
-
-
-
- if val, ok := v.config[alias]; ok {
- delete(v.config, alias)
- v.config[key] = val
- }
- if val, ok := v.kvstore[alias]; ok {
- delete(v.kvstore, alias)
- v.kvstore[key] = val
- }
- if val, ok := v.defaults[alias]; ok {
- delete(v.defaults, alias)
- v.defaults[key] = val
- }
- if val, ok := v.override[alias]; ok {
- delete(v.override, alias)
- v.override[key] = val
- }
- v.aliases[alias] = key
- }
- } else {
- v.logger.Warn("creating circular reference alias", "alias", alias, "key", key, "real_key", v.realKey(key))
- }
- }
- func (v *Viper) realKey(key string) string {
- newkey, exists := v.aliases[key]
- if exists {
- v.logger.Debug("key is an alias", "alias", key, "to", newkey)
- return v.realKey(newkey)
- }
- return key
- }
- func InConfig(key string) bool { return v.InConfig(key) }
- func (v *Viper) InConfig(key string) bool {
- lcaseKey := strings.ToLower(key)
-
- lcaseKey = v.realKey(lcaseKey)
- path := strings.Split(lcaseKey, v.keyDelim)
- return v.searchIndexableWithPathPrefixes(v.config, path) != nil
- }
- func SetDefault(key string, value interface{}) { v.SetDefault(key, value) }
- func (v *Viper) SetDefault(key string, value interface{}) {
-
- key = v.realKey(strings.ToLower(key))
- value = toCaseInsensitiveValue(value)
- path := strings.Split(key, v.keyDelim)
- lastKey := strings.ToLower(path[len(path)-1])
- deepestMap := deepSearch(v.defaults, path[0:len(path)-1])
-
- deepestMap[lastKey] = value
- }
- func Set(key string, value interface{}) { v.Set(key, value) }
- func (v *Viper) Set(key string, value interface{}) {
-
- key = v.realKey(strings.ToLower(key))
- value = toCaseInsensitiveValue(value)
- path := strings.Split(key, v.keyDelim)
- lastKey := strings.ToLower(path[len(path)-1])
- deepestMap := deepSearch(v.override, path[0:len(path)-1])
-
- deepestMap[lastKey] = value
- }
- func ReadInConfig() error { return v.ReadInConfig() }
- func (v *Viper) ReadInConfig() error {
- v.logger.Info("attempting to read in config file")
- filename, err := v.getConfigFile()
- if err != nil {
- return err
- }
- if !stringInSlice(v.getConfigType(), SupportedExts) {
- return UnsupportedConfigError(v.getConfigType())
- }
- v.logger.Debug("reading file", "file", filename)
- file, err := afero.ReadFile(v.fs, filename)
- if err != nil {
- return err
- }
- config := make(map[string]interface{})
- err = v.unmarshalReader(bytes.NewReader(file), config)
- if err != nil {
- return err
- }
- v.config = config
- return nil
- }
- func MergeInConfig() error { return v.MergeInConfig() }
- func (v *Viper) MergeInConfig() error {
- v.logger.Info("attempting to merge in config file")
- filename, err := v.getConfigFile()
- if err != nil {
- return err
- }
- if !stringInSlice(v.getConfigType(), SupportedExts) {
- return UnsupportedConfigError(v.getConfigType())
- }
- file, err := afero.ReadFile(v.fs, filename)
- if err != nil {
- return err
- }
- return v.MergeConfig(bytes.NewReader(file))
- }
- func ReadConfig(in io.Reader) error { return v.ReadConfig(in) }
- func (v *Viper) ReadConfig(in io.Reader) error {
- v.config = make(map[string]interface{})
- return v.unmarshalReader(in, v.config)
- }
- func MergeConfig(in io.Reader) error { return v.MergeConfig(in) }
- func (v *Viper) MergeConfig(in io.Reader) error {
- cfg := make(map[string]interface{})
- if err := v.unmarshalReader(in, cfg); err != nil {
- return err
- }
- return v.MergeConfigMap(cfg)
- }
- func MergeConfigMap(cfg map[string]interface{}) error { return v.MergeConfigMap(cfg) }
- func (v *Viper) MergeConfigMap(cfg map[string]interface{}) error {
- if v.config == nil {
- v.config = make(map[string]interface{})
- }
- insensitiviseMap(cfg)
- mergeMaps(cfg, v.config, nil)
- return nil
- }
- func WriteConfig() error { return v.WriteConfig() }
- func (v *Viper) WriteConfig() error {
- filename, err := v.getConfigFile()
- if err != nil {
- return err
- }
- return v.writeConfig(filename, true)
- }
- func SafeWriteConfig() error { return v.SafeWriteConfig() }
- func (v *Viper) SafeWriteConfig() error {
- if len(v.configPaths) < 1 {
- return errors.New("missing configuration for 'configPath'")
- }
- return v.SafeWriteConfigAs(filepath.Join(v.configPaths[0], v.configName+"."+v.configType))
- }
- func WriteConfigAs(filename string) error { return v.WriteConfigAs(filename) }
- func (v *Viper) WriteConfigAs(filename string) error {
- return v.writeConfig(filename, true)
- }
- func SafeWriteConfigAs(filename string) error { return v.SafeWriteConfigAs(filename) }
- func (v *Viper) SafeWriteConfigAs(filename string) error {
- alreadyExists, err := afero.Exists(v.fs, filename)
- if alreadyExists && err == nil {
- return ConfigFileAlreadyExistsError(filename)
- }
- return v.writeConfig(filename, false)
- }
- func (v *Viper) writeConfig(filename string, force bool) error {
- v.logger.Info("attempting to write configuration to file")
- var configType string
- ext := filepath.Ext(filename)
- if ext != "" && ext != filepath.Base(filename) {
- configType = ext[1:]
- } else {
- configType = v.configType
- }
- if configType == "" {
- return fmt.Errorf("config type could not be determined for %s", filename)
- }
- if !stringInSlice(configType, SupportedExts) {
- return UnsupportedConfigError(configType)
- }
- if v.config == nil {
- v.config = make(map[string]interface{})
- }
- flags := os.O_CREATE | os.O_TRUNC | os.O_WRONLY
- if !force {
- flags |= os.O_EXCL
- }
- f, err := v.fs.OpenFile(filename, flags, v.configPermissions)
- if err != nil {
- return err
- }
- defer f.Close()
- if err := v.marshalWriter(f, configType); err != nil {
- return err
- }
- return f.Sync()
- }
- func unmarshalReader(in io.Reader, c map[string]interface{}) error {
- return v.unmarshalReader(in, c)
- }
- func (v *Viper) unmarshalReader(in io.Reader, c map[string]interface{}) error {
- buf := new(bytes.Buffer)
- buf.ReadFrom(in)
- switch format := strings.ToLower(v.getConfigType()); format {
- case "yaml", "yml", "json", "toml", "hcl", "tfvars", "ini", "properties", "props", "prop", "dotenv", "env":
- err := v.decoderRegistry.Decode(format, buf.Bytes(), c)
- if err != nil {
- return ConfigParseError{err}
- }
- }
- insensitiviseMap(c)
- return nil
- }
- func (v *Viper) marshalWriter(f afero.File, configType string) error {
- c := v.AllSettings()
- switch configType {
- case "yaml", "yml", "json", "toml", "hcl", "tfvars", "ini", "prop", "props", "properties", "dotenv", "env":
- b, err := v.encoderRegistry.Encode(configType, c)
- if err != nil {
- return ConfigMarshalError{err}
- }
- _, err = f.WriteString(string(b))
- if err != nil {
- return ConfigMarshalError{err}
- }
- }
- return nil
- }
- func keyExists(k string, m map[string]interface{}) string {
- lk := strings.ToLower(k)
- for mk := range m {
- lmk := strings.ToLower(mk)
- if lmk == lk {
- return mk
- }
- }
- return ""
- }
- func castToMapStringInterface(
- src map[interface{}]interface{},
- ) map[string]interface{} {
- tgt := map[string]interface{}{}
- for k, v := range src {
- tgt[fmt.Sprintf("%v", k)] = v
- }
- return tgt
- }
- func castMapStringSliceToMapInterface(src map[string][]string) map[string]interface{} {
- tgt := map[string]interface{}{}
- for k, v := range src {
- tgt[k] = v
- }
- return tgt
- }
- func castMapStringToMapInterface(src map[string]string) map[string]interface{} {
- tgt := map[string]interface{}{}
- for k, v := range src {
- tgt[k] = v
- }
- return tgt
- }
- func castMapFlagToMapInterface(src map[string]FlagValue) map[string]interface{} {
- tgt := map[string]interface{}{}
- for k, v := range src {
- tgt[k] = v
- }
- return tgt
- }
- func mergeMaps(
- src, tgt map[string]interface{}, itgt map[interface{}]interface{},
- ) {
- for sk, sv := range src {
- tk := keyExists(sk, tgt)
- if tk == "" {
- v.logger.Trace("", "tk", "\"\"", fmt.Sprintf("tgt[%s]", sk), sv)
- tgt[sk] = sv
- if itgt != nil {
- itgt[sk] = sv
- }
- continue
- }
- tv, ok := tgt[tk]
- if !ok {
- v.logger.Trace("", fmt.Sprintf("ok[%s]", tk), false, fmt.Sprintf("tgt[%s]", sk), sv)
- tgt[sk] = sv
- if itgt != nil {
- itgt[sk] = sv
- }
- continue
- }
- svType := reflect.TypeOf(sv)
- tvType := reflect.TypeOf(tv)
- v.logger.Trace(
- "processing",
- "key", sk,
- "st", svType,
- "tt", tvType,
- "sv", sv,
- "tv", tv,
- )
- switch ttv := tv.(type) {
- case map[interface{}]interface{}:
- v.logger.Trace("merging maps (must convert)")
- tsv, ok := sv.(map[interface{}]interface{})
- if !ok {
- v.logger.Error(
- "Could not cast sv to map[interface{}]interface{}",
- "key", sk,
- "st", svType,
- "tt", tvType,
- "sv", sv,
- "tv", tv,
- )
- continue
- }
- ssv := castToMapStringInterface(tsv)
- stv := castToMapStringInterface(ttv)
- mergeMaps(ssv, stv, ttv)
- case map[string]interface{}:
- v.logger.Trace("merging maps")
- tsv, ok := sv.(map[string]interface{})
- if !ok {
- v.logger.Error(
- "Could not cast sv to map[string]interface{}",
- "key", sk,
- "st", svType,
- "tt", tvType,
- "sv", sv,
- "tv", tv,
- )
- continue
- }
- mergeMaps(tsv, ttv, nil)
- default:
- v.logger.Trace("setting value")
- tgt[tk] = sv
- if itgt != nil {
- itgt[tk] = sv
- }
- }
- }
- }
- func ReadRemoteConfig() error { return v.ReadRemoteConfig() }
- func (v *Viper) ReadRemoteConfig() error {
- return v.getKeyValueConfig()
- }
- func WatchRemoteConfig() error { return v.WatchRemoteConfig() }
- func (v *Viper) WatchRemoteConfig() error {
- return v.watchKeyValueConfig()
- }
- func (v *Viper) WatchRemoteConfigOnChannel() error {
- return v.watchKeyValueConfigOnChannel()
- }
- func (v *Viper) getKeyValueConfig() error {
- if RemoteConfig == nil {
- return RemoteConfigError("Enable the remote features by doing a blank import of the viper/remote package: '_ github.com/spf13/viper/remote'")
- }
- if len(v.remoteProviders) == 0 {
- return RemoteConfigError("No Remote Providers")
- }
- for _, rp := range v.remoteProviders {
- val, err := v.getRemoteConfig(rp)
- if err != nil {
- v.logger.Error(fmt.Errorf("get remote config: %w", err).Error())
- continue
- }
- v.kvstore = val
- return nil
- }
- return RemoteConfigError("No Files Found")
- }
- func (v *Viper) getRemoteConfig(provider RemoteProvider) (map[string]interface{}, error) {
- reader, err := RemoteConfig.Get(provider)
- if err != nil {
- return nil, err
- }
- err = v.unmarshalReader(reader, v.kvstore)
- return v.kvstore, err
- }
- func (v *Viper) watchKeyValueConfigOnChannel() error {
- if len(v.remoteProviders) == 0 {
- return RemoteConfigError("No Remote Providers")
- }
- for _, rp := range v.remoteProviders {
- respc, _ := RemoteConfig.WatchChannel(rp)
-
- go func(rc <-chan *RemoteResponse) {
- for {
- b := <-rc
- reader := bytes.NewReader(b.Value)
- v.unmarshalReader(reader, v.kvstore)
- }
- }(respc)
- return nil
- }
- return RemoteConfigError("No Files Found")
- }
- func (v *Viper) watchKeyValueConfig() error {
- if len(v.remoteProviders) == 0 {
- return RemoteConfigError("No Remote Providers")
- }
- for _, rp := range v.remoteProviders {
- val, err := v.watchRemoteConfig(rp)
- if err != nil {
- v.logger.Error(fmt.Errorf("watch remote config: %w", err).Error())
- continue
- }
- v.kvstore = val
- return nil
- }
- return RemoteConfigError("No Files Found")
- }
- func (v *Viper) watchRemoteConfig(provider RemoteProvider) (map[string]interface{}, error) {
- reader, err := RemoteConfig.Watch(provider)
- if err != nil {
- return nil, err
- }
- err = v.unmarshalReader(reader, v.kvstore)
- return v.kvstore, err
- }
- func AllKeys() []string { return v.AllKeys() }
- func (v *Viper) AllKeys() []string {
- m := map[string]bool{}
-
- m = v.flattenAndMergeMap(m, castMapStringToMapInterface(v.aliases), "")
- m = v.flattenAndMergeMap(m, v.override, "")
- m = v.mergeFlatMap(m, castMapFlagToMapInterface(v.pflags))
- m = v.mergeFlatMap(m, castMapStringSliceToMapInterface(v.env))
- m = v.flattenAndMergeMap(m, v.config, "")
- m = v.flattenAndMergeMap(m, v.kvstore, "")
- m = v.flattenAndMergeMap(m, v.defaults, "")
-
- a := make([]string, 0, len(m))
- for x := range m {
- a = append(a, x)
- }
- return a
- }
- func (v *Viper) flattenAndMergeMap(shadow map[string]bool, m map[string]interface{}, prefix string) map[string]bool {
- if shadow != nil && prefix != "" && shadow[prefix] {
-
- return shadow
- }
- if shadow == nil {
- shadow = make(map[string]bool)
- }
- var m2 map[string]interface{}
- if prefix != "" {
- prefix += v.keyDelim
- }
- for k, val := range m {
- fullKey := prefix + k
- switch val.(type) {
- case map[string]interface{}:
- m2 = val.(map[string]interface{})
- case map[interface{}]interface{}:
- m2 = cast.ToStringMap(val)
- default:
-
- shadow[strings.ToLower(fullKey)] = true
- continue
- }
-
- shadow = v.flattenAndMergeMap(shadow, m2, fullKey)
- }
- return shadow
- }
- func (v *Viper) mergeFlatMap(shadow map[string]bool, m map[string]interface{}) map[string]bool {
-
- outer:
- for k := range m {
- path := strings.Split(k, v.keyDelim)
-
- var parentKey string
- for i := 1; i < len(path); i++ {
- parentKey = strings.Join(path[0:i], v.keyDelim)
- if shadow[parentKey] {
-
- continue outer
- }
- }
-
- shadow[strings.ToLower(k)] = true
- }
- return shadow
- }
- func AllSettings() map[string]interface{} { return v.AllSettings() }
- func (v *Viper) AllSettings() map[string]interface{} {
- m := map[string]interface{}{}
-
- for _, k := range v.AllKeys() {
- value := v.Get(k)
- if value == nil {
-
-
- continue
- }
- path := strings.Split(k, v.keyDelim)
- lastKey := strings.ToLower(path[len(path)-1])
- deepestMap := deepSearch(m, path[0:len(path)-1])
-
- deepestMap[lastKey] = value
- }
- return m
- }
- func SetFs(fs afero.Fs) { v.SetFs(fs) }
- func (v *Viper) SetFs(fs afero.Fs) {
- v.fs = fs
- }
- func SetConfigName(in string) { v.SetConfigName(in) }
- func (v *Viper) SetConfigName(in string) {
- if in != "" {
- v.configName = in
- v.configFile = ""
- }
- }
- func SetConfigType(in string) { v.SetConfigType(in) }
- func (v *Viper) SetConfigType(in string) {
- if in != "" {
- v.configType = in
- }
- }
- func SetConfigPermissions(perm os.FileMode) { v.SetConfigPermissions(perm) }
- func (v *Viper) SetConfigPermissions(perm os.FileMode) {
- v.configPermissions = perm.Perm()
- }
- func IniLoadOptions(in ini.LoadOptions) Option {
- return optionFunc(func(v *Viper) {
- v.iniLoadOptions = in
- })
- }
- func (v *Viper) getConfigType() string {
- if v.configType != "" {
- return v.configType
- }
- cf, err := v.getConfigFile()
- if err != nil {
- return ""
- }
- ext := filepath.Ext(cf)
- if len(ext) > 1 {
- return ext[1:]
- }
- return ""
- }
- func (v *Viper) getConfigFile() (string, error) {
- if v.configFile == "" {
- cf, err := v.findConfigFile()
- if err != nil {
- return "", err
- }
- v.configFile = cf
- }
- return v.configFile, nil
- }
- func Debug() { v.Debug() }
- func DebugTo(w io.Writer) { v.DebugTo(w) }
- func (v *Viper) Debug() { v.DebugTo(os.Stdout) }
- func (v *Viper) DebugTo(w io.Writer) {
- fmt.Fprintf(w, "Aliases:\n%#v\n", v.aliases)
- fmt.Fprintf(w, "Override:\n%#v\n", v.override)
- fmt.Fprintf(w, "PFlags:\n%#v\n", v.pflags)
- fmt.Fprintf(w, "Env:\n%#v\n", v.env)
- fmt.Fprintf(w, "Key/Value Store:\n%#v\n", v.kvstore)
- fmt.Fprintf(w, "Config:\n%#v\n", v.config)
- fmt.Fprintf(w, "Defaults:\n%#v\n", v.defaults)
- }
|