util.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. return parent, nil
  28. }
  29. return p.Package, nil
  30. }
  31. func writeIndent(writer io.Writer, indent int) {
  32. for i := 0; i < indent; i++ {
  33. fmt.Fprint(writer, "\t")
  34. }
  35. }
  36. func writeProperty(writer io.Writer, name, tp, tag, comment string, indent int) error {
  37. writeIndent(writer, indent)
  38. var err error
  39. if len(comment) > 0 {
  40. comment = strings.TrimPrefix(comment, "//")
  41. comment = "//" + comment
  42. _, err = fmt.Fprintf(writer, "%s %s %s %s\n", strings.Title(name), tp, tag, comment)
  43. } else {
  44. _, err = fmt.Fprintf(writer, "%s %s %s\n", strings.Title(name), tp, tag)
  45. }
  46. return err
  47. }
  48. func getAuths(api *spec.ApiSpec) []string {
  49. authNames := collection.NewSet()
  50. for _, g := range api.Service.Groups {
  51. if value, ok := util.GetAnnotationValue(g.Annotations, "server", "jwt"); ok {
  52. authNames.Add(value)
  53. }
  54. if value, ok := util.GetAnnotationValue(g.Annotations, "server", "signature"); ok {
  55. authNames.Add(value)
  56. }
  57. }
  58. return authNames.KeysStr()
  59. }
  60. func getMiddleware(api *spec.ApiSpec) []string {
  61. result := collection.NewSet()
  62. for _, g := range api.Service.Groups {
  63. if value, ok := util.GetAnnotationValue(g.Annotations, "server", "middleware"); ok {
  64. for _, item := range strings.Split(value, ",") {
  65. result.Add(strings.TrimSpace(item))
  66. }
  67. }
  68. }
  69. return result.KeysStr()
  70. }
  71. func formatCode(code string) string {
  72. ret, err := goformat.Source([]byte(code))
  73. if err != nil {
  74. return code
  75. }
  76. return string(ret)
  77. }