util.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. package dartgen
  2. import (
  3. "log"
  4. "os"
  5. "reflect"
  6. "strings"
  7. "zero/tools/goctl/api/spec"
  8. "zero/tools/goctl/api/util"
  9. )
  10. func lowCamelCase(s string) string {
  11. if len(s) < 1 {
  12. return ""
  13. }
  14. s = util.ToCamelCase(util.ToSnakeCase(s))
  15. return util.ToLower(s[:1]) + s[1:]
  16. }
  17. func pathToFuncName(path string) string {
  18. if !strings.HasPrefix(path, "/") {
  19. path = "/" + path
  20. }
  21. if !strings.HasPrefix(path, "/api") {
  22. path = "/api" + path
  23. }
  24. path = strings.Replace(path, "/", "_", -1)
  25. path = strings.Replace(path, "-", "_", -1)
  26. camel := util.ToCamelCase(path)
  27. return util.ToLower(camel[:1]) + camel[1:]
  28. }
  29. func tagGet(tag, k string) (reflect.Value, error) {
  30. v, _ := util.TagLookup(tag, k)
  31. out := strings.Split(v, ",")[0]
  32. return reflect.ValueOf(out), nil
  33. }
  34. func convertMemberType(api *spec.ApiSpec) {
  35. for i, t := range api.Types {
  36. for j, mem := range t.Members {
  37. api.Types[i].Members[j].Type = goTypeToDart(mem.Type)
  38. }
  39. }
  40. }
  41. func goTypeToDart(t string) string {
  42. t = strings.Replace(t, "*", "", -1)
  43. if strings.HasPrefix(t, "[]") {
  44. return "List<" + goTypeToDart(t[2:]) + ">"
  45. }
  46. if strings.HasPrefix(t, "map") {
  47. tys, e := util.DecomposeType(t)
  48. if e != nil {
  49. log.Fatal(e)
  50. }
  51. if len(tys) != 2 {
  52. log.Fatal("Map type number !=2")
  53. }
  54. return "Map<String," + goTypeToDart(tys[1]) + ">"
  55. }
  56. switch t {
  57. case "string":
  58. return "String"
  59. case "int", "int32", "int64":
  60. return "int"
  61. case "float", "float32", "float64":
  62. return "double"
  63. case "bool":
  64. return "bool"
  65. default:
  66. return t
  67. }
  68. }
  69. func isDirectType(s string) bool {
  70. return isAtomicType(s) || isListType(s) && isAtomicType(getCoreType(s))
  71. }
  72. func isAtomicType(s string) bool {
  73. switch s {
  74. case "String", "int", "double", "bool":
  75. return true
  76. default:
  77. return false
  78. }
  79. }
  80. func isListType(s string) bool {
  81. return strings.HasPrefix(s, "List<")
  82. }
  83. func isClassListType(s string) bool {
  84. return strings.HasPrefix(s, "List<") && !isAtomicType(getCoreType(s))
  85. }
  86. func getCoreType(s string) string {
  87. if isAtomicType(s) {
  88. return s
  89. }
  90. if isListType(s) {
  91. s = strings.Replace(s, "List<", "", -1)
  92. return strings.Replace(s, ">", "", -1)
  93. }
  94. return s
  95. }
  96. func fileExists(path string) bool {
  97. _, err := os.Stat(path)
  98. return !os.IsNotExist(err)
  99. }