gen.go 1.5 KB

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