-
Notifications
You must be signed in to change notification settings - Fork 2
/
yaml.go
57 lines (45 loc) · 1.34 KB
/
yaml.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package parsers
import (
"bytes"
"github.com/ghodss/yaml"
"github.com/pkg/errors"
)
// ParseYAML unmarshals YAML files and return parsed file content.
func ParseYAML(p []byte, v interface{}) error {
subDocuments := separateSubDocuments(p)
if len(subDocuments) > 1 {
if err := unmarshalMultipleDocuments(subDocuments, v); err != nil {
return errors.Wrap(err, "unmarshal multiple documents")
}
return nil
}
if err := yaml.Unmarshal(p, v); err != nil {
return errors.Wrap(err, "unmarshal yaml")
}
return nil
}
func separateSubDocuments(data []byte) [][]byte {
linebreak := "\n"
if bytes.Contains(data, []byte("\r\n---\r\n")) {
linebreak = "\r\n"
}
return bytes.Split(data, []byte(linebreak+"---"+linebreak))
}
func unmarshalMultipleDocuments(subDocuments [][]byte, v interface{}) error {
var documentStore []interface{}
for _, subDocument := range subDocuments {
var documentObject interface{}
if err := yaml.Unmarshal(subDocument, &documentObject); err != nil {
return errors.Wrap(err, "unmarshal subdocument yaml")
}
documentStore = append(documentStore, documentObject)
}
yamlConfigBytes, err := yaml.Marshal(documentStore)
if err != nil {
return errors.Wrap(err, "marshal yaml document")
}
if err := yaml.Unmarshal(yamlConfigBytes, v); err != nil {
return errors.Wrap(err, "unmarshal yaml")
}
return nil
}