2017-11-01 15:17:01 +00:00
|
|
|
package config
|
|
|
|
|
2017-11-02 22:37:27 +00:00
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"path/filepath"
|
|
|
|
|
|
|
|
"path"
|
|
|
|
"runtime"
|
|
|
|
|
2017-11-09 14:00:02 +00:00
|
|
|
"errors"
|
|
|
|
|
2017-11-02 22:37:27 +00:00
|
|
|
"github.com/BurntSushi/toml"
|
|
|
|
)
|
|
|
|
|
2017-11-01 15:17:01 +00:00
|
|
|
type Config struct {
|
|
|
|
Database Database
|
2017-11-02 22:37:27 +00:00
|
|
|
Client Client
|
|
|
|
}
|
|
|
|
|
2017-11-09 14:00:02 +00:00
|
|
|
var NewErrConfigFileNotFound = func(environment string) error {
|
|
|
|
return errors.New(fmt.Sprintf("No configuration found for environment: %v", environment))
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewConfig(environment string) (*Config, error) {
|
2017-11-02 22:37:27 +00:00
|
|
|
filenameWithExtension := fmt.Sprintf("%s.toml", environment)
|
2017-11-14 15:10:48 +00:00
|
|
|
absolutePath := filepath.Join(ProjectRoot(), "environments", filenameWithExtension)
|
2017-11-09 14:00:02 +00:00
|
|
|
config, err := parseConfigFile(absolutePath)
|
|
|
|
if err != nil {
|
|
|
|
return nil, NewErrConfigFileNotFound(environment)
|
|
|
|
} else {
|
|
|
|
if !filepath.IsAbs(config.Client.IPCPath) {
|
|
|
|
config.Client.IPCPath = filepath.Join(ProjectRoot(), config.Client.IPCPath)
|
|
|
|
}
|
|
|
|
return config, nil
|
2017-11-07 15:39:44 +00:00
|
|
|
}
|
2017-11-02 22:37:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func ProjectRoot() string {
|
|
|
|
var _, filename, _, _ = runtime.Caller(0)
|
2017-11-06 18:53:43 +00:00
|
|
|
return path.Join(path.Dir(filename), "..", "..")
|
2017-11-02 22:37:27 +00:00
|
|
|
}
|
|
|
|
|
2017-11-09 14:00:02 +00:00
|
|
|
func parseConfigFile(filePath string) (*Config, error) {
|
2017-11-02 22:37:27 +00:00
|
|
|
var cfg Config
|
2017-11-09 14:00:02 +00:00
|
|
|
_, err := os.Stat(filePath)
|
2017-11-02 22:37:27 +00:00
|
|
|
if err != nil {
|
2017-11-09 14:00:02 +00:00
|
|
|
return nil, err
|
|
|
|
} else {
|
|
|
|
if _, err := toml.DecodeFile(filePath, &cfg); err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
return &cfg, err
|
2017-11-02 22:37:27 +00:00
|
|
|
}
|
2017-11-01 15:17:01 +00:00
|
|
|
}
|