PKGBUILD/pkg/config/config.go

69 lines
1.4 KiB
Go
Raw Normal View History

2018-11-19 21:36:21 +00:00
package config
import (
"fmt"
2019-02-17 17:23:59 +00:00
"io"
2018-11-19 21:36:21 +00:00
"os"
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
"git.cryptic.systems/fh-trier/go-flucky-server/pkg/types"
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}$")
type Config interface {
AddSensor(sensor *types.Sensor) error
AddRemote(remote *Remote) error
DisableRemote(nameOrUUID string) error
DisableSensor(nameOrUUID string) error
EnableRemote(nameOrUUID string) error
EnableSensor(nameOrUUID string) error
GetDevice() *Device
GetRemotes() []*Remote
GetSensors() []*types.Sensor
JSONDecoder(r io.Reader) error
JSONWriter(w io.Writer) error
RemoveSensor(nameOrUUID string) error
RemoveRemote(nameOrUUID string) error
SetDevice(device *Device)
ToJSON() (string, error)
}
2018-11-19 21:36:21 +00:00
2019-02-17 17:23:59 +00:00
// 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
func Write(cfg Config, configFile string) error {
2019-02-17 17:23:59 +00:00
f, err := os.Create(configFile)
if err != nil {
return 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
}