103 lines
2.1 KiB
Go
103 lines
2.1 KiB
Go
|
package cmd
|
||
|
|
||
|
import (
|
||
|
"errors"
|
||
|
"fmt"
|
||
|
"os"
|
||
|
"path/filepath"
|
||
|
|
||
|
"git.iamthefij.com/iamthefij/slog"
|
||
|
"github.com/spf13/cobra"
|
||
|
"github.com/spf13/viper"
|
||
|
)
|
||
|
|
||
|
const (
|
||
|
ConfigDirPerms = 0o755
|
||
|
ConfigFilePerms = 0o600
|
||
|
)
|
||
|
|
||
|
var (
|
||
|
ErrMissingExpectedArguments = errors.New("missing expected arguments")
|
||
|
)
|
||
|
|
||
|
const (
|
||
|
ConfigHostname = "hostname"
|
||
|
ConfigUsername = "username"
|
||
|
ConfigPassword = "password"
|
||
|
)
|
||
|
|
||
|
func addConfigPaths() {
|
||
|
if configFile != "" {
|
||
|
viper.SetConfigFile(configFile)
|
||
|
} else {
|
||
|
viper.SetConfigName("config")
|
||
|
viper.SetConfigType("toml")
|
||
|
|
||
|
userConfigDir, err := os.UserConfigDir()
|
||
|
if err == nil {
|
||
|
userConfigPath := filepath.Join(userConfigDir, "imap-notes")
|
||
|
_ = os.MkdirAll(userConfigPath, ConfigDirPerms)
|
||
|
viper.AddConfigPath(userConfigPath)
|
||
|
}
|
||
|
|
||
|
viper.AddConfigPath("$HOME/.imap-notes")
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func initializeConfig() {
|
||
|
addConfigPaths()
|
||
|
|
||
|
if err := viper.ReadInConfig(); err != nil {
|
||
|
slog.OnErrFatalf(viper.SafeWriteConfig(), "failed writing default config")
|
||
|
slog.OnErrFatalf(viper.ReadInConfig(), "failed to read config")
|
||
|
}
|
||
|
}
|
||
|
|
||
|
var configCmd = &cobra.Command{
|
||
|
Use: "config",
|
||
|
Short: "Configure imap-notes",
|
||
|
Long: `Get and set configuration values for IMAP Notes`,
|
||
|
Run: func(cmd *cobra.Command, args []string) {
|
||
|
slog.Infof("Running config cobra command!")
|
||
|
},
|
||
|
}
|
||
|
|
||
|
var configGetCmd = &cobra.Command{
|
||
|
Use: "get",
|
||
|
Short: "Get a config value",
|
||
|
Args: func(cmd *cobra.Command, args []string) error {
|
||
|
if len(args) < 1 {
|
||
|
return fmt.Errorf("missing config name to retrieve: %w", ErrMissingExpectedArguments)
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
},
|
||
|
|
||
|
Run: func(cmd *cobra.Command, args []string) {
|
||
|
for _, arg := range args {
|
||
|
fmt.Printf("%s: %s", arg, viper.Get(arg))
|
||
|
}
|
||
|
fmt.Println("")
|
||
|
},
|
||
|
}
|
||
|
|
||
|
var configSetCmd = &cobra.Command{
|
||
|
Use: "set",
|
||
|
Short: "Set a config value",
|
||
|
ValidArgs: []string{
|
||
|
ConfigHostname,
|
||
|
ConfigUsername,
|
||
|
ConfigPassword,
|
||
|
},
|
||
|
Args: cobra.ExactArgs(2),
|
||
|
Run: func(cmd *cobra.Command, args []string) {
|
||
|
viper.Set(args[0], args[1])
|
||
|
slog.OnErrFatalf(viper.WriteConfig(), "failed writing value to config")
|
||
|
},
|
||
|
}
|
||
|
|
||
|
func addConfigSubcommands() {
|
||
|
configCmd.AddCommand(configGetCmd)
|
||
|
configCmd.AddCommand(configSetCmd)
|
||
|
}
|