backive/config/config.go

82 lines
1.9 KiB
Go
Raw Normal View History

2021-10-04 21:56:44 +02:00
package config
2021-10-12 23:00:24 +02:00
import (
"fmt"
2021-10-12 23:00:24 +02:00
"github.com/qwc/backive/core"
2021-10-04 21:56:44 +02:00
2021-10-12 23:00:24 +02:00
"github.com/spf13/viper"
)
2021-10-04 21:56:44 +02:00
2021-10-18 22:36:54 +02:00
var (
config *Configuration
vconfig *viper.Viper
)
2021-10-27 23:17:18 +02:00
// Configuration struct holding the settings and config items of devices and backups
2021-10-12 23:00:24 +02:00
type Configuration struct {
Settings Settings `mapstructure:"settings"`
Devices Devices `mapstructure:"devices"`
Backups Backups `mapstructure:"backups"`
2021-10-04 21:56:44 +02:00
}
2021-10-27 23:17:18 +02:00
// Settings struct holds the global configuration items
2021-10-04 21:56:44 +02:00
type Settings struct {
2021-10-12 23:00:24 +02:00
SystemMountPoint string `mapstructure:"systemMountPoint"`
UserMountPoint string `mapstructure:"userMountPoint"`
2021-10-04 21:56:44 +02:00
}
2021-10-27 23:17:18 +02:00
// Devices is nothing else than a name to Device type mapping
2021-10-12 23:00:24 +02:00
type Devices map[string]core.Device
2021-10-04 22:14:16 +02:00
2021-10-27 23:17:18 +02:00
// Backups is nothing else than a name to Backup type mapping
2021-10-12 23:00:24 +02:00
type Backups map[string]core.Backup
2021-10-04 22:14:16 +02:00
2021-10-27 23:17:18 +02:00
// CreateViper creates a viper instance for usage later
2021-10-12 23:00:24 +02:00
func CreateViper() *viper.Viper {
vconfig := viper.New()
vconfig.SetConfigName("backive")
vconfig.SetConfigType("yaml")
vconfig.AddConfigPath("/etc/backive/") // system config
vconfig.AddConfigPath("$HOME/.backive/")
vconfig.AddConfigPath(".")
return vconfig
}
2021-10-04 21:56:44 +02:00
2021-10-27 23:17:18 +02:00
// Load loads the configuration from the disk
2021-10-12 23:00:24 +02:00
func Load() *Configuration {
vconfig := CreateViper()
if err := vconfig.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
panic(fmt.Errorf("Fatal: No config file could be found!"))
}
panic(fmt.Errorf("Fatal error config file: %w \n", err))
}
var cfg *Configuration
2021-10-18 22:36:54 +02:00
//Unmarshal all into Configuration type
err := vconfig.Unmarshal(cfg)
if err != nil {
fmt.Printf("Error occured when loading config: %v\n", err)
panic("No configuration available!")
}
2021-10-18 22:36:54 +02:00
for k, v := range cfg.Backups {
v.Name = k
}
for k, v := range cfg.Devices {
v.Name = k
}
return cfg
2021-10-04 21:56:44 +02:00
}
2021-10-18 22:36:54 +02:00
2021-10-27 23:17:18 +02:00
// Init Initializes the configuration
2021-10-18 22:36:54 +02:00
func Init() {
config = Load()
}
2021-10-27 23:17:18 +02:00
// Get returns the Configuration global variable
2021-10-18 22:36:54 +02:00
func Get() *Configuration {
return config
}