-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtemplate.go
103 lines (90 loc) · 2.53 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
package skeletonkit
import (
"bytes"
"io/fs"
"path/filepath"
"text/template"
"github.com/josharian/txtarfs"
"golang.org/x/tools/imports"
"golang.org/x/tools/txtar"
)
// DefaultFuncMap is a default functions which using in a template.
var DefaultFuncMap = template.FuncMap{
"gitkeep": func() string {
return ".gitkeep"
},
"gomod": func() string {
return "go.mod"
},
"gomodinit": func(path string) string {
f, err := ModInit(path)
if err != nil {
panic(err)
}
return f
},
}
// TemplateOption is an option for a template.
// It can decorate the template.
type TemplateOption func(*template.Template) (*template.Template, error)
// TemplateWithFuncs add funcs to a template.
func TemplateWithFuncs(funcs template.FuncMap) TemplateOption {
return func(tmpl *template.Template) (*template.Template, error) {
return tmpl.Funcs(funcs), nil
}
}
// TemplateWithDelims sets delims of a template.
func TemplateWithDelims(left, right string) TemplateOption {
return func(tmpl *template.Template) (*template.Template, error) {
return tmpl.Delims(left, right), nil
}
}
// ParseTemplate parses a template which represents as txtar format from given a file system.
// The name is template name. If stripPrefix is not empty string, ParseTemplate uses sub directory of stripPrefix.
func ParseTemplate(tmplFS fs.FS, name, stripPrefix string, options ...TemplateOption) (*template.Template, error) {
fsys := tmplFS
if stripPrefix != "" {
var err error
fsys, err = fs.Sub(tmplFS, stripPrefix)
if err != nil {
return nil, err
}
}
ar, err := txtarfs.From(fsys)
if err != nil {
return nil, err
}
tmpl := template.New(name).Delims("@@", "@@").Funcs(DefaultFuncMap)
for _, opt := range options {
tmpl, err = opt(tmpl)
if err != nil {
return nil, err
}
}
return tmpl.Parse(string(txtar.Format(ar)))
}
// ExecuteTemplate executes a template with data.
// ExecuteTemplate also parses the excuted string as a txtar format and return it as a file system.
func ExecuteTemplate(tmpl *template.Template, data interface{}) (fs.FS, error) {
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return nil, err
}
ar := txtar.Parse(buf.Bytes())
for i := range ar.Files {
if filepath.Ext(ar.Files[i].Name) != ".go" ||
len(bytes.TrimSpace(ar.Files[i].Data)) == 0 {
continue
}
opt := &imports.Options{
Comments: true,
FormatOnly: true,
}
src, err := imports.Process(ar.Files[i].Name, ar.Files[i].Data, opt)
if err != nil {
return nil, err
}
ar.Files[i].Data = src
}
return txtarfs.As(ar), nil
}