decred.org/dcrdex@v1.0.5/dex/config/config.go (about) 1 // This code is available on the terms of the project LICENSE.md file, 2 // also available online at https://blueoakcouncil.org/license/1.0.0. 3 4 package config 5 6 import ( 7 "bytes" 8 "fmt" 9 10 "gopkg.in/ini.v1" 11 ) 12 13 func loadINIConfig(cfgPathOrData any) (*ini.File, error) { 14 loadOpts := ini.LoadOptions{Insensitive: true} 15 return ini.LoadSources(loadOpts, cfgPathOrData) 16 } 17 18 // Parse returns a collection of all key-value options in the provided config 19 // file path or []byte data. 20 func Parse(cfgPathOrData any) (map[string]string, error) { 21 cfgFile, err := loadINIConfig(cfgPathOrData) 22 if err != nil { 23 return nil, err 24 } 25 cfgKeyValues := make(map[string]string) 26 for _, section := range cfgFile.Sections() { 27 for _, key := range section.Keys() { 28 cfgKeyValues[key.Name()] = key.String() 29 } 30 } 31 return cfgKeyValues, nil 32 } 33 34 // ParseInto parses config options from the provided config file path or []byte 35 // data into the specified interface. 36 func ParseInto(cfgPathOrData, obj any) error { 37 cfgFile, err := loadINIConfig(cfgPathOrData) 38 if err != nil { 39 return err 40 } 41 for _, section := range cfgFile.Sections() { 42 err := section.MapTo(obj) 43 if err != nil { 44 return err 45 } 46 } 47 return nil 48 } 49 50 // Data generates a config []byte data from a settings map. 51 func Data(settings map[string]string) []byte { 52 var buffer bytes.Buffer 53 for key, value := range settings { 54 buffer.WriteString(fmt.Sprintf("%s=%s\n", key, value)) 55 } 56 return buffer.Bytes() 57 } 58 59 // Unmapify parses config options from the provided settings map into the 60 // specified interface. 61 func Unmapify(settings map[string]string, obj any) error { 62 cfgData := Data(settings) 63 return ParseInto(cfgData, obj) 64 } 65 66 // Mapify takes an interface with ini tags, and parses it into 67 // a settings map. obj must be a pointer to a struct. 68 func Mapify(obj any) (map[string]string, error) { 69 cfg := ini.Empty() 70 err := ini.ReflectFrom(cfg, obj) 71 if err != nil { 72 return nil, err 73 } 74 cfgKeyValues := make(map[string]string) 75 for _, section := range cfg.Sections() { 76 for _, key := range section.Keys() { 77 cfgKeyValues[key.Name()] = key.String() 78 } 79 } 80 return cfgKeyValues, nil 81 }