/
update.go
136 lines (106 loc) · 2.12 KB
/
update.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package main
import (
"bytes"
"crypto/md5"
"encoding/hex"
"flag"
"fmt"
"go/format"
"io"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"strings"
"text/template"
)
var (
publicDir string
benchDir string
)
func init() {
flag.StringVar(&publicDir, "publicdir", "../webapp/public", "path to webapp/public directory")
flag.StringVar(&benchDir, "benchdir", "./src/bench", "path to bench/src/bench directory")
}
func must(err error) {
if err != nil {
panic(err)
}
}
type TemplateArg struct {
StaticFiles []*StaticFile
}
type StaticFile struct {
Path string
Size int64
Hash string
}
const staticFileTemplate = `
package bench
type StaticFile struct {
Path string
Size int64
Hash string
}
var (
StaticFiles = []*StaticFile {
{{ range .StaticFiles }} &StaticFile { "{{ .Path }}", {{ .Size }}, "{{ .Hash }}" },
{{ end }}
}
)
`
func prepareStaticFiles() []*StaticFile {
var ret []*StaticFile
err := filepath.Walk(publicDir, func(path string, info os.FileInfo, err error) error {
must(err)
if info.IsDir() {
return nil
}
subPath := path[len(publicDir):]
f, err := os.Open(path)
must(err)
defer f.Close()
h := md5.New()
_, err = io.Copy(h, f)
must(err)
hash := hex.EncodeToString(h.Sum(nil))
ret = append(ret, &StaticFile{
Path: subPath,
Size: info.Size(),
Hash: hash,
})
return nil
})
must(err)
return ret
}
func writeStaticFileGo() {
const saveName = "staticfile.go"
files := prepareStaticFiles()
t := template.Must(template.New(saveName).Parse(staticFileTemplate))
var buf bytes.Buffer
t.Execute(&buf, TemplateArg{
StaticFiles: files,
})
fmt.Print(buf.String())
data, err := format.Source(buf.Bytes())
must(err)
err = ioutil.WriteFile(path.Join(benchDir, saveName), data, 0644)
must(err)
log.Println("save", saveName)
}
func main() {
flag.Parse()
publicDir, err := filepath.Abs(publicDir)
must(err)
if !strings.HasSuffix(publicDir, "/public") {
log.Fatalln("invalid publicdir path")
}
benchDir, err := filepath.Abs(benchDir)
must(err)
if !strings.HasSuffix(benchDir, "src/bench") {
log.Fatalln("invalid benchdir path")
}
writeStaticFileGo()
}