user-config/config_file.go

98 lines
2.5 KiB
Go
Raw Normal View History

2016-02-09 14:32:36 +00:00
// Package userConfig eases the use of config files in a user's home directory
package userConfig
import (
"bytes"
"errors"
2016-03-27 01:53:27 +00:00
"fmt"
2016-02-09 14:32:36 +00:00
"io/ioutil"
2016-03-27 01:53:27 +00:00
"os"
2016-02-09 14:32:36 +00:00
"strings"
"github.com/BurntSushi/toml"
)
// GeneralConfig is the basic config structure
// All configs make with package userConfig will have this file
type GeneralConfig struct {
Name string `toml:"-"`
Path string `toml:"-"`
ConfigFiles []string `toml:"additional_config"`
RawFiles []string `toml:"raw_files"`
Values map[string]string `toml:"general"`
}
// NewGeneralConfig generates a General Config struct
func NewGeneralConfig(name, path string) (*GeneralConfig, error) {
gf := &GeneralConfig{Name: name, Path: path}
gf.ConfigFiles = []string{}
gf.RawFiles = []string{}
gf.Values = make(map[string]string)
2016-03-27 01:53:27 +00:00
// Check if file exists
fmt.Println("Checking if config file exists...")
var f os.FileInfo
var err error
if f, err = os.Stat(gf.GetFullPath()); os.IsNotExist(err) {
fmt.Println("Nope, saving default config...")
if err = gf.Save(); err != nil {
fmt.Println("Error saving default config...")
return gf, err
}
}
fmt.Println(f)
2016-02-09 14:32:36 +00:00
if err := gf.Load(); err != nil {
return gf, err
}
return gf, nil
}
// Load loads config files into the config
func (gf *GeneralConfig) Load() error {
if strings.TrimSpace(gf.Name) == "" || strings.TrimSpace(gf.Path) == "" {
2016-03-27 01:53:27 +00:00
return errors.New("Invalid ConfigFile Name: " + gf.GetFullPath())
2016-02-09 14:32:36 +00:00
}
// Config files end with .conf
2016-03-27 01:53:27 +00:00
tomlData, err := ioutil.ReadFile(gf.GetFullPath())
2016-02-09 14:32:36 +00:00
if err != nil {
return err
}
if _, err := toml.Decode(string(tomlData), &gf); err != nil {
return err
}
return nil
}
// Save writes the config to file(s)
func (gf *GeneralConfig) Save() error {
buf := new(bytes.Buffer)
2016-03-27 01:53:27 +00:00
fmt.Println("Save Config: " + gf.GetFullPath())
2016-02-09 14:32:36 +00:00
if err := toml.NewEncoder(buf).Encode(gf); err != nil {
return err
}
2016-03-27 01:53:27 +00:00
return ioutil.WriteFile(gf.GetFullPath(), buf.Bytes(), 0644)
2016-02-09 14:32:36 +00:00
}
// Set sets a key/value pair in gf, if unable to save, revert to old value
// (and return the error)
func (gf *GeneralConfig) Set(k, v string) error {
oldVal := gf.Values[k]
gf.Values[k] = v
if err := gf.Save(); err != nil {
gf.Values[k] = oldVal
return err
}
return nil
}
// Get gets a key/value pair from gf
func (gf *GeneralConfig) Get(k string) string {
return gf.Values[k]
2016-03-27 01:53:27 +00:00
}
// GetFullPath returns the full path & filename to the config file
func (gf *GeneralConfig) GetFullPath() string {
return gf.Path + "/" + gf.Name + ".conf"
2016-02-09 14:32:36 +00:00
}