Check for lack of config file

This commit is contained in:
raul 2024-05-22 15:37:48 +02:00
parent ed4c775384
commit b7739c039e
1 changed files with 9 additions and 19 deletions

View File

@ -5,7 +5,7 @@ Copyright © 2024 raul
package cmd
import (
"fmt"
"log"
"os"
"github.com/spf13/cobra"
@ -14,7 +14,6 @@ import (
var cfgFile string
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "cert400",
Short: "A brief description of your application",
@ -29,8 +28,6 @@ to quickly create a Cobra application.`,
// Run: func(cmd *cobra.Command, args []string) { },
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
err := rootCmd.Execute()
if err != nil {
@ -40,18 +37,9 @@ func Execute() {
func init() {
cobra.OnInitialize(initConfig)
// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "Config file (default is $HOME/.config/cert400/cert400.toml)")
// Cobra also supports local flags, which will only run
// when this action is called directly.
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
@ -61,16 +49,18 @@ func initConfig() {
home, err := os.UserHomeDir()
cobra.CheckErr(err)
// Search config in home directory with name ".cert400" (without extension).
viper.AddConfigPath(home + "/.config/cert400")
viper.SetConfigName("cert400")
viper.SetConfigType("toml")
viper.AddConfigPath(home + "/.config/cert400/")
viper.SetConfigFile(home + "/.config/cert400/cert400.toml")
}
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 := viper.ReadInConfig(); err != nil {
if os.IsNotExist(err) {
log.Fatalln("Missing config file at $HOME/.config/cert400/cert400.toml")
} else {
log.Fatal(err)
}
}
}