Fix config file being generated in working dir
This commit is contained in:
47
cmd/root.go
47
cmd/root.go
@@ -3,9 +3,11 @@ package cmd
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
|
"os/user"
|
||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
"github.com/spf13/viper"
|
"github.com/spf13/viper"
|
||||||
|
|
||||||
"gitlab.com/DeveloperDurp/DurpCLI/cmd/auth"
|
"gitlab.com/DeveloperDurp/DurpCLI/cmd/auth"
|
||||||
"gitlab.com/DeveloperDurp/DurpCLI/cmd/cfg"
|
"gitlab.com/DeveloperDurp/DurpCLI/cmd/cfg"
|
||||||
"gitlab.com/DeveloperDurp/DurpCLI/cmd/net"
|
"gitlab.com/DeveloperDurp/DurpCLI/cmd/net"
|
||||||
@@ -35,36 +37,39 @@ func setDefaults() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
cobra.OnInitialize(initConfig)
|
//if cfgFile != "" {
|
||||||
|
// viper.SetConfigFile(cfgFile)
|
||||||
|
//} else {
|
||||||
|
// cobra.CheckErr(err)
|
||||||
|
//}
|
||||||
setDefaults()
|
setDefaults()
|
||||||
|
initConfig()
|
||||||
err := viper.WriteConfigAs(".DurpCLI.yaml")
|
loadConfig()
|
||||||
if err != nil {
|
|
||||||
fmt.Println(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
rootCmd.AddCommand(net.NetCmd)
|
rootCmd.AddCommand(net.NetCmd)
|
||||||
rootCmd.AddCommand(auth.AuthCmd)
|
rootCmd.AddCommand(auth.AuthCmd)
|
||||||
rootCmd.AddCommand(cfg.Cfgcmd)
|
rootCmd.AddCommand(cfg.Cfgcmd)
|
||||||
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.DurpCLI.yaml)")
|
rootCmd.PersistentFlags().
|
||||||
|
StringVar(&cfgFile, "config", "", "config file (default is $HOME/.DurpCLI.yaml)")
|
||||||
|
|
||||||
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
|
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
|
||||||
}
|
}
|
||||||
|
|
||||||
func initConfig() {
|
func initConfig() {
|
||||||
if cfgFile != "" {
|
usr, err := user.Current()
|
||||||
viper.SetConfigFile(cfgFile)
|
if err != nil {
|
||||||
} else {
|
os.Exit(1)
|
||||||
home, err := os.UserHomeDir()
|
}
|
||||||
cobra.CheckErr(err)
|
viper.SetConfigType("yaml")
|
||||||
|
viper.SetConfigName(".durpcli")
|
||||||
viper.AddConfigPath(home)
|
viper.AddConfigPath(usr.HomeDir)
|
||||||
viper.SetConfigType("yaml")
|
}
|
||||||
viper.SetConfigName(".DurpCLI")
|
|
||||||
|
func loadConfig() {
|
||||||
|
viper.AutomaticEnv()
|
||||||
|
err := viper.ReadInConfig()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("Config file not found. Creating a new one with defaults...")
|
||||||
|
viper.SafeWriteConfig()
|
||||||
}
|
}
|
||||||
|
|
||||||
viper.AutomaticEnv()
|
|
||||||
viper.ReadInConfig()
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user