Skip to content

Commit

Permalink
implemented config sub-command
Browse files Browse the repository at this point in the history
  • Loading branch information
phiros committed Apr 1, 2019
1 parent 446e91c commit 9a67051
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 5 deletions.
67 changes: 67 additions & 0 deletions cmd-config.go
Original file line number Diff line number Diff line change
@@ -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)
}
5 changes: 2 additions & 3 deletions cmd/cmd.go → cmd.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package cmd
package main

import (
"fmt"
Expand All @@ -15,10 +15,9 @@ var rootCmd = &cobra.Command{
},
}

func Execute() {
func cmdLineHandler() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}

12 changes: 10 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
@@ -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()
}

0 comments on commit 9a67051

Please sign in to comment.