-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
95 lines (79 loc) · 1.69 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
package ttgo
import (
"bytes"
"os"
"path/filepath"
"text/template"
"github.com/Masterminds/sprig/v3"
"gopkg.in/yaml.v3"
)
type Template struct {
file string
tmpl *template.Template
}
func NewTemplate(file string) (*Template, error) {
if file == "" {
tmpl, err := template.New("").Funcs(sprig.TxtFuncMap()).Parse("{{. | toPrettyJson}}")
if err != nil {
return nil, err
}
te := &Template{
tmpl: tmpl,
}
return te, nil
}
abs, err := filepath.Abs(file)
if err != nil {
return nil, err
}
abs = filepath.Clean(abs)
p, err := os.ReadFile(abs)
if err != nil {
return nil, err
}
te := &Template{
file: abs,
}
tmpl := template.New(filepath.Base(abs))
tmpl = tmpl.Funcs(te.FuncMap())
tmpl = tmpl.Funcs(sprig.TxtFuncMap())
tmpl, err = tmpl.Parse(string(p))
if err != nil {
return nil, err
}
te.tmpl = tmpl
return te, nil
}
func (te *Template) FuncMap() map[string]any {
return map[string]any{
"partial": te.partial,
"writeFile": writeFile,
"fromYaml": fromYaml,
"toYaml": toYaml,
}
}
func (te *Template) Execute(data any) (string, error) {
b := new(bytes.Buffer)
err := te.tmpl.Execute(b, data)
return b.String(), err
}
func (te *Template) partial(file string, data any) (string, error) {
abs := filepath.Clean(filepath.Join(filepath.Dir(te.file), file))
pa, err := NewTemplate(abs)
if err != nil {
return "", err
}
return pa.Execute(data)
}
func writeFile(file, content string) (string, error) {
return "", os.WriteFile(file, []byte(content), 0644)
}
func fromYaml(s string) (any, error) {
var v any
err := yaml.Unmarshal([]byte(s), &v)
return v, err
}
func toYaml(v any) (string, error) {
p, err := yaml.Marshal(v)
return string(p), err
}