-
Notifications
You must be signed in to change notification settings - Fork 1
/
load.go
240 lines (194 loc) · 5.33 KB
/
load.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
package html
import (
"fmt"
"html/template"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
"text/template/parse"
)
// Loader collects the available template sources.
// It creates new sets and triggers the template parsing.
type Loader struct {
conf Config
mutex sync.Mutex
sources map[string]*Source
treeCache map[string]map[string]*parse.Tree
}
// Config controls the behaviour of the template loading and rendering.
type Config struct {
// Directories define the file paths to search for templates,
// ordered by descending priority.
Directories []string
// AutoReload is whether the templates should be reloaded on rendering.
// This is useful in development, but should be disabled in production.
AutoReload bool
// DelimLeft is the delimiter that marks the start of a template action.
DelimLeft string
// DelimRight is the delimiter that marks the stop of a template action.
DelimRight string
}
// Source is a template data source. It contains an optional path to
// the source's file source.
type Source struct {
Content string
FilePath string
Name string
}
// NewLoader creates a new loader. It scans the provided source directories
// and collects all available template sources.
func NewLoader(conf Config) (l *Loader, err error) {
l = &Loader{conf: conf, treeCache: make(map[string]map[string]*parse.Tree)}
err = l.scan()
return l, err
}
func (l *Loader) scan() error {
l.mutex.Lock()
defer l.mutex.Unlock()
directories := l.conf.Directories
l.sources = make(map[string]*Source)
for i := len(l.conf.Directories); i > 0; i-- {
dir := directories[i-1]
if _, err := os.Stat(dir); err != nil {
return err
}
err := filepath.Walk(dir, func(path string, info os.FileInfo, fileErr error) error {
if fileErr != nil {
return fileErr
}
if l.ignoreFile(info) {
return nil
}
tmplName, err := l.nameForTemplate(dir, path)
if err != nil {
return err
}
l.sources[tmplName] = &Source{Name: tmplName, FilePath: path}
return nil
})
if err != nil {
return err
}
}
return nil
}
func (l *Loader) ignoreFile(info os.FileInfo) bool {
fileName := info.Name()
ignoreFile := strings.HasPrefix(fileName, "_") || !strings.HasSuffix(fileName, ".html")
if info.IsDir() || ignoreFile {
return true
}
return false
}
func (l *Loader) nameForTemplate(dir, path string) (string, error) {
tmplName, err := filepath.Rel(dir, path)
if err != nil {
return "", err
}
if os.PathSeparator == '\\' {
tmplName = strings.Replace(tmplName, `\`, `/`, -1) // replaces path separator on windows
}
return strings.ToLower(strings.Replace(tmplName, ".html", "", 1)), nil
}
// NewSet returns a new initialized set.
func (l *Loader) NewSet() *Set {
return newSet(l)
}
// AddFile adds a file-based template source.
// It overwrites any existing source with the same name.
func (l *Loader) AddFile(name, filePath string) *Loader {
return l.addSource(&Source{Name: name, FilePath: filePath})
}
// AddText adds a text-based template source.
// It overwrites any existing source with the same name.
func (l *Loader) AddText(name string, content string) *Loader {
return l.addSource(&Source{Name: name, Content: content})
}
func (l *Loader) addSource(source *Source) *Loader {
l.mutex.Lock()
defer l.mutex.Unlock()
l.sources[source.Name] = source
return l
}
// Sources returns the sources found by scanning the provided directories.
func (l *Loader) Sources() []*Source {
l.mutex.Lock()
defer l.mutex.Unlock()
ret := make([]*Source, len(l.sources))
var i int
for _, src := range l.sources {
ret[i] = src
i++
}
return ret
}
func (l *Loader) buildTemplate(s *Set) (*template.Template, error) {
l.mutex.Lock()
defer l.mutex.Unlock()
err := l.loadSources(s)
if err != nil {
return nil, err
}
tmpl, err := l.parseSources(s)
if err != nil {
return nil, err
}
return tmpl, nil
}
func (l *Loader) loadSources(s *Set) error {
for _, source := range s.sources {
var loadSourceFromPath string
if source.FilePath != "" {
if src, ok := l.sources[source.FilePath]; ok {
loadSourceFromPath = src.FilePath
} else {
return fmt.Errorf("template %q not found", source.FilePath)
}
}
content, err := ioutil.ReadFile(loadSourceFromPath)
if err != nil {
return err
}
source.Content = string(content)
}
return nil
}
func (l *Loader) parseSources(s *Set) (*template.Template, error) {
var useCache = !l.conf.AutoReload
var parsedTrees []*parse.Tree
parsedNames := make(map[string]bool)
for _, source := range s.sources {
var trees map[string]*parse.Tree
cacheKey := source.FilePath
if useCache && cacheKey != "" {
if cachedTrees, ok := l.treeCache[cacheKey]; ok {
trees = cachedTrees
}
}
var err error
trees, err = parse.Parse(source.Name, source.Content, l.conf.DelimLeft, l.conf.DelimRight, s.funcs)
if err != nil {
return nil, err
}
for name, tree := range trees {
if name == rootTemplateName {
isRootTmpl := len(trees) == 1 && trees[rootTemplateName] != nil
if !isRootTmpl {
continue
}
alreadyParsed := parsedNames[name]
if alreadyParsed {
return nil, fmt.Errorf("html/template: redefinition of root template")
}
}
parsedTrees = append(parsedTrees, tree)
parsedNames[name] = true
}
if useCache && cacheKey != "" {
l.treeCache[cacheKey] = trees
}
}
return createTemplate(parsedTrees, s.funcs)
}