Skip to content

Commit

Permalink
config: factored out some config handling code into config.go
Browse files Browse the repository at this point in the history
  • Loading branch information
phiros committed Apr 1, 2019
1 parent 8c43afa commit 0119f7d
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 33 deletions.
36 changes: 3 additions & 33 deletions cmd-config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,9 @@ package main

import (
"fmt"
"github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"os"
"path/filepath"
"reflect"
"strings"
)

Expand All @@ -20,7 +17,7 @@ var configCommand = &cobra.Command{
Short: "sets or reads a config property",
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
printFullConfig()
configPrintAll()
return
}

Expand All @@ -36,36 +33,9 @@ var configCommand = &cobra.Command{
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.MergeInConfig()
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
}
err = viper.WriteConfigAs(filepath.Join(dir, configFileName))
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
}
configSet(configKey, configValue)
return
}
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))
}
fmt.Println(configGet(configKey))
},
}

func printFullConfig() {
err := viper.ReadInConfig()
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
}
c := viper.AllSettings()
fmt.Printf("%v\n", c)
}
47 changes: 47 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package main

import (
"fmt"
"github.com/mitchellh/go-homedir"
"github.com/spf13/viper"
"os"
"path/filepath"
)

func configGet(key string) string {
err := viper.ReadInConfig()
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
}
return viper.GetString(key)
}

func configSet(key string, value string) {
err := viper.ReadInConfig()
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
}

viper.Set(key, value)
dir, err := homedir.Dir()
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
}
err = viper.MergeInConfig()
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
}
err = viper.WriteConfigAs(filepath.Join(dir, configFileName))
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
}
}

func configPrintAll() {
err := viper.ReadInConfig()
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
}
c := viper.AllSettings()
fmt.Printf("%v\n", c)
}

0 comments on commit 0119f7d

Please sign in to comment.