genassets.go 1.7 KB

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