Faster and more portable assets generator

This commit is contained in:
Jakob Borg 2014-03-17 22:56:07 +01:00
parent ef8cf3bc30
commit 222272b75c
3 changed files with 87 additions and 28 deletions

View File

@ -1,27 +0,0 @@
#!/usr/bin/env bash
cat <<EOT
package auto
import "compress/gzip"
import "bytes"
import "io/ioutil"
var Assets = make(map[string][]byte)
func init() {
var data []byte
var gr *gzip.Reader
EOT
cd gui
for f in $(find . -type f) ; do
f="${f#./}"
echo "gr, _ = gzip.NewReader(bytes.NewBuffer([]byte{"
gzip -n -c $f | od -vt x1 | sed 's/^[0-9a-f]*//' | sed 's/\([0-9a-f][0-9a-f]\)/0x\1,/g'
echo "}))"
echo "data, _ = ioutil.ReadAll(gr)"
echo "Assets[\"$f\"] = data"
done
echo "}"

View File

@ -10,7 +10,7 @@ build() {
}
prepare() {
./assets.sh | gofmt > auto/gui.files.go
go run cmd/assets/assets.go gui > auto/gui.files.go
go get -d
}

86
cmd/assets/assets.go Normal file
View File

@ -0,0 +1,86 @@
package main
import (
"bytes"
"compress/gzip"
"flag"
"fmt"
"go/format"
"io"
"os"
"path/filepath"
"text/template"
)
var tpl = template.Must(template.New("assets").Parse(`package auto
import (
"bytes"
"compress/gzip"
"encoding/hex"
"io/ioutil"
)
var Assets = make(map[string][]byte)
func init() {
var bs []byte
var gr *gzip.Reader
{{range $asset := .assets}}
bs, _ = hex.DecodeString("{{$asset.HexData}}")
gr, _ = gzip.NewReader(bytes.NewBuffer(bs))
bs, _ = ioutil.ReadAll(gr)
Assets["{{$asset.Name}}"] = bs
{{end}}
}
`))
type asset struct {
Name string
HexData string
}
var assets []asset
func walkerFor(basePath string) filepath.WalkFunc {
return func(name string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.Mode().IsRegular() {
fd, err := os.Open(name)
if err != nil {
return err
}
var buf bytes.Buffer
gw := gzip.NewWriter(&buf)
io.Copy(gw, fd)
fd.Close()
gw.Flush()
gw.Close()
name, _ = filepath.Rel(basePath, name)
assets = append(assets, asset{
Name: name,
HexData: fmt.Sprintf("%x", buf.Bytes()),
})
}
return nil
}
}
func main() {
flag.Parse()
filepath.Walk(flag.Arg(0), walkerFor(flag.Arg(0)))
var buf bytes.Buffer
tpl.Execute(&buf, map[string][]asset{"assets": assets})
bs, err := format.Source(buf.Bytes())
if err != nil {
panic(err)
}
os.Stdout.Write(bs)
}