-
Notifications
You must be signed in to change notification settings - Fork 0
/
history.go
131 lines (106 loc) · 2.12 KB
/
history.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package main
import (
"bytes"
"text/template"
"time"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
)
type HistoryHandler interface {
Record(name, body string)
Parse(input string) string
}
var historyHandler HistoryHandler = &History{}
type History struct {
Records map[string]*Record
}
func NewHistory() *History {
return &History{
Records: make(map[string]*Record),
}
}
func (h *History) Record(name, result string) {
h.Records[name] = &Record{
Body: result,
}
}
func (h *History) Parse(input string) string {
tmpl, err := template.
New("History parser").
Funcs(template.FuncMap{
"fromJson": func(name, path string) string {
r := h.From(name)
if r != nil {
return r.Json(path)
}
MissingTemplateEntryError.Inc()
logrus.
WithField("function", "fromJson").
WithField("entry", name).
WithField("path", path).
Error("Missing json template")
return ""
},
"uuid": func() uuid.UUID {
return uuid.New()
},
"now": func() time.Time {
return time.Now()
},
"add": func(values ...int) int {
add := 0
for _, v := range values {
add += v
}
return add
},
"sub": func(values ...int) int {
if len(values) <= 0 {
return 0
}
sub := values[0]
for i := 1; i < len(values); i++ {
sub -= values[i]
}
return sub
},
"mul": func(values ...int) int {
if len(values) <= 0 {
return 0
}
mul := values[0]
for i := 1; i < len(values); i++ {
mul *= values[i]
}
return mul
},
}).
Parse(input)
if err != nil {
ParseTemplateError.Inc()
logrus.
WithError(err).
Error("Error parsing templated input")
return input
}
buf := bytes.NewBufferString("")
err = tmpl.Execute(buf, nil)
if err != nil {
ExecuteTemplateError.Inc()
logrus.
WithError(err).
Error("Error executing template")
return input
}
return buf.String()
}
func (h *History) From(name string) *Record {
return h.Records[name]
}
type Record struct {
Body string
}
func (r *Record) Json(path string) string {
return gjson.Get(r.Body, path).String()
}