newservice.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package new
  2. import (
  3. _ "embed"
  4. "errors"
  5. "html/template"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "github.com/spf13/cobra"
  10. "github.com/wuntsong-org/go-zero-plus/tools/goctlwt/api/gogen"
  11. conf "github.com/wuntsong-org/go-zero-plus/tools/goctlwt/config"
  12. "github.com/wuntsong-org/go-zero-plus/tools/goctlwt/util"
  13. "github.com/wuntsong-org/go-zero-plus/tools/goctlwt/util/pathx"
  14. )
  15. //go:embed api.tpl
  16. var apiTemplate string
  17. var (
  18. // VarStringHome describes the goctl home.
  19. VarStringHome string
  20. // VarStringRemote describes the remote git repository.
  21. VarStringRemote string
  22. // VarStringBranch describes the git branch.
  23. VarStringBranch string
  24. // VarStringStyle describes the style of output files.
  25. VarStringStyle string
  26. )
  27. // CreateServiceCommand fast create service
  28. func CreateServiceCommand(_ *cobra.Command, args []string) error {
  29. dirName := args[0]
  30. if len(VarStringStyle) == 0 {
  31. VarStringStyle = conf.DefaultFormat
  32. }
  33. if strings.Contains(dirName, "-") {
  34. return errors.New("api new command service name not support strikethrough, because this will used by function name")
  35. }
  36. abs, err := filepath.Abs(dirName)
  37. if err != nil {
  38. return err
  39. }
  40. err = pathx.MkdirIfNotExist(abs)
  41. if err != nil {
  42. return err
  43. }
  44. dirName = filepath.Base(filepath.Clean(abs))
  45. filename := dirName + ".api"
  46. apiFilePath := filepath.Join(abs, filename)
  47. fp, err := os.Create(apiFilePath)
  48. if err != nil {
  49. return err
  50. }
  51. defer fp.Close()
  52. if len(VarStringRemote) > 0 {
  53. repo, _ := util.CloneIntoGitHome(VarStringRemote, VarStringBranch)
  54. if len(repo) > 0 {
  55. VarStringHome = repo
  56. }
  57. }
  58. if len(VarStringHome) > 0 {
  59. pathx.RegisterGoctlHome(VarStringHome)
  60. }
  61. text, err := pathx.LoadTemplate(category, apiTemplateFile, apiTemplate)
  62. if err != nil {
  63. return err
  64. }
  65. t := template.Must(template.New("template").Parse(text))
  66. if err := t.Execute(fp, map[string]string{
  67. "name": dirName,
  68. "handler": strings.Title(dirName),
  69. }); err != nil {
  70. return err
  71. }
  72. err = gogen.DoGenProject(apiFilePath, abs, VarStringStyle)
  73. return err
  74. }