From 9a67051769ec4289644a30dd25498fda508d9a27 Mon Sep 17 00:00:00 2001 From: Philipp Rosenkranz Date: Mon, 1 Apr 2019 13:17:36 +0200 Subject: [PATCH] implemented config sub-command --- cmd-config.go | 67 ++++++++++++++++++++++++++++++++++++++++++++ cmd/cmd.go => cmd.go | 5 ++-- main.go | 12 ++++++-- 3 files changed, 79 insertions(+), 5 deletions(-) create mode 100644 cmd-config.go rename cmd/cmd.go => cmd.go (89%) diff --git a/cmd-config.go b/cmd-config.go new file mode 100644 index 0000000..045935c --- /dev/null +++ b/cmd-config.go @@ -0,0 +1,67 @@ +package main + +import ( + "fmt" + "github.com/mitchellh/go-homedir" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "os" + "path/filepath" + "reflect" + "strings" +) + +func init() { + rootCmd.AddCommand(configCommand) +} + +var configCommand = &cobra.Command{ + Use: "config", + Short: "sets or reads a config property", + Run: func(cmd *cobra.Command, args []string) { + if len(args) == 0 { + printFullConfig() + return + } + + firstArgument := args[0] + configKey := firstArgument + containsEquals := strings.Index(firstArgument, "=") > 0 + if containsEquals { + // write to config + configKeyValue := strings.Split(firstArgument, "=") + configKey := configKeyValue[0] + configValue := configKeyValue[1] + viper.Set(configKey, configValue) + dir, err := homedir.Dir() + if err != nil { + _, _ = fmt.Fprintln(os.Stderr, err) + } + err = viper.WriteConfigAs(filepath.Join(dir, configFileName)) + if err != nil { + _, _ = fmt.Fprintln(os.Stderr, err) + } + return + } + err := viper.ReadInConfig() + if err != nil { + _, _ = fmt.Fprintln(os.Stderr, err) + } + configValue := viper.Get(configKey) + switch v := configValue.(type) { + case string: + fmt.Println(v) + default: + _, _ = fmt.Fprintf(os.Stderr, "unknown type %v\n", reflect.TypeOf(v)) + } + }, +} + +func printFullConfig() { + err := viper.ReadInConfig() + if err != nil { + _, _ = fmt.Fprintln(os.Stderr, err) + } + c := viper.AllSettings() + fmt.Printf("%v\n", c) +} diff --git a/cmd/cmd.go b/cmd.go similarity index 89% rename from cmd/cmd.go rename to cmd.go index 2427349..a6f8719 100644 --- a/cmd/cmd.go +++ b/cmd.go @@ -1,4 +1,4 @@ -package cmd +package main import ( "fmt" @@ -15,10 +15,9 @@ var rootCmd = &cobra.Command{ }, } -func Execute() { +func cmdLineHandler() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } } - diff --git a/main.go b/main.go index 8cd4a26..6e54ba2 100644 --- a/main.go +++ b/main.go @@ -1,7 +1,15 @@ package main -import "github.com/phiros/mite-go/cmd" +import ( + "github.com/spf13/viper" +) + +const configFileName = ".mite-go.toml" +const configPath = "$HOME" func main() { - cmd.Execute() + viper.AddConfigPath(configPath) + viper.SetConfigName(".mite-go") + viper.SetConfigType("toml") + cmdLineHandler() }