2023-02-06 13:53:16 +00:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
2023-04-14 09:04:46 +00:00
|
|
|
"fmt"
|
2023-02-06 13:53:16 +00:00
|
|
|
"os"
|
|
|
|
"path"
|
|
|
|
|
|
|
|
"github.com/spf13/viper"
|
|
|
|
)
|
|
|
|
|
|
|
|
// ReadConfigDir reads all config files from provided directory in alphabetical order
|
|
|
|
// and merge its content with current viper configuration.
|
|
|
|
func ReadConfigDir(v *viper.Viper, configDir string) error {
|
|
|
|
entries, err := os.ReadDir(configDir)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, entry := range entries {
|
|
|
|
if entry.IsDir() {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
ext := path.Ext(entry.Name())
|
2023-04-14 09:04:46 +00:00
|
|
|
if ext != ".yaml" && ext != ".yml" && ext != ".json" {
|
2023-02-06 13:53:16 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if err = mergeConfig(v, path.Join(configDir, entry.Name())); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// mergeConfig reads config file and merge its content with current viper.
|
2023-04-14 09:04:46 +00:00
|
|
|
func mergeConfig(v *viper.Viper, fileName string) error {
|
|
|
|
cv := viper.New()
|
|
|
|
cv.SetConfigFile(fileName)
|
|
|
|
err := cv.ReadInConfig()
|
2023-02-06 13:53:16 +00:00
|
|
|
if err != nil {
|
2023-04-14 09:04:46 +00:00
|
|
|
return fmt.Errorf("failed to read config: %w", err)
|
2023-02-06 13:53:16 +00:00
|
|
|
}
|
2023-04-14 09:04:46 +00:00
|
|
|
if err = v.MergeConfigMap(cv.AllSettings()); err != nil {
|
|
|
|
return fmt.Errorf("failed to merge config: %w", err)
|
2023-02-06 13:53:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|