util.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package gogen
  2. import (
  3. "fmt"
  4. goformat "go/format"
  5. "io"
  6. "os"
  7. "path"
  8. "path/filepath"
  9. "strings"
  10. "github.com/tal-tech/go-zero/core/collection"
  11. "github.com/tal-tech/go-zero/tools/goctl/api/spec"
  12. "github.com/tal-tech/go-zero/tools/goctl/api/util"
  13. goctlutil "github.com/tal-tech/go-zero/tools/goctl/util"
  14. )
  15. func getParentPackage(dir string) (string, error) {
  16. absDir, err := filepath.Abs(dir)
  17. if err != nil {
  18. return "", err
  19. }
  20. absDir = strings.ReplaceAll(absDir, `\`, `/`)
  21. var rootPath, hasGoMod = goctlutil.FindGoModPath(dir)
  22. if hasGoMod {
  23. return rootPath, nil
  24. }
  25. gopath := os.Getenv("GOPATH")
  26. parent := path.Join(gopath, "src")
  27. pos := strings.Index(absDir, parent)
  28. if pos < 0 {
  29. fmt.Printf("%s not in go.mod project path, or not in GOPATH of %s directory\n", absDir, gopath)
  30. var tempPath = filepath.Dir(absDir)
  31. rootPath = absDir[len(tempPath)+1:]
  32. } else {
  33. rootPath = absDir[len(parent)+1:]
  34. }
  35. return rootPath, nil
  36. }
  37. func writeIndent(writer io.Writer, indent int) {
  38. for i := 0; i < indent; i++ {
  39. fmt.Fprint(writer, "\t")
  40. }
  41. }
  42. func writeProperty(writer io.Writer, name, tp, tag, comment string, indent int) error {
  43. writeIndent(writer, indent)
  44. var err error
  45. if len(comment) > 0 {
  46. comment = strings.TrimPrefix(comment, "//")
  47. comment = "//" + comment
  48. _, err = fmt.Fprintf(writer, "%s %s %s %s\n", strings.Title(name), tp, tag, comment)
  49. } else {
  50. _, err = fmt.Fprintf(writer, "%s %s %s\n", strings.Title(name), tp, tag)
  51. }
  52. return err
  53. }
  54. func getAuths(api *spec.ApiSpec) []string {
  55. var authNames = collection.NewSet()
  56. for _, g := range api.Service.Groups {
  57. if value, ok := util.GetAnnotationValue(g.Annotations, "server", "jwt"); ok {
  58. authNames.Add(value)
  59. }
  60. if value, ok := util.GetAnnotationValue(g.Annotations, "server", "signature"); ok {
  61. authNames.Add(value)
  62. }
  63. }
  64. return authNames.KeysStr()
  65. }
  66. func formatCode(code string) string {
  67. ret, err := goformat.Source([]byte(code))
  68. if err != nil {
  69. return code
  70. }
  71. return string(ret)
  72. }