-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
176 lines (145 loc) · 3.92 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
package main
import (
"bytes"
"flag"
"fmt"
"go/format"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"text/template"
)
//定义命令行参数方式1
var blobFileName string
var embedFolder string
func Init() {
flag.StringVar(&blobFileName, "o", "box_blob.go", "out file name")
flag.StringVar(&embedFolder, "d", "static", "directory to pack")
flag.Parse()
pwd, _ := os.Getwd()
fmt.Println("pwd: ", pwd)
fmt.Println("out file name: " + blobFileName + ", directory to pack: " + embedFolder)
}
var conv = map[string]interface{}{"conv": fmtByteSlice}
var tmplBlob = template.Must(template.New("").Funcs(conv).Parse(`
// Code generated by go generate; DO NOT EDIT.
// +build !codeanalysis
package {{.pkg}}
func init() {
{{- range $name, $file := .configs }}
box.Add("{{ $name }}", []byte{ {{ conv $file }} })
{{- end }}
}`),
)
var tmpl = template.Must(template.New("").Funcs(conv).Parse(`
// Code generated by go generate; DO NOT EDIT.
package {{.pkg}}
type embedBox struct {
storage map[string][]byte
}
// Create new box for embed files
func newEmbedBox() *embedBox {
return &embedBox{storage: make(map[string][]byte)}
}
// Add a file to box
func (e *embedBox) Add(file string, content []byte) {
e.storage[file] = content
}
// Get file's content
// Always use / for looking up
// For example: /init/README.md is actually configs/init/README.md
func (e *embedBox) Get(file string) []byte {
if f, ok := e.storage[file]; ok {
return f
}
return nil
}
// Find for a file
func (e *embedBox) Has(file string) bool {
if _, ok := e.storage[file]; ok {
return true
}
return false
}
// Return inner storage
func (e *embedBox) Map() map[string][]byte {
return e.storage
}
// Embed box expose
var box = newEmbedBox()
`),
)
func fmtByteSlice(s []byte) string {
builder := strings.Builder{}
for _, v := range s {
builder.WriteString(fmt.Sprintf("%d,", int(v)))
}
return builder.String()
}
func main() {
Init()
// Checking directory with files
if _, err := os.Stat(embedFolder); os.IsNotExist(err) {
log.Fatalf("Static directory:%s does not exists!", embedFolder)
}
// Create map for filenames
configs := make(map[string][]byte)
infos := make(map[string]interface{})
infos["pkg"] = os.Getenv("GOPACKAGE")
if infos["pkg"] == "" {
infos["pkg"] = "main"
}
infos["configs"] = configs
// Walking through embed directory
err := filepath.Walk(embedFolder, func(path string, info os.FileInfo, err error) error {
relativePath := filepath.ToSlash(strings.TrimPrefix(path, embedFolder))
if info.IsDir() {
// Skip directories
log.Println(path, "is a directory, skipping...")
return nil
} else {
// If element is a simple file, embed
log.Println(path, "is a file, packing in...")
b, err := ioutil.ReadFile(path)
if err != nil {
// If file not reading
log.Printf("Error reading %s: %s", path, err)
return err
}
// Add file name to map
configs[relativePath] = b
}
return nil
})
if err != nil {
log.Fatal("Error walking through embed directory:", err)
}
// Create buffer
builderBox := &bytes.Buffer{}
builderBoxBlob := &bytes.Buffer{}
// Execute template
if err = tmpl.Execute(builderBox, infos); err != nil {
log.Fatal("Error executing template", err)
}
if err = tmplBlob.Execute(builderBoxBlob, infos); err != nil {
log.Fatal("Error executing template", err)
}
// Formatting generated code
data, err := format.Source(builderBox.Bytes())
if err != nil {
log.Fatal("Error formatting generated code", err)
}
// Writing blob file
if err = ioutil.WriteFile(blobFileName, data, os.ModePerm); err != nil {
log.Fatal("Error writing blob file", err)
}
dataBlob, err := format.Source(builderBoxBlob.Bytes())
if err != nil {
log.Fatal("Error formatting generated code", err)
}
if err = ioutil.WriteFile(strings.TrimSuffix(filepath.Base(blobFileName), filepath.Ext(blobFileName))+"_blob.go", dataBlob, os.ModePerm); err != nil {
log.Fatal("Error writing blob file", err)
}
}