Skip to content

Commit

Permalink
Add better error handling for config loading process
Browse files Browse the repository at this point in the history
  • Loading branch information
cmuench committed Aug 29, 2020
1 parent 8f9a548 commit 3a33628
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 8 deletions.
8 changes: 7 additions & 1 deletion inotify-proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/cmuench/inotify-proxy/internal/util"
"github.com/cmuench/inotify-proxy/internal/watcher"
"github.com/gookit/color"
"os"
"strings"
)

Expand Down Expand Up @@ -41,7 +42,12 @@ func main() {
func loadConfig(c config.Config, includedDirectories []string, profilePtr *string) []string {
if util.FileExists("inotify-proxy.yaml") {
color.Info.Println("load config")
c = config.ReadFile("inotify-proxy.yaml")
c, err := config.ReadFile("inotify-proxy.yaml");

if err != nil {
color.Errorf("error: Invalid config provided.\n")
os.Exit(1)
}

for _, watch := range c.Watch {
includedDirectories = append(includedDirectories, watch.Dir)
Expand Down
24 changes: 17 additions & 7 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,30 @@ type Config struct {
Profile string `yaml:"profile"`
}

func ReadFile(filename string) Config {
yamlData, err := ioutil.ReadFile(filename)
func ReadFile(filename string) (Config, error) {
var (
c Config
err error
yamlData []byte
)
yamlData, err = ioutil.ReadFile(filename)

if err != nil {
panic(err)
return c, err
}

c, err = Parse(yamlData)

return c, err
}

func Parse(yamlData []byte) (Config, error) {
var c Config
err = yaml.Unmarshal(yamlData, &c)
err := yaml.Unmarshal(yamlData, &c)

if err != nil {
panic(err)
return c, err
}

return c
return c, nil
}

33 changes: 33 additions & 0 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package config

import (
"github.com/stretchr/testify/assert"
"testing"
)

func TestParseValidYaml(t *testing.T) {

validYamlData := `
---
watch:
- dir: /tmp/watch1
- dir: /tmp/watch2
profile: magento2
`
c, err := Parse([]byte(validYamlData))

assert.NoError(t, err, "Config is valid and should not throw an error")
assert.IsType(t, Config{}, c)
}

func TestParseInvalidYaml(t *testing.T) {
invalidYamlData := `
---
watch
`
_, err := Parse([]byte(invalidYamlData))

assert.Error(t, err, "Config is invalid and should throw an error")
}

0 comments on commit 3a33628

Please sign in to comment.