util.go 1.8 KB

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