2018-11-19 21:36:21 +00:00
|
|
|
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
|
|
|
|
|
2018-11-20 21:55:06 +00:00
|
|
|
// If no config file exists, return an error
|
2018-11-19 21:36:21 +00:00
|
|
|
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)
|
|
|
|
|
2018-11-20 21:55:06 +00:00
|
|
|
// If no config file exists, return an error
|
2018-11-19 21:36:21 +00:00
|
|
|
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
|
|
|
|
}
|