-
Notifications
You must be signed in to change notification settings - Fork 263
/
Copy pathtemplate.go
259 lines (222 loc) · 5.77 KB
/
template.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
/*
Copyright 2017 WALLIX
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package template
import (
"crypto/rand"
"fmt"
"strings"
"time"
"github.com/fatih/color"
"github.com/oklog/ulid"
"github.com/wallix/awless/template/env"
"github.com/wallix/awless/template/internal/ast"
)
type Template struct {
ID string
*ast.AST
}
func (s *Template) DryRun(renv env.Running) (tpl *Template, err error) {
renv.SetDryRun(true)
defer renv.SetDryRun(false)
tpl, err = s.Run(renv)
if err != nil {
return
}
errs := &Errors{}
for _, cmd := range tpl.CommandNodesIterator() {
if cmderr := cmd.Err(); cmderr != nil {
errs.add(cmderr)
}
}
if _, any := errs.Errors(); any {
err = errs
}
return
}
func (s *Template) Run(renv env.Running) (*Template, error) {
vars := map[string]interface{}{}
current := &Template{AST: &ast.AST{}}
current.ID = ulid.MustNew(ulid.Timestamp(time.Now()), rand.Reader).String()
for _, sts := range s.Statements {
clone := sts.Clone()
current.Statements = append(current.Statements, clone)
switch n := clone.Node.(type) {
case *ast.CommandNode:
n.ProcessRefs(vars)
if stop := processCmdNode(renv, n); stop {
return current, nil
}
case *ast.DeclarationNode:
ident := n.Ident
expr := n.Expr
switch n := expr.(type) {
case *ast.CommandNode:
n.ProcessRefs(vars)
if stop := processCmdNode(renv, n); stop {
return current, nil
}
vars[ident] = n.Result()
default:
return current, fmt.Errorf("unknown type of node: %T", expr)
}
default:
return current, fmt.Errorf("unknown type of node: %T", clone.Node)
}
}
return current, nil
}
func processCmdNode(renv env.Running, n *ast.CommandNode) bool {
if renv.IsDryRun() {
n.CmdResult, n.CmdErr = n.Command.Run(renv, n.ToDriverParams())
n.CmdErr = prefixError(n.CmdErr, fmt.Sprintf("dry run: %s %s", n.Action, n.Entity))
} else {
n.CmdResult, n.CmdErr = n.Run(renv, n.ToDriverParams())
var res, status string
if n.CmdResult != nil {
res = " (" + color.New(color.FgCyan).Sprint(n.CmdResult) + ") "
}
if n.CmdErr != nil {
status = color.New(color.FgRed).Sprint("KO")
} else {
status = color.New(color.FgGreen).Sprint("OK")
}
renv.Log().Infof("%s %s %s%s", status, n.Action, n.Entity, res)
if n.CmdErr != nil {
renv.Log().MultiLineError(n.CmdErr)
}
}
return n.CmdErr != nil
}
func prefixError(err error, prefix string) error {
if err == nil {
return err
}
return fmt.Errorf("%s: %s", prefix, err.Error())
}
func (s *Template) Validate(rules ...Validator) (all []error) {
for _, rule := range rules {
errs := rule.Execute(s)
all = append(all, errs...)
}
return
}
func (t *Template) HasErrors() bool {
for _, cmd := range t.CommandNodesIterator() {
if cmd.CmdErr != nil {
return true
}
}
return false
}
func (t *Template) UniqueDefinitions(apis map[string]string) (res []string) {
unique := make(map[string]struct{})
for _, cmd := range t.CommandNodesIterator() {
key := fmt.Sprintf("%s%s", cmd.Action, cmd.Entity)
if api, found := apis[key]; found {
unique[api] = struct{}{}
}
}
for api := range unique {
res = append(res, api)
}
return
}
func (s *Template) visitCommandNodes(fn func(n *ast.CommandNode)) {
for _, cmd := range s.CommandNodesIterator() {
fn(cmd)
}
}
func (s *Template) visitCommandNodesE(fn func(n *ast.CommandNode) error) error {
for _, cmd := range s.CommandNodesIterator() {
if err := fn(cmd); err != nil {
return err
}
}
return nil
}
func (s *Template) CommandNodesIterator() (nodes []*ast.CommandNode) {
for _, sts := range s.Statements {
switch nn := sts.Node.(type) {
case *ast.CommandNode:
nodes = append(nodes, nn)
case *ast.DeclarationNode:
expr := sts.Node.(*ast.DeclarationNode).Expr
switch expr.(type) {
case *ast.CommandNode:
nodes = append(nodes, expr.(*ast.CommandNode))
}
}
}
return
}
func (s *Template) CommandNodesReverseIterator() (nodes []*ast.CommandNode) {
for i := len(s.Statements) - 1; i >= 0; i-- {
sts := s.Statements[i]
switch sts.Node.(type) {
case *ast.CommandNode:
nodes = append(nodes, sts.Node.(*ast.CommandNode))
case *ast.DeclarationNode:
expr := sts.Node.(*ast.DeclarationNode).Expr
switch expr.(type) {
case *ast.CommandNode:
nodes = append(nodes, expr.(*ast.CommandNode))
}
}
}
return
}
func (s *Template) declarationNodesIterator() (nodes []*ast.DeclarationNode) {
for _, sts := range s.Statements {
switch n := sts.Node.(type) {
case *ast.DeclarationNode:
nodes = append(nodes, n)
}
}
return
}
func (s *Template) expressionNodesIterator() (nodes []ast.ExpressionNode) {
for _, st := range s.Statements {
if expr := extractExpressionNode(st); expr != nil {
nodes = append(nodes, expr)
}
}
return
}
func extractExpressionNode(st *ast.Statement) ast.ExpressionNode {
switch n := st.Node.(type) {
case *ast.DeclarationNode:
return n.Expr
case ast.ExpressionNode:
return n
}
return nil
}
type Errors struct {
errs []error
}
func (d *Errors) Errors() ([]error, bool) {
return d.errs, len(d.errs) > 0
}
func (d *Errors) add(err error) {
d.errs = append(d.errs, err)
}
func (d *Errors) Error() string {
var all []string
for _, err := range d.errs {
all = append(all, err.Error())
}
return strings.Join(all, "\n")
}
func MatchStringParamValue(s string) bool {
return ast.SimpleStringValue.MatchString(s)
}