/
context.go
74 lines (61 loc) · 1.51 KB
/
context.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
package codegen
import (
"go/token"
"log"
"path"
"path/filepath"
"text/template"
)
// Context represents the context in which a code generation operation is run.
type Context struct {
Dir string
SearchPaths []string
Fset *token.FileSet
Templates map[string]*template.Template
PackageName string
Imports map[string]bool
Results map[string]string
}
// NewContext initializes a new code generation context.
func NewContext(dir string, searchPaths []string) (*Context, error) {
result := &Context{
Dir: dir,
SearchPaths: searchPaths,
Fset: token.NewFileSet(),
PackageName: "main", // default to main
Results: map[string]string{},
}
return result, result.Populate()
}
// Populate fills in the rest of the context based upon the context's
// config.
func (ctx *Context) Populate() error {
ctx.Templates = make(map[string]*template.Template)
ctx.Imports = make(map[string]bool)
for _, dir := range ctx.SearchPaths {
err := ctx.searchDir(dir)
if err != nil {
return err
}
}
return nil
}
func (ctx *Context) searchDir(dir string) error {
// search directory for every template in the package
pat := path.Join(dir, "*.tmpl")
paths, err := filepath.Glob(pat)
if err != nil {
return err
}
for _, p := range paths {
base := path.Base(p)
name := base[:len(base)-len(".tmpl")]
t, err := template.New(base).ParseFiles(p)
if err != nil {
return err
}
ctx.Templates[name] = t
}
log.Printf("found %d templates in %s", len(paths), dir)
return nil
}