PKGBUILD/pkg/config/io.go

60 lines
1.3 KiB
Go
Raw Normal View History

package config
import (
"encoding/json"
"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) (*Configuration, error) {
fc := &Configuration{}
f, err := os.Open(configFile)
if err != nil {
return nil, fmt.Errorf("Can not open file %v: %v", configFile, err)
}
defer f.Close()
jsonDecoder := json.NewDecoder(f)
if err := jsonDecoder.Decode(&fc); err != nil {
return nil, fmt.Errorf("Can not unmarshal JSON: %v", err)
}
return fc, nil
}
// 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)
}
}
f, err := os.Create(configFile)
if err != nil {
return fmt.Errorf("Can not write config file: %v", err)
}
defer f.Close()
encoder := json.NewEncoder(f)
encoder.SetIndent("", " ")
err = encoder.Encode(cfg)
if err != nil {
return fmt.Errorf("Error in encoding struct to json: %v", err)
}
return nil
}