newservice.go 1.8 KB

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