2026-01-01 12:33:52 +05:30
|
|
|
package config
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
|
|
|
|
"os"
|
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
|
|
"github.com/spf13/viper"
|
|
|
|
|
)
|
|
|
|
|
|
2026-04-15 01:16:05 +05:30
|
|
|
// loadViperConfig loads the configuration using Viper.
|
|
|
|
|
// Precedence (highest to lowest): cobra flags > env vars > config file > defaults.
|
|
|
|
|
// Cobra flags write directly to the config struct after this function runs.
|
2026-03-31 19:21:01 +05:30
|
|
|
func loadViperConfig() error {
|
2026-01-01 12:33:52 +05:30
|
|
|
configPath, err := configFilePath()
|
|
|
|
|
if err != nil {
|
2026-03-31 19:21:01 +05:30
|
|
|
return fmt.Errorf("failed to get config file path: %w", err)
|
2026-01-01 12:33:52 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
|
|
v := viper.New()
|
|
|
|
|
v.SetConfigType("yaml")
|
|
|
|
|
v.SetEnvPrefix("PMG")
|
|
|
|
|
v.AutomaticEnv()
|
|
|
|
|
v.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
|
|
|
|
|
|
2026-04-15 20:06:53 +05:30
|
|
|
// Load the embedded template as the base so Viper knows all keys and their
|
|
|
|
|
// defaults. This is required for AutomaticEnv to resolve PMG_* env vars for
|
|
|
|
|
// keys that are absent from or newer than the user's config file.
|
|
|
|
|
if err := v.ReadConfig(strings.NewReader(templateConfig)); err != nil {
|
|
|
|
|
return fmt.Errorf("failed to load default config: %w", err)
|
|
|
|
|
}
|
2026-04-15 01:16:05 +05:30
|
|
|
|
2026-04-15 20:06:53 +05:30
|
|
|
// Merge user config on top if it exists.
|
2026-04-15 01:16:05 +05:30
|
|
|
if _, statErr := os.Stat(configPath); statErr == nil {
|
|
|
|
|
v.SetConfigFile(configPath)
|
|
|
|
|
if err := v.MergeInConfig(); err != nil {
|
|
|
|
|
return fmt.Errorf("failed to read config file %s: %w", configPath, err)
|
|
|
|
|
}
|
2026-01-01 12:33:52 +05:30
|
|
|
}
|
|
|
|
|
|
2026-04-08 21:04:17 +05:30
|
|
|
merged := globalConfig.Config
|
|
|
|
|
if err := v.Unmarshal(&merged); err != nil {
|
2026-03-31 19:21:01 +05:30
|
|
|
return fmt.Errorf("failed to unmarshal config: %w", err)
|
2026-01-01 12:33:52 +05:30
|
|
|
}
|
|
|
|
|
|
2026-04-08 21:04:17 +05:30
|
|
|
globalConfig.Config = merged
|
2026-03-31 19:21:01 +05:30
|
|
|
return nil
|
2026-01-01 12:33:52 +05:30
|
|
|
}
|