-
Notifications
You must be signed in to change notification settings - Fork 0
/
tpl.go
80 lines (66 loc) · 1.61 KB
/
tpl.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
package feature
import (
"bytes"
"context"
"fmt"
"os"
"strings"
"text/template"
"gopkg.in/yaml.v3"
"github.com/joesonw/gofigure"
)
var _ gofigure.Feature = (*TemplateFeature)(nil)
type TemplateFeature struct {
funcs template.FuncMap
values map[string]any
}
func Template() *TemplateFeature {
return &TemplateFeature{
funcs: template.FuncMap{},
values: map[string]any{},
}
}
func (f *TemplateFeature) Funcs(funcs template.FuncMap) *TemplateFeature {
f.funcs = funcs
return f
}
func (f *TemplateFeature) Valeus(values map[string]any) *TemplateFeature {
f.values = values
return f
}
func (*TemplateFeature) Name() string {
return "!tpl"
}
func (f *TemplateFeature) Resolve(ctx context.Context, loader *gofigure.Loader, node *gofigure.Node) (*gofigure.Node, error) {
if node.Kind() != yaml.ScalarNode {
return nil, fmt.Errorf("!tpl only supports scalar node")
}
tpl, err := template.New(node.Keypath()).
Funcs(f.funcs).
Funcs(template.FuncMap{
"config": func(path string) (string, error) {
result, err := loader.GetNode(ctx, path)
if err != nil {
return "", err
}
if result == nil {
return "", nil
}
b, err := yaml.Marshal(result)
if err != nil {
return "", err
}
return strings.TrimSpace(string(b)), nil
},
"env": os.Getenv,
}).
Parse(node.Value())
if err != nil {
return nil, fmt.Errorf("unable to parse template: %w", err)
}
var w bytes.Buffer
if err := tpl.Execute(&w, f.values); err != nil {
return nil, fmt.Errorf("unable to execute template: %w", err)
}
return gofigure.NewScalarNode(strings.TrimSpace(w.String())), nil
}