go-zero/tools/goctl/api/apigen/gen.go

71 lines
1.5 KiB
Go
Raw Normal View History

2020-07-29 17:11:41 +08:00
package apigen
import (
_ "embed"
2020-07-29 17:11:41 +08:00
"errors"
"fmt"
"html/template"
2020-07-29 17:11:41 +08:00
"path/filepath"
"strings"
"github.com/logrusorgru/aurora"
"github.com/urfave/cli"
"github.com/zeromicro/go-zero/tools/goctl/util"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
2020-07-29 17:11:41 +08:00
)
//go:embed api.tpl
var apiTemplate string
2020-07-29 17:11:41 +08:00
2021-02-20 19:50:03 +08:00
// ApiCommand create api template file
2020-07-29 17:11:41 +08:00
func ApiCommand(c *cli.Context) error {
apiFile := c.String("o")
if len(apiFile) == 0 {
return errors.New("missing -o")
}
fp, err := pathx.CreateIfNotExist(apiFile)
2020-07-29 17:11:41 +08:00
if err != nil {
return err
}
defer fp.Close()
2021-09-07 10:16:10 +08:00
home := c.String("home")
remote := c.String("remote")
2022-03-05 22:52:32 +08:00
branch := c.String("branch")
if len(remote) > 0 {
2022-03-05 22:52:32 +08:00
repo, _ := util.CloneIntoGitHome(remote, branch)
if len(repo) > 0 {
home = repo
}
}
2021-09-07 10:16:10 +08:00
if len(home) > 0 {
pathx.RegisterGoctlHome(home)
2021-09-07 10:16:10 +08:00
}
text, err := pathx.LoadTemplate(category, apiTemplateFile, apiTemplate)
2021-09-07 10:16:10 +08:00
if err != nil {
return err
}
baseName := pathx.FileNameWithoutExt(filepath.Base(apiFile))
2020-07-29 17:11:41 +08:00
if strings.HasSuffix(strings.ToLower(baseName), "-api") {
baseName = baseName[:len(baseName)-4]
} else if strings.HasSuffix(strings.ToLower(baseName), "api") {
baseName = baseName[:len(baseName)-3]
}
2021-09-07 10:16:10 +08:00
t := template.Must(template.New("etcTemplate").Parse(text))
2020-07-29 17:11:41 +08:00
if err := t.Execute(fp, map[string]string{
"gitUser": getGitName(),
"gitEmail": getGitEmail(),
"serviceName": baseName + "-api",
}); err != nil {
return err
}
fmt.Println(aurora.Green("Done."))
return nil
}