forked from golang/config
81 lines
1.8 KiB
Go
81 lines
1.8 KiB
Go
package config
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/pelletier/go-toml/v2"
|
|
"io/ioutil"
|
|
"os"
|
|
"path/filepath"
|
|
)
|
|
|
|
type Config[T any] struct {
|
|
Name string
|
|
Filename string
|
|
ConfigFile *string
|
|
Config T
|
|
}
|
|
|
|
func getConfigDir(n string) string {
|
|
// Find config directory
|
|
|
|
// Linux (XDG base directory specification compliant)
|
|
xdg_config_home := os.Getenv("XDG_CONFIG_HOME")
|
|
|
|
var base string
|
|
if xdg_config_home != "" {
|
|
base = xdg_config_home
|
|
} else {
|
|
home := os.Getenv("HOME")
|
|
base = filepath.Join(home, ".config")
|
|
}
|
|
return filepath.Join(base, n)
|
|
}
|
|
|
|
func (c *Config[T]) Get() (bool, error) {
|
|
config_dir := getConfigDir(c.Name)
|
|
|
|
err := os.MkdirAll(config_dir, 0755)
|
|
if err != nil {
|
|
return false, fmt.Errorf("Could not create config directory: %v", err)
|
|
}
|
|
|
|
configFile := filepath.Join(config_dir, c.Filename+".toml")
|
|
c.ConfigFile = &configFile
|
|
|
|
// open file, creating it if empty
|
|
config_file, err := os.OpenFile(*c.ConfigFile, os.O_RDWR|os.O_CREATE, 0755)
|
|
defer config_file.Close()
|
|
|
|
if err != nil {
|
|
return false, fmt.Errorf("Could not open config file: %v", err)
|
|
}
|
|
|
|
fi, err := config_file.Stat()
|
|
if err != nil {
|
|
return false, fmt.Errorf("Could not get config file size: %v", err)
|
|
}
|
|
|
|
if fi.Size() == 0 {
|
|
// if file is empty, write default config
|
|
data, err := toml.Marshal(c.Config)
|
|
if err != nil {
|
|
return false, fmt.Errorf("Could not write default config to file: %v", err)
|
|
}
|
|
config_file.Write(data)
|
|
// return nil as the user must edit the config file
|
|
return true, nil
|
|
} else {
|
|
// try to parse config file
|
|
data, err := ioutil.ReadAll(config_file)
|
|
if err != nil {
|
|
return false, fmt.Errorf("Could not read data from config file: %v", err)
|
|
}
|
|
err = toml.Unmarshal(data, &c.Config)
|
|
if err != nil {
|
|
return false, fmt.Errorf("Could not parse config file contents: %v", err)
|
|
}
|
|
return false, nil
|
|
}
|
|
|
|
}
|