1
0

generate.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package main
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "io/fs"
  8. "log"
  9. "os"
  10. "os/exec"
  11. "path"
  12. "runtime"
  13. "strings"
  14. )
  15. type VersionInfo struct {
  16. Version string `json:"version"`
  17. BuildId int `json:"build_id"`
  18. TotalBuild int `json:"total_build"`
  19. }
  20. func main() {
  21. _, file, _, ok := runtime.Caller(0)
  22. if !ok {
  23. log.Print("Unable to get the current file")
  24. return
  25. }
  26. basePath := path.Join(path.Dir(file), "../../")
  27. versionFile, err := os.Open(path.Join(basePath, "app/dist/version.json"))
  28. if err != nil {
  29. if errors.Is(err, fs.ErrNotExist) {
  30. log.Print("\"dist/version.json\" not found, load from src instead")
  31. versionFile, err = os.Open(path.Join(basePath, "app/src/version.json"))
  32. }
  33. if err != nil {
  34. log.Fatal(err)
  35. return
  36. }
  37. }
  38. defer func(versionFile fs.File) {
  39. err := versionFile.Close()
  40. if err != nil {
  41. log.Fatal(err)
  42. }
  43. }(versionFile)
  44. // Read the version.json file
  45. data, err := io.ReadAll(versionFile)
  46. if err != nil {
  47. log.Fatalf("Failed to read version.json: %v", err)
  48. }
  49. // Parse the JSON data
  50. var versionInfo VersionInfo
  51. err = json.Unmarshal(data, &versionInfo)
  52. if err != nil {
  53. log.Fatalf("Failed to parse JSON: %v", err)
  54. }
  55. // get current git commit hash
  56. cmd := exec.Command("git", "-C", basePath, "rev-parse", "HEAD")
  57. commitHash, err := cmd.Output()
  58. if err != nil {
  59. log.Printf("Failed to get git commit hash: %v", err)
  60. commitHash = []byte("")
  61. }
  62. // Generate the version.gen.go file content
  63. genContent := fmt.Sprintf(`// Code generated by cmd/version/generate.go; DO NOT EDIT.
  64. package version
  65. func init() {
  66. Version = "%s"
  67. BuildId = %d
  68. TotalBuild = %d
  69. Hash = "%s"
  70. }
  71. `, versionInfo.Version, versionInfo.BuildId, versionInfo.TotalBuild, strings.TrimRight(string(commitHash), "\r\n"))
  72. genPath := path.Join(basePath, "internal/version/version.gen.go")
  73. err = os.WriteFile(genPath, []byte(genContent), 0644)
  74. if err != nil {
  75. log.Fatalf("Failed to write version.gen.go: %v", err)
  76. }
  77. fmt.Println("version.gen.go has been generated successfully.")
  78. }