PKGBUILD/pkg/config/config.go

57 lines
1.1 KiB
Go
Raw Normal View History

2018-11-19 21:36:21 +00:00
package config
import (
"fmt"
"os"
"path/filepath"
2019-02-17 17:23:59 +00:00
"regexp"
2018-11-19 21:36:21 +00:00
)
2019-02-17 17:23:59 +00:00
var validUUID = regexp.MustCompile("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
// Read the configuration file
func Read(configFile string) (*FluckyConfig, error) {
2018-11-19 21:36:21 +00:00
2019-02-17 17:23:59 +00:00
fc := &FluckyConfig{}
2018-11-19 21:36:21 +00:00
2019-02-17 17:23:59 +00:00
f, err := os.Open(configFile)
2018-11-19 21:36:21 +00:00
if err != nil {
2019-02-17 17:23:59 +00:00
return nil, fmt.Errorf("Can not open file %v: %v", configFile, err)
2018-11-19 21:36:21 +00:00
}
defer f.Close()
2019-02-17 17:23:59 +00:00
err = fc.JSONDecoder(f)
if err != nil {
2019-02-17 17:23:59 +00:00
return nil, fmt.Errorf("Can not decode json file %v: %v", configFile, err)
}
2019-02-17 17:23:59 +00:00
return fc, nil
}
2019-02-17 17:23:59 +00:00
// Write the configuration into a file, specified by the configuration filepath
2019-02-22 12:08:58 +00:00
func Write(cfg *FluckyConfig, configFile string) error {
if _, err := os.Stat(configFile); os.IsNotExist(err) {
configDir := filepath.Dir(configFile)
err := os.MkdirAll(configDir, os.ModeDir)
if err != nil {
return fmt.Errorf("Can not create config directory %v: %v", configDir, err)
}
}
2019-02-17 17:23:59 +00:00
f, err := os.Create(configFile)
if err != nil {
return fmt.Errorf("Can not write config file: %v", err)
}
2019-02-17 17:23:59 +00:00
defer f.Close()
2019-02-17 17:23:59 +00:00
err = cfg.JSONWriter(f)
2018-11-19 21:36:21 +00:00
if err != nil {
return err
}
return nil
2019-02-17 17:23:59 +00:00
2018-11-19 21:36:21 +00:00
}