mirror of
https://git.sr.ht/~phw/scotty
synced 2025-04-25 13:57:56 +02:00
Initialize config if it does not exist, set database relative to config dir
This commit is contained in:
parent
c101749faa
commit
ce5cdceb1f
6 changed files with 100 additions and 27 deletions
27
cmd/root.go
27
cmd/root.go
|
@ -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())
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue