util.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package gogen
  2. import (
  3. "fmt"
  4. goformat "go/format"
  5. "io"
  6. "strings"
  7. "github.com/tal-tech/go-zero/core/collection"
  8. "github.com/tal-tech/go-zero/tools/goctl/api/spec"
  9. "github.com/tal-tech/go-zero/tools/goctl/api/util"
  10. "github.com/tal-tech/go-zero/tools/goctl/util/project"
  11. )
  12. func getParentPackage(dir string) (string, error) {
  13. p, err := project.Prepare(dir, false)
  14. if err != nil {
  15. return "", err
  16. }
  17. return p.GoMod.Module, nil
  18. }
  19. func writeIndent(writer io.Writer, indent int) {
  20. for i := 0; i < indent; i++ {
  21. fmt.Fprint(writer, "\t")
  22. }
  23. }
  24. func writeProperty(writer io.Writer, name, tp, tag, comment string, indent int) error {
  25. 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 formatCode(code string) string {
  49. ret, err := goformat.Source([]byte(code))
  50. if err != nil {
  51. return code
  52. }
  53. return string(ret)
  54. }