forked from hairyhenderson/gomplate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
402 lines (335 loc) · 11.5 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
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
package gomplate
import (
"context"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path"
"path/filepath"
"strings"
"text/template"
"github.com/hack-pad/hackpadfs"
"github.com/hairyhenderson/go-fsimpl"
"github.com/hairyhenderson/gomplate/v4/internal/config"
"github.com/hairyhenderson/gomplate/v4/internal/datafs"
"github.com/hairyhenderson/gomplate/v4/internal/iohelpers"
"github.com/hairyhenderson/gomplate/v4/tmpl"
// TODO: switch back if/when fs.FS support gets merged upstream
"github.com/hairyhenderson/xignore"
)
// ignorefile name, like .gitignore
const gomplateignore = ".gomplateignore"
func addTmplFuncs(f template.FuncMap, root *template.Template, tctx interface{}, path string) {
t := tmpl.New(root, tctx, path)
tns := func() *tmpl.Template { return t }
f["tmpl"] = tns
f["tpl"] = t.Inline
}
// copyFuncMap - copies the template.FuncMap into a new map so we can modify it
// without affecting the original
func copyFuncMap(funcMap template.FuncMap) template.FuncMap {
if funcMap == nil {
return nil
}
newFuncMap := make(template.FuncMap, len(funcMap))
for k, v := range funcMap {
newFuncMap[k] = v
}
return newFuncMap
}
// parseTemplate - parses text as a Go template with the given name and options
func parseTemplate(ctx context.Context, name, text string, funcs template.FuncMap, tmplctx interface{}, nested config.Templates, leftDelim, rightDelim string) (tmpl *template.Template, err error) {
tmpl = template.New(name)
tmpl.Option("missingkey=error")
funcMap := copyFuncMap(funcs)
// the "tmpl" funcs get added here because they need access to the root template and context
addTmplFuncs(funcMap, tmpl, tmplctx, name)
tmpl.Funcs(funcMap)
tmpl.Delims(leftDelim, rightDelim)
_, err = tmpl.Parse(text)
if err != nil {
return nil, err
}
err = parseNestedTemplates(ctx, nested, tmpl)
if err != nil {
return nil, fmt.Errorf("parse nested templates: %w", err)
}
return tmpl, nil
}
func parseNestedTemplates(ctx context.Context, nested config.Templates, tmpl *template.Template) error {
fsp := datafs.FSProviderFromContext(ctx)
for alias, n := range nested {
u := *n.URL
fname := path.Base(u.Path)
if strings.HasSuffix(u.Path, "/") {
fname = "."
}
u.Path = path.Dir(u.Path)
fsys, err := fsp.New(&u)
if err != nil {
return fmt.Errorf("filesystem provider for %q unavailable: %w", &u, err)
}
// TODO: maybe need to do something with root here?
if _, reldir := datafs.ResolveLocalPath(u.Path); reldir != "" && reldir != "." {
fsys, err = fs.Sub(fsys, reldir)
if err != nil {
return fmt.Errorf("sub filesystem for %q unavailable: %w", &u, err)
}
}
// inject context & header in case they're useful...
fsys = fsimpl.WithContextFS(ctx, fsys)
fsys = fsimpl.WithHeaderFS(n.Header, fsys)
// valid fs.FS paths have no trailing slash
fname = strings.TrimRight(fname, "/")
// first determine if the template path is a directory, in which case we
// need to load all the files in the directory (but not recursively)
fi, err := fs.Stat(fsys, fname)
if err != nil {
return fmt.Errorf("stat %q: %w", fname, err)
}
if fi.IsDir() {
err = parseNestedTemplateDir(ctx, fsys, alias, fname, tmpl)
} else {
err = parseNestedTemplate(ctx, fsys, alias, fname, tmpl)
}
if err != nil {
return err
}
}
return nil
}
func parseNestedTemplateDir(ctx context.Context, fsys fs.FS, alias, fname string, tmpl *template.Template) error {
files, err := fs.ReadDir(fsys, fname)
if err != nil {
return fmt.Errorf("readDir %q: %w", fname, err)
}
for _, f := range files {
if !f.IsDir() {
err = parseNestedTemplate(ctx, fsys,
path.Join(alias, f.Name()),
path.Join(fname, f.Name()),
tmpl,
)
if err != nil {
return err
}
}
}
return nil
}
func parseNestedTemplate(_ context.Context, fsys fs.FS, alias, fname string, tmpl *template.Template) error {
b, err := fs.ReadFile(fsys, fname)
if err != nil {
return fmt.Errorf("readFile %q: %w", fname, err)
}
_, err = tmpl.New(alias).Parse(string(b))
if err != nil {
return fmt.Errorf("parse nested template %q: %w", fname, err)
}
return nil
}
// gatherTemplates - gather and prepare templates for rendering
// nolint: gocyclo
func gatherTemplates(ctx context.Context, cfg *config.Config, outFileNamer func(context.Context, string) (string, error)) ([]Template, error) {
mode, modeOverride, err := cfg.GetMode()
if err != nil {
return nil, err
}
var templates []Template
switch {
// the arg-provided input string gets a special name
case cfg.Input != "":
// open the output file - no need to close it, as it will be closed by the
// caller later
target, oerr := openOutFile(ctx, cfg.OutputFiles[0], 0o755, mode, modeOverride, cfg.Stdout, cfg.SuppressEmpty)
if oerr != nil {
return nil, fmt.Errorf("openOutFile: %w", oerr)
}
templates = []Template{{
Name: "<arg>",
Text: cfg.Input,
Writer: target,
}}
case cfg.InputDir != "":
// input dirs presume output dirs are set too
templates, err = walkDir(ctx, cfg, cfg.InputDir, outFileNamer, cfg.ExcludeGlob, mode, modeOverride)
if err != nil {
return nil, fmt.Errorf("walkDir: %w", err)
}
case cfg.Input == "":
templates = make([]Template, len(cfg.InputFiles))
for i, f := range cfg.InputFiles {
templates[i], err = fileToTemplate(ctx, cfg, f, cfg.OutputFiles[i], mode, modeOverride)
if err != nil {
return nil, fmt.Errorf("fileToTemplate: %w", err)
}
}
}
return templates, nil
}
// walkDir - given an input dir `dir` and an output dir `outDir`, and a list
// of .gomplateignore and exclude globs (if any), walk the input directory and create a list of
// tplate objects, and an error, if any.
func walkDir(ctx context.Context, cfg *config.Config, dir string, outFileNamer func(context.Context, string) (string, error), excludeGlob []string, mode os.FileMode, modeOverride bool) ([]Template, error) {
dir = filepath.ToSlash(filepath.Clean(dir))
// we want a filesystem rooted at dir, for relative matching
fsys, err := datafs.FSysForPath(ctx, dir)
if err != nil {
return nil, fmt.Errorf("filesystem provider for %q unavailable: %w", dir, err)
}
// we need dir to be relative to the root of fsys
// TODO: maybe need to do something with root here?
_, reldir := datafs.ResolveLocalPath(dir)
subfsys, err := fs.Sub(fsys, reldir)
if err != nil {
return nil, fmt.Errorf("sub: %w", err)
}
// just check . because fsys is subbed to dir already
dirStat, err := fs.Stat(subfsys, ".")
if err != nil {
return nil, fmt.Errorf("stat %q (%q): %w", dir, reldir, err)
}
dirMode := dirStat.Mode()
templates := make([]Template, 0)
matcher := xignore.NewMatcher(subfsys)
matches, err := matcher.Matches(".", &xignore.MatchesOptions{
Ignorefile: gomplateignore,
Nested: true, // allow nested ignorefile
AfterPatterns: excludeGlob,
})
if err != nil {
return nil, fmt.Errorf("ignore matching failed for %s: %w", dir, err)
}
// Unmatched ignorefile rules's files
for _, file := range matches.UnmatchedFiles {
// we want to pass an absolute (as much as possible) path to fileToTemplate
inPath := filepath.Join(dir, file)
inPath = filepath.ToSlash(inPath)
// but outFileNamer expects only the filename itself
outFile, err := outFileNamer(ctx, file)
if err != nil {
return nil, fmt.Errorf("outFileNamer: %w", err)
}
tpl, err := fileToTemplate(ctx, cfg, inPath, outFile, mode, modeOverride)
if err != nil {
return nil, fmt.Errorf("fileToTemplate: %w", err)
}
// Ensure file parent dirs - use separate fsys for output file
outfsys, err := datafs.FSysForPath(ctx, outFile)
if err != nil {
return nil, fmt.Errorf("fsysForPath: %w", err)
}
if err = hackpadfs.MkdirAll(outfsys, filepath.Dir(outFile), dirMode); err != nil {
return nil, fmt.Errorf("mkdirAll %q: %w", outFile, err)
}
templates = append(templates, tpl)
}
return templates, nil
}
func fileToTemplate(ctx context.Context, cfg *config.Config, inFile, outFile string, mode os.FileMode, modeOverride bool) (Template, error) {
source := ""
//nolint:nestif
if inFile == "-" {
b, err := io.ReadAll(cfg.Stdin)
if err != nil {
return Template{}, fmt.Errorf("read from stdin: %w", err)
}
source = string(b)
} else {
fsys, err := datafs.FSysForPath(ctx, inFile)
if err != nil {
return Template{}, fmt.Errorf("fsysForPath: %w", err)
}
si, err := fs.Stat(fsys, inFile)
if err != nil {
return Template{}, fmt.Errorf("stat %q: %w", inFile, err)
}
if mode == 0 {
mode = si.Mode()
}
// we read the file and store in memory immediately, to prevent leaking
// file descriptors.
b, err := fs.ReadFile(fsys, inFile)
if err != nil {
return Template{}, fmt.Errorf("readAll %q: %w", inFile, err)
}
source = string(b)
}
// open the output file - no need to close it, as it will be closed by the
// caller later
target, err := openOutFile(ctx, outFile, 0755, mode, modeOverride, cfg.Stdout, cfg.SuppressEmpty)
if err != nil {
return Template{}, fmt.Errorf("openOutFile: %w", err)
}
tmpl := Template{
Name: inFile,
Text: source,
Writer: target,
}
return tmpl, nil
}
// openOutFile returns a writer for the given file, creating the file if it
// doesn't exist yet, and creating the parent directories if necessary. Will
// defer actual opening until the first write (or the first non-empty write if
// 'suppressEmpty' is true). If the file already exists, it will not be
// overwritten until the first difference is encountered.
//
// TODO: the 'suppressEmpty' behaviour should be always enabled, in the next
// major release (v4.x).
func openOutFile(ctx context.Context, filename string, dirMode, mode os.FileMode, modeOverride bool, stdout io.Writer, suppressEmpty bool) (out io.Writer, err error) {
if suppressEmpty {
out = iohelpers.NewEmptySkipper(func() (io.Writer, error) {
if filename == "-" {
return stdout, nil
}
return createOutFile(ctx, filename, dirMode, mode, modeOverride)
})
return out, nil
}
if filename == "-" {
return stdout, nil
}
return createOutFile(ctx, filename, dirMode, mode, modeOverride)
}
func createOutFile(ctx context.Context, filename string, dirMode, mode os.FileMode, modeOverride bool) (out io.WriteCloser, err error) {
// we only support writing out to local files for now
fsys, err := datafs.FSysForPath(ctx, filename)
if err != nil {
return nil, fmt.Errorf("fsysForPath: %w", err)
}
mode = iohelpers.NormalizeFileMode(mode.Perm())
if modeOverride {
err = hackpadfs.Chmod(fsys, filename, mode)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return nil, fmt.Errorf("failed to chmod output file %q with mode %q: %w", filename, mode, err)
}
}
open := func() (out io.WriteCloser, err error) {
// Ensure file parent dirs
if err = hackpadfs.MkdirAll(fsys, filepath.Dir(filename), dirMode); err != nil {
return nil, fmt.Errorf("mkdirAll %q: %w", filename, err)
}
f, err := hackpadfs.OpenFile(fsys, filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode)
if err != nil {
return out, fmt.Errorf("failed to open output file '%s' for writing: %w", filename, err)
}
out = f.(io.WriteCloser)
return out, err
}
// if the output file already exists, we'll use a SameSkipper
fi, err := hackpadfs.Stat(fsys, filename)
if err != nil {
// likely means the file just doesn't exist - further errors will be more useful
return iohelpers.LazyWriteCloser(open), nil
}
if fi.IsDir() {
// error because this is a directory
return nil, isDirError(fi.Name())
}
out = iohelpers.SameSkipper(iohelpers.LazyReadCloser(func() (io.ReadCloser, error) {
return hackpadfs.OpenFile(fsys, filename, os.O_RDONLY, mode)
}), open)
return out, err
}