new/clear-command (#8)

Reviewed-on: #8
Co-authored-by: jake <jake.young.dev@gmail.com>
Co-committed-by: jake <jake.young.dev@gmail.com>
This commit is contained in:
2025-05-11 04:27:47 +00:00
committed by jake
parent 386a766185
commit f8282c3676
5 changed files with 65 additions and 5 deletions

43
cmd/clear.go Normal file
View File

@@ -0,0 +1,43 @@
/*
Copyright © 2025 Jake jake.young.dev@gmail.com
*/
package cmd
import (
"fmt"
"os"
"code.jakeyoungdev.com/jake/mctl/models"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// clearCmd represents the clear command
var clearCmd = &cobra.Command{
Use: "clear",
Short: "Clear config file",
Long: `Clears all configuration values for mctl, all server configuration will be lost`,
Run: func(cmd *cobra.Command, args []string) {
home, err := os.UserHomeDir()
cobra.CheckErr(err)
viper.AddConfigPath(home)
viper.SetConfigType("yaml")
viper.SetConfigName(".mctl")
err = viper.ReadInConfig()
if err == nil {
//clear values if file exists
for _, v := range models.ConfigFields {
viper.Set(v, "")
}
err := viper.WriteConfig()
cobra.CheckErr(err)
fmt.Println("Config file cleared, use 'config' command to re-populate it")
}
},
}
func init() {
rootCmd.AddCommand(clearCmd)
}

View File

@@ -76,9 +76,8 @@ func initConfig() {
viper.SetConfigName(".mctl")
viper.AutomaticEnv()
err = viper.ReadInConfig()
cobra.CheckErr(err)
if err := viper.ReadInConfig(); err != nil {
if err != nil {
//file does not exist, create it
viper.Set("server", cfgserver)
viper.Set("password", "")