summaryrefslogtreecommitdiff
path: root/internal/templatemanager/templatemanager.go
blob: ff1214a40b314b4545324f882ffe48514f48566b (plain)
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
package templatemanager

import (
	"bytes"
	"fmt"
	"html/template"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/SayaAndy/saya-today-web/l10n"
)

type TemplateManager struct {
	templates map[string]templateManagerRender
}

type templateManagerRender struct {
	Main         string
	Tmpl         *template.Template
	LastModified time.Time
}

type TemplateManagerTemplates struct {
	Name  string
	Files []string
}

var templateFuncMap = template.FuncMap{
	"contains": strings.Contains,
	"iterate": func(count uint) []uint {
		items := make([]uint, count)
		for i := range count {
			items[i] = i
		}
		return items
	},
	"replace": strings.ReplaceAll,
	"fdiv": func(a, b int) float64 {
		return float64(a) / float64(b)
	},
	"l": func(path ...any) any {
		return l10n.T.GetPath(path...)
	},
	"join": strings.Join,
}

func NewTemplateManager(templates ...TemplateManagerTemplates) (*TemplateManager, error) {
	templateMap := make(map[string]templateManagerRender)

	for _, tmplStruct := range templates {
		tmpl := template.New(tmplStruct.Name).Funcs(templateFuncMap)
		if len(tmplStruct.Files) == 0 {
			templateMap[tmplStruct.Name] = templateManagerRender{
				Main: "",
				Tmpl: tmpl,
			}
			continue
		}
		tmpl, err := tmpl.ParseFiles(tmplStruct.Files...)
		if err != nil {
			return nil, err
		}
		modTime, err := setLastModified(tmplStruct.Files...)
		if err != nil {
			return nil, err
		}

		templateMap[tmplStruct.Name] = templateManagerRender{
			Main:         filepath.Base(tmplStruct.Files[0]),
			Tmpl:         tmpl,
			LastModified: modTime,
		}
	}

	return &TemplateManager{
		templates: templateMap,
	}, nil
}

func (tm *TemplateManager) Render(name string, data any, files ...string) ([]byte, error) {
	tmpl, exists := tm.templates[name]
	if !exists {
		return nil, fmt.Errorf("template %s not found", name)
	}

	var err error
	var tempTmpl *template.Template
	var mainTmpl string = tmpl.Main
	if len(files) == 0 {
		if mainTmpl == "" {
			return []byte{}, nil
		}
		tempTmpl = tmpl.Tmpl
	} else {
		tempTmpl, err = tmpl.Tmpl.Clone()
		if err != nil {
			return nil, fmt.Errorf("couldn't clone existing template for rendering: %w", err)
		}
		tempTmpl, err = tempTmpl.ParseFiles(files...)
		if err != nil {
			return nil, fmt.Errorf("couldn't include additional files in template rendering: %w", err)
		}
		if mainTmpl == "" {
			mainTmpl = filepath.Base(files[0])
		}
	}

	var buf bytes.Buffer
	err = tempTmpl.ExecuteTemplate(&buf, mainTmpl, data)
	return buf.Bytes(), err
}

func (tm *TemplateManager) Add(name string, files ...string) error {
	tmpl := template.New(name).Funcs(templateFuncMap)

	if len(files) == 0 {
		tm.templates[name] = templateManagerRender{
			Main: "",
			Tmpl: tmpl,
		}
		return nil
	}

	tmpl, err := tmpl.ParseFiles(files...)
	if err != nil {
		return fmt.Errorf("failed to add template into manager: %w", err)
	}

	modTime, err := setLastModified(files...)
	if err != nil {
		return fmt.Errorf("failed to add template into manager: %w", err)
	}

	tm.templates[name] = templateManagerRender{
		Main:         filepath.Base(files[0]),
		Tmpl:         tmpl,
		LastModified: modTime,
	}

	return nil
}

func (tm *TemplateManager) GetLastModified(name string) (time.Time, error) {
	tmpl, exists := tm.templates[name]
	if !exists {
		return time.Time{}, fmt.Errorf("template %s not found", name)
	}

	return tmpl.LastModified, nil
}

func setLastModified(filenames ...string) (time.Time, error) {
	lastModified := time.Time{}
	for _, filename := range filenames {
		stat, err := os.Stat(filename)
		if err != nil {
			return lastModified, fmt.Errorf("failed to stat file: path '%s': %w", filename, err)
		}
		modTime := stat.ModTime()
		if lastModified.Before(modTime) {
			lastModified = modTime
		}
	}
	return lastModified, nil
}