genassets.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. "os"
  16. "path/filepath"
  17. "strings"
  18. "text/template"
  19. )
  20. var tpl = template.Must(template.New("assets").Parse(`package auto
  21. import (
  22. "encoding/base64"
  23. )
  24. func Assets() map[string][]byte {
  25. var assets = make(map[string][]byte, {{.Assets | len}})
  26. {{range $asset := .Assets}}
  27. assets["{{$asset.Name}}"], _ = base64.StdEncoding.DecodeString("{{$asset.Data}}"){{end}}
  28. return assets
  29. }
  30. `))
  31. type asset struct {
  32. Name string
  33. Data string
  34. }
  35. var assets []asset
  36. func walkerFor(basePath string) filepath.WalkFunc {
  37. return func(name string, info os.FileInfo, err error) error {
  38. if err != nil {
  39. return err
  40. }
  41. if strings.HasPrefix(filepath.Base(name), ".") {
  42. // Skip dotfiles
  43. return nil
  44. }
  45. if info.Mode().IsRegular() {
  46. fd, err := os.Open(name)
  47. if err != nil {
  48. return err
  49. }
  50. var buf bytes.Buffer
  51. gw := gzip.NewWriter(&buf)
  52. io.Copy(gw, fd)
  53. fd.Close()
  54. gw.Flush()
  55. gw.Close()
  56. name, _ = filepath.Rel(basePath, name)
  57. assets = append(assets, asset{
  58. Name: filepath.ToSlash(name),
  59. Data: base64.StdEncoding.EncodeToString(buf.Bytes()),
  60. })
  61. }
  62. return nil
  63. }
  64. }
  65. type templateVars struct {
  66. Assets []asset
  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. })
  75. bs, err := format.Source(buf.Bytes())
  76. if err != nil {
  77. panic(err)
  78. }
  79. os.Stdout.Write(bs)
  80. }