genassets.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. // +build ignore
  7. package main
  8. import (
  9. "bytes"
  10. "compress/gzip"
  11. "encoding/base64"
  12. "flag"
  13. "go/format"
  14. "io"
  15. "net/http"
  16. "os"
  17. "path/filepath"
  18. "strings"
  19. "text/template"
  20. "time"
  21. )
  22. var tpl = template.Must(template.New("assets").Parse(`package auto
  23. import (
  24. "encoding/base64"
  25. )
  26. const (
  27. AssetsBuildDate = "{{.BuildDate}}"
  28. )
  29. func Assets() map[string][]byte {
  30. var assets = make(map[string][]byte, {{.Assets | len}})
  31. {{range $asset := .Assets}}
  32. assets["{{$asset.Name}}"], _ = base64.StdEncoding.DecodeString("{{$asset.Data}}"){{end}}
  33. return assets
  34. }
  35. `))
  36. type asset struct {
  37. Name string
  38. Data string
  39. }
  40. var assets []asset
  41. func walkerFor(basePath string) filepath.WalkFunc {
  42. return func(name string, info os.FileInfo, err error) error {
  43. if err != nil {
  44. return err
  45. }
  46. if strings.HasPrefix(filepath.Base(name), ".") {
  47. // Skip dotfiles
  48. return nil
  49. }
  50. if info.Mode().IsRegular() {
  51. fd, err := os.Open(name)
  52. if err != nil {
  53. return err
  54. }
  55. var buf bytes.Buffer
  56. gw := gzip.NewWriter(&buf)
  57. io.Copy(gw, fd)
  58. fd.Close()
  59. gw.Flush()
  60. gw.Close()
  61. name, _ = filepath.Rel(basePath, name)
  62. assets = append(assets, asset{
  63. Name: filepath.ToSlash(name),
  64. Data: base64.StdEncoding.EncodeToString(buf.Bytes()),
  65. })
  66. }
  67. return nil
  68. }
  69. }
  70. type templateVars struct {
  71. Assets []asset
  72. BuildDate string
  73. }
  74. func main() {
  75. flag.Parse()
  76. filepath.Walk(flag.Arg(0), walkerFor(flag.Arg(0)))
  77. var buf bytes.Buffer
  78. tpl.Execute(&buf, templateVars{
  79. Assets: assets,
  80. BuildDate: time.Now().UTC().Format(http.TimeFormat),
  81. })
  82. bs, err := format.Source(buf.Bytes())
  83. if err != nil {
  84. panic(err)
  85. }
  86. os.Stdout.Write(bs)
  87. }