gen.go 3.4 KB

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