...
1 package gonja
2
3 import (
4 "io/ioutil"
5 "sync"
6
7 "github.com/goph/emperror"
8
9 "github.com/noirbizarre/gonja/builtins"
10 "github.com/noirbizarre/gonja/config"
11 "github.com/noirbizarre/gonja/exec"
12 "github.com/noirbizarre/gonja/loaders"
13 )
14
15 type Environment struct {
16 *exec.EvalConfig
17 Loader loaders.Loader
18
19 Cache map[string]*exec.Template
20 CacheMutex sync.Mutex
21 }
22
23 func NewEnvironment(cfg *config.Config, loader loaders.Loader) *Environment {
24 env := &Environment{
25 EvalConfig: exec.NewEvalConfig(cfg),
26 Loader: loader,
27 Cache: map[string]*exec.Template{},
28 }
29 env.EvalConfig.Loader = env
30 env.Filters.Update(builtins.Filters)
31 env.Statements.Update(builtins.Statements)
32 env.Tests.Update(builtins.Tests)
33 env.Globals.Merge(builtins.Globals)
34 env.Globals.Set("gonja", map[string]interface{}{
35 "version": VERSION,
36 })
37 return env
38 }
39
40
41
42
43 func (env *Environment) CleanCache(filenames ...string) {
44 env.CacheMutex.Lock()
45 defer env.CacheMutex.Unlock()
46
47 if len(filenames) == 0 {
48 env.Cache = map[string]*exec.Template{}
49 }
50
51 for _, filename := range filenames {
52 delete(env.Cache, filename)
53 }
54 }
55
56
57
58
59
60
61 func (env *Environment) FromCache(filename string) (*exec.Template, error) {
62 if env.Config.Debug {
63
64 return env.FromFile(filename)
65 }
66
67 env.CacheMutex.Lock()
68 defer env.CacheMutex.Unlock()
69
70 tpl, has := env.Cache[filename]
71
72
73 if !has {
74 tpl, err := env.FromFile(filename)
75 if err != nil {
76 return nil, err
77 }
78 env.Cache[filename] = tpl
79 return tpl, nil
80 }
81
82
83 return tpl, nil
84 }
85
86
87 func (env *Environment) FromString(tpl string) (*exec.Template, error) {
88 return exec.NewTemplate("string", tpl, env.EvalConfig)
89 }
90
91
92 func (env *Environment) FromBytes(tpl []byte) (*exec.Template, error) {
93 return exec.NewTemplate("bytes", string(tpl), env.EvalConfig)
94 }
95
96
97 func (env *Environment) FromFile(filename string) (*exec.Template, error) {
98 fd, err := env.Loader.Get(filename)
99 if err != nil {
100 return nil, emperror.With(err, "filename", filename)
101 }
102 buf, err := ioutil.ReadAll(fd)
103 if err != nil {
104 return nil, emperror.With(err, "filename", filename)
105 }
106
107 return exec.NewTemplate(filename, string(buf), env.EvalConfig)
108 }
109
110 func (env *Environment) GetTemplate(filename string) (*exec.Template, error) {
111 return env.FromFile(filename)
112 }
113
View as plain text