PKGBUILD/pkg/config/config.go

57 lines
1.1 KiB
Go

package config
import (
"fmt"
"os"
"path/filepath"
"regexp"
)
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) {
fc := &FluckyConfig{}
f, err := os.Open(configFile)
if err != nil {
return nil, fmt.Errorf("Can not open file %v: %v", configFile, err)
}
defer f.Close()
err = fc.JSONDecoder(f)
if err != nil {
return nil, fmt.Errorf("Can not decode json file %v: %v", configFile, err)
}
return fc, nil
}
// Write the configuration into a file, specified by the configuration filepath
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)
}
}
f, err := os.Create(configFile)
if err != nil {
return fmt.Errorf("Can not write config file: %v", err)
}
defer f.Close()
err = cfg.JSONWriter(f)
if err != nil {
return err
}
return nil
}