genassets.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 https://mozilla.org/MPL/2.0/.
  6. // +build ignore
  7. package main
  8. import (
  9. "bytes"
  10. "compress/gzip"
  11. "flag"
  12. "fmt"
  13. "go/format"
  14. "io"
  15. "os"
  16. "path/filepath"
  17. "strings"
  18. "text/template"
  19. "time"
  20. )
  21. var tpl = template.Must(template.New("assets").Parse(`package auto
  22. const Generated int64 = {{.Generated}}
  23. func Assets() map[string][]byte {
  24. var assets = make(map[string][]byte, {{.Assets | len}})
  25. {{range $asset := .Assets}}
  26. assets["{{$asset.Name}}"] = {{$asset.Data}}{{end}}
  27. return assets
  28. }
  29. `))
  30. type asset struct {
  31. Name string
  32. Data string
  33. }
  34. var assets []asset
  35. func walkerFor(basePath string) filepath.WalkFunc {
  36. return func(name string, info os.FileInfo, err error) error {
  37. if err != nil {
  38. return err
  39. }
  40. if strings.HasPrefix(filepath.Base(name), ".") {
  41. // Skip dotfiles
  42. return nil
  43. }
  44. if info.Mode().IsRegular() {
  45. fd, err := os.Open(name)
  46. if err != nil {
  47. return err
  48. }
  49. var buf bytes.Buffer
  50. gw := gzip.NewWriter(&buf)
  51. io.Copy(gw, fd)
  52. fd.Close()
  53. gw.Flush()
  54. gw.Close()
  55. name, _ = filepath.Rel(basePath, name)
  56. assets = append(assets, asset{
  57. Name: filepath.ToSlash(name),
  58. Data: fmt.Sprintf("%#v", buf.Bytes()), // "[]byte{0x00, 0x01, ...}"
  59. })
  60. }
  61. return nil
  62. }
  63. }
  64. type templateVars struct {
  65. Assets []asset
  66. Generated int64
  67. }
  68. func main() {
  69. flag.Parse()
  70. filepath.Walk(flag.Arg(0), walkerFor(flag.Arg(0)))
  71. var buf bytes.Buffer
  72. tpl.Execute(&buf, templateVars{
  73. Assets: assets,
  74. Generated: time.Now().Unix(),
  75. })
  76. bs, err := format.Source(buf.Bytes())
  77. if err != nil {
  78. panic(err)
  79. }
  80. os.Stdout.Write(bs)
  81. }