fix: set config, set remote

This commit is contained in:
2018-11-19 22:36:21 +01:00
parent 54dd2191d6
commit dd7ea3156e
24 changed files with 1338 additions and 58 deletions

99
pkg/config/config.go Normal file
View File

@ -0,0 +1,99 @@
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, create a new one on the location
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, create a new one on the location
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
}