92 lines
2.1 KiB
Go
92 lines
2.1 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)
|
|
if xdg_config_home := os.Getenv("XDG_CONFIG_HOME"); xdg_config_home != "" {
|
|
return filepath.Join(xdg_config_home, n)
|
|
}
|
|
|
|
return filepath.Join(os.Getenv("HOME"), ".config", n)
|
|
}
|
|
|
|
func (c *Config[T]) Get() (bool, error) {
|
|
configDir := getConfigDir(c.Name)
|
|
|
|
err := os.MkdirAll(configDir, 0755)
|
|
if err != nil {
|
|
return false, fmt.Errorf("Could not create config directory: %w", err)
|
|
}
|
|
|
|
configFilepath := filepath.Join(configDir, c.Filename+".toml")
|
|
c.ConfigFile = &configFilepath
|
|
|
|
// open file, creating it if empty
|
|
configFile, err := os.OpenFile(*c.ConfigFile, os.O_RDWR|os.O_CREATE, 0644)
|
|
defer configFile.Close()
|
|
|
|
if err != nil {
|
|
return false, fmt.Errorf("Could not open config file: %w", err)
|
|
}
|
|
|
|
fi, err := configFile.Stat()
|
|
if err != nil {
|
|
return false, fmt.Errorf("Could not get config file size: %w", 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: %w", err)
|
|
}
|
|
configFile.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(configFile)
|
|
if err != nil {
|
|
return false, fmt.Errorf("Could not read data from config file: %w", err)
|
|
}
|
|
err = toml.Unmarshal(data, &c.Config)
|
|
if err != nil {
|
|
return false, fmt.Errorf("Could not parse config file contents: %w", err)
|
|
}
|
|
return false, nil
|
|
}
|
|
|
|
}
|
|
|
|
func (c *Config[T]) Write() error {
|
|
data, err := toml.Marshal(c.Config)
|
|
if err != nil {
|
|
return fmt.Errorf("Could not marshal config: %w", err)
|
|
}
|
|
|
|
configFile, err := os.OpenFile(*c.ConfigFile, os.O_RDWR, 0644)
|
|
defer configFile.Close()
|
|
|
|
_, err = configFile.Write(data)
|
|
if err != nil {
|
|
return fmt.Errorf("Could not write to config file: %w", err)
|
|
}
|
|
return nil
|
|
}
|