-
Notifications
You must be signed in to change notification settings - Fork 1
/
templit.go
94 lines (78 loc) · 2.25 KB
/
templit.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
package templit
import (
"fmt"
"os"
"path/filepath"
"strings"
"text/template"
)
// Executor is a wrapper around the template.Template type
type Executor struct {
*template.Template
git GitClient
}
// New returns a new Executor
func NewExecutor(gitClient GitClient) *Executor {
return &Executor{
Template: template.New("main").Funcs(DefaultFuncMap),
git: gitClient,
}
}
// ParsePath parses the given path
func (e *Executor) ParsePath(inputPath string) error {
// check if input is a directory
info, err := os.Stat(inputPath)
if err != nil {
return fmt.Errorf("failed to stat input: %w", err)
}
if !info.IsDir() {
content, err := os.ReadFile(inputPath)
if err != nil {
return fmt.Errorf("failed to read file: %w", err)
}
if _, err := e.New(inputPath).Parse(string(content)); err != nil {
return fmt.Errorf("failed to parse template: %w", err)
}
return nil
}
err = filepath.Walk(inputPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("failed to walk directory: %w", err)
}
if info.IsDir() {
return nil
}
// Read, parse, and execute template only if it's a file
content, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("failed to read file: %w", err)
}
if _, err := e.New(path).Parse(string(content)); err != nil {
return fmt.Errorf("failed to parse template: %w", err)
}
return nil
})
if err != nil {
return fmt.Errorf("failed to parse templates: %w", err)
}
return nil
}
// Render executes the template with the given data
func (e Executor) Render(name string, data interface{}) (string, error) {
var buf strings.Builder
if err := e.ExecuteTemplate(&buf, name, data); err != nil {
return "", fmt.Errorf("failed to execute template %s: %w", name, err)
}
return buf.String(), nil
}
// StringRender renders the given template string with the given data
func (e Executor) StringRender(templateString string, data interface{}) (string, error) {
if _, err := e.New("temp").Parse(templateString); err != nil {
return "", fmt.Errorf("error parsing template: %w", err)
}
var buf strings.Builder
if err := e.ExecuteTemplate(&buf, "temp", data); err != nil {
return "", fmt.Errorf("error executing template: %w", err)
}
return buf.String(), nil
}