PKGBUILD/pkg/config/config.go
Markus Pesch 6d9368e86c
fix: temperature, sensor
changes:
- sensor temperature add
- sensor temperature list
- sensor temperature rm
- temperature get
- temperature log
- temperature push
2018-11-21 19:30:14 +01:00

99 lines
2.1 KiB
Go

package config
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/satori/go.uuid"
"git.cryptic.systems/fh-trier/go-flucky/pkg/types"
)
var configFilename = "config.json"
func Create(configDir string, force bool) error {
configPath := filepath.Join(configDir, configFilename)
config := &types.Config{
DeviceID: uuid.NewV4().String(),
}
// If no config file exists, create a new one on the location
if !force {
if _, err := os.Stat(configPath); !os.IsNotExist(err) {
return fmt.Errorf("%v already exists. Use -f to overwrite", configPath)
}
}
if _, err := os.Stat(configPath); os.IsNotExist(err) {
err := os.MkdirAll(configDir, os.ModePerm)
if err != nil {
return fmt.Errorf("Can not create directory: %v", err)
}
}
f, err := os.Create(configPath)
if err != nil {
return fmt.Errorf("Can not create config: %v", err)
}
defer f.Close()
config.JSONWriter(f)
return nil
}
func Read(configDir string) (*types.Config, error) {
configPath := filepath.Join(configDir, configFilename)
var config types.Config
// If no config file exists, return an error
if _, err := os.Stat(configPath); os.IsNotExist(err) {
return nil, fmt.Errorf("Can not find config %v: %v", configPath, err)
}
// open config file
jsonFile, err := os.Open(configPath)
if err != nil {
return nil, fmt.Errorf("Can not open file %v: %v", configPath, err)
}
defer jsonFile.Close()
jsonParser := json.NewDecoder(jsonFile)
if err := jsonParser.Decode(&config); err != nil {
return nil, err
}
return &config, nil
}
func Write(config *types.Config, configDir string) error {
configPath := filepath.Join(configDir, configFilename)
// If no config file exists, return an error
if _, err := os.Stat(configPath); os.IsNotExist(err) {
return fmt.Errorf("Can not find config %v: %v", configPath, err)
}
// open config file
jsonFile, err := os.Create(configPath)
if err != nil {
return fmt.Errorf("Can not open file %v: %v", configPath, err)
}
defer jsonFile.Close()
err = config.JSONWriter(jsonFile)
if err != nil {
return err
}
return nil
}