1
0

gen.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package ktgen
  2. import (
  3. _ "embed"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "text/template"
  8. "github.com/iancoleman/strcase"
  9. "github.com/wuntsong-org/go-zero-plus/tools/goctlwt/api/spec"
  10. )
  11. var (
  12. //go:embed apibase.tpl
  13. apiBaseTemplate string
  14. //go:embed api.tpl
  15. apiTemplate string
  16. )
  17. func genBase(dir, pkg string, api *spec.ApiSpec) error {
  18. e := os.MkdirAll(dir, 0o755)
  19. if e != nil {
  20. return e
  21. }
  22. path := filepath.Join(dir, "BaseApi.kt")
  23. if _, e := os.Stat(path); e == nil {
  24. fmt.Println("BaseApi.kt already exists, skipped it.")
  25. return nil
  26. }
  27. file, e := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o644)
  28. if e != nil {
  29. return e
  30. }
  31. defer file.Close()
  32. t, e := template.New("n").Parse(apiBaseTemplate)
  33. if e != nil {
  34. return e
  35. }
  36. e = t.Execute(file, pkg)
  37. if e != nil {
  38. return e
  39. }
  40. return nil
  41. }
  42. func genApi(dir, pkg string, api *spec.ApiSpec) error {
  43. properties := api.Info.Properties
  44. if properties == nil {
  45. return fmt.Errorf("none properties")
  46. }
  47. title := properties["Title"]
  48. if len(title) == 0 {
  49. return fmt.Errorf("none title")
  50. }
  51. desc := properties["Desc"]
  52. if len(desc) == 0 {
  53. return fmt.Errorf("none desc")
  54. }
  55. name := strcase.ToCamel(title + "Api")
  56. path := filepath.Join(dir, name+".kt")
  57. api.Info.Title = name
  58. api.Info.Desc = desc
  59. e := os.MkdirAll(dir, 0o755)
  60. if e != nil {
  61. return e
  62. }
  63. file, e := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0o644)
  64. if e != nil {
  65. return e
  66. }
  67. defer file.Close()
  68. t, e := template.New("api").Funcs(funcsMap).Parse(apiTemplate)
  69. if e != nil {
  70. return e
  71. }
  72. type data struct {
  73. *spec.ApiSpec
  74. Pkg string
  75. }
  76. return t.Execute(file, data{api, pkg})
  77. }