util.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package gogen
  2. import (
  3. "fmt"
  4. goformat "go/format"
  5. "io"
  6. "os"
  7. "path"
  8. "path/filepath"
  9. "strings"
  10. "github.com/tal-tech/go-zero/core/collection"
  11. "github.com/tal-tech/go-zero/tools/goctl/api/spec"
  12. "github.com/tal-tech/go-zero/tools/goctl/api/util"
  13. goctlutil "github.com/tal-tech/go-zero/tools/goctl/util"
  14. )
  15. const goModeIdentifier = "go.mod"
  16. func getParentPackage(dir string) (string, error) {
  17. absDir, err := filepath.Abs(dir)
  18. if err != nil {
  19. return "", err
  20. }
  21. absDir = strings.ReplaceAll(absDir, `\`, `/`)
  22. var rootPath string
  23. var tempPath = absDir
  24. var hasGoMod = false
  25. for {
  26. tempPath = filepath.Dir(tempPath)
  27. if goctlutil.FileExists(filepath.Join(tempPath, goModeIdentifier)) {
  28. tempPath = filepath.Dir(tempPath)
  29. rootPath = absDir[len(tempPath)+1:]
  30. hasGoMod = true
  31. break
  32. }
  33. if tempPath == string(filepath.Separator) {
  34. break
  35. }
  36. }
  37. if !hasGoMod {
  38. gopath := os.Getenv("GOPATH")
  39. parent := path.Join(gopath, "src")
  40. pos := strings.Index(absDir, parent)
  41. if pos < 0 {
  42. message := fmt.Sprintf("%s not in gomod project path, or not in GOPATH of %s directory", absDir, gopath)
  43. println(message)
  44. tempPath = filepath.Dir(absDir)
  45. rootPath = absDir[len(tempPath)+1:]
  46. } else {
  47. rootPath = absDir[len(parent)+1:]
  48. }
  49. }
  50. return rootPath, nil
  51. }
  52. func writeIndent(writer io.Writer, indent int) {
  53. for i := 0; i < indent; i++ {
  54. fmt.Fprint(writer, "\t")
  55. }
  56. }
  57. func writeProperty(writer io.Writer, name, tp, tag, comment string, indent int) error {
  58. writeIndent(writer, indent)
  59. var err error
  60. if len(comment) > 0 {
  61. comment = strings.TrimPrefix(comment, "//")
  62. comment = "//" + comment
  63. _, err = fmt.Fprintf(writer, "%s %s %s %s\n", strings.Title(name), tp, tag, comment)
  64. } else {
  65. _, err = fmt.Fprintf(writer, "%s %s %s\n", strings.Title(name), tp, tag)
  66. }
  67. return err
  68. }
  69. func getAuths(api *spec.ApiSpec) []string {
  70. var authNames = collection.NewSet()
  71. for _, g := range api.Service.Groups {
  72. if value, ok := util.GetAnnotationValue(g.Annotations, "server", "jwt"); ok {
  73. authNames.Add(value)
  74. }
  75. if value, ok := util.GetAnnotationValue(g.Annotations, "server", "signature"); ok {
  76. authNames.Add(value)
  77. }
  78. }
  79. return authNames.KeysStr()
  80. }
  81. func formatCode(code string) string {
  82. ret, err := goformat.Source([]byte(code))
  83. if err != nil {
  84. return code
  85. }
  86. return string(ret)
  87. }