-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgenerate.go
88 lines (73 loc) · 1.99 KB
/
generate.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
//go:build ignore
// +build ignore
package main
import (
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"text/template"
)
const tpl = `// Code generated by go generate; DO NOT EDIT.
package {{ .Package }}
var {{ .Map }} = map[string]string{
{{ range $constant, $content := .Files }}` + "\t" + `"{{ $constant }}": ` + "`{{ $content }}`" + `,
{{ end }}}
`
var bundleTpl = template.Must(template.New("").Parse(tpl))
type Bundle struct {
Package string
Map string
Files map[string]string
}
func (b *Bundle) Write(filename string) {
f, err := os.Create(filename)
if err != nil {
panic(err)
}
defer f.Close()
bundleTpl.Execute(f, b)
}
func NewBundle(pkg, mapName string) *Bundle {
return &Bundle{
Package: pkg,
Map: mapName,
Files: make(map[string]string),
}
}
func stripExtension(filename string) string {
filename = strings.TrimSuffix(filename, path.Ext(filename))
return strings.Replace(filename, " ", "_", -1)
}
func readFile(filename string) []byte {
data, err := ioutil.ReadFile(filename)
if err != nil {
panic(err)
}
return data
}
func glob(pattern string) []string {
files, _ := filepath.Glob(pattern)
for i := range files {
if strings.Contains(files[i], "\\") {
files[i] = filepath.ToSlash(files[i])
}
}
return files
}
func generateMap(target string, pkg string, mapName string, srcFiles []string) {
bundle := NewBundle(pkg, mapName)
for _, srcFile := range srcFiles {
data := readFile(srcFile)
filename := stripExtension(path.Base(srcFile))
bundle.Files[filename] = string(data)
}
bundle.Write(target)
}
func main() {
generateMap(path.Join("storage", "sql.go"), "storage", "SqlMap", glob("storage/sql/*.sql"))
generateMap(path.Join("web", "handler", "html.go"), "handler", "TplMap", glob("web/handler/html/*.gohtml"))
generateMap(path.Join("web", "handler", "common.go"), "handler", "TplCommonMap", glob("web/handler/html/common/*.gohtml"))
generateMap(path.Join("assets", "static_stylesheet.go"), "assets", "AssetsMap", glob("assets/*.css"))
}