gencomponents.go 1.3 KB

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