-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathtemplate.go
237 lines (204 loc) · 4.99 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
package flexibleconfig
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"os"
"path"
"path/filepath"
"strings"
"text/template"
"github.com/Masterminds/sprig/v3"
"github.com/luraproject/lura/v2/config"
)
type Config struct {
Settings string
Partials string
Templates string
Parser config.Parser
Path string
}
func NewTemplateParser(cfg Config) *TemplateParser {
t := &TemplateParser{
Partials: cfg.Partials,
Templates: []string{},
Parser: cfg.Parser,
Vars: map[string]interface{}{},
Path: cfg.Path,
err: parserError{errors: map[string]error{}},
}
if cfg.Settings != "" {
files, err := os.ReadDir(cfg.Settings)
if err != nil {
t.err.errors[cfg.Settings] = err
files = []os.DirEntry{}
}
for _, settingsFile := range files {
if !strings.HasSuffix(settingsFile.Name(), ".json") {
continue
}
b, err := os.ReadFile(filepath.Join(cfg.Settings, settingsFile.Name()))
if err != nil {
t.err.errors[settingsFile.Name()] = err
continue
}
var v map[string]interface{}
if err := json.Unmarshal(b, &v); err != nil {
t.err.errors[settingsFile.Name()] = err
continue
}
t.Vars[strings.TrimSuffix(filepath.Base(settingsFile.Name()), ".json")] = v
}
}
if cfg.Templates != "" {
files, err := os.ReadDir(cfg.Templates)
if err != nil {
t.err.errors[cfg.Templates] = err
files = []os.DirEntry{}
}
for _, settingsFile := range files {
if !strings.HasSuffix(settingsFile.Name(), ".tmpl") {
continue
}
t.Templates = append(t.Templates, filepath.Join(cfg.Templates, settingsFile.Name()))
}
}
t.funcMap = sprig.GenericFuncMap()
t.funcMap["marshal"] = t.marshal
t.funcMap["include"] = t.include
return t
}
type TemplateParser struct {
Vars map[string]interface{}
Partials string
Parser config.Parser
Templates []string
Path string
err parserError
funcMap template.FuncMap
lastSource []byte
}
func (t *TemplateParser) AddFunc(name string, f interface{}) {
t.funcMap[name] = f
}
func (t *TemplateParser) Parse(configFile string) (config.ServiceConfig, error) {
if len(t.err.errors) != 0 {
return config.ServiceConfig{}, t.err
}
tmpfile, err := os.CreateTemp("", "KrakenD_parsed_config_template_")
if err != nil {
log.Fatal("Couldn't create the temporary file:", err)
}
defer os.Remove(tmpfile.Name())
var buf bytes.Buffer
tmpl, err := template.New("config").Funcs(t.funcMap).ParseFiles(configFile)
if err != nil {
log.Fatal("Unable to parse configuration file:", err)
return t.Parser.Parse(configFile)
}
if len(t.Templates) > 0 {
tmpl, err = tmpl.ParseFiles(t.Templates...)
if err != nil {
log.Fatal("Error parsing sub-templates:", err)
return t.Parser.Parse(configFile)
}
}
err = tmpl.ExecuteTemplate(&buf, filepath.Base(configFile), t.Vars)
if err != nil {
log.Fatal("Found error while executing template:", err)
return t.Parser.Parse(configFile)
}
if _, err = tmpfile.Write(buf.Bytes()); err != nil {
log.Fatal("Unable to write the temporary configuration file:", err)
return t.Parser.Parse(configFile)
}
if err = tmpfile.Close(); err != nil {
log.Fatal("Unable to close the file after writing:", err)
}
filename := tmpfile.Name() + ".json"
if t.Path != "" {
filename = t.Path
}
if err := renameFile(tmpfile.Name(), filename); err != nil {
return config.ServiceConfig{}, err
}
t.lastSource, _ = os.ReadFile(filename)
cfg, err := t.Parser.Parse(filename)
if t.Path == "" {
os.Remove(filename)
}
return cfg, err
}
func (t *TemplateParser) LastSource() ([]byte, error) {
if t.lastSource == nil {
return nil, fmt.Errorf("no content")
}
return t.lastSource, nil
}
func (*TemplateParser) marshal(v interface{}) string {
a, _ := json.Marshal(v)
return string(a)
}
func (t *TemplateParser) include(v interface{}) string {
a, _ := os.ReadFile(path.Join(t.Partials, v.(string)))
return string(a)
}
type parserError struct {
errors map[string]error
}
func (p parserError) Error() string {
msgs := make([]string, len(p.errors))
var j int
for i, e := range p.errors {
msgs[j] = fmt.Sprintf("\t- %s: %s", i, e.Error())
j++
}
return "loading flexible-config settings:\n" + strings.Join(msgs, "\n")
}
func renameFile(src, dst string) (err error) {
err = copyFile(src, dst)
if err != nil {
return fmt.Errorf("failed to copy source file %s to %s: %s", src, dst, err)
}
err = os.RemoveAll(src)
if err != nil {
return fmt.Errorf("failed to cleanup source file %s: %s", src, err)
}
return nil
}
// credit https://gist.github.com/r0l1/92462b38df26839a3ca324697c8cba04
func copyFile(src, dst string) (err error) {
in, err := os.Open(src)
if err != nil {
return
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return
}
defer func() {
if e := out.Close(); e != nil {
err = e
}
}()
_, err = io.Copy(out, in)
if err != nil {
return
}
err = out.Sync()
if err != nil {
return
}
si, err := os.Stat(src)
if err != nil {
return
}
err = os.Chmod(dst, si.Mode())
if err != nil {
return
}
return
}