gen.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. package gogen
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "os"
  7. "os/exec"
  8. "path"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/logrusorgru/aurora"
  15. "github.com/urfave/cli"
  16. "github.com/tal-tech/go-zero/core/logx"
  17. apiformat "github.com/tal-tech/go-zero/tools/goctl/api/format"
  18. "github.com/tal-tech/go-zero/tools/goctl/api/parser"
  19. apiutil "github.com/tal-tech/go-zero/tools/goctl/api/util"
  20. "github.com/tal-tech/go-zero/tools/goctl/util"
  21. )
  22. const tmpFile = "%s-%d"
  23. var tmpDir = path.Join(os.TempDir(), "goctl")
  24. func GoCommand(c *cli.Context) error {
  25. apiFile := c.String("api")
  26. dir := c.String("dir")
  27. force := c.Bool("force")
  28. if len(apiFile) == 0 {
  29. return errors.New("missing -api")
  30. }
  31. if len(dir) == 0 {
  32. return errors.New("missing -dir")
  33. }
  34. return DoGenProject(apiFile, dir, force)
  35. }
  36. func DoGenProject(apiFile, dir string, force bool) error {
  37. p, err := parser.NewParser(apiFile)
  38. if err != nil {
  39. return err
  40. }
  41. api, err := p.Parse()
  42. if err != nil {
  43. return err
  44. }
  45. logx.Must(util.MkdirIfNotExist(dir))
  46. logx.Must(genEtc(dir, api))
  47. logx.Must(genConfig(dir, api))
  48. logx.Must(genMain(dir, api))
  49. logx.Must(genServiceContext(dir, api))
  50. logx.Must(genTypes(dir, api, force))
  51. logx.Must(genHandlers(dir, api))
  52. logx.Must(genRoutes(dir, api, force))
  53. logx.Must(genLogic(dir, api))
  54. createGoModFileIfNeed(dir)
  55. if err := backupAndSweep(apiFile); err != nil {
  56. return err
  57. }
  58. if err := apiformat.ApiFormatByPath(apiFile); err != nil {
  59. return err
  60. }
  61. fmt.Println(aurora.Green("Done."))
  62. return nil
  63. }
  64. func backupAndSweep(apiFile string) error {
  65. var err error
  66. var wg sync.WaitGroup
  67. wg.Add(2)
  68. _ = os.MkdirAll(tmpDir, os.ModePerm)
  69. go func() {
  70. _, fileName := filepath.Split(apiFile)
  71. _, e := apiutil.Copy(apiFile, fmt.Sprintf(path.Join(tmpDir, tmpFile), fileName, time.Now().Unix()))
  72. if e != nil {
  73. err = e
  74. }
  75. wg.Done()
  76. }()
  77. go func() {
  78. if e := sweep(); e != nil {
  79. err = e
  80. }
  81. wg.Done()
  82. }()
  83. wg.Wait()
  84. return err
  85. }
  86. func sweep() error {
  87. keepTime := time.Now().AddDate(0, 0, -7)
  88. return filepath.Walk(tmpDir, func(fpath string, info os.FileInfo, err error) error {
  89. if info.IsDir() {
  90. return nil
  91. }
  92. pos := strings.LastIndexByte(info.Name(), '-')
  93. if pos > 0 {
  94. timestamp := info.Name()[pos+1:]
  95. seconds, err := strconv.ParseInt(timestamp, 10, 64)
  96. if err != nil {
  97. // print error and ignore
  98. fmt.Println(aurora.Red(fmt.Sprintf("sweep ignored file: %s", fpath)))
  99. return nil
  100. }
  101. tm := time.Unix(seconds, 0)
  102. if tm.Before(keepTime) {
  103. if err := os.Remove(fpath); err != nil {
  104. fmt.Println(aurora.Red(fmt.Sprintf("failed to remove file: %s", fpath)))
  105. return err
  106. }
  107. }
  108. }
  109. return nil
  110. })
  111. }
  112. func createGoModFileIfNeed(dir string) {
  113. absDir, err := filepath.Abs(dir)
  114. if err != nil {
  115. panic(err)
  116. }
  117. _, hasGoMod := util.FindGoModPath(dir)
  118. if hasGoMod {
  119. return
  120. }
  121. gopath := os.Getenv("GOPATH")
  122. parent := path.Join(gopath, "src")
  123. pos := strings.Index(absDir, parent)
  124. if pos >= 0 {
  125. return
  126. }
  127. moduleName := absDir[len(filepath.Dir(absDir))+1:]
  128. cmd := exec.Command("go", "mod", "init", moduleName)
  129. cmd.Dir = dir
  130. var stdout, stderr bytes.Buffer
  131. cmd.Stdout = &stdout
  132. cmd.Stderr = &stderr
  133. if err = cmd.Run(); err != nil {
  134. fmt.Println(err.Error())
  135. }
  136. outStr, errStr := string(stdout.Bytes()), string(stderr.Bytes())
  137. fmt.Printf(outStr + "\n" + errStr)
  138. }