Skip to content

Commit

Permalink
feat: configを専用sub commandで更新できるように
Browse files Browse the repository at this point in the history
  • Loading branch information
anoriqq committed May 6, 2022
1 parent ce93654 commit 4302c75
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
46 changes: 46 additions & 0 deletions internal/cmd/config.go
Original file line number Diff line number Diff line change
@@ -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
}
7 changes: 6 additions & 1 deletion internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit 4302c75

Please sign in to comment.