util.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package gogen
  2. import (
  3. "fmt"
  4. goformat "go/format"
  5. "io"
  6. "path/filepath"
  7. "strings"
  8. "zero/core/collection"
  9. "zero/tools/goctl/api/spec"
  10. "zero/tools/goctl/api/util"
  11. "zero/tools/goctl/vars"
  12. )
  13. func getParentPackage(dir string) (string, error) {
  14. absDir, err := filepath.Abs(dir)
  15. if err != nil {
  16. return "", err
  17. }
  18. pos := strings.Index(absDir, vars.ProjectName)
  19. if pos < 0 {
  20. return "", fmt.Errorf("%s not in project directory", dir)
  21. }
  22. return absDir[pos:], 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. var 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 formatCode(code string) string {
  54. ret, err := goformat.Source([]byte(code))
  55. if err != nil {
  56. return code
  57. }
  58. return string(ret)
  59. }