breaktime/cmd/config.go

90 lines
1.9 KiB
Go

/*
Copyright © 2023 Brian Buller <brian@bullercodeworks.com>
*/
package cmd
import (
"fmt"
"os"
"os/exec"
"sort"
"strconv"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// configCmd represents the config command
var configCmd = &cobra.Command{
Use: "config",
Short: "Edit breaktime config using your default editor",
RunE: opConfig,
}
func init() { rootCmd.AddCommand(configCmd) }
func opConfig(cmd *cobra.Command, args []string) error {
updConfig := make(map[string]string)
if len(args) == 1 && args[0] == "edit" {
file := viper.ConfigFileUsed()
editor := os.Getenv("EDITOR")
if editor == "" {
return fmt.Errorf("No EDITOR set")
}
fmt.Println("Starting", editor, file)
c := exec.Command(editor, file)
c.Stdin = os.Stdin
c.Stdout = os.Stdout
return c.Run()
}
if len(args) > 0 {
// We're setting arguments
for _, a := range args {
pts := strings.Split(a, "=")
if len(pts) == 2 {
updConfig[pts[0]] = pts[1]
} else {
return fmt.Errorf("Unable to parse config values.")
}
}
}
var settings []string
for k, v := range viper.AllSettings() {
switch v.(type) {
case bool:
if nv, ok := updConfig[k]; ok {
v = nv == "true"
viper.Set(k, v)
viper.WriteConfig()
}
settings = append(settings, fmt.Sprintf("%s: %t", k, v))
case float64:
if nv, ok := updConfig[k]; ok {
var err error
v, err = strconv.ParseFloat(nv, 64)
if err != nil {
return fmt.Errorf("Unable to parse float value")
}
viper.Set(k, v)
viper.WriteConfig()
}
settings = append(settings, fmt.Sprintf("%s: %f", k, v))
default:
if nv, ok := updConfig[k]; ok {
v = nv
viper.Set(k, v)
viper.WriteConfig()
}
settings = append(settings, fmt.Sprintf("%s: %s", k, v))
}
}
sort.Strings(settings)
fmt.Println("Configuration File:", viper.ConfigFileUsed())
for _, v := range settings {
fmt.Println(v)
}
return nil
}