Initialize config if it does not exist, set database relative to config dir

This commit is contained in:
Philipp Wolfer 2023-12-05 16:31:52 +01:00
parent c101749faa
commit ce5cdceb1f
No known key found for this signature in database
GPG key ID: 8FDF744D4919943B
6 changed files with 100 additions and 27 deletions

View file

@ -19,10 +19,10 @@ package cmd
import (
"fmt"
"os"
"path"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"go.uploadedlobster.com/scotty/internal/config"
"go.uploadedlobster.com/scotty/internal/version"
)
@ -56,7 +56,7 @@ func init() {
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.
configDir := defaultConfigDir()
configDir := config.DefaultConfigDir()
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "",
fmt.Sprintf("config file (default is %s/scotty.yaml)", configDir))
@ -65,27 +65,12 @@ func init() {
// rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
func defaultConfigDir() string {
configDir, err := os.UserConfigDir()
cobra.CheckErr(err)
return path.Join(configDir, version.AppName)
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
viper.AddConfigPath(defaultConfigDir())
viper.SetConfigType("toml")
viper.SetConfigName(version.AppName)
}
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
if err := config.InitConfig(cfgFile); err != nil {
fmt.Fprintln(os.Stderr, "Failed reading config:", err)
} else {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}