Skip to content

Commit

Permalink
Merge pull request #60 from hidevopsio/yaml
Browse files Browse the repository at this point in the history
added func ReadYamlFromFile
  • Loading branch information
john-deng authored Dec 4, 2018
2 parents f8a7c03 + 4afa16c commit fe2f4f6
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 1 deletion.
4 changes: 3 additions & 1 deletion pkg/system/config/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,6 @@ logging:

# added for test only
fake:
name: ${app.name}
name: ${app.name}

foo: foo name
8 changes: 8 additions & 0 deletions pkg/system/config/test-file.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
foo: foo name
bar: bar name
---

# test

* test
31 changes: 31 additions & 0 deletions pkg/system/yaml.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package system

import (
"bytes"
"github.com/spf13/afero"
"gopkg.in/yaml.v2"
"strings"
)

// ReadYamlFromFile read yaml from file directly
func ReadYamlFromFile(file string) (prop map[string]interface{}, err error) {
fs := afero.NewOsFs()
var fb []byte
fb, err = afero.ReadFile(fs, file)
if err == nil {
buf := new(bytes.Buffer)
r := bytes.NewReader(fb)
buf.ReadFrom(r)
str := string(buf.Bytes())
s := strings.Split(str, "---")
var src []byte
if len(s) == 1 {
src = buf.Bytes()
} else {
src = []byte(s[1])
}

err = yaml.Unmarshal(src, &prop)
}
return
}
19 changes: 19 additions & 0 deletions pkg/system/yaml_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package system

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

func TestReadYamlProperties(t *testing.T) {

res, err := ReadYamlFromFile("config/test-file.yml")

assert.Equal(t, nil, err)
assert.Equal(t, "foo name", res["foo"])

res, err = ReadYamlFromFile("config/application.yml")

assert.Equal(t, nil, err)
assert.Equal(t, "foo name", res["foo"])
}

0 comments on commit fe2f4f6

Please sign in to comment.