use goctl template to generate all kinds of templates

master
kevin 4 years ago
parent 85a815bea0
commit dfe6e88529

@ -0,0 +1,11 @@
package errorx
func Chain(fns ...func() error) error {
for _, fn := range fns {
if err := fn(); err != nil {
return err
}
}
return nil
}

@ -0,0 +1,27 @@
package errorx
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
)
func TestChain(t *testing.T) {
var errDummy = errors.New("dummy")
assert.Nil(t, Chain(func() error {
return nil
}, func() error {
return nil
}))
assert.Equal(t, errDummy, Chain(func() error {
return errDummy
}, func() error {
return nil
}))
assert.Equal(t, errDummy, Chain(func() error {
return nil
}, func() error {
return errDummy
}))
}

@ -8,7 +8,7 @@ import (
"github.com/tal-tech/go-zero/tools/goctl/api/spec" "github.com/tal-tech/go-zero/tools/goctl/api/spec"
"github.com/tal-tech/go-zero/tools/goctl/api/util" "github.com/tal-tech/go-zero/tools/goctl/api/util"
"github.com/tal-tech/go-zero/tools/goctl/templatex" ctlutil "github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/tal-tech/go-zero/tools/goctl/vars" "github.com/tal-tech/go-zero/tools/goctl/vars"
) )
@ -48,7 +48,7 @@ func genConfig(dir string, api *spec.ApiSpec) error {
} }
var authImportStr = fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceUrl) var authImportStr = fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceUrl)
text, err := templatex.LoadTemplate(category, configTemplateFile, configTemplate) text, err := ctlutil.LoadTemplate(category, configTemplateFile, configTemplate)
if err != nil { if err != nil {
return err return err
} }

@ -8,7 +8,7 @@ import (
"github.com/tal-tech/go-zero/tools/goctl/api/spec" "github.com/tal-tech/go-zero/tools/goctl/api/spec"
"github.com/tal-tech/go-zero/tools/goctl/api/util" "github.com/tal-tech/go-zero/tools/goctl/api/util"
"github.com/tal-tech/go-zero/tools/goctl/templatex" ctlutil "github.com/tal-tech/go-zero/tools/goctl/util"
) )
const ( const (
@ -40,7 +40,7 @@ func genEtc(dir string, api *spec.ApiSpec) error {
port = strconv.Itoa(defaultPort) port = strconv.Itoa(defaultPort)
} }
text, err := templatex.LoadTemplate(category, etcTemplateFile, etcTemplate) text, err := ctlutil.LoadTemplate(category, etcTemplateFile, etcTemplate)
if err != nil { if err != nil {
return err return err
} }

@ -9,7 +9,6 @@ import (
"github.com/tal-tech/go-zero/tools/goctl/api/spec" "github.com/tal-tech/go-zero/tools/goctl/api/spec"
apiutil "github.com/tal-tech/go-zero/tools/goctl/api/util" apiutil "github.com/tal-tech/go-zero/tools/goctl/api/util"
"github.com/tal-tech/go-zero/tools/goctl/templatex"
"github.com/tal-tech/go-zero/tools/goctl/util" "github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/tal-tech/go-zero/tools/goctl/vars" "github.com/tal-tech/go-zero/tools/goctl/vars"
) )
@ -94,7 +93,7 @@ func doGenToFile(dir, handler string, group spec.Group, route spec.Route, handle
} }
defer fp.Close() defer fp.Close()
text, err := templatex.LoadTemplate(category, handlerTemplateFile, handlerTemplate) text, err := util.LoadTemplate(category, handlerTemplateFile, handlerTemplate)
if err != nil { if err != nil {
return err return err
} }

@ -9,7 +9,6 @@ import (
"github.com/tal-tech/go-zero/tools/goctl/api/spec" "github.com/tal-tech/go-zero/tools/goctl/api/spec"
"github.com/tal-tech/go-zero/tools/goctl/api/util" "github.com/tal-tech/go-zero/tools/goctl/api/util"
"github.com/tal-tech/go-zero/tools/goctl/templatex"
ctlutil "github.com/tal-tech/go-zero/tools/goctl/util" ctlutil "github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/tal-tech/go-zero/tools/goctl/vars" "github.com/tal-tech/go-zero/tools/goctl/vars"
) )
@ -94,7 +93,7 @@ func genLogicByRoute(dir string, group spec.Group, route spec.Route) error {
requestString = "req " + "types." + strings.Title(route.RequestType.Name) requestString = "req " + "types." + strings.Title(route.RequestType.Name)
} }
text, err := templatex.LoadTemplate(category, logicTemplateFile, logicTemplate) text, err := ctlutil.LoadTemplate(category, logicTemplateFile, logicTemplate)
if err != nil { if err != nil {
return err return err
} }

@ -8,7 +8,6 @@ import (
"github.com/tal-tech/go-zero/tools/goctl/api/spec" "github.com/tal-tech/go-zero/tools/goctl/api/spec"
"github.com/tal-tech/go-zero/tools/goctl/api/util" "github.com/tal-tech/go-zero/tools/goctl/api/util"
"github.com/tal-tech/go-zero/tools/goctl/templatex"
ctlutil "github.com/tal-tech/go-zero/tools/goctl/util" ctlutil "github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/tal-tech/go-zero/tools/goctl/vars" "github.com/tal-tech/go-zero/tools/goctl/vars"
) )
@ -61,7 +60,7 @@ func genMain(dir string, api *spec.ApiSpec) error {
return err return err
} }
text, err := templatex.LoadTemplate(category, mainTemplateFile, mainTemplate) text, err := ctlutil.LoadTemplate(category, mainTemplateFile, mainTemplate)
if err != nil { if err != nil {
return err return err
} }

@ -7,7 +7,6 @@ import (
"github.com/tal-tech/go-zero/tools/goctl/api/spec" "github.com/tal-tech/go-zero/tools/goctl/api/spec"
"github.com/tal-tech/go-zero/tools/goctl/api/util" "github.com/tal-tech/go-zero/tools/goctl/api/util"
"github.com/tal-tech/go-zero/tools/goctl/templatex"
ctlutil "github.com/tal-tech/go-zero/tools/goctl/util" ctlutil "github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/tal-tech/go-zero/tools/goctl/vars" "github.com/tal-tech/go-zero/tools/goctl/vars"
) )
@ -52,7 +51,7 @@ func genServiceContext(dir string, api *spec.ApiSpec) error {
return err return err
} }
text, err := templatex.LoadTemplate(category, contextTemplateFile, contextTemplate) text, err := ctlutil.LoadTemplate(category, contextTemplateFile, contextTemplate)
if err != nil { if err != nil {
return err return err
} }

@ -1,7 +1,7 @@
package gogen package gogen
import ( import (
"github.com/tal-tech/go-zero/tools/goctl/templatex" "github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/urfave/cli" "github.com/urfave/cli"
) )
@ -25,5 +25,5 @@ var templates = map[string]string{
} }
func GenTemplates(_ *cli.Context) error { func GenTemplates(_ *cli.Context) error {
return templatex.InitTemplates(category, templates) return util.InitTemplates(category, templates)
} }

@ -102,13 +102,6 @@ var (
}, },
}, },
Action: gogen.GoCommand, Action: gogen.GoCommand,
Subcommands: []cli.Command{
{
Name: "template",
Usage: "initialize the api templates",
Action: gogen.GenTemplates,
},
},
}, },
{ {
Name: "java", Name: "java",
@ -339,6 +332,11 @@ var (
Usage: "the features of the latest version", Usage: "the features of the latest version",
Action: feature.Feature, Action: feature.Feature,
}, },
{
Name: "template",
Usage: "initialize the api templates",
Action: gogen.GenTemplates,
},
} }
) )

@ -5,7 +5,7 @@ import (
"github.com/tal-tech/go-zero/core/collection" "github.com/tal-tech/go-zero/core/collection"
"github.com/tal-tech/go-zero/tools/goctl/model/sql/template" "github.com/tal-tech/go-zero/tools/goctl/model/sql/template"
"github.com/tal-tech/go-zero/tools/goctl/templatex" "github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/tal-tech/go-zero/tools/goctl/util/stringx" "github.com/tal-tech/go-zero/tools/goctl/util/stringx"
) )
@ -22,7 +22,7 @@ func genDelete(table Table, withCache bool) (string, error) {
} }
camel := table.Name.ToCamel() camel := table.Name.ToCamel()
output, err := templatex.With("delete"). output, err := util.With("delete").
Parse(template.Delete). Parse(template.Delete).
Execute(map[string]interface{}{ Execute(map[string]interface{}{
"upperStartCamelObject": camel, "upperStartCamelObject": camel,

@ -5,7 +5,7 @@ import (
"github.com/tal-tech/go-zero/tools/goctl/model/sql/parser" "github.com/tal-tech/go-zero/tools/goctl/model/sql/parser"
"github.com/tal-tech/go-zero/tools/goctl/model/sql/template" "github.com/tal-tech/go-zero/tools/goctl/model/sql/template"
"github.com/tal-tech/go-zero/tools/goctl/templatex" "github.com/tal-tech/go-zero/tools/goctl/util"
) )
func genFields(fields []parser.Field) (string, error) { func genFields(fields []parser.Field) (string, error) {
@ -25,7 +25,7 @@ func genField(field parser.Field) (string, error) {
if err != nil { if err != nil {
return "", err return "", err
} }
output, err := templatex.With("types"). output, err := util.With("types").
Parse(template.Field). Parse(template.Field).
Execute(map[string]interface{}{ Execute(map[string]interface{}{
"name": field.Name.ToCamel(), "name": field.Name.ToCamel(),

@ -2,13 +2,13 @@ package gen
import ( import (
"github.com/tal-tech/go-zero/tools/goctl/model/sql/template" "github.com/tal-tech/go-zero/tools/goctl/model/sql/template"
"github.com/tal-tech/go-zero/tools/goctl/templatex" "github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/tal-tech/go-zero/tools/goctl/util/stringx" "github.com/tal-tech/go-zero/tools/goctl/util/stringx"
) )
func genFindOne(table Table, withCache bool) (string, error) { func genFindOne(table Table, withCache bool) (string, error) {
camel := table.Name.ToCamel() camel := table.Name.ToCamel()
output, err := templatex.With("findOne"). output, err := util.With("findOne").
Parse(template.FindOne). Parse(template.FindOne).
Execute(map[string]interface{}{ Execute(map[string]interface{}{
"withCache": withCache, "withCache": withCache,

@ -5,12 +5,12 @@ import (
"strings" "strings"
"github.com/tal-tech/go-zero/tools/goctl/model/sql/template" "github.com/tal-tech/go-zero/tools/goctl/model/sql/template"
"github.com/tal-tech/go-zero/tools/goctl/templatex" "github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/tal-tech/go-zero/tools/goctl/util/stringx" "github.com/tal-tech/go-zero/tools/goctl/util/stringx"
) )
func genFindOneByField(table Table, withCache bool) (string, string, error) { func genFindOneByField(table Table, withCache bool) (string, string, error) {
t := templatex.With("findOneByField").Parse(template.FindOneByField) t := util.With("findOneByField").Parse(template.FindOneByField)
var list []string var list []string
camelTableName := table.Name.ToCamel() camelTableName := table.Name.ToCamel()
for _, field := range table.Fields { for _, field := range table.Fields {
@ -36,7 +36,7 @@ func genFindOneByField(table Table, withCache bool) (string, string, error) {
list = append(list, output.String()) list = append(list, output.String())
} }
if withCache { if withCache {
out, err := templatex.With("findOneByFieldExtraMethod").Parse(template.FindOneByFieldExtraMethod).Execute(map[string]interface{}{ out, err := util.With("findOneByFieldExtraMethod").Parse(template.FindOneByFieldExtraMethod).Execute(map[string]interface{}{
"upperStartCamelObject": camelTableName, "upperStartCamelObject": camelTableName,
"primaryKeyLeft": table.CacheKey[table.PrimaryKey.Name.Source()].Left, "primaryKeyLeft": table.CacheKey[table.PrimaryKey.Name.Source()].Left,
"lowerStartCamelObject": stringx.From(camelTableName).UnTitle(), "lowerStartCamelObject": stringx.From(camelTableName).UnTitle(),

@ -9,7 +9,6 @@ import (
"github.com/tal-tech/go-zero/tools/goctl/model/sql/parser" "github.com/tal-tech/go-zero/tools/goctl/model/sql/parser"
"github.com/tal-tech/go-zero/tools/goctl/model/sql/template" "github.com/tal-tech/go-zero/tools/goctl/model/sql/template"
"github.com/tal-tech/go-zero/tools/goctl/templatex"
"github.com/tal-tech/go-zero/tools/goctl/util" "github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/tal-tech/go-zero/tools/goctl/util/console" "github.com/tal-tech/go-zero/tools/goctl/util/console"
"github.com/tal-tech/go-zero/tools/goctl/util/stringx" "github.com/tal-tech/go-zero/tools/goctl/util/stringx"
@ -120,7 +119,7 @@ type (
) )
func (g *defaultGenerator) genModel(in parser.Table, withCache bool) (string, error) { func (g *defaultGenerator) genModel(in parser.Table, withCache bool) (string, error) {
t := templatex.With("model"). t := util.With("model").
Parse(template.Model). Parse(template.Model).
GoFmt(true) GoFmt(true)

@ -2,12 +2,12 @@ package gen
import ( import (
"github.com/tal-tech/go-zero/tools/goctl/model/sql/template" "github.com/tal-tech/go-zero/tools/goctl/model/sql/template"
"github.com/tal-tech/go-zero/tools/goctl/templatex" "github.com/tal-tech/go-zero/tools/goctl/util"
) )
func genImports(withCache, timeImport bool) (string, error) { func genImports(withCache, timeImport bool) (string, error) {
if withCache { if withCache {
buffer, err := templatex.With("import").Parse(template.Imports).Execute(map[string]interface{}{ buffer, err := util.With("import").Parse(template.Imports).Execute(map[string]interface{}{
"time": timeImport, "time": timeImport,
}) })
if err != nil { if err != nil {
@ -15,7 +15,7 @@ func genImports(withCache, timeImport bool) (string, error) {
} }
return buffer.String(), nil return buffer.String(), nil
} else { } else {
buffer, err := templatex.With("import").Parse(template.ImportsNoCache).Execute(map[string]interface{}{ buffer, err := util.With("import").Parse(template.ImportsNoCache).Execute(map[string]interface{}{
"time": timeImport, "time": timeImport,
}) })
if err != nil { if err != nil {

@ -5,7 +5,7 @@ import (
"github.com/tal-tech/go-zero/core/collection" "github.com/tal-tech/go-zero/core/collection"
"github.com/tal-tech/go-zero/tools/goctl/model/sql/template" "github.com/tal-tech/go-zero/tools/goctl/model/sql/template"
"github.com/tal-tech/go-zero/tools/goctl/templatex" "github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/tal-tech/go-zero/tools/goctl/util/stringx" "github.com/tal-tech/go-zero/tools/goctl/util/stringx"
) )
@ -34,7 +34,7 @@ func genInsert(table Table, withCache bool) (string, error) {
expressionValues = append(expressionValues, "data."+camel) expressionValues = append(expressionValues, "data."+camel)
} }
camel := table.Name.ToCamel() camel := table.Name.ToCamel()
output, err := templatex.With("insert"). output, err := util.With("insert").
Parse(template.Insert). Parse(template.Insert).
Execute(map[string]interface{}{ Execute(map[string]interface{}{
"withCache": withCache, "withCache": withCache,

@ -2,11 +2,11 @@ package gen
import ( import (
"github.com/tal-tech/go-zero/tools/goctl/model/sql/template" "github.com/tal-tech/go-zero/tools/goctl/model/sql/template"
"github.com/tal-tech/go-zero/tools/goctl/templatex" "github.com/tal-tech/go-zero/tools/goctl/util"
) )
func genNew(table Table, withCache bool) (string, error) { func genNew(table Table, withCache bool) (string, error) {
output, err := templatex.With("new"). output, err := util.With("new").
Parse(template.New). Parse(template.New).
Execute(map[string]interface{}{ Execute(map[string]interface{}{
"withCache": withCache, "withCache": withCache,

@ -2,14 +2,14 @@ package gen
import ( import (
"github.com/tal-tech/go-zero/tools/goctl/model/sql/template" "github.com/tal-tech/go-zero/tools/goctl/model/sql/template"
"github.com/tal-tech/go-zero/tools/goctl/templatex" "github.com/tal-tech/go-zero/tools/goctl/util"
) )
func genTag(in string) (string, error) { func genTag(in string) (string, error) {
if in == "" { if in == "" {
return in, nil return in, nil
} }
output, err := templatex.With("tag"). output, err := util.With("tag").
Parse(template.Tag). Parse(template.Tag).
Execute(map[string]interface{}{ Execute(map[string]interface{}{
"field": in, "field": in,

@ -2,7 +2,7 @@ package gen
import ( import (
"github.com/tal-tech/go-zero/tools/goctl/model/sql/template" "github.com/tal-tech/go-zero/tools/goctl/model/sql/template"
"github.com/tal-tech/go-zero/tools/goctl/templatex" "github.com/tal-tech/go-zero/tools/goctl/util"
) )
func genTypes(table Table, withCache bool) (string, error) { func genTypes(table Table, withCache bool) (string, error) {
@ -11,7 +11,7 @@ func genTypes(table Table, withCache bool) (string, error) {
if err != nil { if err != nil {
return "", err return "", err
} }
output, err := templatex.With("types"). output, err := util.With("types").
Parse(template.Types). Parse(template.Types).
Execute(map[string]interface{}{ Execute(map[string]interface{}{
"withCache": withCache, "withCache": withCache,

@ -4,7 +4,7 @@ import (
"strings" "strings"
"github.com/tal-tech/go-zero/tools/goctl/model/sql/template" "github.com/tal-tech/go-zero/tools/goctl/model/sql/template"
"github.com/tal-tech/go-zero/tools/goctl/templatex" "github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/tal-tech/go-zero/tools/goctl/util/stringx" "github.com/tal-tech/go-zero/tools/goctl/util/stringx"
) )
@ -22,7 +22,7 @@ func genUpdate(table Table, withCache bool) (string, error) {
} }
expressionValues = append(expressionValues, "data."+table.PrimaryKey.Name.ToCamel()) expressionValues = append(expressionValues, "data."+table.PrimaryKey.Name.ToCamel())
camelTableName := table.Name.ToCamel() camelTableName := table.Name.ToCamel()
output, err := templatex.With("update"). output, err := util.With("update").
Parse(template.Update). Parse(template.Update).
Execute(map[string]interface{}{ Execute(map[string]interface{}{
"withCache": withCache, "withCache": withCache,

@ -4,7 +4,7 @@ import (
"strings" "strings"
"github.com/tal-tech/go-zero/tools/goctl/model/sql/template" "github.com/tal-tech/go-zero/tools/goctl/model/sql/template"
"github.com/tal-tech/go-zero/tools/goctl/templatex" "github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/tal-tech/go-zero/tools/goctl/util/stringx" "github.com/tal-tech/go-zero/tools/goctl/util/stringx"
) )
@ -14,7 +14,7 @@ func genVars(table Table, withCache bool) (string, error) {
keys = append(keys, v.VarExpression) keys = append(keys, v.VarExpression)
} }
camel := table.Name.ToCamel() camel := table.Name.ToCamel()
output, err := templatex.With("var"). output, err := util.With("var").
Parse(template.Vars). Parse(template.Vars).
GoFmt(true). GoFmt(true).
Execute(map[string]interface{}{ Execute(map[string]interface{}{

@ -7,7 +7,6 @@ import (
"github.com/tal-tech/go-zero/core/collection" "github.com/tal-tech/go-zero/core/collection"
"github.com/tal-tech/go-zero/tools/goctl/rpc/parser" "github.com/tal-tech/go-zero/tools/goctl/rpc/parser"
"github.com/tal-tech/go-zero/tools/goctl/templatex"
"github.com/tal-tech/go-zero/tools/goctl/util" "github.com/tal-tech/go-zero/tools/goctl/util"
) )
@ -123,8 +122,8 @@ func (g *defaultRpcGenerator) genCall() error {
} }
filename := filepath.Join(callPath, typesFilename) filename := filepath.Join(callPath, typesFilename)
head := templatex.GetHead(g.Ctx.ProtoSource) head := util.GetHead(g.Ctx.ProtoSource)
err = templatex.With("types").GoFmt(true).Parse(callTemplateTypes).SaveTo(map[string]interface{}{ err = util.With("types").GoFmt(true).Parse(callTemplateTypes).SaveTo(map[string]interface{}{
"head": head, "head": head,
"const": constLit, "const": constLit,
"filePackage": service.Name.Lower(), "filePackage": service.Name.Lower(),
@ -147,7 +146,7 @@ func (g *defaultRpcGenerator) genCall() error {
return err return err
} }
err = templatex.With("shared").GoFmt(true).Parse(callTemplateText).SaveTo(map[string]interface{}{ err = util.With("shared").GoFmt(true).Parse(callTemplateText).SaveTo(map[string]interface{}{
"name": service.Name.Lower(), "name": service.Name.Lower(),
"head": head, "head": head,
"filePackage": service.Name.Lower(), "filePackage": service.Name.Lower(),
@ -167,7 +166,7 @@ func (g *defaultRpcGenerator) genFunction(service *parser.RpcService) ([]string,
imports.AddStr(fmt.Sprintf(`%v "%v"`, pkgName, g.mustGetPackage(dirPb))) imports.AddStr(fmt.Sprintf(`%v "%v"`, pkgName, g.mustGetPackage(dirPb)))
for _, method := range service.Funcs { for _, method := range service.Funcs {
imports.AddStr(g.ast.Imports[method.ParameterIn.Package]) imports.AddStr(g.ast.Imports[method.ParameterIn.Package])
buffer, err := templatex.With("sharedFn").Parse(callFunctionTemplate).Execute(map[string]interface{}{ buffer, err := util.With("sharedFn").Parse(callFunctionTemplate).Execute(map[string]interface{}{
"rpcServiceName": service.Name.Title(), "rpcServiceName": service.Name.Title(),
"method": method.Name.Title(), "method": method.Name.Title(),
"package": pkgName, "package": pkgName,
@ -190,7 +189,7 @@ func (g *defaultRpcGenerator) getInterfaceFuncs(service *parser.RpcService) ([]s
functions := make([]string, 0) functions := make([]string, 0)
for _, method := range service.Funcs { for _, method := range service.Funcs {
buffer, err := templatex.With("interfaceFn").Parse(callInterfaceFunctionTemplate).Execute( buffer, err := util.With("interfaceFn").Parse(callInterfaceFunctionTemplate).Execute(
map[string]interface{}{ map[string]interface{}{
"hasComment": method.HaveDoc(), "hasComment": method.HaveDoc(),
"comment": method.GetDoc(), "comment": method.GetDoc(),

@ -4,7 +4,6 @@ import (
"fmt" "fmt"
"path/filepath" "path/filepath"
"github.com/tal-tech/go-zero/tools/goctl/templatex"
"github.com/tal-tech/go-zero/tools/goctl/util" "github.com/tal-tech/go-zero/tools/goctl/util"
) )
@ -23,7 +22,7 @@ func (g *defaultRpcGenerator) genEtc() error {
return nil return nil
} }
return templatex.With("etc").Parse(etcTemplate).SaveTo(map[string]interface{}{ return util.With("etc").Parse(etcTemplate).SaveTo(map[string]interface{}{
"serviceName": g.Ctx.ServiceName.Lower(), "serviceName": g.Ctx.ServiceName.Lower(),
}, fileName, false) }, fileName, false)
} }

@ -7,7 +7,6 @@ import (
"github.com/tal-tech/go-zero/core/collection" "github.com/tal-tech/go-zero/core/collection"
"github.com/tal-tech/go-zero/tools/goctl/rpc/parser" "github.com/tal-tech/go-zero/tools/goctl/rpc/parser"
"github.com/tal-tech/go-zero/tools/goctl/templatex"
"github.com/tal-tech/go-zero/tools/goctl/util" "github.com/tal-tech/go-zero/tools/goctl/util"
) )
@ -62,7 +61,7 @@ func (g *defaultRpcGenerator) genLogic() error {
svcImport := fmt.Sprintf(`"%v"`, g.mustGetPackage(dirSvc)) svcImport := fmt.Sprintf(`"%v"`, g.mustGetPackage(dirSvc))
imports.AddStr(svcImport) imports.AddStr(svcImport)
imports.AddStr(importList...) imports.AddStr(importList...)
err = templatex.With("logic").GoFmt(true).Parse(logicTemplate).SaveTo(map[string]interface{}{ err = util.With("logic").GoFmt(true).Parse(logicTemplate).SaveTo(map[string]interface{}{
"logicName": fmt.Sprintf("%sLogic", method.Name.Title()), "logicName": fmt.Sprintf("%sLogic", method.Name.Title()),
"functions": functions, "functions": functions,
"imports": strings.Join(imports.KeysStr(), util.NL), "imports": strings.Join(imports.KeysStr(), util.NL),
@ -83,7 +82,7 @@ func (g *defaultRpcGenerator) genLogicFunction(packageName string, method *parse
} }
imports.AddStr(g.ast.Imports[method.ParameterIn.Package]) imports.AddStr(g.ast.Imports[method.ParameterIn.Package])
imports.AddStr(g.ast.Imports[method.ParameterOut.Package]) imports.AddStr(g.ast.Imports[method.ParameterOut.Package])
buffer, err := templatex.With("fun").Parse(logicFunctionTemplate).Execute(map[string]interface{}{ buffer, err := util.With("fun").Parse(logicFunctionTemplate).Execute(map[string]interface{}{
"logicName": fmt.Sprintf("%sLogic", method.Name.Title()), "logicName": fmt.Sprintf("%sLogic", method.Name.Title()),
"method": method.Name.Title(), "method": method.Name.Title(),
"request": method.ParameterIn.StarExpression, "request": method.ParameterIn.StarExpression,

@ -6,7 +6,6 @@ import (
"strings" "strings"
"github.com/tal-tech/go-zero/tools/goctl/rpc/parser" "github.com/tal-tech/go-zero/tools/goctl/rpc/parser"
"github.com/tal-tech/go-zero/tools/goctl/templatex"
"github.com/tal-tech/go-zero/tools/goctl/util" "github.com/tal-tech/go-zero/tools/goctl/util"
) )
@ -58,8 +57,8 @@ func (g *defaultRpcGenerator) genMain() error {
configImport := fmt.Sprintf(`"%v"`, g.mustGetPackage(dirConfig)) configImport := fmt.Sprintf(`"%v"`, g.mustGetPackage(dirConfig))
imports = append(imports, configImport, pbImport, remoteImport, svcImport) imports = append(imports, configImport, pbImport, remoteImport, svcImport)
srv, registers := g.genServer(pkg, file.Service) srv, registers := g.genServer(pkg, file.Service)
head := templatex.GetHead(g.Ctx.ProtoSource) head := util.GetHead(g.Ctx.ProtoSource)
return templatex.With("main").GoFmt(true).Parse(mainTemplate).SaveTo(map[string]interface{}{ return util.With("main").GoFmt(true).Parse(mainTemplate).SaveTo(map[string]interface{}{
"head": head, "head": head,
"package": pkg, "package": pkg,
"serviceName": g.Ctx.ServiceName.Lower(), "serviceName": g.Ctx.ServiceName.Lower(),

@ -7,7 +7,6 @@ import (
"github.com/tal-tech/go-zero/core/collection" "github.com/tal-tech/go-zero/core/collection"
"github.com/tal-tech/go-zero/tools/goctl/rpc/parser" "github.com/tal-tech/go-zero/tools/goctl/rpc/parser"
"github.com/tal-tech/go-zero/tools/goctl/templatex"
"github.com/tal-tech/go-zero/tools/goctl/util" "github.com/tal-tech/go-zero/tools/goctl/util"
) )
@ -52,7 +51,7 @@ func (g *defaultRpcGenerator) genHandler() error {
imports := collection.NewSet() imports := collection.NewSet()
imports.AddStr(logicImport, svcImport) imports.AddStr(logicImport, svcImport)
head := templatex.GetHead(g.Ctx.ProtoSource) head := util.GetHead(g.Ctx.ProtoSource)
for _, service := range file.Service { for _, service := range file.Service {
filename := fmt.Sprintf("%vserver.go", service.Name.Lower()) filename := fmt.Sprintf("%vserver.go", service.Name.Lower())
serverFile := filepath.Join(serverPath, filename) serverFile := filepath.Join(serverPath, filename)
@ -61,7 +60,7 @@ func (g *defaultRpcGenerator) genHandler() error {
return err return err
} }
imports.AddStr(importList...) imports.AddStr(importList...)
err = templatex.With("server").GoFmt(true).Parse(serverTemplate).SaveTo(map[string]interface{}{ err = util.With("server").GoFmt(true).Parse(serverTemplate).SaveTo(map[string]interface{}{
"head": head, "head": head,
"types": fmt.Sprintf(typeFmt, service.Name.Title()), "types": fmt.Sprintf(typeFmt, service.Name.Title()),
"server": service.Name.Title(), "server": service.Name.Title(),
@ -86,7 +85,7 @@ func (g *defaultRpcGenerator) genFunctions(service *parser.RpcService) ([]string
} }
imports.AddStr(g.ast.Imports[method.ParameterIn.Package]) imports.AddStr(g.ast.Imports[method.ParameterIn.Package])
imports.AddStr(g.ast.Imports[method.ParameterOut.Package]) imports.AddStr(g.ast.Imports[method.ParameterOut.Package])
buffer, err := templatex.With("func").Parse(functionTemplate).Execute(map[string]interface{}{ buffer, err := util.With("func").Parse(functionTemplate).Execute(map[string]interface{}{
"server": service.Name.Title(), "server": service.Name.Title(),
"logicName": fmt.Sprintf("%sLogic", method.Name.Title()), "logicName": fmt.Sprintf("%sLogic", method.Name.Title()),
"method": method.Name.Title(), "method": method.Name.Title(),

@ -4,7 +4,7 @@ import (
"fmt" "fmt"
"path/filepath" "path/filepath"
"github.com/tal-tech/go-zero/tools/goctl/templatex" "github.com/tal-tech/go-zero/tools/goctl/util"
) )
const svcTemplate = `package svc const svcTemplate = `package svc
@ -25,7 +25,7 @@ func NewServiceContext(c config.Config) *ServiceContext {
func (g *defaultRpcGenerator) genSvc() error { func (g *defaultRpcGenerator) genSvc() error {
svcPath := g.dirM[dirSvc] svcPath := g.dirM[dirSvc]
fileName := filepath.Join(svcPath, fileServiceContext) fileName := filepath.Join(svcPath, fileServiceContext)
return templatex.With("svc").GoFmt(true).Parse(svcTemplate).SaveTo(map[string]interface{}{ return util.With("svc").GoFmt(true).Parse(svcTemplate).SaveTo(map[string]interface{}{
"imports": fmt.Sprintf(`"%v"`, g.mustGetPackage(dirConfig)), "imports": fmt.Sprintf(`"%v"`, g.mustGetPackage(dirConfig)),
}, fileName, false) }, fileName, false)
} }

@ -4,7 +4,7 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/tal-tech/go-zero/tools/goctl/templatex" "github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/tal-tech/go-zero/tools/goctl/util/console" "github.com/tal-tech/go-zero/tools/goctl/util/console"
"github.com/tal-tech/go-zero/tools/goctl/util/stringx" "github.com/tal-tech/go-zero/tools/goctl/util/stringx"
) )
@ -43,7 +43,7 @@ func (r *rpcTemplate) MustGenerate(showState bool) {
r.Info("generating template...") r.Info("generating template...")
protoFilename := filepath.Base(r.out) protoFilename := filepath.Base(r.out)
serviceName := stringx.From(strings.TrimSuffix(protoFilename, filepath.Ext(protoFilename))) serviceName := stringx.From(strings.TrimSuffix(protoFilename, filepath.Ext(protoFilename)))
err := templatex.With("t").Parse(rpcTemplateText).SaveTo(map[string]string{ err := util.With("t").Parse(rpcTemplateText).SaveTo(map[string]string{
"package": serviceName.UnTitle(), "package": serviceName.UnTitle(),
"serviceName": serviceName.Title(), "serviceName": serviceName.Title(),
}, r.out, false) }, r.out, false)

@ -12,7 +12,6 @@ import (
"github.com/tal-tech/go-zero/core/lang" "github.com/tal-tech/go-zero/core/lang"
sx "github.com/tal-tech/go-zero/core/stringx" sx "github.com/tal-tech/go-zero/core/stringx"
"github.com/tal-tech/go-zero/tools/goctl/templatex"
"github.com/tal-tech/go-zero/tools/goctl/util" "github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/tal-tech/go-zero/tools/goctl/util/console" "github.com/tal-tech/go-zero/tools/goctl/util/console"
"github.com/tal-tech/go-zero/tools/goctl/util/stringx" "github.com/tal-tech/go-zero/tools/goctl/util/stringx"
@ -590,7 +589,7 @@ func (a *PbAst) GenTypesCode() (string, error) {
types = append(types, typeCode) types = append(types, typeCode)
} }
buffer, err := templatex.With("type").Parse(typeTemplate).Execute(map[string]interface{}{ buffer, err := util.With("type").Parse(typeTemplate).Execute(map[string]interface{}{
"types": strings.Join(types, util.NL+util.NL), "types": strings.Join(types, util.NL+util.NL),
}) })
if err != nil { if err != nil {
@ -615,7 +614,7 @@ func (s *Struct) genCode(containsTypeStatement bool) (string, error) {
comment = f.Comment[0] comment = f.Comment[0]
} }
doc = strings.Join(f.Document, util.NL) doc = strings.Join(f.Document, util.NL)
buffer, err := templatex.With(sx.Rand()).Parse(fieldTemplate).Execute(map[string]interface{}{ buffer, err := util.With(sx.Rand()).Parse(fieldTemplate).Execute(map[string]interface{}{
"name": f.Name.Title(), "name": f.Name.Title(),
"type": f.Type.InvokeTypeExpression, "type": f.Type.InvokeTypeExpression,
"tag": f.JsonTag, "tag": f.JsonTag,
@ -630,7 +629,7 @@ func (s *Struct) genCode(containsTypeStatement bool) (string, error) {
fields = append(fields, buffer.String()) fields = append(fields, buffer.String())
} }
buffer, err := templatex.With("struct").Parse(structTemplate).Execute(map[string]interface{}{ buffer, err := util.With("struct").Parse(structTemplate).Execute(map[string]interface{}{
"type": containsTypeStatement, "type": containsTypeStatement,
"name": s.Name.Title(), "name": s.Name.Title(),
"fields": strings.Join(fields, util.NL), "fields": strings.Join(fields, util.NL),

@ -10,7 +10,6 @@ import (
"github.com/emicklei/proto" "github.com/emicklei/proto"
"github.com/tal-tech/go-zero/core/collection" "github.com/tal-tech/go-zero/core/collection"
"github.com/tal-tech/go-zero/core/lang" "github.com/tal-tech/go-zero/core/lang"
"github.com/tal-tech/go-zero/tools/goctl/templatex"
"github.com/tal-tech/go-zero/tools/goctl/util" "github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/tal-tech/go-zero/tools/goctl/util/stringx" "github.com/tal-tech/go-zero/tools/goctl/util/stringx"
) )
@ -263,7 +262,7 @@ func (e *Enum) GenEnumCode() (string, error) {
} }
element = append(element, code) element = append(element, code)
} }
buffer, err := templatex.With("enum").Parse(enumTemplate).Execute(map[string]interface{}{ buffer, err := util.With("enum").Parse(enumTemplate).Execute(map[string]interface{}{
"element": strings.Join(element, util.NL), "element": strings.Join(element, util.NL),
}) })
if err != nil { if err != nil {
@ -273,7 +272,7 @@ func (e *Enum) GenEnumCode() (string, error) {
} }
func (e *Enum) GenEnumTypeCode() (string, error) { func (e *Enum) GenEnumTypeCode() (string, error) {
buffer, err := templatex.With("enumAlias").Parse(enumTypeTemplate).Execute(map[string]interface{}{ buffer, err := util.With("enumAlias").Parse(enumTypeTemplate).Execute(map[string]interface{}{
"name": e.Name.Source(), "name": e.Name.Source(),
}) })
if err != nil { if err != nil {
@ -283,7 +282,7 @@ func (e *Enum) GenEnumTypeCode() (string, error) {
} }
func (e *EnumField) GenEnumFieldCode(parentName string) (string, error) { func (e *EnumField) GenEnumFieldCode(parentName string) (string, error) {
buffer, err := templatex.With("enumField").Parse(enumFiledTemplate).Execute(map[string]interface{}{ buffer, err := util.With("enumField").Parse(enumFiledTemplate).Execute(map[string]interface{}{
"key": e.Key, "key": e.Key,
"name": parentName, "name": parentName,
"value": e.Value, "value": e.Value,

@ -0,0 +1,33 @@
package tpl
import (
"fmt"
"github.com/logrusorgru/aurora"
"github.com/tal-tech/go-zero/core/errorx"
"github.com/tal-tech/go-zero/tools/goctl/api/gogen"
"github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/urfave/cli"
)
const templateParentPath = "/"
func GenTemplates(ctx *cli.Context) error {
if err := errorx.Chain(
func() error {
return gogen.GenTemplates(ctx)
},
); err != nil {
return err
}
dir, err := util.GetTemplateDir(templateParentPath)
if err != nil {
return err
}
fmt.Printf("Templates are generated in %s, %s\n", aurora.Green(dir),
aurora.Red("edit on your risk!"))
return nil
}

@ -1,24 +1,29 @@
package templatex package util
import ( import (
"fmt"
"io/ioutil" "io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"github.com/logrusorgru/aurora"
"github.com/tal-tech/go-zero/tools/goctl/util"
) )
const goctlDir = ".goctl" const goctlDir = ".goctl"
func GetTemplateDir(category string) (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(home, goctlDir, category), nil
}
func InitTemplates(category string, templates map[string]string) error { func InitTemplates(category string, templates map[string]string) error {
dir, err := getTemplateDir(category) dir, err := GetTemplateDir(category)
if err != nil { if err != nil {
return err return err
} }
if err := util.MkdirIfNotExist(dir); err != nil { if err := MkdirIfNotExist(dir); err != nil {
return err return err
} }
@ -28,20 +33,17 @@ func InitTemplates(category string, templates map[string]string) error {
} }
} }
fmt.Printf("Templates are generated in %s, %s\n", aurora.Green(dir),
aurora.Red("edit on your risk!"))
return nil return nil
} }
func LoadTemplate(category, file, builtin string) (string, error) { func LoadTemplate(category, file, builtin string) (string, error) {
dir, err := getTemplateDir(category) dir, err := GetTemplateDir(category)
if err != nil { if err != nil {
return "", err return "", err
} }
file = filepath.Join(dir, file) file = filepath.Join(dir, file)
if !util.FileExists(file) { if !FileExists(file) {
return builtin, nil return builtin, nil
} }
@ -54,7 +56,7 @@ func LoadTemplate(category, file, builtin string) (string, error) {
} }
func createTemplate(file, content string) error { func createTemplate(file, content string) error {
if util.FileExists(file) { if FileExists(file) {
println(1) println(1)
return nil return nil
} }
@ -68,12 +70,3 @@ func createTemplate(file, content string) error {
_, err = f.WriteString(content) _, err = f.WriteString(content)
return err return err
} }
func getTemplateDir(category string) (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(home, goctlDir, category), nil
}

@ -1,4 +1,4 @@
package templatex package util
var headTemplate = `// Code generated by goctl. DO NOT EDIT! var headTemplate = `// Code generated by goctl. DO NOT EDIT!
// Source: {{.source}}` // Source: {{.source}}`

@ -1,12 +1,10 @@
package templatex package util
import ( import (
"bytes" "bytes"
goformat "go/format" goformat "go/format"
"io/ioutil" "io/ioutil"
"text/template" "text/template"
"github.com/tal-tech/go-zero/tools/goctl/util"
) )
const regularPerm = 0666 const regularPerm = 0666
@ -34,7 +32,7 @@ func (t *defaultTemplate) GoFmt(format bool) *defaultTemplate {
} }
func (t *defaultTemplate) SaveTo(data interface{}, path string, forceUpdate bool) error { func (t *defaultTemplate) SaveTo(data interface{}, path string, forceUpdate bool) error {
if util.FileExists(path) && !forceUpdate { if FileExists(path) && !forceUpdate {
return nil return nil
} }
Loading…
Cancel
Save