1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- package main
- import (
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "io/fs"
- "log"
- "os"
- "os/exec"
- "path"
- "runtime"
- "strings"
- )
- type VersionInfo struct {
- Version string `json:"version"`
- BuildId int `json:"build_id"`
- TotalBuild int `json:"total_build"`
- }
- func main() {
- _, file, _, ok := runtime.Caller(0)
- if !ok {
- log.Print("Unable to get the current file")
- return
- }
- basePath := path.Join(path.Dir(file), "../../")
- versionFile, err := os.Open(path.Join(basePath, "app/dist/version.json"))
- if err != nil {
- if errors.Is(err, fs.ErrNotExist) {
- log.Print("\"dist/version.json\" not found, load from src instead")
- versionFile, err = os.Open(path.Join(basePath, "app/src/version.json"))
- }
- if err != nil {
- log.Fatal(err)
- return
- }
- }
- defer func(versionFile fs.File) {
- err := versionFile.Close()
- if err != nil {
- log.Fatal(err)
- }
- }(versionFile)
- // Read the version.json file
- data, err := io.ReadAll(versionFile)
- if err != nil {
- log.Fatalf("Failed to read version.json: %v", err)
- }
- // Parse the JSON data
- var versionInfo VersionInfo
- err = json.Unmarshal(data, &versionInfo)
- if err != nil {
- log.Fatalf("Failed to parse JSON: %v", err)
- }
- // get current git commit hash
- cmd := exec.Command("git", "-C", basePath, "rev-parse", "HEAD")
- commitHash, err := cmd.Output()
- if err != nil {
- log.Printf("Failed to get git commit hash: %v", err)
- commitHash = []byte("")
- }
- // Generate the version.gen.go file content
- genContent := fmt.Sprintf(`// Code generated by cmd/version/generate.go; DO NOT EDIT.
- package version
- func init() {
- Version = "%s"
- BuildId = %d
- TotalBuild = %d
- Hash = "%s"
- }
- `, versionInfo.Version, versionInfo.BuildId, versionInfo.TotalBuild, strings.TrimRight(string(commitHash), "\r\n"))
- genPath := path.Join(basePath, "internal/version/version.gen.go")
- err = os.WriteFile(genPath, []byte(genContent), 0644)
- if err != nil {
- log.Fatalf("Failed to write version.gen.go: %v", err)
- }
- fmt.Println("version.gen.go has been generated successfully.")
- }
|