-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtemplates.go
99 lines (82 loc) · 1.82 KB
/
templates.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
package main
import (
"bytes"
"flag"
"fmt"
"go/format"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
)
var (
templateType = flag.String("t", "text", "Type of template (text/html)")
source = flag.String("s", path.Join(".", "templates"), "Location of templates")
output = flag.String("o", "", "Output file")
)
func main() {
flag.Parse()
if *templateType != "html" && *templateType != "text" {
log.Fatalf("unexpected template type given: %s", *templateType)
}
buf := new(bytes.Buffer)
fmt.Fprint(buf, fmt.Sprintf(`package templates
import "%s/template"
var templates = map[string]string{`, *templateType))
if err := filepath.Walk(*source, func(path string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
if *templateType == "text" {
// Ignore non-templates files
if filepath.Ext(path) != ".tmpl" {
return nil
}
} else {
// Ignore non-templates files
if filepath.Ext(path) != ".html" {
return nil
}
}
b, err := ioutil.ReadFile(path)
if err != nil {
return err
}
fmt.Fprintf(buf, "\"%s\": `%s`,\n", filepath.Base(path), b)
return nil
}); err != nil {
log.Fatal(err)
}
fmt.Fprint(buf, `}
// Parse parses declared templates.
func Parse(t *template.Template) (*template.Template, error) {
for name, s := range templates {
var tmpl *template.Template
if t == nil {
t = template.New(name)
}
if name == t.Name() {
tmpl = t
} else {
tmpl = t.New(name)
}
if _, err := tmpl.Parse(s); err != nil {
return nil, err
}
}
return t, nil
}`)
clean, err := format.Source(buf.Bytes())
if err != nil {
log.Fatal(err)
}
file := os.Stdout
if *output != "" {
file, err = os.Create(*output)
if err != nil {
log.Fatal(err)
}
}
fmt.Fprintln(file, string(clean))
}