forked from isucon/isucon11-qualify
/
assets.go
100 lines (85 loc) · 1.75 KB
/
assets.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
//go:generate go run .
package main
import (
"fmt"
"hash/crc32"
"io"
"log"
"os"
"path/filepath"
"strings"
"text/template"
)
var (
rootPrefix string
)
type Variable struct {
Hash map[string]string
Map map[string]string
}
func hash(path string) string {
blob, err := os.Open(path)
if err != nil {
log.Fatal(err)
}
defer blob.Close()
bytes, err := io.ReadAll(blob)
if err != nil {
log.Fatal(err)
}
return fmt.Sprintf("%x", crc32.ChecksumIEEE(bytes))
}
func glob(v *Variable, prefix string) {
matches, err := filepath.Glob(filepath.Join(prefix, "*"))
if err != nil {
panic(err)
}
for _, match := range matches {
stat, err := os.Stat(match)
if err != nil {
log.Fatal(err)
}
if stat.IsDir() {
glob(v, match)
continue
}
filename := strings.TrimPrefix(match, rootPrefix+"/")
v.Hash["/"+filename] = hash(match)
splitted := strings.Split(filename, ".")
if len(splitted) > 2 {
basename := splitted[0]
ext := splitted[2]
v.Map["/"+basename+"."+ext] = "/" + filename
} else {
v.Map["/"+filename] = "/" + filename
}
}
}
func main() {
prefix := filepath.Join("..", "..", "webapp", "public")
rootPrefix = prefix
v := &Variable{
Hash: map[string]string{},
Map: map[string]string{},
}
glob(v, prefix)
io, err := os.Create(filepath.Join("../scenario", "assets.go"))
if err != nil {
log.Fatal(err)
}
err = template.Must(template.New("prog").Parse(prog)).Execute(io, v)
if err != nil {
log.Fatal(err)
}
}
const prog = `// Code generated by gen/assets.go; DO NOT EDIT.
package scenario
var (
resourcesHash = map[string]string{ {{range $key, $value := .Hash}}
"{{$key}}": "{{$value}}",{{end}}
}
resourcesMap = map[string]string{ {{range $key, $value := .Map}}
"{{$key}}": "{{$value}}",{{end}}
}
)
`