Skip to content

Commit

Permalink
RHCLOUD-34576 Moving config reading to PreRun function
Browse files Browse the repository at this point in the history
 - Was initially checking spf13/viper#233
   but none of the suggestions there seemed to work.
   In our case it looked like viper or cobra wasn't loading the value at all.
 - Moved some code to the PreRun and that seems to work. Some users suggest
   that the code shouldn't be in the init and use the PreRun instead.
  • Loading branch information
josejulio committed Aug 13, 2024
1 parent c8e21f9 commit 308ff16
Showing 1 changed file with 13 additions and 13 deletions.
26 changes: 13 additions & 13 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,19 @@ var (
Use: Name,
Version: Version,
Short: "A simple common inventory system",
PreRunE: func(cmd *cobra.Command, args []string) error {
if err := viper.ReadInConfig(); err != nil {
return err
} else {
msg := fmt.Sprintf("Using config file: %s", viper.ConfigFileUsed())
logger.Debug(msg)
}

// put the values into the options struct.
err := viper.Unmarshal(&options)

return err
},
}

options = struct {
Expand Down Expand Up @@ -122,17 +135,4 @@ func initConfig() {

viper.SetEnvPrefix(Name)
viper.AutomaticEnv()

if err := viper.ReadInConfig(); err != nil {
panic(err)
} else {
msg := fmt.Sprintf("Using config file: %s", viper.ConfigFileUsed())
logger.Debug(msg)
}

// put the values into the options struct.
err := viper.Unmarshal(&options)
if err != nil {
panic(err)
}
}

0 comments on commit 308ff16

Please sign in to comment.