-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
258 lines (221 loc) · 5.29 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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
package main
import (
"bytes"
"compress/gzip"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"text/template"
flag "github.com/spf13/pflag"
)
var (
pkg = flag.StringP("package", "p", "main", "Package name")
output = flag.StringP("output", "o", "assets.go", "Output file")
prefix = flag.StringP("trim", "t", "", "Trim file prefix")
omitWrite = flag.Bool("omit-write", false, "Disable write access (not generated)")
)
func main() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s [flags] ASSETS [ASSETS ...] \n", os.Args[0])
flag.PrintDefaults()
}
flag.ErrHelp = fmt.Errorf("")
flag.Parse()
assets := flag.Args()
logger := log.New(os.Stdout, "", log.Ldate|log.Ltime|log.Lmicroseconds)
// Check output file
if *output == "" {
log.Fatal("invalid output file")
}
// Check for assets
if len(assets) == 0 {
log.Fatal("no assets provided")
}
// Create new template and parse
tmpl := template.New("")
tmpl = tmpl.Funcs(template.FuncMap{"StringsJoin": strings.Join})
tmpl, err := tmpl.Parse(assetTemplate)
if err != nil {
log.Fatal(err)
}
// Execute template
content := Content{
PackageName: *pkg,
Assets: readAssets(logger, assets),
OmitWrite: *omitWrite,
}
// Execute template
var buf bytes.Buffer
if err := tmpl.Execute(&buf, content); err != nil {
log.Fatal(err)
}
log.Println(fmt.Sprintf("Preformatted file size: %d", buf.Len()))
// Open output file
fh, err := os.Create(*output)
if err != nil {
log.Fatal(err)
}
defer fh.Close()
// Format generated code into output file
cmd := exec.Command("gofmt")
cmd.Stdin = &buf
cmd.Stdout = fh
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
}
// Content represents the content stored in the template.
type Content struct {
OmitWrite bool
PackageName string
Assets []Asset
}
// Asset represents file asset.
type Asset struct {
AssetID string
Name string
FileParts []string
}
func readAssets(logger *log.Logger, files []string) []Asset {
var index int
var fileparts []Asset
for _, glob := range files {
matches, err := filepath.Glob(glob)
if err != nil {
log.Fatal(err)
}
for _, file := range matches {
// Skip directories
stat, err := os.Stat(file)
if stat.IsDir() {
continue
} else if err != nil {
log.Fatal(err)
}
// logger.Println(file)
parts, err := readParts(logger, file)
if err != nil {
log.Fatal(err)
}
logger.Println(fmt.Sprintf("File: %s, Parts: %d", file, len(parts)))
fileparts = append(fileparts, Asset{
AssetID: fmt.Sprintf("asset%04d", index),
Name: strings.TrimPrefix(file, *prefix),
FileParts: parts,
})
index++
}
}
if index == 0 {
logger.Fatal("no assets found")
}
return fileparts
}
func readParts(logger *log.Logger, filename string) ([]string, error) {
// Open file
fh, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
defer fh.Close()
// Read file
content, err := ioutil.ReadAll(fh)
if err != nil {
return nil, err
}
// Compress file
var buf bytes.Buffer
writer := gzip.NewWriter(&buf)
writer.Write(content)
writer.Flush()
writer.Close()
// Read parts
var parts []string
data := make([]byte, 80)
partReader := strings.NewReader(base64.StdEncoding.EncodeToString(buf.Bytes()))
for {
n, err := partReader.Read(data)
if n > 0 {
parts = append(parts, string(data[:n]))
} else if n == 0 || err == io.EOF {
break
} else {
return nil, err
}
}
return parts, nil
}
var assetTemplate = `// Code generated by simpleassets DO NOT EDIT.
package {{.PackageName}}
import (
"bytes"
"compress/gzip"
"encoding/base64"
"fmt"
"io/ioutil"
"strings"
)
// Asset stores the file data.
type Asset struct {
Name string
Compressed bool
Data string
}
// Stored assets by filename
var assets = map[string]Asset{}
// ReadAsset reads an asset from the store.
func ReadAsset(name string) ([]byte, error) {
// Get asset from map and verify
asset, ok := assets[name]
if !ok {
return nil, fmt.Errorf("asset does not exist: %s", name)
}
// Decode base64
decoded, err := base64.StdEncoding.DecodeString(asset.Data)
if err != nil {
return nil, err
}
// Decompress if required
if asset.Compressed {
reader, err := gzip.NewReader(bytes.NewReader(decoded))
if err != nil {
return nil, err
}
return ioutil.ReadAll(reader)
}
return decoded, nil
}
{{ if not .OmitWrite}}
// WriteAsset writes an asset to the store.
func WriteAsset(name string, data []byte) {
encoded := base64.StdEncoding.EncodeToString([]byte(data))
// Add to list of asset names if needed
if _, ok := assets[name]; !ok {
assetNames = append(assetNames, name)
}
// Store assset
assets[name] = Asset{Name: name, Compressed: false, Data: encoded}
}{{end}}
// List of asset names
var assetNames = []string{ {{ range $index, $element := .Assets}}
"{{$element.Name}}",{{end}}
}
// ListAssetNames returns the list of asset names
func ListAssetNames() []string {
return assetNames
}
func init() { {{ range $index, $element := .Assets}}
assets["{{$element.Name}}"] = Asset{ Name: "{{$element.Name}}", Compressed: true, Data: {{$element.AssetID}}} {{end}}
}
{{ range $index, $element := .Assets}}
var {{$element.AssetID}} = strings.Join([]string{ {{ range $partindex, $part := $element.FileParts }}
"{{$part}}",{{end}}
}, "")
{{end}}
`