Skip to content

Commit

Permalink
feat: 优化生成代码的速度
Browse files Browse the repository at this point in the history
  • Loading branch information
2637309949 committed Apr 6, 2021
1 parent 85a0a65 commit cee975f
Show file tree
Hide file tree
Showing 5 changed files with 878 additions and 27 deletions.
61 changes: 36 additions & 25 deletions cmd/dolphin/gen/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,30 +77,59 @@ func (gen *Gen) AddPipe(modules ...pipe.Pipe) {
gen.Pipes = append(gen.Pipes, modules...)
}

// BuildWithDir defined
func (gen *Gen) BuildWithDir(dir string, args []string) (err error) {
// BuildDir defined
func (gen *Gen) BuildDir(dir string, args []string) (err error) {
defer func() {
if rErr := recover(); rErr != nil {
err = fmt.Errorf("%v", rErr)
}
}()
// generate code
cfgs := []*pipe.TmplCfg{}
for i := range gen.Pipes {
cfgs, err := gen.Pipes[i].Build(dir, args, gen.App)
items, err := gen.Pipes[i].Build(dir, args, gen.App)
cfgs = append(cfgs, items...)
if err != nil {
return err
}
for j := range cfgs {
err = gen.BuildWithCfg(cfgs[j])
for j := range items {
err = gen.Build(cfgs[j])
if err != nil {
panic(err)
}
}
}
// fmt code
filePaths := funk.Keys(funk.Map(funk.Filter(cfgs, func(cfg *pipe.TmplCfg) bool { return cfg.GOFmt && path.Ext(cfg.FilePath) == ".go" }), func(cfg *pipe.TmplCfg) (string, string) { return path.Dir(cfg.FilePath), path.Dir(cfg.FilePath) })).([]string)
if len(filePaths) > 0 {
if err := utils.InstallPackages("golang.org/x/tools/cmd/goimports"); err != nil {
logrus.Error(err)
}
for i := range filePaths {
cmd := exec.Command("goimports", "-w", filePaths[i])
if err := cmd.Run(); err != nil && err != exec.ErrNotFound {
logrus.Error(err)
}
}
}
// rpc code
filePaths = funk.Keys(funk.Map(funk.Filter(cfgs, func(cfg *pipe.TmplCfg) bool { return cfg.GOProto && path.Ext(cfg.FilePath) == ".proto" }), func(cfg *pipe.TmplCfg) (string, string) { return cfg.FilePath, cfg.FilePath })).([]string)
if len(filePaths) > 0 {
if err := utils.InstallPackages("github.com/golang/protobuf/proto", "github.com/golang/protobuf/protoc-gen-go"); err != nil {
logrus.Error(err)
}
for i := range filePaths {
cmd := exec.Command("protoc", "-I", path.Dir(filePaths[i]), filePaths[i], "--go_out=plugins=grpc:"+path.Dir(filePaths[i]))
if err := cmd.Run(); err != nil && err != exec.ErrNotFound {
logrus.Error(err)
}
}
}
return nil
}

// BuildWithCfg defined
func (gen *Gen) BuildWithCfg(cfg *pipe.TmplCfg) error {
func (gen *Gen) Build(cfg *pipe.TmplCfg) error {
var err error
var tpl *template.Template
tpl = template.New("template")
Expand Down Expand Up @@ -135,29 +164,11 @@ func (gen *Gen) BuildWithCfg(cfg *pipe.TmplCfg) error {
if err = tpl.Execute(bfw, cfg.Data); err != nil {
return err
}
sbt := string(bf.Bytes())
sbt := bf.String()
sbt = strings.ReplaceAll(sbt, "'", "'")
_, err = w.WriteString(sbt)
if err != nil {
return err
}
if cfg.GOFmt && path.Ext(cfg.FilePath) == ".go" {
if err := utils.InstallPackages("golang.org/x/tools/cmd/goimports"); err != nil {
logrus.Error(err)
}
cmd := exec.Command("goimports", "-w", cfg.FilePath)
if err := cmd.Run(); err != nil && err != exec.ErrNotFound {
logrus.Error(err)
}
}
if cfg.GOProto && path.Ext(cfg.FilePath) == ".proto" {
if err := utils.InstallPackages("github.com/golang/protobuf/proto", "github.com/golang/protobuf/protoc-gen-go"); err != nil {
logrus.Error(err)
}
cmd := exec.Command("protoc", "-I", path.Dir(cfg.FilePath), cfg.FilePath, "--go_out=plugins=grpc:"+path.Dir(cfg.FilePath))
if err := cmd.Run(); err != nil && err != exec.ErrNotFound {
logrus.Error(err)
}
}
return nil
}
4 changes: 2 additions & 2 deletions cmd/dolphin/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ var (
}
g := gen.New(p.Application)
g.AddPipe(gen.GetPipesByName(pipes...)...)
err = g.BuildWithDir(wd, args)
err = g.BuildDir(wd, args)
return err
},
}
Expand Down Expand Up @@ -150,7 +150,7 @@ var (
}
g := gen.New(p.Application)
g.AddPipe(gen.GetPipesByName("boilerplate")...)
return g.BuildWithDir(wd, args)
return g.BuildDir(wd, args)
}
logrus.Warn("It is not allowed to initialize a non-empty project")
return nil
Expand Down
280 changes: 280 additions & 0 deletions examples/aisle/app/organ.go.new.new
Original file line number Diff line number Diff line change
@@ -0,0 +1,280 @@
// Code generated by dol build. Only Generate by tools if not existed.
// source: organ.go

package app

import (
"errors"
"aisle/model"
"aisle/srv"

"github.com/2637309949/dolphin/packages/gin/binding"
"github.com/2637309949/dolphin/packages/go-funk"
"github.com/2637309949/dolphin/packages/logrus"
"github.com/2637309949/dolphin/packages/null"
"github.com/2637309949/dolphin/packages/time"
)

// OrganAdd api implementation
// @Summary 添加城市
// @Tags 城市
// @Accept application/json
// @Param Authorization header string false "认证令牌"
// @Param organ body model.Organ false "城市信息"
// @Failure 403 {object} model.Fail
// @Success 200 {object} model.Success
// @Failure 500 {object} model.Fail
// @Router /api/organ/add [post]
func OrganAdd(ctx *Context) {
var payload model.Organ
if err := ctx.ShouldBindBodyWith(&payload, binding.JSON); err != nil {
logrus.Error(err)
ctx.Fail(err)
return
}
payload.CreateTime = null.TimeFrom(time.Now().Value())
payload.Creater = null.StringFrom(ctx.GetToken().GetUserID())
payload.UpdateTime = null.TimeFrom(time.Now().Value())
payload.Updater = null.StringFrom(ctx.GetToken().GetUserID())
payload.IsDelete = null.IntFrom(0)
ret, err := ctx.DB.Insert(&payload)
if err != nil {
logrus.Error(err)
ctx.Fail(err)
return
}
ctx.Success(ret)
}

// OrganBatchAdd api implementation
// @Summary 添加城市
// @Tags 城市
// @Accept application/json
// @Param Authorization header string false "认证令牌"
// @Param organ body []model.Organ false "城市信息"
// @Failure 403 {object} model.Fail
// @Success 200 {object} model.Success
// @Failure 500 {object} model.Fail
// @Router /api/organ/batch_add [post]
func OrganBatchAdd(ctx *Context) {
var payload []model.Organ
if err := ctx.ShouldBindBodyWith(&payload, binding.JSON); err != nil {
logrus.Error(err)
ctx.Fail(err)
return
}
for i := range payload {
payload[i].CreateTime = null.TimeFrom(time.Now().Value())
payload[i].Creater = null.StringFrom(ctx.GetToken().GetUserID())
payload[i].UpdateTime = null.TimeFrom(time.Now().Value())
payload[i].Updater = null.StringFrom(ctx.GetToken().GetUserID())
payload[i].IsDelete = null.IntFrom(0)
}
ret, err := ctx.DB.Insert(&payload)
if err != nil {
logrus.Error(err)
ctx.Fail(err)
return
}
ctx.Success(ret)
}

// OrganDel api implementation
// @Summary 删除城市
// @Tags 城市
// @Accept application/json
// @Param Authorization header string false "认证令牌"
// @Param organ body model.Organ false "城市"
// @Failure 403 {object} model.Fail
// @Success 200 {object} model.Success
// @Failure 500 {object} model.Fail
// @Router /api/organ/del [delete]
func OrganDel(ctx *Context) {
var payload model.Organ
if err := ctx.ShouldBindBodyWith(&payload, binding.JSON); err != nil {
logrus.Error(err)
ctx.Fail(err)
return
}
ret, err := ctx.DB.In("id", payload.ID.String).Update(&model.Organ{
UpdateTime: null.TimeFrom(time.Now().Value()),
Updater: null.StringFrom(ctx.GetToken().GetUserID()),
IsDelete: null.IntFrom(1),
})
if err != nil {
logrus.Error(err)
ctx.Fail(err)
return
}
ctx.Success(ret)
}

// OrganBatchDel api implementation
// @Summary 删除城市
// @Tags 城市
// @Accept application/json
// @Param Authorization header string false "认证令牌"
// @Param organ body []model.Organ false "城市信息"
// @Failure 403 {object} model.Fail
// @Success 200 {object} model.Success
// @Failure 500 {object} model.Fail
// @Router /api/organ/batch_del [put]
func OrganBatchDel(ctx *Context) {
var payload []model.Organ
if err := ctx.ShouldBindBodyWith(&payload, binding.JSON); err != nil {
logrus.Error(err)
ctx.Fail(err)
return
}
var ids = funk.Map(payload, func(form model.Organ) string { return form.ID.String }).([]string)
ret, err := ctx.DB.In("id", ids).Update(&model.Organ{
UpdateTime: null.TimeFrom(time.Now().Value()),
Updater: null.StringFrom(ctx.GetToken().GetUserID()),
IsDelete: null.IntFrom(1),
})
if err != nil {
logrus.Error(err)
ctx.Fail(err)
return
}
ctx.Success(ret)
}

// OrganUpdate api implementation
// @Summary 更新城市
// @Tags 城市
// @Accept application/json
// @Param Authorization header string false "认证令牌"
// @Param organ body model.Organ false "城市信息"
// @Failure 403 {object} model.Fail
// @Success 200 {object} model.Success
// @Failure 500 {object} model.Fail
// @Router /api/organ/update [put]
func OrganUpdate(ctx *Context) {
var payload model.Organ
if err := ctx.ShouldBindBodyWith(&payload, binding.JSON); err != nil {
logrus.Error(err)
ctx.Fail(err)
return
}
payload.Updater = null.StringFrom(ctx.GetToken().GetUserID())
payload.UpdateTime = null.TimeFrom(time.Now().Value())
ret, err := ctx.DB.ID(payload.ID.String).Update(&payload)
if err != nil {
logrus.Error(err)
ctx.Fail(err)
return
}
ctx.Success(ret)
}

// OrganBatchUpdate api implementation
// @Summary 更新城市
// @Tags 城市
// @Accept application/json
// @Param Authorization header string false "认证令牌"
// @Param organ body []model.Organ false "城市信息"
// @Failure 403 {object} model.Fail
// @Success 200 {object} model.Success
// @Failure 500 {object} model.Fail
// @Router /api/organ/batch_update [put]
func OrganBatchUpdate(ctx *Context) {
var payload []model.Organ
var err error
var ret []int64
var r int64
if err := ctx.ShouldBindBodyWith(&payload, binding.JSON); err != nil {
logrus.Error(err)
ctx.Fail(err)
return
}
s := ctx.DB.NewSession()
s.Begin()
defer s.Close()
s.Begin()
defer s.Close()
for i := range payload {
payload[i].UpdateTime = null.TimeFrom(time.Now().Value())
payload[i].Updater = null.StringFrom(ctx.GetToken().GetUserID())
r, err = s.ID(payload[i].ID.String).Update(&payload[i])
if err != nil {
logrus.Error(err)
s.Rollback()
ctx.Fail(err)
return
}
ret = append(ret, r)
}
if err != nil {
logrus.Error(err)
s.Rollback()
ctx.Fail(err)
return
}
err = s.Commit()
if err != nil {
logrus.Error(err)
ctx.Fail(err)
return
}
ctx.Success(ret)
}

// OrganPage api implementation
// @Summary 城市分页查询
// @Tags 城市
// @Param Authorization header string false "认证令牌"
// @Param page query int false "页码"
// @Param size query int false "单页数"
// @Failure 403 {object} model.Fail
// @Success 200 {object} model.Success
// @Failure 500 {object} model.Fail
// @Router /api/organ/page [get]
func OrganPage(ctx *Context) {
q := ctx.TypeQuery()
q.SetInt("page", 1)
q.SetInt("size", 15)
q.SetRule("organ_page")
q.SetString("creater")
q.SetString("updater")
q.SetRange("create_time")
q.SetRange("update_time")
q.SetInt("is_delete", 0)()
q.SetString("sort", "update_time desc")
q.SetTags()
ret, err := ctx.PageSearch(ctx.DB, "organ", "page", "organ", q.Value())
if err != nil {
logrus.Error(err)
ctx.Fail(err)
return
}
ctx.Success(ret)
}

// OrganGet api implementation
// @Summary 获取城市信息
// @Tags 城市
// @Param Authorization header string false "认证令牌"
// @Param id query string false "城市id"
// @Failure 403 {object} model.Fail
// @Success 200 {object} model.Success
// @Failure 500 {object} model.Fail
// @Router /api/organ/get [get]
func OrganGet(ctx *Context) {
var entity model.Organ
err := ctx.ShouldBindQuery(&entity)
if err != nil {
logrus.Error(err)
ctx.Fail(err)
return
}
if ext, err := ctx.DB.Get(&entity); err != nil {
logrus.Error(err)
ctx.Fail(err)
return
} else if !ext {
ctx.Fail(errors.New("not found"))
return
}
ctx.Success(entity)
}
Loading

0 comments on commit cee975f

Please sign in to comment.