main.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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}}")
  33. {{end}}
  34. return assets
  35. }
  36. `))
  37. type asset struct {
  38. Name string
  39. Data string
  40. }
  41. var assets []asset
  42. func walkerFor(basePath string) filepath.WalkFunc {
  43. return func(name string, info os.FileInfo, err error) error {
  44. if err != nil {
  45. return err
  46. }
  47. if strings.HasPrefix(filepath.Base(name), ".") {
  48. // Skip dotfiles
  49. return nil
  50. }
  51. if info.Mode().IsRegular() {
  52. fd, err := os.Open(name)
  53. if err != nil {
  54. return err
  55. }
  56. var buf bytes.Buffer
  57. gw := gzip.NewWriter(&buf)
  58. io.Copy(gw, fd)
  59. fd.Close()
  60. gw.Flush()
  61. gw.Close()
  62. name, _ = filepath.Rel(basePath, name)
  63. assets = append(assets, asset{
  64. Name: filepath.ToSlash(name),
  65. Data: base64.StdEncoding.EncodeToString(buf.Bytes()),
  66. })
  67. }
  68. return nil
  69. }
  70. }
  71. type templateVars struct {
  72. Assets []asset
  73. BuildDate string
  74. }
  75. func main() {
  76. flag.Parse()
  77. filepath.Walk(flag.Arg(0), walkerFor(flag.Arg(0)))
  78. var buf bytes.Buffer
  79. tpl.Execute(&buf, templateVars{
  80. Assets: assets,
  81. BuildDate: time.Now().UTC().Format(http.TimeFormat),
  82. })
  83. bs, err := format.Source(buf.Bytes())
  84. if err != nil {
  85. panic(err)
  86. }
  87. os.Stdout.Write(bs)
  88. }