util.go 2.2 KB

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