Skip to content

Commit

Permalink
Merge pull request #177 from tphakala/config-refactor
Browse files Browse the repository at this point in the history
refactor: Refactor configuration package to improve settings handling
  • Loading branch information
tphakala authored May 26, 2024
2 parents 9882971 + 20e20cf commit 11f1335
Show file tree
Hide file tree
Showing 3 changed files with 115 additions and 8 deletions.
94 changes: 87 additions & 7 deletions internal/conf/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ package conf

import (
"embed"
"errors"
"fmt"
"io/fs"
"log"
"os"
"path/filepath"
"sync"
"time"

"github.com/spf13/viper"
Expand Down Expand Up @@ -151,8 +151,18 @@ const (
// buildTime is the time when the binary was built.
var buildDate string

// settingsInstance is the current settings instance
var (
settingsInstance *Settings
once sync.Once
settingsMutex sync.RWMutex
)

// Load reads the configuration file and environment variables into GlobalConfig.
func Load() (*Settings, error) {
settingsMutex.Lock()
defer settingsMutex.Unlock()

// Create a new settings struct
settings := &Settings{}

Expand All @@ -166,12 +176,11 @@ func Load() (*Settings, error) {
return nil, fmt.Errorf("error unmarshaling config into struct: %w", err)
}

// Validate MQTT settings
if settings.Realtime.MQTT.Enabled {
if settings.Realtime.MQTT.Broker == "" {
return nil, errors.New("MQTT broker URL is required when MQTT is enabled")
}
}
// Validate settings
validateSettings(settings)

// Save settings instance
settingsInstance = settings
return settings, nil
}

Expand Down Expand Up @@ -220,10 +229,12 @@ func createDefaultConfig() error {
configPath := filepath.Join(configPaths[0], "config.yaml")
defaultConfig := getDefaultConfig()

// Create directories for config file
if err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {
return fmt.Errorf("error creating directories for config file: %w", err)
}

// Write default config file
if err := os.WriteFile(configPath, []byte(defaultConfig), 0644); err != nil {
return fmt.Errorf("error writing default config file: %w", err)
}
Expand All @@ -240,3 +251,72 @@ func getDefaultConfig() string {
}
return string(data)
}

// GetSettings returns the current settings instance
func GetSettings() *Settings {
settingsMutex.RLock()
defer settingsMutex.RUnlock()
return settingsInstance
}

// SaveSettings saves the current settings to the YAML file
func SaveSettings() error {
settingsMutex.RLock()
defer settingsMutex.RUnlock()

// Convert settingsInstance to a map
settingsMap, err := structToMap(settingsInstance)
if err != nil {
return fmt.Errorf("error converting settings to map: %w", err)
}

// Merge the settings map with viper
err = viper.MergeConfigMap(settingsMap)
if err != nil {
return fmt.Errorf("error merging settings with viper: %w", err)
}

// Write the updated settings to the config file
return viper.WriteConfig()
}

// UpdateSettings updates the settings in memory and persists them to the YAML file
func UpdateSettings(newSettings *Settings) error {
settingsMutex.Lock()
defer settingsMutex.Unlock()

// Validate new settings
if err := validateSettings(newSettings); err != nil {
return fmt.Errorf("invalid settings: %w", err)
}

settingsInstance = newSettings

// Convert newSettings to a map
settingsMap, err := structToMap(newSettings)
if err != nil {
return fmt.Errorf("error converting settings to map: %w", err)
}

// Merge the settings map with viper
err = viper.MergeConfigMap(settingsMap)
if err != nil {
return fmt.Errorf("error merging settings with viper: %w", err)
}

// Write the updated settings to the config file
return viper.WriteConfig()
}

// Settings returns the current settings instance, initializing it if necessary
func Setting() *Settings {
once.Do(func() {
if settingsInstance == nil {
_, err := Load()
if err != nil {
log.Fatalf("Error loading settings: %v", err)
}
}
})
return GetSettings()
}
14 changes: 13 additions & 1 deletion internal/conf/utils.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// conf/utils.go
// conf/utils.go various util functions for configuration package
package conf

import (
Expand All @@ -10,6 +10,8 @@ import (
"path/filepath"
"runtime"
"strings"

"github.com/mitchellh/mapstructure"
)

// getDefaultConfigPaths returns a list of default configuration paths for the current operating system.
Expand Down Expand Up @@ -165,3 +167,13 @@ func GetBoardModel() string {
model := strings.TrimSpace(string(data))
return model
}

// structToMap converts a struct to a map using mapstructure
func structToMap(settings *Settings) (map[string]interface{}, error) {
var result map[string]interface{}
err := mapstructure.Decode(settings, &result)
if err != nil {
return nil, err
}
return result, nil
}
15 changes: 15 additions & 0 deletions internal/conf/validate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// conf/validate.go config settings validation code goes here
package conf

import "errors"

// validateSettings validates the settings
func validateSettings(settings *Settings) error {
// Add your validation logic here
if settings.Realtime.MQTT.Enabled && settings.Realtime.MQTT.Broker == "" {
return errors.New("MQTT broker URL is required when MQTT is enabled")
}
// Other options to validate go here

return nil
}

0 comments on commit 11f1335

Please sign in to comment.