PKGBUILD/pkg/config/config.go

60 lines
1.3 KiB
Go
Raw Normal View History

2018-11-19 21:36:21 +00:00
package config
import (
"encoding/json"
2018-11-19 21:36:21 +00:00
"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) (*Configuration, error) {
2018-11-19 21:36:21 +00:00
fc := &Configuration{}
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()
jsonDecoder := json.NewDecoder(f)
if err := jsonDecoder.Decode(&fc); err != nil {
return nil, fmt.Errorf("Can not unmarshal JSON: %v", 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
func Write(cfg *Configuration, 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()
encoder := json.NewEncoder(f)
encoder.SetIndent("", " ")
err = encoder.Encode(cfg)
2018-11-19 21:36:21 +00:00
if err != nil {
return fmt.Errorf("Error in encoding struct to json: %v", err)
2018-11-19 21:36:21 +00:00
}
return nil
2019-02-17 17:23:59 +00:00
2018-11-19 21:36:21 +00:00
}