From 4302c751db5e4d9e13f81c78cc280e416f4d2cb2 Mon Sep 17 00:00:00 2001 From: anoriqq Date: Fri, 6 May 2022 18:37:37 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20config=E3=82=92=E5=B0=82=E7=94=A8sub=20?= =?UTF-8?q?command=E3=81=A7=E6=9B=B4=E6=96=B0=E3=81=A7=E3=81=8D=E3=82=8B?= =?UTF-8?q?=E3=82=88=E3=81=86=E3=81=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/cmd/config.go | 46 +++++++++++++++++++++++++++++++++++++++ internal/config/config.go | 7 +++++- 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 internal/cmd/config.go diff --git a/internal/cmd/config.go b/internal/cmd/config.go new file mode 100644 index 0000000..2680992 --- /dev/null +++ b/internal/cmd/config.go @@ -0,0 +1,46 @@ +package cmd + +import ( + "errors" + "fmt" + "strings" + + "github.com/anoriqq/qpm/internal/config" + "github.com/spf13/cobra" +) + +var configCmd = &cobra.Command{ + Use: "config", + Short: "update config", + Example: ` # set ScriptDir to ~/.qpm + qpm config ScriptDir ~/.qpm`, + RunE: configRun, +} + +func init() { + rootCmd.AddCommand(configCmd) +} + +var r = strings.NewReplacer("{", "", "}", "", ":", ": ") + +func configRun(_ *cobra.Command, args []string) error { + if len(args) < 2 { + return errors.New("config field and value is required") + } + if len(args) != 2 { + return errors.New("too many arguments") + } + + configField, configValue := args[0], args[1] + + switch strings.ToLower(configField) { + case "scriptdir": + config.SetScriptDir(configValue) + default: + return fmt.Errorf("unknown config field: %s", configField) + } + + fmt.Println(r.Replace(fmt.Sprintf("%+v\n", config.Cfg))) + + return nil +} diff --git a/internal/config/config.go b/internal/config/config.go index 3a628ba..4ad7992 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -87,5 +87,10 @@ func HasScriptDir() bool { func SetScriptDir(scriptDir string) error { viper.Set("ScriptDir", scriptDir) - return viper.WriteConfig() + err := viper.WriteConfig() + if err != nil { + return err + } + + return viper.Unmarshal(&Cfg) }