2019-05-17 19:06:13 +05:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
|
|
|
// stdlib
|
2019-05-19 14:41:03 +05:00
|
|
|
"errors"
|
2019-05-17 19:06:13 +05:00
|
|
|
"flag"
|
|
|
|
"io/ioutil"
|
|
|
|
"log"
|
|
|
|
"os/user"
|
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
// other
|
|
|
|
"gopkg.in/yaml.v2"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
configPathRaw string
|
|
|
|
Cfg *Config
|
|
|
|
)
|
|
|
|
|
|
|
|
// Initialize initializes package.
|
|
|
|
func Initialize() {
|
|
|
|
log.Println("Initializing configuration...")
|
|
|
|
|
2019-05-19 14:41:03 +05:00
|
|
|
flag.StringVar(&configPathRaw, "conf", "", "Path to configuration file.")
|
|
|
|
|
|
|
|
Cfg = &Config{}
|
2019-05-17 19:06:13 +05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Load loads configuration into memory and parses it into Config struct.
|
2019-05-19 14:41:03 +05:00
|
|
|
func Load() error {
|
2019-05-17 19:06:13 +05:00
|
|
|
if configPathRaw == "" {
|
2019-05-19 14:41:03 +05:00
|
|
|
return errors.New("No configuration file path defined! See '-h'!")
|
2019-05-17 19:06:13 +05:00
|
|
|
}
|
|
|
|
|
|
|
|
log.Println("Loading configuration from file:", configPathRaw)
|
|
|
|
|
|
|
|
// Replace home directory if "~" was specified.
|
|
|
|
if strings.Contains(configPathRaw, "~") {
|
|
|
|
u, err := user.Current()
|
|
|
|
if err != nil {
|
2019-05-19 14:41:03 +05:00
|
|
|
// Well, I don't know how to test this.
|
|
|
|
return errors.New("Failed to get current user's data: " + err.Error())
|
2019-05-17 19:06:13 +05:00
|
|
|
}
|
|
|
|
|
|
|
|
configPathRaw = strings.Replace(configPathRaw, "~", u.HomeDir, 1)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get absolute path to configuration file.
|
|
|
|
configPath, err := filepath.Abs(configPathRaw)
|
|
|
|
if err != nil {
|
2019-05-19 14:41:03 +05:00
|
|
|
// Can't think of situation when it's testable.
|
|
|
|
return errors.New("Failed to get real configuration file path:" + err.Error())
|
2019-05-17 19:06:13 +05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Read it.
|
|
|
|
configFileData, err := ioutil.ReadFile(configPath)
|
|
|
|
if err != nil {
|
2019-05-19 14:41:03 +05:00
|
|
|
return errors.New("Failed to load configuration file data:" + err.Error())
|
2019-05-17 19:06:13 +05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Parse it.
|
|
|
|
err1 := yaml.Unmarshal(configFileData, Cfg)
|
|
|
|
if err1 != nil {
|
2019-05-19 14:41:03 +05:00
|
|
|
return errors.New("Failed to parse configuration file:" + err1.Error())
|
2019-05-17 19:06:13 +05:00
|
|
|
}
|
|
|
|
|
|
|
|
log.Printf("Configuration file parsed: %+v\n", Cfg)
|
2019-05-19 14:41:03 +05:00
|
|
|
return nil
|
2019-05-17 19:06:13 +05:00
|
|
|
}
|