-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathconvert.go
More file actions
290 lines (274 loc) · 6.3 KB
/
convert.go
File metadata and controls
290 lines (274 loc) · 6.3 KB
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
package main
import (
"bufio"
"bytes"
"encoding/base64"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strconv"
"strings"
"text/template"
"time"
"go.yaml.in/yaml/v3"
)
func main() {
raw, err := os.ReadFile("/in/compose.yaml")
if err != nil {
fmt.Fprintln(os.Stderr, "failed to read compose file /in/compose.yaml")
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
var model map[string]any
err = yaml.Unmarshal(raw, &model)
if err != nil {
fmt.Fprintln(os.Stderr, "failed to parse compose file /in/compose.yaml")
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
err = Convert(model, "/templates", "/out")
if err != nil {
fmt.Fprintln(os.Stderr, "failed to apply template")
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
}
func Convert(model map[string]any, templateDir string, out string) error {
dir, err := os.ReadDir(templateDir)
if err != nil {
return fmt.Errorf("cannot access templates dir: %w", err)
}
for _, entry := range dir {
if entry.Name() == "_index.tmpl" {
continue
}
f := filepath.Join(templateDir, entry.Name())
newOut := filepath.Join(out, entry.Name())
if entry.IsDir() {
// Create directory lazily - it will be created when files are written
err := os.MkdirAll(newOut, fs.ModePerm)
if err != nil && !os.IsExist(err) {
return err
}
if err := Convert(model, f, newOut); err != nil {
return err
}
// Clean up empty directories
if isEmpty, _ := isDirEmpty(newOut); isEmpty {
os.Remove(newOut)
}
continue
}
err := applyTemplate(model, f, out)
if err != nil {
return err
}
}
index := filepath.Join(templateDir, "_index.tmpl")
if _, err := os.Stat(index); err == nil {
files, err := os.ReadDir(out)
if err != nil {
return err
}
err = applyTemplate(files, index, out)
if err != nil {
return err
}
}
return nil
}
func isDirEmpty(path string) (bool, error) {
entries, err := os.ReadDir(path)
if err != nil {
return false, err
}
return len(entries) == 0, nil
}
func applyTemplate(model any, file string, output string) error {
tmpl, err := template.New(filepath.Base(file)).Funcs(helpers).ParseFiles(file)
if err != nil {
ExitError("cannot parse template "+file, err)
}
buff := bytes.Buffer{}
err = tmpl.Execute(&buff, model)
if err != nil {
ExitError("cannot execute template "+file, err)
}
decoder := yaml.NewDecoder(&buff)
for {
var doc yaml.Node
err := decoder.Decode(&doc)
if err == io.EOF {
break
}
if err != nil {
ExitError("failed to parse generated yaml "+file, err)
}
out := bytes.Buffer{}
encoder := yaml.NewEncoder(&out)
err = encoder.Encode(&doc)
if err != nil {
ExitError("failed to parse generated yaml "+file, err)
}
cleanOut := strings.ReplaceAll(out.String(), "⌦", "{{")
cleanOut = strings.ReplaceAll(cleanOut, "⌫", "}}")
fileOut := fileComment(&doc)
if fileOut != "" {
f := filepath.Join(output, fileOut)
os.WriteFile(f, []byte(cleanOut), 0o700)
fmt.Printf("Kubernetes resource \033[32;1m%s\033[0;m created\n", fileOut)
} else {
fmt.Println(cleanOut)
}
}
return nil
}
func fileComment(node *yaml.Node) string {
if node.HeadComment == "" {
if len(node.Content) > 0 {
return fileComment(node.Content[0])
}
return ""
}
for _, s := range strings.Split(node.HeadComment, "\n") {
s := strings.TrimSpace(s)
if strings.HasPrefix(s, "#! ") {
return s[3:]
}
}
return ""
}
var helpers = map[string]any{
"helmValue": func(s string, args ...any) string {
return fmt.Sprintf("⌦ %s ⌫", fmt.Sprintf(s, args...))
},
"isString": func(v any) bool {
_, ok := v.(string)
return ok
},
"hasAttribute": func(m any, attribute string) bool {
if m == nil {
return false
}
mapValue, ok := m.(map[string]any)
if !ok {
return false
}
_, exists := mapValue[attribute]
return exists
},
"getAttribute": func(m any, attribute string) any {
if m == nil {
return nil
}
mapValue, ok := m.(map[string]any)
if !ok {
return nil
}
return mapValue[attribute]
},
"required": func(attr string, a any) any {
if a != nil {
return a
}
ExitError("missing required attribute in compose model", errors.New(attr))
return nil
},
"seconds": func(s any) float64 {
duration, _ := time.ParseDuration(s.(string))
return duration.Seconds()
},
"uppercase": func(s string) string {
return strings.ToUpper(s)
},
"title": func(s string) string {
return strings.Title(s)
},
"safe": func(s string) string {
return safe(s)
},
"truncate": func(n int, s []any) []any {
return s[n:]
},
"join": func(sep string, s []any) string {
var ss []string
for _, a := range s {
ss = append(ss, a.(string))
}
return strings.Join(ss, sep)
},
"base64": func(s string) string {
return base64.StdEncoding.EncodeToString([]byte(s))
},
"readfile": func(s string) string {
file, err := os.ReadFile(s)
if err != nil {
ExitError("failed to read "+s, err)
}
return string(file)
},
"getenv": func(s string) string {
return os.Getenv(s)
},
"dir": func(s string) string {
return filepath.Dir(s)
},
"indent": func(s string, indent int) string {
indentation := strings.Repeat(" ", indent)
lines := strings.Builder{}
sc := bufio.NewScanner(strings.NewReader(s))
for sc.Scan() {
lines.WriteString(indentation)
lines.WriteString(sc.Text())
lines.WriteString("\n")
}
return lines.String()
},
"map": func(s string, rules ...string) string {
for _, rule := range rules {
before, after, _ := strings.Cut(rule, "->")
if s == strings.TrimSpace(before) {
return strings.TrimSpace(after)
}
}
return s
},
"portName": func(service string, port any) string {
var portAsString string
switch port.(type) {
case string:
portAsString = port.(string)
break
case int:
portAsString = strconv.Itoa(port.(int))
break
}
shrinkTo := 15 - (len(portAsString) + 1)
if len(service) < shrinkTo {
shrinkTo = len(service)
}
return safe(fmt.Sprintf("%s-%s", service[0:shrinkTo], portAsString))
},
}
func safe(s string) string {
s = strings.ToLower(s)
s = strings.Map(func(r rune) rune {
if ('a' <= r && r <= 'z') ||
('A' <= r && r <= 'Z') ||
('0' <= r && r <= '9') {
return r
}
return '-'
}, s)
for len(s) > 0 && s[0] == '-' {
s = s[1:]
}
return s
}
func ExitError(message string, err error) {
fmt.Fprintf(os.Stderr, "%s: %s\n", message, err)
os.Exit(1)
}