1
0
mirror of https://github.com/mrusme/neonmodem.git synced 2024-12-04 14:46:37 -05:00

Fixed config paths, added Save func

This commit is contained in:
マリウス 2022-12-29 17:45:57 -05:00
parent 6059e71033
commit 61af5b1faa
No known key found for this signature in database
GPG Key ID: 272ED814BF63261F

View File

@ -1,8 +1,11 @@
package config package config
import ( import (
"os"
"path"
"strings" "strings"
"github.com/pelletier/go-toml/v2"
"github.com/spf13/viper" "github.com/spf13/viper"
) )
@ -16,25 +19,33 @@ var VERSION string
type ServiceStatus int8 type ServiceStatus int8
type Config struct { type SystemConfig struct {
Debug string
Systems []struct {
Type string Type string
Config map[string]interface{} Config map[string]interface{}
} }
type Config struct {
Debug string
Systems []SystemConfig
} }
func Load() (Config, error) { func Load() (Config, error) {
cfgDir, err := os.UserConfigDir()
if err != nil {
return Config{}, err
}
homeDir, err := os.UserHomeDir()
if err != nil {
return Config{}, err
}
viper.SetDefault("Debug", "true") viper.SetDefault("Debug", "true")
viper.SetConfigName("gobbs.toml") viper.SetConfigName("gobbs")
viper.SetConfigType("toml") viper.SetConfigType("toml")
viper.AddConfigPath("/etc/") viper.AddConfigPath(cfgDir)
viper.AddConfigPath("$XDG_CONFIG_HOME/") viper.AddConfigPath(homeDir)
viper.AddConfigPath("$HOME/.config/")
viper.AddConfigPath("$HOME/")
viper.AddConfigPath(".")
viper.SetEnvPrefix("gobbs") viper.SetEnvPrefix("gobbs")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
@ -43,6 +54,8 @@ func Load() (Config, error) {
if err := viper.ReadInConfig(); err != nil { if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok { if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
return Config{}, err return Config{}, err
} else {
return Config{}, nil
} }
} }
@ -53,3 +66,26 @@ func Load() (Config, error) {
return config, nil return config, nil
} }
func (cfg *Config) Save() error {
cfgFile := viper.ConfigFileUsed()
if cfgFile == "" {
cfgDir, err := os.UserConfigDir()
if err != nil {
return err
}
cfgFile = path.Join(cfgDir, "gobbs.toml")
}
fd, err := os.OpenFile(cfgFile, os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
return err
}
defer fd.Close()
if err := toml.NewEncoder(fd).Encode(cfg); err != nil {
return err
}
return nil
}