util.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package gogen
  2. import (
  3. "fmt"
  4. goformat "go/format"
  5. "io"
  6. "path/filepath"
  7. "strings"
  8. "github.com/tal-tech/go-zero/core/collection"
  9. "github.com/tal-tech/go-zero/tools/goctl/api/spec"
  10. "github.com/tal-tech/go-zero/tools/goctl/api/util"
  11. goctlutil "github.com/tal-tech/go-zero/tools/goctl/util"
  12. "github.com/tal-tech/go-zero/tools/goctl/util/project"
  13. )
  14. func getParentPackage(dir string) (string, error) {
  15. p, err := project.Prepare(dir, false)
  16. if err != nil {
  17. return "", err
  18. }
  19. if len(p.GoMod.Path) > 0 {
  20. goModePath := filepath.Clean(filepath.Dir(p.GoMod.Path))
  21. absPath, err := filepath.Abs(dir)
  22. if err != nil {
  23. return "", err
  24. }
  25. parent := filepath.Clean(goctlutil.JoinPackages(p.GoMod.Module, absPath[len(goModePath):]))
  26. parent = strings.ReplaceAll(parent, "\\", "/")
  27. parent = strings.ReplaceAll(parent, `\`, "/")
  28. return parent, nil
  29. }
  30. return p.Package, nil
  31. }
  32. func writeIndent(writer io.Writer, indent int) {
  33. for i := 0; i < indent; i++ {
  34. fmt.Fprint(writer, "\t")
  35. }
  36. }
  37. func writeProperty(writer io.Writer, name, tp, tag, comment string, indent int) error {
  38. writeIndent(writer, indent)
  39. var err error
  40. if len(comment) > 0 {
  41. comment = strings.TrimPrefix(comment, "//")
  42. comment = "//" + comment
  43. _, err = fmt.Fprintf(writer, "%s %s %s %s\n", strings.Title(name), tp, tag, comment)
  44. } else {
  45. _, err = fmt.Fprintf(writer, "%s %s %s\n", strings.Title(name), tp, tag)
  46. }
  47. return err
  48. }
  49. func getAuths(api *spec.ApiSpec) []string {
  50. authNames := collection.NewSet()
  51. for _, g := range api.Service.Groups {
  52. if value, ok := util.GetAnnotationValue(g.Annotations, "server", "jwt"); ok {
  53. authNames.Add(value)
  54. }
  55. if value, ok := util.GetAnnotationValue(g.Annotations, "server", "signature"); ok {
  56. authNames.Add(value)
  57. }
  58. }
  59. return authNames.KeysStr()
  60. }
  61. func getMiddleware(api *spec.ApiSpec) []string {
  62. result := collection.NewSet()
  63. for _, g := range api.Service.Groups {
  64. if value, ok := util.GetAnnotationValue(g.Annotations, "server", "middleware"); ok {
  65. for _, item := range strings.Split(value, ",") {
  66. result.Add(strings.TrimSpace(item))
  67. }
  68. }
  69. }
  70. return result.KeysStr()
  71. }
  72. func formatCode(code string) string {
  73. ret, err := goformat.Source([]byte(code))
  74. if err != nil {
  75. return code
  76. }
  77. return string(ret)
  78. }