utils.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. package configor
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "os"
  8. "path"
  9. "reflect"
  10. "strings"
  11. "time"
  12. "github.com/BurntSushi/toml"
  13. "gopkg.in/yaml.v2"
  14. )
  15. // UnmatchedTomlKeysError errors are returned by the Load function when
  16. // ErrorOnUnmatchedKeys is set to true and there are unmatched keys in the input
  17. // toml config file. The string returned by Error() contains the names of the
  18. // missing keys.
  19. type UnmatchedTomlKeysError struct {
  20. Keys []toml.Key
  21. }
  22. func (e *UnmatchedTomlKeysError) Error() string {
  23. return fmt.Sprintf("There are keys in the config file that do not match any field in the given struct: %v", e.Keys)
  24. }
  25. func (configor *Configor) getENVPrefix(config interface{}) string {
  26. if configor.Config.ENVPrefix == "" {
  27. if prefix := os.Getenv("CONFIGOR_ENV_PREFIX"); prefix != "" {
  28. return prefix
  29. }
  30. return "Configor"
  31. }
  32. return configor.Config.ENVPrefix
  33. }
  34. func getConfigurationFileWithENVPrefix(file, env string) (string, time.Time, error) {
  35. var (
  36. envFile string
  37. extname = path.Ext(file)
  38. )
  39. if extname == "" {
  40. envFile = fmt.Sprintf("%v.%v", file, env)
  41. } else {
  42. envFile = fmt.Sprintf("%v.%v%v", strings.TrimSuffix(file, extname), env, extname)
  43. }
  44. if fileInfo, err := os.Stat(envFile); err == nil && fileInfo.Mode().IsRegular() {
  45. return envFile, fileInfo.ModTime(), nil
  46. }
  47. return "", time.Now(), fmt.Errorf("failed to find file %v", file)
  48. }
  49. func (configor *Configor) getConfigurationFiles(watchMode bool, files ...string) ([]string, map[string]time.Time, []error) {
  50. var resultKeys []string
  51. var results = map[string]time.Time{}
  52. var resultsErrors []error = make([]error, 0, len(files))
  53. if !watchMode && (configor.Config.Debug || configor.Config.Verbose) {
  54. fmt.Printf("Current environment: '%v'\n", configor.GetEnvironment())
  55. }
  56. for i := len(files) - 1; i >= 0; i-- {
  57. foundFile := false
  58. file := files[i]
  59. // check configuration
  60. if fileInfo, err := os.Stat(file); err == nil && fileInfo.Mode().IsRegular() {
  61. foundFile = true
  62. resultKeys = append(resultKeys, file)
  63. results[file] = fileInfo.ModTime()
  64. }
  65. // check configuration with env
  66. if file, modTime, err := getConfigurationFileWithENVPrefix(file, configor.GetEnvironment()); err == nil {
  67. foundFile = true
  68. resultKeys = append(resultKeys, file)
  69. results[file] = modTime
  70. }
  71. // check example configuration
  72. if !foundFile {
  73. if example, modTime, err := getConfigurationFileWithENVPrefix(file, "example"); err == nil {
  74. if !watchMode && !configor.Silent {
  75. fmt.Printf("Failed to find configuration %v, using example file %v\n", file, example)
  76. }
  77. resultKeys = append(resultKeys, example)
  78. results[example] = modTime
  79. } else if !configor.Silent {
  80. fmt.Printf("Failed to find configuration %v\n", file)
  81. resultsErrors = append(resultsErrors, errors.New(fmt.Sprintf("Failed to find configuration %v\n", file)))
  82. }
  83. }
  84. }
  85. return resultKeys, results, resultsErrors
  86. }
  87. func processFile(config interface{}, file string, errorOnUnmatchedKeys bool) error {
  88. data, err := os.ReadFile(file)
  89. if err != nil {
  90. return err
  91. }
  92. switch {
  93. case strings.HasSuffix(file, ".yaml") || strings.HasSuffix(file, ".yml"):
  94. if errorOnUnmatchedKeys {
  95. return yaml.UnmarshalStrict(data, config)
  96. }
  97. return yaml.Unmarshal(data, config)
  98. case strings.HasSuffix(file, ".toml"):
  99. return unmarshalToml(data, config, errorOnUnmatchedKeys)
  100. case strings.HasSuffix(file, ".json"):
  101. return unmarshalJSON(data, config, errorOnUnmatchedKeys)
  102. default:
  103. if err := unmarshalToml(data, config, errorOnUnmatchedKeys); err == nil {
  104. return nil
  105. } else if errUnmatchedKeys, ok := err.(*UnmatchedTomlKeysError); ok {
  106. return errUnmatchedKeys
  107. }
  108. if err := unmarshalJSON(data, config, errorOnUnmatchedKeys); err == nil {
  109. return nil
  110. } else if strings.Contains(err.Error(), "json: unknown field") {
  111. return err
  112. }
  113. var yamlError error
  114. if errorOnUnmatchedKeys {
  115. yamlError = yaml.UnmarshalStrict(data, config)
  116. } else {
  117. yamlError = yaml.Unmarshal(data, config)
  118. }
  119. if yamlError == nil {
  120. return nil
  121. } else if yErr, ok := yamlError.(*yaml.TypeError); ok {
  122. return yErr
  123. }
  124. return errors.New("failed to decode config")
  125. }
  126. }
  127. // GetStringTomlKeys returns a string array of the names of the keys that are passed in as args
  128. func GetStringTomlKeys(list []toml.Key) []string {
  129. arr := make([]string, len(list))
  130. for index, key := range list {
  131. arr[index] = key.String()
  132. }
  133. return arr
  134. }
  135. func unmarshalToml(data []byte, config interface{}, errorOnUnmatchedKeys bool) error {
  136. metadata, err := toml.Decode(string(data), config)
  137. if err == nil && len(metadata.Undecoded()) > 0 && errorOnUnmatchedKeys {
  138. return &UnmatchedTomlKeysError{Keys: metadata.Undecoded()}
  139. }
  140. return err
  141. }
  142. // unmarshalJSON unmarshals the given data into the config interface.
  143. // If the errorOnUnmatchedKeys boolean is true, an error will be returned if there
  144. // are keys in the data that do not match fields in the config interface.
  145. func unmarshalJSON(data []byte, config interface{}, errorOnUnmatchedKeys bool) error {
  146. reader := strings.NewReader(string(data))
  147. decoder := json.NewDecoder(reader)
  148. if errorOnUnmatchedKeys {
  149. decoder.DisallowUnknownFields()
  150. }
  151. err := decoder.Decode(config)
  152. if err != nil && err != io.EOF {
  153. return err
  154. }
  155. return nil
  156. }
  157. func getPrefixForStruct(prefixes []string, fieldStruct *reflect.StructField) []string {
  158. if fieldStruct.Anonymous && fieldStruct.Tag.Get("anonymous") == "true" {
  159. return prefixes
  160. }
  161. return append(prefixes, fieldStruct.Name)
  162. }
  163. func (configor *Configor) processDefaults(config interface{}) error {
  164. configValue := reflect.Indirect(reflect.ValueOf(config))
  165. if configValue.Kind() != reflect.Struct {
  166. return errors.New("invalid config, should be struct")
  167. }
  168. configType := configValue.Type()
  169. for i := 0; i < configType.NumField(); i++ {
  170. var (
  171. fieldStruct = configType.Field(i)
  172. field = configValue.Field(i)
  173. )
  174. if !field.CanAddr() || !field.CanInterface() {
  175. continue
  176. }
  177. if isBlank := reflect.DeepEqual(field.Interface(), reflect.Zero(field.Type()).Interface()); isBlank {
  178. // Set default configuration if blank
  179. if value := fieldStruct.Tag.Get("default"); value != "" {
  180. if err := yaml.Unmarshal([]byte(value), field.Addr().Interface()); err != nil {
  181. return err
  182. }
  183. }
  184. }
  185. for field.Kind() == reflect.Ptr {
  186. field = field.Elem()
  187. }
  188. switch field.Kind() {
  189. case reflect.Struct:
  190. if err := configor.processDefaults(field.Addr().Interface()); err != nil {
  191. return err
  192. }
  193. case reflect.Slice:
  194. for i := 0; i < field.Len(); i++ {
  195. if reflect.Indirect(field.Index(i)).Kind() == reflect.Struct {
  196. if err := configor.processDefaults(field.Index(i).Addr().Interface()); err != nil {
  197. return err
  198. }
  199. }
  200. }
  201. }
  202. }
  203. return nil
  204. }
  205. func (configor *Configor) processTags(config interface{}, prefixes ...string) error {
  206. configValue := reflect.Indirect(reflect.ValueOf(config))
  207. if configValue.Kind() != reflect.Struct {
  208. return errors.New("invalid config, should be struct")
  209. }
  210. configType := configValue.Type()
  211. for i := 0; i < configType.NumField(); i++ {
  212. var (
  213. envNames []string
  214. fieldStruct = configType.Field(i)
  215. field = configValue.Field(i)
  216. envName = fieldStruct.Tag.Get("env") // read configuration from shell env
  217. )
  218. if !field.CanAddr() || !field.CanInterface() {
  219. continue
  220. }
  221. if envName == "" {
  222. envNames = append(envNames, strings.Join(append(prefixes, fieldStruct.Name), "_")) // Configor_DB_Name
  223. envNames = append(envNames, strings.ToUpper(strings.Join(append(prefixes, fieldStruct.Name), "_"))) // CONFIGOR_DB_NAME
  224. } else {
  225. envNames = []string{envName}
  226. }
  227. if configor.Config.Verbose {
  228. fmt.Printf("Trying to load struct `%v`'s field `%v` from env %v\n", configType.Name(), fieldStruct.Name, strings.Join(envNames, ", "))
  229. }
  230. // Load From Shell ENV
  231. for _, env := range envNames {
  232. if value := os.Getenv(env); value != "" {
  233. if configor.Config.Debug || configor.Config.Verbose {
  234. fmt.Printf("Loading configuration for struct `%v`'s field `%v` from env %v...\n", configType.Name(), fieldStruct.Name, env)
  235. }
  236. switch reflect.Indirect(field).Kind() {
  237. case reflect.Bool:
  238. switch strings.ToLower(value) {
  239. case "", "0", "f", "false":
  240. field.Set(reflect.ValueOf(false))
  241. default:
  242. field.Set(reflect.ValueOf(true))
  243. }
  244. case reflect.String:
  245. field.Set(reflect.ValueOf(value))
  246. default:
  247. if err := yaml.Unmarshal([]byte(value), field.Addr().Interface()); err != nil {
  248. return err
  249. }
  250. }
  251. break
  252. }
  253. }
  254. if isBlank := reflect.DeepEqual(field.Interface(), reflect.Zero(field.Type()).Interface()); isBlank && fieldStruct.Tag.Get("required") == "true" {
  255. // return error if it is required but blank
  256. return errors.New(fieldStruct.Name + " is required, but blank")
  257. }
  258. for field.Kind() == reflect.Ptr {
  259. field = field.Elem()
  260. }
  261. if field.Kind() == reflect.Struct {
  262. if err := configor.processTags(field.Addr().Interface(), getPrefixForStruct(prefixes, &fieldStruct)...); err != nil {
  263. return err
  264. }
  265. }
  266. if field.Kind() == reflect.Slice {
  267. if arrLen := field.Len(); arrLen > 0 {
  268. for i := 0; i < arrLen; i++ {
  269. if reflect.Indirect(field.Index(i)).Kind() == reflect.Struct {
  270. if err := configor.processTags(field.Index(i).Addr().Interface(), append(getPrefixForStruct(prefixes, &fieldStruct), fmt.Sprint(i))...); err != nil {
  271. return err
  272. }
  273. }
  274. }
  275. } else {
  276. // load slice from env
  277. newVal := reflect.New(field.Type().Elem()).Elem()
  278. if newVal.Kind() == reflect.Struct {
  279. idx := 0
  280. for {
  281. newVal = reflect.New(field.Type().Elem()).Elem()
  282. if err := configor.processTags(newVal.Addr().Interface(), append(getPrefixForStruct(prefixes, &fieldStruct), fmt.Sprint(idx))...); err != nil {
  283. return err
  284. } else if reflect.DeepEqual(newVal.Interface(), reflect.New(field.Type().Elem()).Elem().Interface()) {
  285. break
  286. } else {
  287. idx++
  288. field.Set(reflect.Append(field, newVal))
  289. }
  290. }
  291. }
  292. }
  293. }
  294. }
  295. return nil
  296. }
  297. func (configor *Configor) load(config interface{}, watchMode bool, files ...string) (err error, changed bool) {
  298. defer func() {
  299. if configor.Config.Debug || configor.Config.Verbose {
  300. if err != nil {
  301. fmt.Printf("Failed to load configuration from %v, got %v\n", files, err)
  302. }
  303. fmt.Printf("Configuration:\n %#v\n", config)
  304. }
  305. }()
  306. configFiles, configModTimeMap, resultsErrors := configor.getConfigurationFiles(watchMode, files...)
  307. if len(resultsErrors) > 0 {
  308. return resultsErrors[0], false
  309. }
  310. if watchMode {
  311. if len(configModTimeMap) == len(configor.configModTimes) {
  312. var changed bool
  313. for f, t := range configModTimeMap {
  314. if v, ok := configor.configModTimes[f]; !ok || t.After(v) {
  315. changed = true
  316. }
  317. }
  318. if !changed {
  319. return nil, false
  320. }
  321. }
  322. }
  323. // process defaults
  324. configor.processDefaults(config)
  325. for _, file := range configFiles {
  326. if configor.Config.Debug || configor.Config.Verbose {
  327. fmt.Printf("Loading configurations from file '%v'...\n", file)
  328. }
  329. if err = processFile(config, file, configor.GetErrorOnUnmatchedKeys()); err != nil {
  330. return err, true
  331. }
  332. }
  333. configor.configModTimes = configModTimeMap
  334. if prefix := configor.getENVPrefix(config); prefix == "-" {
  335. err = configor.processTags(config)
  336. } else {
  337. err = configor.processTags(config, prefix)
  338. }
  339. return err, true
  340. }