campaigner/config/config.go

60 lines
1.2 KiB
Go
Raw Normal View History

2020-02-29 00:23:26 +01:00
package config
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"os/user"
2020-02-29 00:49:55 +01:00
"git.ctrlz.es/mgdelacroix/campaigner/model"
)
2020-02-29 00:23:26 +01:00
func getConfigPath() (string, error) {
user, err := user.Current()
if err != nil {
return "", err
}
return user.HomeDir + "/.campaigner", nil
}
2020-02-29 00:49:55 +01:00
func ReadConfig() (*model.Config, error) {
2020-02-29 00:23:26 +01:00
configPath, err := getConfigPath()
if err != nil {
return nil, err
}
if _, err := os.Stat(configPath); err != nil {
2020-02-29 00:49:55 +01:00
return &model.Config{}, nil
2020-02-29 00:23:26 +01:00
}
fileContents, err := ioutil.ReadFile(configPath)
if err != nil {
return nil, fmt.Errorf("there was a problem reading the config file: %w", err)
}
2020-02-29 00:49:55 +01:00
var config model.Config
2020-02-29 00:23:26 +01:00
if err := json.Unmarshal(fileContents, &config); err != nil {
return nil, fmt.Errorf("there was a problem parsing the config file: %w", err)
}
return &config, nil
}
2020-02-29 00:49:55 +01:00
func SaveConfig(config *model.Config) error {
2020-02-29 00:23:26 +01:00
configPath, err := getConfigPath()
if err != nil {
return err
}
marshaledConfig, err := json.MarshalIndent(config, "", " ")
if err != nil {
return err
}
if err := ioutil.WriteFile(configPath, marshaledConfig, 0600); err != nil {
return fmt.Errorf("cannot save the config: %w", err)
}
return nil
}