gen.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. apiFile := c.String("o")
  19. if len(apiFile) == 0 {
  20. return errors.New("missing -o")
  21. }
  22. fp, err := pathx.CreateIfNotExist(apiFile)
  23. if err != nil {
  24. return err
  25. }
  26. defer fp.Close()
  27. home := c.String("home")
  28. remote := c.String("remote")
  29. branch := c.String("branch")
  30. if len(remote) > 0 {
  31. repo, _ := util.CloneIntoGitHome(remote, branch)
  32. if len(repo) > 0 {
  33. home = repo
  34. }
  35. }
  36. if len(home) > 0 {
  37. pathx.RegisterGoctlHome(home)
  38. }
  39. text, err := pathx.LoadTemplate(category, apiTemplateFile, apiTemplate)
  40. if err != nil {
  41. return err
  42. }
  43. baseName := pathx.FileNameWithoutExt(filepath.Base(apiFile))
  44. if strings.HasSuffix(strings.ToLower(baseName), "-api") {
  45. baseName = baseName[:len(baseName)-4]
  46. } else if strings.HasSuffix(strings.ToLower(baseName), "api") {
  47. baseName = baseName[:len(baseName)-3]
  48. }
  49. t := template.Must(template.New("etcTemplate").Parse(text))
  50. if err := t.Execute(fp, map[string]string{
  51. "gitUser": getGitName(),
  52. "gitEmail": getGitEmail(),
  53. "serviceName": baseName + "-api",
  54. }); err != nil {
  55. return err
  56. }
  57. fmt.Println(aurora.Green("Done."))
  58. return nil
  59. }