gen.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package apigen
  2. import (
  3. _ "embed"
  4. "errors"
  5. "fmt"
  6. "html/template"
  7. "path/filepath"
  8. "strings"
  9. "github.com/gookit/color"
  10. "github.com/spf13/cobra"
  11. "github.com/wuntsong-org/go-zero-plus/tools/goctlwt/util"
  12. "github.com/wuntsong-org/go-zero-plus/tools/goctlwt/util/pathx"
  13. )
  14. //go:embed api.tpl
  15. var apiTemplate string
  16. var (
  17. // VarStringOutput describes the output.
  18. VarStringOutput string
  19. // VarStringHome describes the goctl home.
  20. VarStringHome string
  21. // VarStringRemote describes the remote git repository.
  22. VarStringRemote string
  23. // VarStringBranch describes the git branch.
  24. VarStringBranch string
  25. )
  26. // CreateApiTemplate create api template file
  27. func CreateApiTemplate(_ *cobra.Command, _ []string) error {
  28. apiFile := VarStringOutput
  29. if len(apiFile) == 0 {
  30. return errors.New("missing -o")
  31. }
  32. fp, err := pathx.CreateIfNotExist(apiFile)
  33. if err != nil {
  34. return err
  35. }
  36. defer fp.Close()
  37. if len(VarStringRemote) > 0 {
  38. repo, _ := util.CloneIntoGitHome(VarStringRemote, VarStringBranch)
  39. if len(repo) > 0 {
  40. VarStringHome = repo
  41. }
  42. }
  43. if len(VarStringHome) > 0 {
  44. pathx.RegisterGoctlHome(VarStringHome)
  45. }
  46. text, err := pathx.LoadTemplate(category, apiTemplateFile, apiTemplate)
  47. if err != nil {
  48. return err
  49. }
  50. baseName := pathx.FileNameWithoutExt(filepath.Base(apiFile))
  51. if strings.HasSuffix(strings.ToLower(baseName), "-api") {
  52. baseName = baseName[:len(baseName)-4]
  53. } else if strings.HasSuffix(strings.ToLower(baseName), "api") {
  54. baseName = baseName[:len(baseName)-3]
  55. }
  56. t := template.Must(template.New("etcTemplate").Parse(text))
  57. if err := t.Execute(fp, map[string]string{
  58. "gitUser": getGitName(),
  59. "gitEmail": getGitEmail(),
  60. "serviceName": baseName + "-api",
  61. }); err != nil {
  62. return err
  63. }
  64. fmt.Println(color.Green.Render("Done."))
  65. return nil
  66. }