add(cli): create starting configuration file if none found

This commit is contained in:
2023-10-26 16:29:44 +02:00
parent 398122a689
commit 84bf78d8a9

View File

@@ -9,6 +9,7 @@ import (
) )
const VERSION string = "0.1" const VERSION string = "0.1"
const CONFIG_DIR string = "/.config/gitw"
var ( var (
version bool version bool
@@ -33,12 +34,30 @@ func init() {
} }
func initConfig() { func initConfig() {
home := os.Getenv("HOME")
viper.SetConfigName("config") viper.SetConfigName("config")
viper.SetConfigType("yaml") viper.SetConfigType("yaml")
viper.AddConfigPath("$HOME/.config/gitw") viper.AddConfigPath(home + CONFIG_DIR)
viper.AutomaticEnv() viper.AutomaticEnv()
if err := viper.ReadInConfig(); err != nil { if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
// config file not found, create starting configuration file for the user
viper.Set("base_url", "<git-http-base-url>")
viper.Set("user_name", "<git-user-name>")
viper.Set("access_code", "<git-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) fmt.Fprintf(os.Stderr, "Failed to read configuration file: %s\n", err)
os.Exit(-1) os.Exit(-1)
} }
} }
}