gen.go 3.6 KB

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