Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: add projectPkg and servicePkg parameters to gen api template(go module) #3786

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
Open
18 changes: 9 additions & 9 deletions tools/goctl/api/gogen/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,20 +86,20 @@ func DoGenProject(apiFile, dir, style string) error {
}

logx.Must(pathx.MkdirIfNotExist(dir))
rootPkg, err := golang.GetParentPackage(dir)
projectPkg, rootPkg, err := golang.GetParentPackage(dir)
if err != nil {
return err
}

logx.Must(genEtc(dir, cfg, api))
logx.Must(genConfig(dir, cfg, api))
logx.Must(genMain(dir, rootPkg, cfg, api))
logx.Must(genServiceContext(dir, rootPkg, cfg, api))
logx.Must(genTypes(dir, cfg, api))
logx.Must(genRoutes(dir, rootPkg, cfg, api))
logx.Must(genHandlers(dir, rootPkg, cfg, api))
logx.Must(genLogic(dir, rootPkg, cfg, api))
logx.Must(genMiddleware(dir, cfg, api))
logx.Must(genConfig(dir, projectPkg, rootPkg, cfg, api))
logx.Must(genMain(dir, projectPkg, rootPkg, cfg, api))
logx.Must(genServiceContext(dir, projectPkg, rootPkg, cfg, api))
logx.Must(genTypes(dir, projectPkg, rootPkg, cfg, api))
logx.Must(genRoutes(dir, projectPkg, rootPkg, cfg, api))
logx.Must(genHandlers(dir, projectPkg, rootPkg, cfg, api))
logx.Must(genLogic(dir, projectPkg, rootPkg, cfg, api))
logx.Must(genMiddleware(dir, projectPkg, rootPkg, cfg, api))

if err := backupAndSweep(apiFile); err != nil {
return err
Expand Down
4 changes: 3 additions & 1 deletion tools/goctl/api/gogen/genconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const (
//go:embed config.tpl
var configTemplate string

func genConfig(dir string, cfg *config.Config, api *spec.ApiSpec) error {
func genConfig(dir, projectPkg, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error {
filename, err := format.FileNamingFormat(cfg.NamingFormat, configFile)
if err != nil {
return err
Expand Down Expand Up @@ -57,6 +57,8 @@ func genConfig(dir string, cfg *config.Config, api *spec.ApiSpec) error {
templateFile: configTemplateFile,
builtinTemplate: configTemplate,
data: map[string]string{
"projectPkg": projectPkg,
"servicePkg": rootPkg,
"authImport": authImportStr,
"auth": strings.Join(auths, "\n"),
"jwtTrans": strings.Join(jwtTransList, "\n"),
Expand Down
11 changes: 7 additions & 4 deletions tools/goctl/api/gogen/genhandlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ const defaultLogicPackage = "logic"
var handlerTemplate string

type handlerInfo struct {
ProjectPkg string
ServicePkg string
PkgName string
ImportPackages string
ImportHttpxPackage string
Expand All @@ -31,7 +33,7 @@ type handlerInfo struct {
HasRequest bool
}

func genHandler(dir, rootPkg string, cfg *config.Config, group spec.Group, route spec.Route) error {
func genHandler(dir, projectPkg, rootPkg string, cfg *config.Config, group spec.Group, route spec.Route) error {
handler := getHandlerName(route)
handlerPath := getHandlerFolderPath(group, route)
pkgName := handlerPath[strings.LastIndex(handlerPath, "/")+1:]
Expand All @@ -40,8 +42,9 @@ func genHandler(dir, rootPkg string, cfg *config.Config, group spec.Group, route
handler = strings.Title(handler)
logicName = pkgName
}

return doGenToFile(dir, handler, cfg, group, route, handlerInfo{
ProjectPkg: projectPkg,
ServicePkg: rootPkg,
PkgName: pkgName,
ImportPackages: genHandlerImports(group, route, rootPkg),
HandlerName: handler,
Expand Down Expand Up @@ -74,10 +77,10 @@ func doGenToFile(dir, handler string, cfg *config.Config, group spec.Group,
})
}

func genHandlers(dir, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error {
func genHandlers(dir, projectPkg, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error {
for _, group := range api.Service.Groups {
for _, route := range group.Routes {
if err := genHandler(dir, rootPkg, cfg, group, route); err != nil {
if err := genHandler(dir, projectPkg, rootPkg, cfg, group, route); err != nil {
return err
}
}
Expand Down
8 changes: 5 additions & 3 deletions tools/goctl/api/gogen/genlogic.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ import (
//go:embed logic.tpl
var logicTemplate string

func genLogic(dir, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error {
func genLogic(dir, projectPkg, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error {
for _, g := range api.Service.Groups {
for _, r := range g.Routes {
err := genLogicByRoute(dir, rootPkg, cfg, g, r)
err := genLogicByRoute(dir, projectPkg, rootPkg, cfg, g, r)
if err != nil {
return err
}
Expand All @@ -30,7 +30,7 @@ func genLogic(dir, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error
return nil
}

func genLogicByRoute(dir, rootPkg string, cfg *config.Config, group spec.Group, route spec.Route) error {
func genLogicByRoute(dir, projectPkg, rootPkg string, cfg *config.Config, group spec.Group, route spec.Route) error {
logic := getLogicName(route)
goFile, err := format.FileNamingFormat(cfg.NamingFormat, logic)
if err != nil {
Expand Down Expand Up @@ -63,6 +63,8 @@ func genLogicByRoute(dir, rootPkg string, cfg *config.Config, group spec.Group,
templateFile: logicTemplateFile,
builtinTemplate: logicTemplate,
data: map[string]string{
"projectPkg": projectPkg,
"rootPkg": rootPkg,
"pkgName": subDir[strings.LastIndex(subDir, "/")+1:],
"imports": imports,
"logic": strings.Title(logic),
Expand Down
4 changes: 3 additions & 1 deletion tools/goctl/api/gogen/genmain.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import (
//go:embed main.tpl
var mainTemplate string

func genMain(dir, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error {
func genMain(dir, projectPkg, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error {
name := strings.ToLower(api.Service.Name)
filename, err := format.FileNamingFormat(cfg.NamingFormat, name)
if err != nil {
Expand All @@ -36,6 +36,8 @@ func genMain(dir, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error {
templateFile: mainTemplateFile,
builtinTemplate: mainTemplate,
data: map[string]string{
"projectPkg": projectPkg,
"servicePkg": rootPkg,
"importPackages": genMainImports(rootPkg),
"serviceName": configName,
},
Expand Down
6 changes: 4 additions & 2 deletions tools/goctl/api/gogen/genmiddleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
//go:embed middleware.tpl
var middlewareImplementCode string

func genMiddleware(dir string, cfg *config.Config, api *spec.ApiSpec) error {
func genMiddleware(dir, projectPkg, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error {
middlewares := getMiddleware(api)
for _, item := range middlewares {
middlewareFilename := strings.TrimSuffix(strings.ToLower(item), "middleware") + "_middleware"
Expand All @@ -31,7 +31,9 @@ func genMiddleware(dir string, cfg *config.Config, api *spec.ApiSpec) error {
templateFile: middlewareImplementCodeFile,
builtinTemplate: middlewareImplementCode,
data: map[string]string{
"name": strings.Title(name),
"projectPkg": projectPkg,
"servicePkg": rootPkg,
"name": strings.Title(name),
},
})
if err != nil {
Expand Down
4 changes: 3 additions & 1 deletion tools/goctl/api/gogen/genroutes.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ type (
}
)

func genRoutes(dir, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error {
func genRoutes(dir, projectPkg, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error {
var builder strings.Builder
groups, err := getRoutes(api)
if err != nil {
Expand Down Expand Up @@ -188,6 +188,8 @@ rest.WithPrefix("%s"),`, g.prefix)
templateFile: routesTemplateFile,
builtinTemplate: routesTemplate,
data: map[string]any{
"projectPkg": projectPkg,
"servicePkg": rootPkg,
"hasTimeout": hasTimeout,
"importPackages": genRouteImports(rootPkg, api),
"routesAdditions": strings.TrimSpace(builder.String()),
Expand Down
4 changes: 3 additions & 1 deletion tools/goctl/api/gogen/gensvc.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const contextFilename = "service_context"
//go:embed svc.tpl
var contextTemplate string

func genServiceContext(dir, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error {
func genServiceContext(dir, projectPkg, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error {
filename, err := format.FileNamingFormat(cfg.NamingFormat, contextFilename)
if err != nil {
return err
Expand Down Expand Up @@ -49,6 +49,8 @@ func genServiceContext(dir, rootPkg string, cfg *config.Config, api *spec.ApiSpe
templateFile: contextTemplateFile,
builtinTemplate: contextTemplate,
data: map[string]string{
"projectPkg": projectPkg,
"servicePkg": rootPkg,
"configImport": configImport,
"config": "config.Config",
"middleware": middlewareStr,
Expand Down
4 changes: 3 additions & 1 deletion tools/goctl/api/gogen/gentypes.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func BuildTypes(types []spec.Type) (string, error) {
return builder.String(), nil
}

func genTypes(dir string, cfg *config.Config, api *spec.ApiSpec) error {
func genTypes(dir, projectPkg, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error {
val, err := BuildTypes(api.Types)
if err != nil {
return err
Expand All @@ -62,6 +62,8 @@ func genTypes(dir string, cfg *config.Config, api *spec.ApiSpec) error {
templateFile: typesTemplateFile,
builtinTemplate: typesTemplate,
data: map[string]any{
"projectPkg": projectPkg,
"servicePkg": rootPkg,
"types": val,
"containsTime": false,
},
Expand Down
11 changes: 5 additions & 6 deletions tools/goctl/pkg/golang/path.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,28 @@ import (
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)

func GetParentPackage(dir string) (string, error) {
func GetParentPackage(dir string) (string, string, error) {
abs, err := filepath.Abs(dir)
if err != nil {
return "", err
return "", "", err
}

projectCtx, err := ctx.Prepare(abs)
if err != nil {
return "", err
return "", "", err
}

// fix https://github.com/zeromicro/go-zero/issues/1058
wd := projectCtx.WorkDir
d := projectCtx.Dir
same, err := pathx.SameFile(wd, d)
if err != nil {
return "", err
return "", "", err
}

trim := strings.TrimPrefix(projectCtx.WorkDir, projectCtx.Dir)
if same {
trim = strings.TrimPrefix(strings.ToLower(projectCtx.WorkDir), strings.ToLower(projectCtx.Dir))
}

return filepath.ToSlash(filepath.Join(projectCtx.Path, trim)), nil
return projectCtx.Path, filepath.ToSlash(filepath.Join(projectCtx.Path, trim)), nil
}
8 changes: 4 additions & 4 deletions tools/goctl/quickstart/mono.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,17 +65,17 @@ func (m mono) createAPIProject() {
configPath := filepath.Join(apiWorkDir, "internal", "config")
svcPath := filepath.Join(apiWorkDir, "internal", "svc")
typesPath := filepath.Join(apiWorkDir, "internal", "types")
svcPkg, err := golang.GetParentPackage(svcPath)
_, svcPkg, err := golang.GetParentPackage(svcPath)
logx.Must(err)
typesPkg, err := golang.GetParentPackage(typesPath)
_, typesPkg, err := golang.GetParentPackage(typesPath)
logx.Must(err)
configPkg, err := golang.GetParentPackage(configPath)
_, configPkg, err := golang.GetParentPackage(configPath)
logx.Must(err)

var rpcClientPkg string
if m.callRPC {
rpcClientPath := filepath.Join(rpcWorkDir, "greet")
rpcClientPkg, err = golang.GetParentPackage(rpcClientPath)
_, rpcClientPkg, err = golang.GetParentPackage(rpcClientPath)
logx.Must(err)
}

Expand Down
5 changes: 5 additions & 0 deletions tools/goctl/rpc/generator/gencall.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ func (g *Generator) GenCall(ctx DirContext, proto parser.Proto, cfg *conf.Config
}

func (g *Generator) genCallGroup(ctx DirContext, proto parser.Proto, cfg *conf.Config) error {
projectPkg := ctx.GetPath().Source()
servicePkg := ctx.GetMain().Package

dir := ctx.GetCall()
head := util.GetHead(proto.Name)
for _, service := range proto.Service {
Expand Down Expand Up @@ -105,6 +108,8 @@ func (g *Generator) genCallGroup(ctx DirContext, proto parser.Proto, cfg *conf.C
aliasKeys := alias.KeysStr()
sort.Strings(aliasKeys)
if err = util.With("shared").GoFmt(true).Parse(text).SaveTo(map[string]any{
"projectPkg": projectPkg,
"servicePkg": servicePkg,
"name": callFilename,
"alias": strings.Join(aliasKeys, pathx.NL),
"head": head,
Expand Down
5 changes: 5 additions & 0 deletions tools/goctl/rpc/generator/genlogic.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ func (g *Generator) GenLogic(ctx DirContext, proto parser.Proto, cfg *conf.Confi

func (g *Generator) genLogicInCompatibility(ctx DirContext, proto parser.Proto,
cfg *conf.Config) error {
projectPkg := ctx.GetPath().Source()
servicePkg := ctx.GetMain().Package

dir := ctx.GetLogic()
service := proto.Service[0].Service.Name
for _, rpc := range proto.Service[0].RPC {
Expand All @@ -61,6 +64,8 @@ func (g *Generator) genLogicInCompatibility(ctx DirContext, proto parser.Proto,
return err
}
err = util.With("logic").GoFmt(true).Parse(text).SaveTo(map[string]any{
"projectPkg": projectPkg,
"servicePkg": servicePkg,
"logicName": fmt.Sprintf("%sLogic", stringx.From(rpc.Name).ToCamel()),
"functions": functions,
"packageName": "logic",
Expand Down
5 changes: 5 additions & 0 deletions tools/goctl/rpc/generator/genmain.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ func (g *Generator) GenMain(ctx DirContext, proto parser.Proto, cfg *conf.Config
return err
}

projectPkg := ctx.GetPath().Source()
servicePkg := ctx.GetMain().Package

fileName := filepath.Join(ctx.GetMain().Filename, fmt.Sprintf("%v.go", mainFilename))
imports := make([]string, 0)
pbImport := fmt.Sprintf(`"%v"`, ctx.GetPb().Package)
Expand Down Expand Up @@ -74,6 +77,8 @@ func (g *Generator) GenMain(ctx DirContext, proto parser.Proto, cfg *conf.Config
}

return util.With("main").GoFmt(true).Parse(text).SaveTo(map[string]any{
"projectPkg": projectPkg,
"servicePkg": servicePkg,
"serviceName": etcFileName,
"imports": strings.Join(imports, pathx.NL),
"pkg": proto.PbPackage,
Expand Down
7 changes: 6 additions & 1 deletion tools/goctl/rpc/generator/genserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ func (g *Generator) GenServer(ctx DirContext, proto parser.Proto, cfg *conf.Conf
}

func (g *Generator) genServerGroup(ctx DirContext, proto parser.Proto, cfg *conf.Config) error {
projectPkg := ctx.GetPath().Source()
servicePkg := ctx.GetMain().Package

dir := ctx.GetServer()
for _, service := range proto.Service {
var (
Expand Down Expand Up @@ -90,7 +93,9 @@ func (g *Generator) genServerGroup(ctx DirContext, proto parser.Proto, cfg *conf
}

if err = util.With("server").GoFmt(true).Parse(text).SaveTo(map[string]any{
"head": head,
"projectPkg": projectPkg,
"servicePkg": servicePkg,
"head": head,
"unimplementedServer": fmt.Sprintf("%s.Unimplemented%sServer", proto.PbPackage,
stringx.From(service.Name).ToCamel()),
"server": stringx.From(service.Name).ToCamel(),
Expand Down
8 changes: 7 additions & 1 deletion tools/goctl/rpc/generator/gensvc.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ var svcTemplate string
// GenSvc generates the servicecontext.go file, which is the resource dependency of a service,
// such as rpc dependency, model dependency, etc.
func (g *Generator) GenSvc(ctx DirContext, _ parser.Proto, cfg *conf.Config) error {
projectPkg := ctx.GetPath().Source()
servicePkg := ctx.GetMain().Package

dir := ctx.GetSvc()

svcFilename, err := format.FileNamingFormat(cfg.NamingFormat, "service_context")
if err != nil {
return err
Expand All @@ -31,6 +35,8 @@ func (g *Generator) GenSvc(ctx DirContext, _ parser.Proto, cfg *conf.Config) err
}

return util.With("svc").GoFmt(true).Parse(text).SaveTo(map[string]any{
"imports": fmt.Sprintf(`"%v"`, ctx.GetConfig().Package),
"projectPkg": projectPkg,
"servicePkg": servicePkg,
"imports": fmt.Sprintf(`"%v"`, ctx.GetConfig().Package),
}, fileName, false)
}
Loading