-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
114 lines (92 loc) · 2.05 KB
/
main.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
package main
import (
"bytes"
"compress/gzip"
"encoding/base64"
"io"
"log"
"os"
"path/filepath"
"strings"
"text/template"
)
type templateInfo struct {
PackageName string
Filename string
Contexts []context
}
type context struct {
Source string
Name string
tpl string
}
func (c context) Tpl() string {
return "`" + c.tpl + "`"
}
const _template = `// Code generated by Embedder. DO NOT EDIT.
package {{ .PackageName }}
{{ if .Contexts -}}
const (
{{- range .Contexts }}
// Source: {{ .Source }}
{{ .Name }} = {{ .Tpl }}
{{- end }}
)
{{- end }}
`
func main() {
if len(os.Args) < 4 {
log.Fatal("Args Usage: DestPackageName, DestFilename, GlobPattern...")
}
info := &templateInfo{
PackageName: os.Args[1],
Filename: os.Args[2],
}
for _, match := range getMatchesFromPattern(os.Args[3:]) {
processMatch(info, match)
}
destFile, err := os.Create(info.Filename)
checkErr(err)
defer destFile.Close()
template.Must(template.New("tpl").Parse(_template)).Execute(destFile, info)
}
func checkErr(err error) {
if err != nil {
log.Panic(err)
}
}
func getMatchesFromPattern(patterns []string) (matches []string) {
for _, pattern := range patterns {
_matches, err := filepath.Glob(pattern)
checkErr(err)
matches = append(matches, _matches...)
}
return
}
func processMatch(packageName *templateInfo, match string) {
name := strings.Title(strings.Split(filepath.Base(match), ".")[0])
sourcefile, err := os.Open(match)
checkErr(err)
defer sourcefile.Close()
buf := &bytes.Buffer{}
w, err := gzip.NewWriterLevel(buf, gzip.BestCompression)
checkErr(err)
_, err = io.Copy(w, sourcefile)
checkErr(err)
w.Close()
packageName.Contexts = append(packageName.Contexts, context{
Source: strings.Replace(match, "\\", "/", -1),
Name: name,
tpl: strings.Join(split(base64.StdEncoding.EncodeToString(buf.Bytes()), 76), "\n"),
})
}
func split(s string, size int) []string {
ss := make([]string, 0, len(s)/size+1)
for len(s) > 0 {
if len(s) < size {
size = len(s)
}
ss, s = append(ss, s[:size]), s[size:]
}
return ss
}