From 9dc4fdb75b6cf845202eb4d6b283ba2a3f745ac5 Mon Sep 17 00:00:00 2001 From: Christopher Sams Date: Wed, 7 Aug 2024 15:49:14 -0500 Subject: [PATCH] Ensure default config file is read correctly Ensure default file `.inventory-api.yaml`, environment variable INVENTORY_API_CONFIG, and command line option `--config` all are recognized. Signed-off-by: Christopher Sams --- cmd/root.go | 46 ++++++++++++++++++++++------------------------ 1 file changed, 22 insertions(+), 24 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index 87706d2e..585fee45 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -97,29 +97,26 @@ func initConfig() { if cfgFile != "" { viper.SetConfigFile(cfgFile) } else { - configFilePath, exists := os.LookupEnv("INVENTORY_API_CONFIG") - if !exists { - log.Fatal("Environment variable INVENTORY_API_CONFIG is not set") + if configFilePath, exists := os.LookupEnv("INVENTORY_API_CONFIG"); exists { + absPath, err := filepath.Abs(configFilePath) + if err != nil { + log.Fatalf("Failed to resolve absolute path for config file: %v", err) + } + // Set the config file path + viper.SetConfigFile(absPath) + if err := viper.ReadInConfig(); err != nil { + log.Fatalf("Error reading INVENTORY_API_CONFIG file, %s", err) + } + } else { + home, err := os.UserHomeDir() + cobra.CheckErr(err) + + viper.AddConfigPath(".") + viper.AddConfigPath(home) + viper.SetConfigType("yaml") + + viper.SetConfigName("." + Name) } - absPath, err := filepath.Abs(configFilePath) - if err != nil { - log.Fatalf("Failed to resolve absolute path for config file: %v", err) - } - // Set the config file path - viper.SetConfigFile(absPath) - if err := viper.ReadInConfig(); err != nil { - log.Fatalf("Error reading INVENTORY_API_CONFIG file, %s", err) - } - - // home, err := os.UserHomeDir() - // cobra.CheckErr(err) - // - // viper.AddConfigPath(".") - // viper.AddConfigPath(home) - // viper.SetConfigType("yaml") - // - // configName := Name - // viper.SetConfigName(configName) } viper.SetEnvPrefix(Name) @@ -127,8 +124,9 @@ func initConfig() { if err := viper.ReadInConfig(); err != nil { panic(err) - // msg := fmt.Sprintf("Using config file: %s", viper.ConfigFileUsed()) - // logger.Debug(msg) + } else { + msg := fmt.Sprintf("Using config file: %s", viper.ConfigFileUsed()) + logger.Debug(msg) } // put the values into the options struct.