fix: add, rename and remove sensor
changes: - Implement function to add, rename and remove sensors
This commit is contained in:
@ -1,6 +1,7 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@ -9,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/volker-raschek/flucky/pkg/internal/format"
|
||||
"github.com/volker-raschek/flucky/pkg/storage"
|
||||
|
||||
uuid "github.com/satori/go.uuid"
|
||||
"github.com/volker-raschek/flucky/pkg/types"
|
||||
@ -154,21 +156,56 @@ func (cnf *Config) GetSensorByID(id string) *types.Sensor {
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoveSensor deletes a sensor by its name or its unique UUID
|
||||
func (cnf *Config) RemoveSensor(name string) error {
|
||||
// RemoveSensor deletes a sensor by its name or its unique UUID, If definitive
|
||||
// is set to true, the sensor will not only be removed in the configuration file
|
||||
// but also in the backend.
|
||||
func (cnf *Config) RemoveSensor(name string, definitive bool) error {
|
||||
|
||||
backend, err := storage.New(cnf.StorageEndpoint, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for i, sensor := range cnf.Sensors {
|
||||
// remove machted name
|
||||
if !validUUID.MatchString(name) &&
|
||||
sensor.Name == name {
|
||||
cnf.Sensors = append(cnf.Sensors[:i], cnf.Sensors[i+1:]...)
|
||||
|
||||
if definitive {
|
||||
err = backend.RemoveSensorByName(context.Background(), name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
// remove machted uuid
|
||||
if validUUID.MatchString(name) &&
|
||||
sensor.ID == name {
|
||||
cnf.Sensors = append(cnf.Sensors[:i], cnf.Sensors[i+1:]...)
|
||||
|
||||
if definitive {
|
||||
err = backend.RemoveSensorByID(context.Background(), name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("Can not find sensor %v", name)
|
||||
}
|
||||
|
||||
// RenameSensor renamed a sensor
|
||||
func (cnf *Config) RenameSensor(oldName string, newName string) error {
|
||||
for _, cnfSensor := range cnf.Sensors {
|
||||
if cnfSensor.Name == oldName {
|
||||
cnfSensor.Name = newName
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("No sensor %v found", oldName)
|
||||
}
|
||||
|
@ -45,7 +45,7 @@ func Read(configFile string) (*Config, error) {
|
||||
func Write(cnf *Config, configFile string) error {
|
||||
if _, err := os.Stat(configFile); os.IsNotExist(err) {
|
||||
configDir := filepath.Dir(configFile)
|
||||
err := os.MkdirAll(configDir, os.ModeDir)
|
||||
err := os.MkdirAll(configDir, 0775)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to create config directory %v: %v", configDir, err)
|
||||
}
|
||||
|
Reference in New Issue
Block a user