lib/assets: Allow assets to remain uncompressed (#6661)

This commit is contained in:
greatroar
2020-05-25 08:51:27 +02:00
committed by GitHub
parent c3b5eba205
commit baa38eea7a
8 changed files with 104 additions and 49 deletions
+40 -14
View File
@@ -15,6 +15,7 @@ import (
"fmt"
"go/format"
"io"
"io/ioutil"
"os"
"path/filepath"
"strconv"
@@ -27,20 +28,35 @@ var tpl = template.Must(template.New("assets").Parse(`// Code generated by genas
package auto
const Generated int64 = {{.Generated}}
import (
"time"
"github.com/syncthing/syncthing/lib/assets"
)
func Assets() map[string]assets.Asset {
var ret = make(map[string]assets.Asset, {{.Assets | len}})
t := time.Unix({{.Generated}}, 0)
func Assets() map[string]string {
var assets = make(map[string]string, {{.Assets | len}})
{{range $asset := .Assets}}
assets["{{$asset.Name}}"] = {{$asset.Data}}{{end}}
return assets
ret["{{$asset.Name}}"] = assets.Asset{
Content: {{$asset.Data}},
Gzipped: {{$asset.Gzipped}},
Length: {{$asset.Length}},
Filename: {{$asset.Name | printf "%q"}},
Modified: t,
}
{{end}}
return ret
}
`))
type asset struct {
Name string
Data string
Name string
Data string
Length int
Gzipped bool
}
var assets []asset
@@ -57,22 +73,32 @@ func walkerFor(basePath string) filepath.WalkFunc {
}
if info.Mode().IsRegular() {
fd, err := os.Open(name)
data, err := ioutil.ReadFile(name)
if err != nil {
return err
}
length := len(data)
var buf bytes.Buffer
gw := gzip.NewWriter(&buf)
io.Copy(gw, fd)
fd.Close()
gw.Flush()
gw, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression)
gw.Write(data)
gw.Close()
// Only replace asset by gzipped version if it is smaller.
// In practice, this means HTML, CSS, SVG etc. get compressed,
// while PNG and WOFF files are left uncompressed.
// lib/assets detects gzip and sets headers/decompresses.
gzipped := buf.Len() < len(data)
if gzipped {
data = buf.Bytes()
}
name, _ = filepath.Rel(basePath, name)
assets = append(assets, asset{
Name: filepath.ToSlash(name),
Data: fmt.Sprintf("%q", buf.String()),
Name: filepath.ToSlash(name),
Data: fmt.Sprintf("%q", string(data)),
Length: length,
Gzipped: gzipped,
})
}