fix: set config, set remote
This commit is contained in:
99
pkg/config/config.go
Normal file
99
pkg/config/config.go
Normal 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
|
||||
}
|
Reference in New Issue
Block a user