util.go 1.6 KB

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