Refactor config to return an error instead of aborting

This commit is contained in:
Eric Meyer
2017-11-09 12:41:02 -06:00
parent 61cf7af2ec
commit aa52088ba7
8 changed files with 60 additions and 24 deletions
+23 -13
View File
@@ -11,6 +11,8 @@ import (
"path"
"runtime"
"errors"
"github.com/BurntSushi/toml"
)
@@ -19,14 +21,22 @@ type Config struct {
Client Client
}
func NewConfig(environment string) Config {
var NewErrConfigFileNotFound = func(environment string) error {
return errors.New(fmt.Sprintf("No configuration found for environment: %v", environment))
}
func NewConfig(environment string) (*Config, error) {
filenameWithExtension := fmt.Sprintf("%s.toml", environment)
absolutePath := filepath.Join(ProjectRoot(), "pkg", "config", "environments", filenameWithExtension)
config := parseConfigFile(absolutePath)
if !filepath.IsAbs(config.Client.IPCPath) {
config.Client.IPCPath = filepath.Join(ProjectRoot(), config.Client.IPCPath)
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
}
return config
}
func ProjectRoot() string {
@@ -34,15 +44,15 @@ func ProjectRoot() string {
return path.Join(path.Dir(filename), "..", "..")
}
func parseConfigFile(configfile string) Config {
func parseConfigFile(filePath string) (*Config, error) {
var cfg Config
_, err := os.Stat(configfile)
_, err := os.Stat(filePath)
if err != nil {
log.Fatal("Config file is missing: ", configfile)
return nil, err
} else {
if _, err := toml.DecodeFile(filePath, &cfg); err != nil {
log.Fatal(err)
}
return &cfg, err
}
if _, err := toml.DecodeFile(configfile, &cfg); err != nil {
log.Fatal(err)
}
return cfg
}
+9 -1
View File
@@ -11,8 +11,9 @@ import (
var _ = Describe("Loading the config", func() {
It("reads the private config using the environment", func() {
privateConfig := config.NewConfig("private")
privateConfig, err := config.NewConfig("private")
Expect(err).To(BeNil())
Expect(privateConfig.Database.Hostname).To(Equal("localhost"))
Expect(privateConfig.Database.Name).To(Equal("vulcanize_private"))
Expect(privateConfig.Database.Port).To(Equal(5432))
@@ -20,4 +21,11 @@ var _ = Describe("Loading the config", func() {
Expect(privateConfig.Client.IPCPath).To(Equal(expandedPath))
})
It("returns an error when there is no matching config file", func() {
config, err := config.NewConfig("bad-config")
Expect(config).To(BeNil())
Expect(err).NotTo(BeNil())
})
})