util.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. "github.com/tal-tech/go-zero/tools/goctl/util/ctx"
  12. )
  13. func getParentPackage(dir string) (string, error) {
  14. abs, err := filepath.Abs(dir)
  15. if err != nil {
  16. return "", err
  17. }
  18. projectCtx, err := ctx.Prepare(abs)
  19. if err != nil {
  20. return "", err
  21. }
  22. return filepath.ToSlash(filepath.Join(projectCtx.Path, strings.TrimPrefix(projectCtx.WorkDir, projectCtx.Dir))), nil
  23. }
  24. func writeIndent(writer io.Writer, indent int) {
  25. for i := 0; i < indent; i++ {
  26. fmt.Fprint(writer, "\t")
  27. }
  28. }
  29. func writeProperty(writer io.Writer, name, tp, tag, comment string, indent int) error {
  30. writeIndent(writer, indent)
  31. var err error
  32. if len(comment) > 0 {
  33. comment = strings.TrimPrefix(comment, "//")
  34. comment = "//" + comment
  35. _, err = fmt.Fprintf(writer, "%s %s %s %s\n", strings.Title(name), tp, tag, comment)
  36. } else {
  37. _, err = fmt.Fprintf(writer, "%s %s %s\n", strings.Title(name), tp, tag)
  38. }
  39. return err
  40. }
  41. func getAuths(api *spec.ApiSpec) []string {
  42. authNames := collection.NewSet()
  43. for _, g := range api.Service.Groups {
  44. if value, ok := util.GetAnnotationValue(g.Annotations, "server", "jwt"); ok {
  45. authNames.Add(value)
  46. }
  47. if value, ok := util.GetAnnotationValue(g.Annotations, "server", "signature"); ok {
  48. authNames.Add(value)
  49. }
  50. }
  51. return authNames.KeysStr()
  52. }
  53. func getMiddleware(api *spec.ApiSpec) []string {
  54. result := collection.NewSet()
  55. for _, g := range api.Service.Groups {
  56. if value, ok := util.GetAnnotationValue(g.Annotations, "server", "middleware"); ok {
  57. for _, item := range strings.Split(value, ",") {
  58. result.Add(strings.TrimSpace(item))
  59. }
  60. }
  61. }
  62. return result.KeysStr()
  63. }
  64. func formatCode(code string) string {
  65. ret, err := goformat.Source([]byte(code))
  66. if err != nil {
  67. return code
  68. }
  69. return string(ret)
  70. }