diff --git a/cmd/root.go b/cmd/root.go index cd89fa2..3b402b7 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -9,6 +9,7 @@ import ( ) const VERSION string = "0.1" +const CONFIG_DIR string = "/.config/gitw" var ( version bool @@ -33,12 +34,30 @@ func init() { } func initConfig() { + home := os.Getenv("HOME") viper.SetConfigName("config") viper.SetConfigType("yaml") - viper.AddConfigPath("$HOME/.config/gitw") + viper.AddConfigPath(home + CONFIG_DIR) viper.AutomaticEnv() if err := viper.ReadInConfig(); err != nil { - fmt.Fprintf(os.Stderr, "Failed to read configuration file: %s\n", err) - os.Exit(-1) + if _, ok := err.(viper.ConfigFileNotFoundError); ok { + // config file not found, create starting configuration file for the user + viper.Set("base_url", "") + viper.Set("user_name", "") + viper.Set("access_code", "") + if err = os.MkdirAll(home+CONFIG_DIR, os.ModePerm); err != nil { + fmt.Fprintf(os.Stderr, "Could not create directories for configuration file: %s\nError: %s\n", home+CONFIG_DIR, err) + os.Exit(-1) + } + if err = viper.SafeWriteConfig(); err != nil { + fmt.Fprintf(os.Stderr, "Failed to write starting configuration file: %s\n", err) + os.Exit(-1) + } + fmt.Printf("Could not find configuration file in %s\nCreated starting configuration for you. Please enter the necessary values accordingly and try again.\n", home+CONFIG_DIR) + os.Exit(2) + } else { + fmt.Fprintf(os.Stderr, "Failed to read configuration file: %s\n", err) + os.Exit(-1) + } } }