This repository has been archived by the owner on May 8, 2022. It is now read-only.
/
theme.go
322 lines (289 loc) · 7.2 KB
/
theme.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
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package theme
import (
"bytes"
"errors"
"fmt"
"html/template"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"sync"
"github.com/Unknwon/com"
"github.com/go-xiaohei/pugo/app/model"
"github.com/go-xiaohei/pugo/app/vars"
"github.com/mcuadros/go-version"
"gopkg.in/inconshreveable/log15.v2"
)
var (
reDefineTag = regexp.MustCompile("{{ ?define \"([^\"]*)\" ?\"?([a-zA-Z0-9]*)?\"? ?}}")
reTemplateTag = regexp.MustCompile("{{ ?template \"([^\"]*)\" ?([^ ]*)? ?}}")
errThemeMetaMissing = errors.New("need add theme meta file")
errThemeOutdatedVersion = errors.New("theme need newer PuGo version")
)
type (
// Theme object, maintains a sort of templates for whole site data
Theme struct {
Meta *Meta
metaFile string
metaError error
dir string
lock sync.Mutex
funcMap template.FuncMap
templates map[string]*template.Template
extensions []string
cache []*namedTemplate
regularTemplateDefs []string
}
namedTemplate struct {
Name string
Src string
}
)
// New returns new theme with dir
func New(dir string) *Theme {
theme := &Theme{
dir: dir,
funcMap: make(template.FuncMap),
extensions: []string{".html"},
}
theme.funcMap["HTML"] = func(v interface{}) template.HTML {
if str, ok := v.(string); ok {
return template.HTML(str)
}
if b, ok := v.([]byte); ok {
return template.HTML(string(b))
}
return template.HTML(fmt.Sprintf("%v", v))
}
theme.funcMap["Include"] = func(values ...interface{}) template.HTML {
var buf bytes.Buffer
if len(values) < 2 {
return template.HTML("<!-- include template without path or data -->")
}
var pathData []string
for i, v := range values {
if i < len(values)-1 {
str, ok := v.(string)
if !ok {
return template.HTML("<!-- include template with non-string path -->")
}
pathData = append(pathData, str)
}
}
tpl := path.Join(pathData...)
if err := theme.Execute(&buf, tpl, values[len(values)-1]); err != nil {
return template.HTML("<!-- template " + tpl + " error:" + err.Error() + "-->")
}
return template.HTML(string(buf.Bytes()))
}
theme.parseMeta()
return theme
}
func (th *Theme) parseMeta() {
for t, f := range model.ShouldThemeMetaFiles() {
file := path.Join(th.dir, f)
if !com.IsFile(file) {
continue
}
data, err := ioutil.ReadFile(file)
if err != nil {
th.metaError = err
return
}
th.Meta, th.metaError = NewMeta(data, t)
if th.Meta != nil {
th.metaFile = file
log15.Debug("Theme|%s", file)
}
return
}
}
// Func add template func to theme
func (th *Theme) Func(key string, fn interface{}) {
th.funcMap[key] = fn
}
// Funcs return all template functions
func (th *Theme) Funcs() template.FuncMap {
return th.funcMap
}
// Load loads templates
func (th *Theme) Load() error {
return th.loadTemplates()
}
// changes from https://github.com/go-macaron/renders/blob/master/renders.go#L43,
// thanks a lot
func (th *Theme) loadTemplates() error {
th.lock.Lock()
defer th.lock.Unlock()
templates := make(map[string]*template.Template)
err := filepath.Walk(th.dir, func(p string, fi os.FileInfo, err error) error {
r, err := filepath.Rel(th.dir, p) // get relative path
if err != nil {
return err
}
ext := getExt(r)
for _, extension := range th.extensions {
if ext == extension {
if err := th.add(p); err != nil {
return err
}
for _, t := range th.regularTemplateDefs {
found := false
defineIdx := 0
// From the beginning (which should) most specifc we look for definitions
for _, nt := range th.cache {
nt.Src = reDefineTag.ReplaceAllStringFunc(nt.Src, func(raw string) string {
parsed := reDefineTag.FindStringSubmatch(raw)
name := parsed[1]
if name != t {
return raw
}
// Don't touch the first definition
if !found {
found = true
return raw
}
defineIdx++
return fmt.Sprintf("{{ define \"%s_invalidated_#%d\" }}", name, defineIdx)
})
}
}
var (
baseTmpl *template.Template
i int
)
for _, nt := range th.cache {
var currentTmpl *template.Template
if i == 0 {
baseTmpl = template.New(nt.Name)
currentTmpl = baseTmpl
} else {
currentTmpl = baseTmpl.New(nt.Name)
}
if _, err := currentTmpl.Funcs(th.funcMap).Parse(nt.Src); err != nil {
return err
}
i++
}
tname := generateTemplateName(th.dir, p)
templates[tname] = baseTmpl
// Make sure we empty the cache between runs
th.cache = th.cache[0:0]
break
//return nil
}
}
return nil
})
th.templates = templates
return err
}
func (th *Theme) add(path string) error {
// Get file content
tplSrc, err := getFileContent(path)
if err != nil {
return err
}
tplName := generateTemplateName(th.dir, path)
// Make sure template is not already included
alreadyIncluded := false
for _, nt := range th.cache {
if nt.Name == tplName {
alreadyIncluded = true
break
}
}
if alreadyIncluded {
return nil
}
// Add to the cache
nt := &namedTemplate{
Name: tplName,
Src: tplSrc,
}
th.cache = append(th.cache, nt)
// Check for any template block
for _, raw := range reTemplateTag.FindAllString(nt.Src, -1) {
parsed := reTemplateTag.FindStringSubmatch(raw)
templatePath := parsed[1]
ext := getExt(templatePath)
if !strings.Contains(templatePath, ext) {
th.regularTemplateDefs = append(th.regularTemplateDefs, templatePath)
continue
}
// Add this template and continue looking for more template blocks
th.add(filepath.Join(th.dir, templatePath))
}
return nil
}
// Execute executes template by name with data,
// write into a Writer
func (th *Theme) Execute(w io.Writer, name string, data interface{}) error {
tpl := th.Template(name)
if tpl == nil {
return fmt.Errorf("template '%s' is missing", name)
}
return tpl.ExecuteTemplate(w, name, data)
}
// StaticDir gets static dir in the theme
func (th *Theme) StaticDir() string {
return path.Join(th.dir, th.Static())
}
// Dir get theme directory
func (th *Theme) Dir() string {
return th.dir
}
// Static gets static dirname in the theme
func (th *Theme) Static() string {
return "static"
}
// Template gets template by name
func (th *Theme) Template(name string) *template.Template {
return th.templates[name]
}
// Validate check theme meta is valid or not
func (th *Theme) Validate() error {
if th.metaFile == "" {
return errThemeMetaMissing
}
if th.metaError != nil {
return th.metaError
}
if th.Meta != nil {
if th.Meta.MinVersion != "" {
if version.Compare(vars.Version, th.Meta.MinVersion, "<") {
return errThemeOutdatedVersion
}
}
}
return nil
}
func generateTemplateName(base, path string) string {
//name := (r[0 : len(r)-len(ext)])
return filepath.ToSlash(path[len(base)+1:])
}
func getFileContent(path string) (string, error) {
file, err := os.Open(path)
if err != nil {
return "", err
}
b, err := ioutil.ReadAll(file)
if err != nil {
return "", err
}
s := string(b)
if len(s) < 1 {
return "", errors.New("render: template file is empty")
}
return s, nil
}
func getExt(s string) string {
if strings.Index(s, ".") == -1 {
return ""
}
return "." + strings.Join(strings.Split(s, ".")[1:], ".")
}