util.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. if tempPath == filepath.Dir(tempPath) {
  27. break
  28. }
  29. tempPath = filepath.Dir(tempPath)
  30. if goctlutil.FileExists(filepath.Join(tempPath, goModeIdentifier)) {
  31. tempPath = filepath.Dir(tempPath)
  32. rootPath = absDir[len(tempPath)+1:]
  33. hasGoMod = true
  34. break
  35. }
  36. if tempPath == string(filepath.Separator) {
  37. break
  38. }
  39. }
  40. if !hasGoMod {
  41. gopath := os.Getenv("GOPATH")
  42. parent := path.Join(gopath, "src")
  43. pos := strings.Index(absDir, parent)
  44. if pos < 0 {
  45. fmt.Printf("%s not in gomod project path, or not in GOPATH of %s directory\n", absDir, gopath)
  46. tempPath = filepath.Dir(absDir)
  47. rootPath = absDir[len(tempPath)+1:]
  48. } else {
  49. rootPath = absDir[len(parent)+1:]
  50. }
  51. }
  52. return rootPath, nil
  53. }
  54. func writeIndent(writer io.Writer, indent int) {
  55. for i := 0; i < indent; i++ {
  56. fmt.Fprint(writer, "\t")
  57. }
  58. }
  59. func writeProperty(writer io.Writer, name, tp, tag, comment string, indent int) error {
  60. writeIndent(writer, indent)
  61. var err error
  62. if len(comment) > 0 {
  63. comment = strings.TrimPrefix(comment, "//")
  64. comment = "//" + comment
  65. _, err = fmt.Fprintf(writer, "%s %s %s %s\n", strings.Title(name), tp, tag, comment)
  66. } else {
  67. _, err = fmt.Fprintf(writer, "%s %s %s\n", strings.Title(name), tp, tag)
  68. }
  69. return err
  70. }
  71. func getAuths(api *spec.ApiSpec) []string {
  72. var authNames = collection.NewSet()
  73. for _, g := range api.Service.Groups {
  74. if value, ok := util.GetAnnotationValue(g.Annotations, "server", "jwt"); ok {
  75. authNames.Add(value)
  76. }
  77. if value, ok := util.GetAnnotationValue(g.Annotations, "server", "signature"); ok {
  78. authNames.Add(value)
  79. }
  80. }
  81. return authNames.KeysStr()
  82. }
  83. func formatCode(code string) string {
  84. ret, err := goformat.Source([]byte(code))
  85. if err != nil {
  86. return code
  87. }
  88. return string(ret)
  89. }