You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

generate-bindata.go 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Copyright 2020 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. //go:build ignore
  4. package main
  5. import (
  6. "bytes"
  7. "crypto/sha1"
  8. "fmt"
  9. "log"
  10. "net/http"
  11. "os"
  12. "path/filepath"
  13. "strconv"
  14. "github.com/shurcooL/vfsgen"
  15. )
  16. func needsUpdate(dir, filename string) (bool, []byte) {
  17. needRegen := false
  18. _, err := os.Stat(filename)
  19. if err != nil {
  20. needRegen = true
  21. }
  22. oldHash, err := os.ReadFile(filename + ".hash")
  23. if err != nil {
  24. oldHash = []byte{}
  25. }
  26. hasher := sha1.New()
  27. err = filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error {
  28. if err != nil {
  29. return err
  30. }
  31. info, err := d.Info()
  32. if err != nil {
  33. return err
  34. }
  35. _, _ = hasher.Write([]byte(d.Name()))
  36. _, _ = hasher.Write([]byte(info.ModTime().String()))
  37. _, _ = hasher.Write([]byte(strconv.FormatInt(info.Size(), 16)))
  38. return nil
  39. })
  40. if err != nil {
  41. return true, oldHash
  42. }
  43. newHash := hasher.Sum([]byte{})
  44. if bytes.Compare(oldHash, newHash) != 0 {
  45. return true, newHash
  46. }
  47. return needRegen, newHash
  48. }
  49. func main() {
  50. if len(os.Args) < 4 {
  51. log.Fatal("Insufficient number of arguments. Need: directory packageName filename")
  52. }
  53. dir, packageName, filename := os.Args[1], os.Args[2], os.Args[3]
  54. var useGlobalModTime bool
  55. if len(os.Args) == 5 {
  56. useGlobalModTime, _ = strconv.ParseBool(os.Args[4])
  57. }
  58. update, newHash := needsUpdate(dir, filename)
  59. if !update {
  60. fmt.Printf("bindata for %s already up-to-date\n", packageName)
  61. return
  62. }
  63. fmt.Printf("generating bindata for %s\n", packageName)
  64. var fsTemplates http.FileSystem = http.Dir(dir)
  65. err := vfsgen.Generate(fsTemplates, vfsgen.Options{
  66. PackageName: packageName,
  67. BuildTags: "bindata",
  68. VariableName: "Assets",
  69. Filename: filename,
  70. UseGlobalModTime: useGlobalModTime,
  71. })
  72. if err != nil {
  73. log.Fatalf("%v\n", err)
  74. }
  75. _ = os.WriteFile(filename+".hash", newHash, 0o666)
  76. }