-
Notifications
You must be signed in to change notification settings - Fork 1
/
tgen.go
241 lines (193 loc) · 5.54 KB
/
tgen.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
package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"os"
"regexp"
"strings"
"text/template"
"github.com/Masterminds/sprig/v3"
"github.com/patrickdappollonio/tgen/tfuncs"
"gopkg.in/yaml.v3"
)
type tgen struct {
Strict bool
templateFileName string
templateFileContent string
yamlValues map[string]any
envValues map[string]string
preDelimiter, postDelimiter string
}
func (t *tgen) setTemplate(name, content string) {
t.templateFileName = name
t.templateFileContent = content
}
func (t *tgen) loadTemplatePath(templatepath string) error {
if templatepath == "" {
return fmt.Errorf("template path is empty")
}
bf, err := tfuncs.ReadFile(templatepath)
if err != nil {
return err
}
t.templateFileName = templatepath
t.templateFileContent = bf
return nil
}
func (t *tgen) loadTemplateFile(overwriteName string, f *os.File) error {
if f == nil {
return fmt.Errorf("template file is empty")
}
name := f.Name()
if overwriteName != "" {
name = overwriteName
}
var buf bytes.Buffer
read, err := io.Copy(&buf, f)
if err != nil {
return fmt.Errorf("unable to read template file %q: %w", name, err)
}
if read == 0 {
return fmt.Errorf("template file %q is empty", name)
}
t.templateFileName = name
t.templateFileContent = buf.String()
return nil
}
func (t *tgen) loadYAMLValues(yamlpath string) error {
if yamlpath == "" {
return fmt.Errorf("yaml values file path is empty")
}
valuesfile := map[string]any{}
bf, err := tfuncs.ReadFile(yamlpath)
if err != nil {
return err
}
if err := yaml.Unmarshal([]byte(bf), &valuesfile); err != nil {
return fmt.Errorf("unable to parse values file %q: %s", yamlpath, err.Error())
}
copied := copyMap(valuesfile)
valuesfile["Values"] = copied
t.yamlValues = valuesfile
return nil
}
func (t *tgen) loadEnvValues(envpath string) error {
envVars := make(map[string]string)
if envpath == "" {
return nil
}
data, err := tfuncs.ReadFile(envpath)
if err != nil {
return err
}
sc := bufio.NewScanner(bytes.NewBufferString(data))
for sc.Scan() {
key, value, err := parseEnvLine(sc.Text())
if err != nil {
return err
}
if key != "" && value != "" {
envVars[key] = value
}
}
t.envValues = envVars
return nil
}
func (t *tgen) setDelimiters(delimiters string) error {
size := len(delimiters)
if size < 2 || size%2 != 0 {
return fmt.Errorf("delimiter size needs to be multiple of two and have 2 or more characters")
}
div := size / 2
t.preDelimiter = delimiters[:div]
t.postDelimiter = delimiters[div:]
return nil
}
func mergeFuncMaps(a, b template.FuncMap) template.FuncMap {
if a == nil {
a = template.FuncMap{}
}
for k, v := range b {
_, found := a[k]
if !found {
a[k] = v
}
}
return a
}
func (t *tgen) render(w io.Writer) error {
funcs := mergeFuncMaps(tfuncs.GetFunctions(t.envValues, t.Strict), sprig.FuncMap())
baseTemplate := template.New(t.templateFileName).Funcs(funcs)
if t.Strict {
baseTemplate = baseTemplate.Option("missingkey=error")
} else {
baseTemplate = baseTemplate.Option("missingkey=zero")
}
if t.preDelimiter != "" && t.postDelimiter != "" {
baseTemplate = baseTemplate.Delims(t.preDelimiter, t.postDelimiter)
}
var temp bytes.Buffer
parsed, err := baseTemplate.Parse(t.templateFileContent)
if err != nil {
return fmt.Errorf("unable to parse template file %q: %s", t.templateFileName, err.Error())
}
if err := parsed.Execute(&temp, t.yamlValues); err != nil {
return t.replaceTemplateRenderError(err)
}
if t.Strict {
_, err = fmt.Fprint(w, temp.String())
return err
}
// Due to an unfortunate agreement and lack of behaviour change in the Go standard
// library, I'm forced to trim the <no value> string from the output directly.
// See helm's engine implementation of this
// https://github.com/helm/helm/blob/7ed9d16dc764a5b94b378a7e217865efaa0d9ac8/pkg/engine/engine.go#L267
// and the original issue, not solved but closed as wontfix:
// https://github.com/golang/go/issues/24963
str := strings.ReplaceAll(temp.String(), "<no value>", "")
_, err = fmt.Fprint(w, str)
return err
}
// reExtractLocation is used to extract the line number from the error message
// as a string like "/foo/bar:1:18"
var reExtractLocation = regexp.MustCompile(`\s([^:]*:\d+:\d+):`)
func (t *tgen) replaceTemplateRenderError(err error) error {
if err == nil {
return nil
}
// Go templates won't propagate the error message back to the caller, so the
// only way to know what happened is to parse the error message and return
// a more meaningful error.
if t, ok := err.(template.ExecError); ok {
// Check if we can unwrap the error bubbled up from the template
if unwrap := errors.Unwrap(t.Err); unwrap != nil {
// The original error does not provide enough contextual information
// to know where the error happened, so we need to extract the line
// number from the error message
matchExpr := reExtractLocation.FindStringSubmatch(t.Err.Error())
match := ""
if len(matchExpr) > 0 {
match = matchExpr[1]
}
switch unwrap.(type) {
case *tfuncs.ErrRequired, *tfuncs.ErrVarNotFound:
return &templateFuncError{line: match, original: unwrap}
default:
// do nothing, the next section will take care
// of checking for additional items
}
}
// If we can't unwrap, it means we're dealing with string-based errors
// which are even harder to validate
switch {
case strings.Contains(err.Error(), "map has no entry for key"):
return &missingKeyErr{name: err.Error()[strings.LastIndex(err.Error(), ":")+2:]}
default:
return t.Err
}
}
return err
}