gen.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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))
  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. // it does not work
  55. format(dir)
  56. createGoModFileIfNeed(dir)
  57. if err := backupAndSweep(apiFile); err != nil {
  58. return err
  59. }
  60. if err = apiformat.ApiFormat(apiFile, false); err != nil {
  61. return err
  62. }
  63. fmt.Println(aurora.Green("Done."))
  64. return nil
  65. }
  66. func backupAndSweep(apiFile string) error {
  67. var err error
  68. var wg sync.WaitGroup
  69. wg.Add(2)
  70. _ = os.MkdirAll(tmpDir, os.ModePerm)
  71. go func() {
  72. _, fileName := filepath.Split(apiFile)
  73. _, e := apiutil.Copy(apiFile, fmt.Sprintf(path.Join(tmpDir, tmpFile), fileName, time.Now().Unix()))
  74. if e != nil {
  75. err = e
  76. }
  77. wg.Done()
  78. }()
  79. go func() {
  80. if e := sweep(); e != nil {
  81. err = e
  82. }
  83. wg.Done()
  84. }()
  85. wg.Wait()
  86. return err
  87. }
  88. func format(dir string) {
  89. cmd := exec.Command("go", "fmt", "./"+dir+"...")
  90. _, err := cmd.CombinedOutput()
  91. if err != nil {
  92. fmt.Println(err.Error())
  93. }
  94. }
  95. func sweep() error {
  96. keepTime := time.Now().AddDate(0, 0, -7)
  97. return filepath.Walk(tmpDir, func(fpath string, info os.FileInfo, err error) error {
  98. if info.IsDir() {
  99. return nil
  100. }
  101. pos := strings.LastIndexByte(info.Name(), '-')
  102. if pos > 0 {
  103. timestamp := info.Name()[pos+1:]
  104. seconds, err := strconv.ParseInt(timestamp, 10, 64)
  105. if err != nil {
  106. // print error and ignore
  107. fmt.Println(aurora.Red(fmt.Sprintf("sweep ignored file: %s", fpath)))
  108. return nil
  109. }
  110. tm := time.Unix(seconds, 0)
  111. if tm.Before(keepTime) {
  112. if err := os.Remove(fpath); err != nil {
  113. fmt.Println(aurora.Red(fmt.Sprintf("failed to remove file: %s", fpath)))
  114. return err
  115. }
  116. }
  117. }
  118. return nil
  119. })
  120. }
  121. func createGoModFileIfNeed(dir string) {
  122. absDir, err := filepath.Abs(dir)
  123. if err != nil {
  124. panic(err)
  125. }
  126. _, hasGoMod := util.FindGoModPath(dir)
  127. if hasGoMod {
  128. return
  129. }
  130. gopath := os.Getenv("GOPATH")
  131. parent := path.Join(gopath, "src")
  132. pos := strings.Index(absDir, parent)
  133. if pos >= 0 {
  134. return
  135. }
  136. moduleName := absDir[len(filepath.Dir(absDir))+1:]
  137. cmd := exec.Command("go", "mod", "init", moduleName)
  138. cmd.Dir = dir
  139. var stdout, stderr bytes.Buffer
  140. cmd.Stdout = &stdout
  141. cmd.Stderr = &stderr
  142. if err = cmd.Run(); err != nil {
  143. fmt.Println(err.Error())
  144. }
  145. outStr, errStr := string(stdout.Bytes()), string(stderr.Bytes())
  146. fmt.Printf(outStr + "\n" + errStr)
  147. }