You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.6 KiB
Go

// Package config provides an interface to load and store config files
// using the XDG standard ($HOME/.config/FRMS) as the base directory
//
// WARNING: only built for Linux
package config
import (
"FRMS/internal/pkg/logging"
"errors"
"fmt"
"os"
"github.com/spf13/viper"
)
// LoadConfig takes a filename as an aruguement and returns a *viper.Viper object.
// Loads and stores config files into the base directory according to XDG standard ($HOME/.config/FRMS/).
// Will create directory and config if they don't exist.
func LoadConfig(filename string) (*viper.Viper, error) {
config := viper.New()
// default config dir
path := fmt.Sprintf("%s/.config/FRMS", os.Getenv("HOME"))
filetype := "yaml"
// checking for existence
if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
if err := os.Mkdir(path, os.ModePerm); err != nil {
return config, err
}
}
logging.Debug(logging.DStart, "Loading config (%s)", filename)
// setting config file info
config.SetConfigName(filename)
config.SetConfigType(filetype)
config.AddConfigPath(path)
config.AutomaticEnv()
// reading in config
if err := config.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
fullpath := fmt.Sprintf("%s/%s.%s", path, filename, filetype)
logging.Debug(logging.DStart, "CON config does not exist!")
if err = config.WriteConfigAs(fullpath); err != nil {
return config, err
}
logging.Debug(logging.DStart, "CON created at %s", fullpath)
} else {
return config, err
}
}
logging.Debug(logging.DStart, "CON Loaded configs from %v", config.ConfigFileUsed())
return config, nil
}