-
Notifications
You must be signed in to change notification settings - Fork 0
/
yt.go
83 lines (72 loc) · 1.54 KB
/
yt.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package yt
import (
"io"
"regexp"
"strings"
"text/template"
"gopkg.in/yaml.v2"
ghodss "github.com/ghodss/yaml"
)
const inheritsRERaw = "^#&inherits (.*)"
var inheritsRE *regexp.Regexp
func init() {
inheritsRE = regexp.MustCompile(inheritsRERaw)
}
//Compile compiles yt documents
func Compile(input []byte, visited map[string]bool) (interface{}, error) {
var (
err error
v interface{}
)
parents := getParents(input)
if len(parents) == 0 {
err = yaml.Unmarshal(input, &v)
} else {
v = map[interface{}]interface{}{}
for _, parent := range parents {
p, queryErr := Query(nil, parent, visited)
if queryErr != nil {
return nil, queryErr
}
v, err = OrthogonalMerge(v, p)
if err != nil {
return nil, err
}
}
var i interface{}
err = yaml.Unmarshal(input, &i)
v = Merge(v, i)
}
return v, err
}
func WriteYAML(v interface{}, output io.Writer) error {
err := yaml.NewEncoder(output).Encode(v)
return err
}
func WriteJSON(v interface{}, output io.Writer) error {
rawYAML, err := yaml.Marshal(v)
if err != nil {
return err
}
rawJSON, err := ghodss.YAMLToJSON(rawYAML)
if err != nil {
return err
}
_, err = output.Write(rawJSON)
return err
}
func WriteTemplate(v interface{}, tpl *template.Template,
output io.Writer) error {
err := tpl.Execute(output, v)
return err
}
func getParents(doc []byte) []string {
var parents []string
for _, s := range strings.Split(string(doc), "\n") {
m := inheritsRE.FindStringSubmatch(s)
if len(m) >= 2 {
parents = append(parents, m[1])
}
}
return parents
}