-
Notifications
You must be signed in to change notification settings - Fork 0
/
templater.go
78 lines (66 loc) · 1.98 KB
/
templater.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
package venom
import (
"fmt"
"strings"
"gopkg.in/yaml.v2"
)
// Templater contains templating values on a testsuite
type Templater struct {
Values map[string]string
}
func newTemplater(inputValues map[string]string) *Templater {
// Copy map to be thread safe with parallel > 1
values := make(map[string]string)
for key, value := range inputValues {
values[key] = value
}
return &Templater{Values: values}
}
// Add add data to templater
func (tmpl *Templater) Add(prefix string, values map[string]string) {
if tmpl.Values == nil {
tmpl.Values = make(map[string]string)
}
dot := ""
if prefix != "" {
dot = "."
}
for k, v := range values {
tmpl.Values[prefix+dot+k] = v
}
}
//ApplyOnStep executes the template on a test step
func (tmpl *Templater) ApplyOnStep(step TestStep) (TestStep, error) {
// Using yaml to encode/decode, it generates map[interface{}]interface{} typed data that json does not like
s, err := yaml.Marshal(step)
if err != nil {
return nil, fmt.Errorf("templater> Error while marshaling: %s", err)
}
sb := tmpl.apply(s)
var t TestStep
if err := yaml.Unmarshal([]byte(sb), &t); err != nil {
return nil, fmt.Errorf("templater> Error while unmarshal: %s, content:%s", err, sb)
}
return t, nil
}
//ApplyOnContext executes the template on a context
func (tmpl *Templater) ApplyOnContext(ctx map[string]interface{}) (map[string]interface{}, error) {
// Using yaml to encode/decode, it generates map[interface{}]interface{} typed data that json does not like
s, err := yaml.Marshal(ctx)
if err != nil {
return nil, fmt.Errorf("templater> Error while marshaling: %s", err)
}
sb := tmpl.apply(s)
var t map[string]interface{}
if err := yaml.Unmarshal([]byte(sb), &t); err != nil {
return nil, fmt.Errorf("templater> Error while unmarshal: %s, content:%s", err, sb)
}
return t, nil
}
func (tmpl *Templater) apply(in []byte) []byte {
out := string(in)
for k, v := range tmpl.Values {
out = strings.Replace(out, "{{."+k+"}}", v, -1)
}
return []byte(out)
}