gencomponents.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package tsgen
  2. import (
  3. "errors"
  4. "path"
  5. "strings"
  6. "text/template"
  7. "github.com/tal-tech/go-zero/tools/goctl/api/spec"
  8. apiutil "github.com/tal-tech/go-zero/tools/goctl/api/util"
  9. "github.com/tal-tech/go-zero/tools/goctl/util"
  10. )
  11. const (
  12. componentsTemplate = `// Code generated by goctl. DO NOT EDIT.
  13. {{.componentTypes}}
  14. `
  15. )
  16. func genComponents(dir string, api *spec.ApiSpec) error {
  17. types := apiutil.GetSharedTypes(api)
  18. if len(types) == 0 {
  19. return nil
  20. }
  21. val, err := buildTypes(types, func(name string) (*spec.Type, error) {
  22. for _, ty := range api.Types {
  23. if strings.ToLower(ty.Name) == strings.ToLower(name) {
  24. return &ty, nil
  25. }
  26. }
  27. return nil, errors.New("inline type " + name + " not exist, please correct api file")
  28. })
  29. if err != nil {
  30. return err
  31. }
  32. outputFile := apiutil.ComponentName(api) + ".ts"
  33. filename := path.Join(dir, outputFile)
  34. if err := util.RemoveIfExist(filename); err != nil {
  35. return err
  36. }
  37. fp, created, err := apiutil.MaybeCreateFile(dir, ".", outputFile)
  38. if err != nil {
  39. return err
  40. }
  41. if !created {
  42. return nil
  43. }
  44. defer fp.Close()
  45. t := template.Must(template.New("componentsTemplate").Parse(componentsTemplate))
  46. return t.Execute(fp, map[string]string{
  47. "componentTypes": val,
  48. })
  49. }
  50. func buildTypes(types []spec.Type, inlineType func(string) (*spec.Type, error)) (string, error) {
  51. var builder strings.Builder
  52. first := true
  53. for _, tp := range types {
  54. if first {
  55. first = false
  56. } else {
  57. builder.WriteString("\n")
  58. }
  59. if err := writeType(&builder, tp, func(name string) (*spec.Type, error) {
  60. return inlineType(name)
  61. }, func(tp string) string {
  62. return ""
  63. }); err != nil {
  64. return "", apiutil.WrapErr(err, "Type "+tp.Name+" generate error")
  65. }
  66. }
  67. return builder.String(), nil
  68. }