gen.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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/zeromicro/go-zero/tools/goctl/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. return t.Execute(file, api)
  73. }