diff --git a/tools/goctl/api/cmd.go b/tools/goctl/api/cmd.go index 0863805285eb..81213389b684 100644 --- a/tools/goctl/api/cmd.go +++ b/tools/goctl/api/cmd.go @@ -69,6 +69,7 @@ func init() { goCmdFlags.StringVar(&gogen.VarStringDir, "dir") goCmdFlags.StringVar(&gogen.VarStringAPI, "api") + goCmdFlags.BoolVarP(&gogen.VarWithoutSuffix, "without-suffix", "w") goCmdFlags.StringVar(&gogen.VarStringHome, "home") goCmdFlags.StringVar(&gogen.VarStringRemote, "remote") goCmdFlags.StringVar(&gogen.VarStringBranch, "branch") @@ -84,6 +85,7 @@ func init() { newCmdFlags.StringVar(&new.VarStringHome, "home") newCmdFlags.StringVar(&new.VarStringRemote, "remote") newCmdFlags.StringVar(&new.VarStringBranch, "branch") + newCmdFlags.BoolVarP(&gogen.VarWithoutSuffix, "without-suffix", "w") newCmdFlags.StringVarWithDefaultValue(&new.VarStringStyle, "style", config.DefaultFormat) pluginCmdFlags.StringVarP(&plugin.VarStringPlugin, "plugin", "p") diff --git a/tools/goctl/api/gogen/gen.go b/tools/goctl/api/gogen/gen.go index 6f568fe5b783..0b60182ad0f2 100644 --- a/tools/goctl/api/gogen/gen.go +++ b/tools/goctl/api/gogen/gen.go @@ -31,6 +31,8 @@ var ( VarStringDir string // VarStringAPI describes the API. VarStringAPI string + // VarWithoutSuffix remove logic etc... + VarWithoutSuffix bool // VarStringHome describes the go home. VarStringHome string // VarStringRemote describes the remote git repository. @@ -45,6 +47,7 @@ var ( func GoCommand(_ *cobra.Command, _ []string) error { apiFile := VarStringAPI dir := VarStringDir + withoutSuffix := VarWithoutSuffix namingStyle := VarStringStyle home := VarStringHome remote := VarStringRemote @@ -65,12 +68,11 @@ func GoCommand(_ *cobra.Command, _ []string) error { if len(dir) == 0 { return errors.New("missing -dir") } - - return DoGenProject(apiFile, dir, namingStyle) + return DoGenProject(apiFile, dir, namingStyle, withoutSuffix) } // DoGenProject gen go project files with api file -func DoGenProject(apiFile, dir, style string) error { +func DoGenProject(apiFile, dir, style string, withoutSuffix bool) error { api, err := parser.Parse(apiFile) if err != nil { return err @@ -96,10 +98,10 @@ func DoGenProject(apiFile, dir, style string) error { 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(genRoutes(dir, rootPkg, cfg, api, withoutSuffix)) + logx.Must(genHandlers(dir, rootPkg, cfg, api, withoutSuffix)) + logx.Must(genLogic(dir, rootPkg, cfg, api, withoutSuffix)) + logx.Must(genMiddleware(dir, cfg, api, withoutSuffix)) if err := backupAndSweep(apiFile); err != nil { return err diff --git a/tools/goctl/api/gogen/gen_test.go b/tools/goctl/api/gogen/gen_test.go index d2cb68426717..67ab99b280d0 100644 --- a/tools/goctl/api/gogen/gen_test.go +++ b/tools/goctl/api/gogen/gen_test.go @@ -280,7 +280,7 @@ func validateWithCamel(t *testing.T, api, camel string) { assert.Nil(t, err) err = initMod(dir) assert.Nil(t, err) - err = DoGenProject(api, dir, camel) + err = DoGenProject(api, dir, camel, false) assert.Nil(t, err) filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { if strings.HasSuffix(path, ".go") { diff --git a/tools/goctl/api/gogen/genhandlers.go b/tools/goctl/api/gogen/genhandlers.go index fa1093ec18fc..59718966e7fc 100644 --- a/tools/goctl/api/gogen/genhandlers.go +++ b/tools/goctl/api/gogen/genhandlers.go @@ -31,8 +31,8 @@ type handlerInfo struct { HasRequest bool } -func genHandler(dir, rootPkg string, cfg *config.Config, group spec.Group, route spec.Route) error { - handler := getHandlerName(route) +func genHandler(dir, rootPkg string, cfg *config.Config, group spec.Group, route spec.Route, withoutSuffix bool) error { + handler := getHandlerName(route, withoutSuffix) handlerPath := getHandlerFolderPath(group, route) pkgName := handlerPath[strings.LastIndex(handlerPath, "/")+1:] logicName := defaultLogicPackage @@ -47,7 +47,7 @@ func genHandler(dir, rootPkg string, cfg *config.Config, group spec.Group, route HandlerName: handler, RequestType: util.Title(route.RequestTypeName()), LogicName: logicName, - LogicType: strings.Title(getLogicName(route)), + LogicType: strings.Title(getLogicName(route, withoutSuffix)), Call: strings.Title(strings.TrimSuffix(handler, "Handler")), HasResp: len(route.ResponseTypeName()) > 0, HasRequest: len(route.RequestTypeName()) > 0, @@ -74,10 +74,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, rootPkg string, cfg *config.Config, api *spec.ApiSpec, withoutSuffix bool) 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, rootPkg, cfg, group, route, withoutSuffix); err != nil { return err } } @@ -122,20 +122,24 @@ func getHandlerFolderPath(group spec.Group, route spec.Route) string { return path.Join(handlerDir, folder) } -func getHandlerName(route spec.Route) string { +func getHandlerName(route spec.Route, withoutSuffix bool) string { handler, err := getHandlerBaseName(route) if err != nil { panic(err) } - - return handler + "Handler" + if !withoutSuffix { + return handler + "Handler" + } + return handler } -func getLogicName(route spec.Route) string { +func getLogicName(route spec.Route, withoutSuffix bool) string { handler, err := getHandlerBaseName(route) if err != nil { panic(err) } - - return handler + "Logic" + if !withoutSuffix { + return handler + "Logic" + } + return handler } diff --git a/tools/goctl/api/gogen/genlogic.go b/tools/goctl/api/gogen/genlogic.go index 287804956fa5..2b9a25f19215 100644 --- a/tools/goctl/api/gogen/genlogic.go +++ b/tools/goctl/api/gogen/genlogic.go @@ -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, rootPkg string, cfg *config.Config, api *spec.ApiSpec, withoutSuffix bool) error { for _, g := range api.Service.Groups { for _, r := range g.Routes { - err := genLogicByRoute(dir, rootPkg, cfg, g, r) + err := genLogicByRoute(dir, rootPkg, cfg, g, r, withoutSuffix) if err != nil { return err } @@ -30,8 +30,8 @@ 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 { - logic := getLogicName(route) +func genLogicByRoute(dir, rootPkg string, cfg *config.Config, group spec.Group, route spec.Route, withoutSuffix bool) error { + logic := getLogicName(route, withoutSuffix) goFile, err := format.FileNamingFormat(cfg.NamingFormat, logic) if err != nil { return err diff --git a/tools/goctl/api/gogen/genmiddleware.go b/tools/goctl/api/gogen/genmiddleware.go index d302b51cc30f..9ad101488a46 100644 --- a/tools/goctl/api/gogen/genmiddleware.go +++ b/tools/goctl/api/gogen/genmiddleware.go @@ -12,16 +12,21 @@ import ( //go:embed middleware.tpl var middlewareImplementCode string -func genMiddleware(dir string, cfg *config.Config, api *spec.ApiSpec) error { +func genMiddleware(dir string, cfg *config.Config, api *spec.ApiSpec, withoutSuffix bool) error { middlewares := getMiddleware(api) for _, item := range middlewares { - middlewareFilename := strings.TrimSuffix(strings.ToLower(item), "middleware") + "_middleware" + middlewareFilename := strings.TrimSuffix(strings.ToLower(item), "middleware") + if !withoutSuffix { + middlewareFilename = strings.TrimSuffix(strings.ToLower(item), "middleware") + "_middleware" + } filename, err := format.FileNamingFormat(cfg.NamingFormat, middlewareFilename) if err != nil { return err } - - name := strings.TrimSuffix(item, "Middleware") + "Middleware" + name := strings.TrimSuffix(item, "Middleware") + if !withoutSuffix { + name = strings.TrimSuffix(item, "Middleware") + "Middleware" + } err = genFile(fileGenConfig{ dir: dir, subdir: middlewareDir, diff --git a/tools/goctl/api/gogen/genroutes.go b/tools/goctl/api/gogen/genroutes.go index 8243d5e4e619..1a76002290fa 100644 --- a/tools/goctl/api/gogen/genroutes.go +++ b/tools/goctl/api/gogen/genroutes.go @@ -74,9 +74,9 @@ type ( } ) -func genRoutes(dir, rootPkg string, cfg *config.Config, api *spec.ApiSpec) error { +func genRoutes(dir, rootPkg string, cfg *config.Config, api *spec.ApiSpec, withoutSuffix bool) error { var builder strings.Builder - groups, err := getRoutes(api) + groups, err := getRoutes(api, withoutSuffix) if err != nil { return err } @@ -218,13 +218,13 @@ func genRouteImports(parentPkg string, api *spec.ApiSpec) string { return fmt.Sprintf("%s\n\n\t%s", projectSection, depSection) } -func getRoutes(api *spec.ApiSpec) ([]group, error) { +func getRoutes(api *spec.ApiSpec, withoutSuffix bool) ([]group, error) { var routes []group for _, g := range api.Service.Groups { var groupedRoutes group for _, r := range g.Routes { - handler := getHandlerName(r) + handler := getHandlerName(r, withoutSuffix) handler = handler + "(serverCtx)" folder := r.GetAnnotation(groupProperty) if len(folder) > 0 { diff --git a/tools/goctl/api/new/newservice.go b/tools/goctl/api/new/newservice.go index 9241d8559afd..9be88761fb6d 100644 --- a/tools/goctl/api/new/newservice.go +++ b/tools/goctl/api/new/newservice.go @@ -83,6 +83,6 @@ func CreateServiceCommand(_ *cobra.Command, args []string) error { return err } - err = gogen.DoGenProject(apiFilePath, abs, VarStringStyle) + err = gogen.DoGenProject(apiFilePath, abs, VarStringStyle, true) return err } diff --git a/tools/goctl/internal/flags/default_en.json b/tools/goctl/internal/flags/default_en.json index 95f2d99caf02..a7c3474d40c6 100644 --- a/tools/goctl/internal/flags/default_en.json +++ b/tools/goctl/internal/flags/default_en.json @@ -37,6 +37,7 @@ "home": "{{.global.home}}", "remote": "{{.global.remote}}", "branch": "{{.global.branch}}", + "without-suffix": "Remove the default suffix when generating files, such as Logic, Handler, Middleware", "style": "{{.global.style}}" }, "new": { @@ -155,6 +156,7 @@ "url": "The data source of database,like \"root:password@tcp(127.0.0.1:3306)/database", "table": "The table or table globbing patterns in the database", "cache": "Generate code with cache [optional]", + "prefix": "Generate code with cache prefix [optional]", "dir": "{{.goctl.model.dir}}", "style": "{{.global.style}}", "idea": "For idea plugin [optional]", @@ -168,6 +170,7 @@ "dir": "{{.goctl.model.dir}}", "style": "{{.global.style}}", "cache": "Generate code with cache [optional]", + "prefix": "Generate code with cache prefix [optional]", "idea": "For idea plugin [optional]", "home": "{{.global.home}}", "remote": "{{.global.remote}}", @@ -182,6 +185,7 @@ "table": "The table or table globbing patterns in the database", "schema": "The schema or schema globbing patterns in the database", "cache": "Generate code with cache [optional]", + "prefix": "Generate code with cache prefix [optional]", "dir": "{{.goctl.model.dir}}", "style": "{{.global.style}}", "idea": "For idea plugin [optional]", @@ -195,6 +199,7 @@ "short": "Generate mongo model", "type": "Specified model type name", "cache": "Generate code with cache [optional]", + "prefix": "Generate code with cache prefix [optional]", "easy": "Generate code with auto generated CollectionName for easy declare [optional]", "dir": "{{.goctl.model.dir}}", "style": "{{.global.style}}", @@ -241,6 +246,7 @@ "multiple": "Generated in multiple rpc service mode", "zrpc_out": "The zrpc output directory", "style": "{{.global.style}}", + "without-suffix": "Remove the default suffix when generating files, such as Logic, Service", "home": "{{.global.home}}", "remote": "{{.global.remote}}", "branch": "{{.global.branch}}", diff --git a/tools/goctl/model/cmd.go b/tools/goctl/model/cmd.go index e340f2c58729..40cf303112b9 100644 --- a/tools/goctl/model/cmd.go +++ b/tools/goctl/model/cmd.go @@ -28,7 +28,9 @@ func init() { ddlCmdFlags.StringVarP(&command.VarStringSrc, "src", "s") ddlCmdFlags.StringVarP(&command.VarStringDir, "dir", "d") ddlCmdFlags.StringVar(&command.VarStringStyle, "style") + ddlCmdFlags.BoolVarP(&command.VarWithoutSuffix, "without-suffix", "w") ddlCmdFlags.BoolVarP(&command.VarBoolCache, "cache", "c") + ddlCmdFlags.StringVar(&command.VarStringPrefix, "prefix") ddlCmdFlags.BoolVar(&command.VarBoolIdea, "idea") ddlCmdFlags.StringVar(&command.VarStringDatabase, "database") ddlCmdFlags.StringVar(&command.VarStringHome, "home") @@ -38,8 +40,10 @@ func init() { datasourceCmdFlags.StringVar(&command.VarStringURL, "url") datasourceCmdFlags.StringSliceVarP(&command.VarStringSliceTable, "table", "t") datasourceCmdFlags.BoolVarP(&command.VarBoolCache, "cache", "c") + datasourceCmdFlags.StringVar(&command.VarStringPrefix, "prefix") datasourceCmdFlags.StringVarP(&command.VarStringDir, "dir", "d") datasourceCmdFlags.StringVar(&command.VarStringStyle, "style") + datasourceCmdFlags.BoolVarP(&command.VarWithoutSuffix, "without-suffix", "w") datasourceCmdFlags.BoolVar(&command.VarBoolIdea, "idea") datasourceCmdFlags.StringVar(&command.VarStringHome, "home") datasourceCmdFlags.StringVar(&command.VarStringRemote, "remote") @@ -49,28 +53,29 @@ func init() { pgDatasourceCmdFlags.StringSliceVarP(&command.VarStringSliceTable, "table", "t") pgDatasourceCmdFlags.StringVarPWithDefaultValue(&command.VarStringSchema, "schema", "s", "public") pgDatasourceCmdFlags.BoolVarP(&command.VarBoolCache, "cache", "c") + pgDatasourceCmdFlags.StringVar(&command.VarStringPrefix, "prefix") pgDatasourceCmdFlags.StringVarP(&command.VarStringDir, "dir", "d") pgDatasourceCmdFlags.StringVar(&command.VarStringStyle, "style") + pgDatasourceCmdFlags.BoolVarP(&command.VarWithoutSuffix, "without-suffix", "w") pgDatasourceCmdFlags.BoolVar(&command.VarBoolIdea, "idea") pgDatasourceCmdFlags.BoolVar(&command.VarBoolStrict, "strict") pgDatasourceCmdFlags.StringVar(&command.VarStringHome, "home") pgDatasourceCmdFlags.StringVar(&command.VarStringRemote, "remote") pgDatasourceCmdFlags.StringVar(&command.VarStringBranch, "branch") - pgCmd.PersistentFlags().StringSliceVarPWithDefaultValue(&command.VarStringSliceIgnoreColumns, - "ignore-columns", "i", []string{"create_at", "created_at", "create_time", "update_at", "updated_at", "update_time"}) mongoCmdFlags.StringSliceVarP(&mongo.VarStringSliceType, "type", "t") mongoCmdFlags.BoolVarP(&mongo.VarBoolCache, "cache", "c") + mongoCmdFlags.StringVar(&command.VarStringPrefix, "prefix") mongoCmdFlags.BoolVarP(&mongo.VarBoolEasy, "easy", "e") mongoCmdFlags.StringVarP(&mongo.VarStringDir, "dir", "d") mongoCmdFlags.StringVar(&mongo.VarStringStyle, "style") + mongoCmdFlags.BoolVarP(&command.VarWithoutSuffix, "without-suffix", "w") mongoCmdFlags.StringVar(&mongo.VarStringHome, "home") mongoCmdFlags.StringVar(&mongo.VarStringRemote, "remote") mongoCmdFlags.StringVar(&mongo.VarStringBranch, "branch") mysqlCmd.PersistentFlags().BoolVar(&command.VarBoolStrict, "strict") - mysqlCmd.PersistentFlags().StringSliceVarPWithDefaultValue(&command.VarStringSliceIgnoreColumns, - "ignore-columns", "i", []string{"create_at", "created_at", "create_time", "update_at", "updated_at", "update_time"}) + mysqlCmd.PersistentFlags().StringSliceVarPWithDefaultValue(&command.VarStringSliceIgnoreColumns, "ignore-columns", "i", []string{"create_at", "created_at", "create_time", "update_at", "updated_at", "update_time"}) mysqlCmd.AddCommand(datasourceCmd, ddlCmd) pgCmd.AddCommand(pgDatasourceCmd) diff --git a/tools/goctl/model/sql/command/command.go b/tools/goctl/model/sql/command/command.go index e29a3092a82e..d80aa5acc8a2 100644 --- a/tools/goctl/model/sql/command/command.go +++ b/tools/goctl/model/sql/command/command.go @@ -29,14 +29,19 @@ var ( VarStringDir string // VarBoolCache describes whether the cache is enabled. VarBoolCache bool + //VarStringPrefix describes a prefix with cache + VarStringPrefix string // VarBoolIdea describes whether is idea or not. VarBoolIdea bool // VarStringURL describes the dsn of the sql. VarStringURL string // VarStringSliceTable describes tables. VarStringSliceTable []string + // VarStringTable describes a table of sql. + VarStringTable string // VarStringStyle describes the style. - VarStringStyle string + VarStringStyle string + VarWithoutSuffix bool // VarStringDatabase describes the database. VarStringDatabase string // VarStringSchema describes the schema of postgresql. @@ -61,8 +66,10 @@ func MysqlDDL(_ *cobra.Command, _ []string) error { src := VarStringSrc dir := VarStringDir cache := VarBoolCache + prefix := VarStringPrefix idea := VarBoolIdea style := VarStringStyle + withoutSuffix := VarWithoutSuffix database := VarStringDatabase home := VarStringHome remote := VarStringRemote @@ -86,9 +93,11 @@ func MysqlDDL(_ *cobra.Command, _ []string) error { dir: dir, cfg: cfg, cache: cache, + prefix: prefix, idea: idea, database: database, strict: VarBoolStrict, + withoutSuffix: withoutSuffix, ignoreColumns: mergeColumns(VarStringSliceIgnoreColumns), } return fromDDL(arg) @@ -100,6 +109,8 @@ func MySqlDataSource(_ *cobra.Command, _ []string) error { url := strings.TrimSpace(VarStringURL) dir := strings.TrimSpace(VarStringDir) cache := VarBoolCache + prefix := VarStringPrefix + withoutSuffix := VarWithoutSuffix idea := VarBoolIdea style := VarStringStyle home := VarStringHome @@ -128,8 +139,10 @@ func MySqlDataSource(_ *cobra.Command, _ []string) error { tablePat: patterns, cfg: cfg, cache: cache, + prefix: prefix, idea: idea, strict: VarBoolStrict, + withoutSuffix: withoutSuffix, ignoreColumns: mergeColumns(VarStringSliceIgnoreColumns), } return fromMysqlDataSource(arg) @@ -189,6 +202,8 @@ func PostgreSqlDataSource(_ *cobra.Command, _ []string) error { url := strings.TrimSpace(VarStringURL) dir := strings.TrimSpace(VarStringDir) cache := VarBoolCache + prefix := VarStringPrefix + withoutSuffix := VarWithoutSuffix idea := VarBoolIdea style := VarStringStyle schema := VarStringSchema @@ -209,20 +224,21 @@ func PostgreSqlDataSource(_ *cobra.Command, _ []string) error { schema = "public" } - patterns := parseTableList(VarStringSliceTable) + pattern := strings.TrimSpace(VarStringTable) cfg, err := config.NewConfig(style) if err != nil { return err } - ignoreColumns := mergeColumns(VarStringSliceIgnoreColumns) - return fromPostgreSqlDataSource(url, patterns, dir, schema, cfg, cache, idea, VarBoolStrict, ignoreColumns) + return fromPostgreSqlDataSource(url, pattern, dir, schema, prefix, cfg, cache, idea, VarBoolStrict, withoutSuffix) } type ddlArg struct { src, dir string cfg *config.Config cache, idea bool + prefix string + withoutSuffix bool database string strict bool ignoreColumns []string @@ -251,7 +267,7 @@ func fromDDL(arg ddlArg) error { } for _, file := range files { - err = generator.StartFromDDL(file, arg.cache, arg.strict, arg.database) + err = generator.StartFromDDL(file, arg.prefix, arg.cache, arg.strict, arg.withoutSuffix, arg.database) if err != nil { return err } @@ -265,7 +281,9 @@ type dataSourceArg struct { tablePat pattern cfg *config.Config cache, idea bool + prefix string strict bool + withoutSuffix bool ignoreColumns []string } @@ -325,10 +343,10 @@ func fromMysqlDataSource(arg dataSourceArg) error { return err } - return generator.StartFromInformationSchema(matchTables, arg.cache, arg.strict) + return generator.StartFromInformationSchema(matchTables, arg.cache, arg.strict, arg.withoutSuffix, arg.prefix) } -func fromPostgreSqlDataSource(url string, pattern pattern, dir, schema string, cfg *config.Config, cache, idea, strict bool, ignoreColumns []string) error { +func fromPostgreSqlDataSource(url, pattern, dir, schema, prefix string, cfg *config.Config, cache, idea, strict, withoutSuffix bool) error { log := console.NewConsole(idea) if len(url) == 0 { log.Error("%v", "expected data source of postgresql, but nothing found") @@ -349,7 +367,12 @@ func fromPostgreSqlDataSource(url string, pattern pattern, dir, schema string, c matchTables := make(map[string]*model.Table) for _, item := range tables { - if !pattern.Match(item) { + match, err := filepath.Match(pattern, item) + if err != nil { + return err + } + + if !match { continue } @@ -370,10 +393,10 @@ func fromPostgreSqlDataSource(url string, pattern pattern, dir, schema string, c return errors.New("no tables matched") } - generator, err := gen.NewDefaultGenerator(dir, cfg, gen.WithConsoleOption(log), gen.WithPostgreSql(), gen.WithIgnoreColumns(ignoreColumns)) + generator, err := gen.NewDefaultGenerator(dir, cfg, gen.WithConsoleOption(log), gen.WithPostgreSql()) if err != nil { return err } - return generator.StartFromInformationSchema(matchTables, cache, strict) + return generator.StartFromInformationSchema(matchTables, cache, strict, withoutSuffix, prefix) } diff --git a/tools/goctl/model/sql/gen/gen.go b/tools/goctl/model/sql/gen/gen.go index 34a07517b5de..0209f15b5f53 100644 --- a/tools/goctl/model/sql/gen/gen.go +++ b/tools/goctl/model/sql/gen/gen.go @@ -109,16 +109,16 @@ func newDefaultOption() Option { } } -func (g *defaultGenerator) StartFromDDL(filename string, withCache, strict bool, database string) error { - modelList, err := g.genFromDDL(filename, withCache, strict, database) +func (g *defaultGenerator) StartFromDDL(filename, prefix string, withCache, strict, withoutSuffix bool, database string) error { + modelList, err := g.genFromDDL(filename, prefix, withCache, strict, database) if err != nil { return err } - return g.createFile(modelList) + return g.createFile(modelList, withoutSuffix) } -func (g *defaultGenerator) StartFromInformationSchema(tables map[string]*model.Table, withCache, strict bool) error { +func (g *defaultGenerator) StartFromInformationSchema(tables map[string]*model.Table, withCache, strict, withoutSuffix bool, prefix string) error { m := make(map[string]*codeTuple) for _, each := range tables { table, err := parser.ConvertDataType(each, strict) @@ -126,7 +126,7 @@ func (g *defaultGenerator) StartFromInformationSchema(tables map[string]*model.T return err } - code, err := g.genModel(*table, withCache) + code, err := g.genModel(*table, withCache, prefix) if err != nil { return err } @@ -141,10 +141,10 @@ func (g *defaultGenerator) StartFromInformationSchema(tables map[string]*model.T } } - return g.createFile(m) + return g.createFile(m, withoutSuffix) } -func (g *defaultGenerator) createFile(modelList map[string]*codeTuple) error { +func (g *defaultGenerator) createFile(modelList map[string]*codeTuple, withoutSuffix bool) error { dirAbs, err := filepath.Abs(g.dir) if err != nil { return err @@ -160,7 +160,12 @@ func (g *defaultGenerator) createFile(modelList map[string]*codeTuple) error { for tableName, codes := range modelList { tn := stringx.From(tableName) modelFilename, err := format.FileNamingFormat(g.cfg.NamingFormat, - fmt.Sprintf("%s_model", tn.Source())) + fmt.Sprintf("%s", tn.Source())) + if !withoutSuffix { + modelFilename, err = format.FileNamingFormat(g.cfg.NamingFormat, + fmt.Sprintf("%s_model", tn.Source())) + } + if err != nil { return err } @@ -208,7 +213,7 @@ func (g *defaultGenerator) createFile(modelList map[string]*codeTuple) error { } // ret1: key-table name,value-code -func (g *defaultGenerator) genFromDDL(filename string, withCache, strict bool, database string) ( +func (g *defaultGenerator) genFromDDL(filename, prefix string, withCache, strict bool, database string) ( map[string]*codeTuple, error, ) { m := make(map[string]*codeTuple) @@ -218,7 +223,7 @@ func (g *defaultGenerator) genFromDDL(filename string, withCache, strict bool, d } for _, e := range tables { - code, err := g.genModel(*e, withCache) + code, err := g.genModel(*e, withCache, prefix) if err != nil { return nil, err } @@ -254,12 +259,12 @@ func (t Table) isIgnoreColumns(columnName string) bool { return false } -func (g *defaultGenerator) genModel(in parser.Table, withCache bool) (string, error) { +func (g *defaultGenerator) genModel(in parser.Table, withCache bool, prefix string) (string, error) { if len(in.PrimaryKey.Name.Source()) == 0 { return "", fmt.Errorf("table %s: missing primary key", in.Name.Source()) } - primaryKey, uniqueKey := genCacheKeys(in) + primaryKey, uniqueKey := genCacheKeys(in, prefix) var table Table table.Table = in diff --git a/tools/goctl/model/sql/gen/gen_test.go b/tools/goctl/model/sql/gen/gen_test.go index 676e044c3a2b..41048191bfe4 100644 --- a/tools/goctl/model/sql/gen/gen_test.go +++ b/tools/goctl/model/sql/gen/gen_test.go @@ -40,7 +40,7 @@ func TestCacheModel(t *testing.T) { }) assert.Nil(t, err) - err = g.StartFromDDL(sqlFile, true, false, "go_zero") + err = g.StartFromDDL(sqlFile, "prefix", true, false, "go_zero") assert.Nil(t, err) assert.True(t, func() bool { _, err := os.Stat(filepath.Join(cacheDir, "TestUserModel.go")) @@ -51,7 +51,7 @@ func TestCacheModel(t *testing.T) { }) assert.Nil(t, err) - err = g.StartFromDDL(sqlFile, false, false, "go_zero") + err = g.StartFromDDL(sqlFile, "prefix", false, false, "go_zero") assert.Nil(t, err) assert.True(t, func() bool { _, err := os.Stat(filepath.Join(noCacheDir, "testusermodel.go")) @@ -78,7 +78,7 @@ func TestNamingModel(t *testing.T) { }) assert.Nil(t, err) - err = g.StartFromDDL(sqlFile, true, false, "go_zero") + err = g.StartFromDDL(sqlFile, "prefix", true, false, "go_zero") assert.Nil(t, err) assert.True(t, func() bool { _, err := os.Stat(filepath.Join(camelDir, "TestUserModel.go")) @@ -89,7 +89,7 @@ func TestNamingModel(t *testing.T) { }) assert.Nil(t, err) - err = g.StartFromDDL(sqlFile, true, false, "go_zero") + err = g.StartFromDDL(sqlFile, "prefix", true, false, "go_zero") assert.Nil(t, err) assert.True(t, func() bool { _, err := os.Stat(filepath.Join(snakeDir, "test_user_model.go")) @@ -118,7 +118,7 @@ func TestFolderName(t *testing.T) { pkg := g.pkg - err = g.StartFromDDL(sqlFile, true, true, "go_zero") + err = g.StartFromDDL(sqlFile, "prefix", true, true, "go_zero") assert.Nil(t, err) assert.True(t, func() bool { _, err := os.Stat(filepath.Join(camelDir, "TestUserModel.go")) @@ -131,7 +131,7 @@ func TestFolderName(t *testing.T) { }) assert.Nil(t, err) - err = g.StartFromDDL(sqlFile, true, true, "go_zero") + err = g.StartFromDDL(sqlFile, "prefix", true, true, "go_zero") assert.Nil(t, err) assert.True(t, func() bool { _, err := os.Stat(filepath.Join(snakeDir, "test_user_model.go")) diff --git a/tools/goctl/model/sql/gen/keys.go b/tools/goctl/model/sql/gen/keys.go index 2a19ff47e553..3418834d2ed7 100644 --- a/tools/goctl/model/sql/gen/keys.go +++ b/tools/goctl/model/sql/gen/keys.go @@ -37,12 +37,12 @@ type Key struct { // Join describes an alias of string slice type Join []string -func genCacheKeys(table parser.Table) (Key, []Key) { +func genCacheKeys(table parser.Table, prefix string) (Key, []Key) { var primaryKey Key var uniqueKey []Key - primaryKey = genCacheKey(table.Db, table.Name, []*parser.Field{&table.PrimaryKey.Field}) + primaryKey = genCacheKey(table.Db, table.Name, []*parser.Field{&table.PrimaryKey.Field}, prefix) for _, each := range table.UniqueIndex { - uniqueKey = append(uniqueKey, genCacheKey(table.Db, table.Name, each)) + uniqueKey = append(uniqueKey, genCacheKey(table.Db, table.Name, each, prefix)) } sort.Slice(uniqueKey, func(i, j int) bool { return uniqueKey[i].VarLeft < uniqueKey[j].VarLeft @@ -51,7 +51,7 @@ func genCacheKeys(table parser.Table) (Key, []Key) { return primaryKey, uniqueKey } -func genCacheKey(db, table stringx.String, in []*parser.Field) Key { +func genCacheKey(db, table stringx.String, in []*parser.Field, prefix string) Key { var ( varLeftJoin, varRightJoin, fieldNameJoin Join varLeft, varRight, varExpression string @@ -61,13 +61,18 @@ func genCacheKey(db, table stringx.String, in []*parser.Field) Key { ) dbName, tableName := util.SafeString(db.Source()), util.SafeString(table.Source()) + cacheRightKey := "cache" + cacheLeftKey := "cache" + if strings.TrimSpace(prefix) != "" { + cacheRightKey = cacheRightKey + ":" + prefix + } if len(dbName) > 0 { - varLeftJoin = append(varLeftJoin, "cache", dbName, tableName) - varRightJoin = append(varRightJoin, "cache", dbName, tableName) + varLeftJoin = append(varLeftJoin, cacheLeftKey, dbName, tableName) + varRightJoin = append(varRightJoin, cacheRightKey, dbName, tableName) keyLeftJoin = append(keyLeftJoin, dbName, tableName) } else { - varLeftJoin = append(varLeftJoin, "cache", tableName) - varRightJoin = append(varRightJoin, "cache", tableName) + varLeftJoin = append(varLeftJoin, cacheLeftKey, tableName) + varRightJoin = append(varRightJoin, cacheRightKey, tableName) keyLeftJoin = append(keyLeftJoin, tableName) } diff --git a/tools/goctl/model/sql/gen/keys_test.go b/tools/goctl/model/sql/gen/keys_test.go index c54cc4fed114..70b1fc6c0df5 100644 --- a/tools/goctl/model/sql/gen/keys_test.go +++ b/tools/goctl/model/sql/gen/keys_test.go @@ -66,7 +66,7 @@ func TestGenCacheKeys(t *testing.T) { Comment: "更新时间", }, }, - }) + }, "prefix") t.Run("primaryCacheKey", func(t *testing.T) { assert.Equal(t, true, func() bool { @@ -161,7 +161,7 @@ func TestGenCacheKeys(t *testing.T) { Comment: "更新时间", }, }, - }) + }, "prefix") assert.Equal(t, true, func() bool { return cacheKeyEqual(primariCacheKey, Key{ diff --git a/tools/goctl/rpc/cli/cli.go b/tools/goctl/rpc/cli/cli.go index 762c57a12e57..43a9c16a211c 100644 --- a/tools/goctl/rpc/cli/cli.go +++ b/tools/goctl/rpc/cli/cli.go @@ -35,7 +35,8 @@ var ( // VarStringSliceGoGRPCOpt describes the grpc options. VarStringSliceGoGRPCOpt []string // VarStringStyle describes the style of output files. - VarStringStyle string + VarStringStyle string + VarWithoutSuffix bool // VarStringZRPCOut describes the zRPC output. VarStringZRPCOut string // VarBoolIdea describes whether idea or not @@ -57,6 +58,7 @@ func RPCNew(_ *cobra.Command, args []string) error { return fmt.Errorf("unexpected ext: %s", ext) } style := VarStringStyle + withoutSuffix := VarWithoutSuffix home := VarStringHome remote := VarStringRemote branch := VarStringBranch @@ -103,7 +105,7 @@ func RPCNew(_ *cobra.Command, args []string) error { } g := generator.NewGenerator(style, verbose) - return g.Generate(&ctx) + return g.Generate(&ctx, withoutSuffix) } // RPCTemplate is the entry for generate rpc template diff --git a/tools/goctl/rpc/cli/zrpc.go b/tools/goctl/rpc/cli/zrpc.go index 558d97786dad..fec715c98668 100644 --- a/tools/goctl/rpc/cli/zrpc.go +++ b/tools/goctl/rpc/cli/zrpc.go @@ -32,6 +32,8 @@ func ZRPC(_ *cobra.Command, args []string) error { goOutList := VarStringSliceGoOut zrpcOut := VarStringZRPCOut style := VarStringStyle + withoutSuffix := VarWithoutSuffix + home := VarStringHome remote := VarStringRemote branch := VarStringBranch @@ -104,7 +106,7 @@ func ZRPC(_ *cobra.Command, args []string) error { ctx.ProtocCmd = strings.Join(protocArgs, " ") ctx.IsGenClient = VarBoolClient g := generator.NewGenerator(style, verbose) - return g.Generate(&ctx) + return g.Generate(&ctx, withoutSuffix) } func wrapProtocCmd(name string, args []string) []string { diff --git a/tools/goctl/rpc/cmd.go b/tools/goctl/rpc/cmd.go index 0bb69c3af1e8..e09bb316eec8 100644 --- a/tools/goctl/rpc/cmd.go +++ b/tools/goctl/rpc/cmd.go @@ -36,6 +36,7 @@ func init() { newCmdFlags.StringSliceVar(&cli.VarStringSliceGoOpt, "go_opt") newCmdFlags.StringSliceVar(&cli.VarStringSliceGoGRPCOpt, "go-grpc_opt") newCmdFlags.StringVarWithDefaultValue(&cli.VarStringStyle, "style", config.DefaultFormat) + newCmdFlags.BoolVarP(&cli.VarWithoutSuffix, "without-suffix", "w") newCmdFlags.BoolVar(&cli.VarBoolIdea, "idea") newCmdFlags.StringVar(&cli.VarStringHome, "home") newCmdFlags.StringVar(&cli.VarStringRemote, "remote") @@ -53,6 +54,7 @@ func init() { protocCmdFlags.StringSliceVar(&cli.VarStringSlicePlugin, "plugin") protocCmdFlags.StringSliceVarP(&cli.VarStringSliceProtoPath, "proto_path", "I") protocCmdFlags.StringVar(&cli.VarStringStyle, "style") + protocCmdFlags.BoolVarP(&cli.VarWithoutSuffix, "without-suffix", "w") protocCmdFlags.StringVar(&cli.VarStringZRPCOut, "zrpc_out") protocCmdFlags.StringVar(&cli.VarStringHome, "home") protocCmdFlags.StringVar(&cli.VarStringRemote, "remote") diff --git a/tools/goctl/rpc/generator/gen.go b/tools/goctl/rpc/generator/gen.go index 3140d997c35b..c6f3a8d80870 100644 --- a/tools/goctl/rpc/generator/gen.go +++ b/tools/goctl/rpc/generator/gen.go @@ -35,7 +35,7 @@ type ZRpcContext struct { // Generate generates a rpc service, through the proto file, // code storage directory, and proto import parameters to control // the source file and target location of the rpc service that needs to be generated -func (g *Generator) Generate(zctx *ZRpcContext) error { +func (g *Generator) Generate(zctx *ZRpcContext, withoutSuffix bool) error { abs, err := filepath.Abs(zctx.Output) if err != nil { return err @@ -62,7 +62,7 @@ func (g *Generator) Generate(zctx *ZRpcContext) error { return err } - dirCtx, err := mkdir(projectCtx, proto, g.cfg, zctx) + dirCtx, err := mkdir(projectCtx, proto, g.cfg, zctx, withoutSuffix) if err != nil { return err } @@ -87,23 +87,23 @@ func (g *Generator) Generate(zctx *ZRpcContext) error { return err } - err = g.GenLogic(dirCtx, proto, g.cfg, zctx) + err = g.GenLogic(dirCtx, proto, g.cfg, zctx, withoutSuffix) if err != nil { return err } - err = g.GenServer(dirCtx, proto, g.cfg, zctx) + err = g.GenServer(dirCtx, proto, g.cfg, zctx, withoutSuffix) if err != nil { return err } - err = g.GenMain(dirCtx, proto, g.cfg, zctx) + err = g.GenMain(dirCtx, proto, g.cfg, zctx, withoutSuffix) if err != nil { return err } if zctx.IsGenClient { - err = g.GenCall(dirCtx, proto, g.cfg, zctx) + err = g.GenCall(dirCtx, proto, g.cfg, zctx, withoutSuffix) } console.NewColorConsole().MarkDone() diff --git a/tools/goctl/rpc/generator/gencall.go b/tools/goctl/rpc/generator/gencall.go index 060877cd619f..4f2db65caa24 100644 --- a/tools/goctl/rpc/generator/gencall.go +++ b/tools/goctl/rpc/generator/gencall.go @@ -36,15 +36,15 @@ var callTemplateText string // GenCall generates the rpc client code, which is the entry point for the rpc service call. // It is a layer of encapsulation for the rpc client and shields the details in the pb. func (g *Generator) GenCall(ctx DirContext, proto parser.Proto, cfg *conf.Config, - c *ZRpcContext) error { + c *ZRpcContext, withoutSuffix bool) error { if !c.Multiple { - return g.genCallInCompatibility(ctx, proto, cfg) + return g.genCallInCompatibility(ctx, proto, cfg, withoutSuffix) } - return g.genCallGroup(ctx, proto, cfg) + return g.genCallGroup(ctx, proto, cfg, withoutSuffix) } -func (g *Generator) genCallGroup(ctx DirContext, proto parser.Proto, cfg *conf.Config) error { +func (g *Generator) genCallGroup(ctx DirContext, proto parser.Proto, cfg *conf.Config, withoutSuffix bool) error { dir := ctx.GetCall() head := util.GetHead(proto.Name) for _, service := range proto.Service { @@ -80,12 +80,12 @@ func (g *Generator) genCallGroup(ctx DirContext, proto parser.Proto, cfg *conf.C serviceName = stringx.From(service.Name + "_zrpc_client").ToCamel() } - functions, err := g.genFunction(proto.PbPackage, serviceName, service, isCallPkgSameToGrpcPkg) + functions, err := g.genFunction(proto.PbPackage, serviceName, service, isCallPkgSameToGrpcPkg, withoutSuffix) if err != nil { return err } - iFunctions, err := g.getInterfaceFuncs(proto.PbPackage, service, isCallPkgSameToGrpcPkg) + iFunctions, err := g.getInterfaceFuncs(proto.PbPackage, service, isCallPkgSameToGrpcPkg, withoutSuffix) if err != nil { return err } @@ -122,7 +122,7 @@ func (g *Generator) genCallGroup(ctx DirContext, proto parser.Proto, cfg *conf.C } func (g *Generator) genCallInCompatibility(ctx DirContext, proto parser.Proto, - cfg *conf.Config) error { + cfg *conf.Config, withoutSuffix bool) error { dir := ctx.GetCall() service := proto.Service[0] head := util.GetHead(proto.Name) @@ -153,12 +153,12 @@ func (g *Generator) genCallInCompatibility(ctx DirContext, proto parser.Proto, } filename := filepath.Join(dir.Filename, fmt.Sprintf("%s.go", callFilename)) - functions, err := g.genFunction(proto.PbPackage, serviceName, service, isCallPkgSameToGrpcPkg) + functions, err := g.genFunction(proto.PbPackage, serviceName, service, isCallPkgSameToGrpcPkg, withoutSuffix) if err != nil { return err } - iFunctions, err := g.getInterfaceFuncs(proto.PbPackage, service, isCallPkgSameToGrpcPkg) + iFunctions, err := g.getInterfaceFuncs(proto.PbPackage, service, isCallPkgSameToGrpcPkg, withoutSuffix) if err != nil { return err } @@ -212,7 +212,7 @@ func getMessageName(msg proto.Message) string { } func (g *Generator) genFunction(goPackage string, serviceName string, service parser.Service, - isCallPkgSameToGrpcPkg bool) ([]string, error) { + isCallPkgSameToGrpcPkg, withoutSuffix bool) ([]string, error) { functions := make([]string, 0) for _, rpc := range service.RPC { @@ -222,12 +222,20 @@ func (g *Generator) genFunction(goPackage string, serviceName string, service pa } comment := parser.GetComment(rpc.Doc()) - streamServer := fmt.Sprintf("%s.%s_%s%s", goPackage, parser.CamelCase(service.Name), - parser.CamelCase(rpc.Name), "Client") - if isCallPkgSameToGrpcPkg { - streamServer = fmt.Sprintf("%s_%s%s", parser.CamelCase(service.Name), + streamServer := fmt.Sprintf("%s.%s_%s", goPackage, parser.CamelCase(service.Name), + parser.CamelCase(rpc.Name)) + if !withoutSuffix { + streamServer = fmt.Sprintf("%s.%s_%s%s", goPackage, parser.CamelCase(service.Name), parser.CamelCase(rpc.Name), "Client") } + if isCallPkgSameToGrpcPkg { + streamServer = fmt.Sprintf("%s_%s", parser.CamelCase(service.Name), + parser.CamelCase(rpc.Name)) + if !withoutSuffix { + streamServer = fmt.Sprintf("%s_%s%s", parser.CamelCase(service.Name), + parser.CamelCase(rpc.Name), "Client") + } + } buffer, err := util.With("sharedFn").Parse(text).Execute(map[string]any{ "serviceName": serviceName, "rpcServiceName": parser.CamelCase(service.Name), @@ -253,7 +261,7 @@ func (g *Generator) genFunction(goPackage string, serviceName string, service pa } func (g *Generator) getInterfaceFuncs(goPackage string, service parser.Service, - isCallPkgSameToGrpcPkg bool) ([]string, error) { + isCallPkgSameToGrpcPkg, withoutSuffix bool) ([]string, error) { functions := make([]string, 0) for _, rpc := range service.RPC { @@ -264,12 +272,20 @@ func (g *Generator) getInterfaceFuncs(goPackage string, service parser.Service, } comment := parser.GetComment(rpc.Doc()) - streamServer := fmt.Sprintf("%s.%s_%s%s", goPackage, parser.CamelCase(service.Name), - parser.CamelCase(rpc.Name), "Client") - if isCallPkgSameToGrpcPkg { - streamServer = fmt.Sprintf("%s_%s%s", parser.CamelCase(service.Name), + streamServer := fmt.Sprintf("%s.%s_%s", goPackage, parser.CamelCase(service.Name), + parser.CamelCase(rpc.Name)) + if !withoutSuffix { + streamServer = fmt.Sprintf("%s.%s_%s%s", goPackage, parser.CamelCase(service.Name), parser.CamelCase(rpc.Name), "Client") } + if isCallPkgSameToGrpcPkg { + streamServer = fmt.Sprintf("%s_%s", parser.CamelCase(service.Name), + parser.CamelCase(rpc.Name)) + if !withoutSuffix { + streamServer = fmt.Sprintf("%s_%s%s", parser.CamelCase(service.Name), + parser.CamelCase(rpc.Name), "Client") + } + } buffer, err := util.With("interfaceFn").Parse(text).Execute( map[string]any{ "hasComment": len(comment) > 0, diff --git a/tools/goctl/rpc/generator/genlogic.go b/tools/goctl/rpc/generator/genlogic.go index 43acd0ea62f6..83dbf5313abb 100644 --- a/tools/goctl/rpc/generator/genlogic.go +++ b/tools/goctl/rpc/generator/genlogic.go @@ -28,27 +28,31 @@ var logicTemplate string // GenLogic generates the logic file of the rpc service, which corresponds to the RPC definition items in proto. func (g *Generator) GenLogic(ctx DirContext, proto parser.Proto, cfg *conf.Config, - c *ZRpcContext) error { + c *ZRpcContext, withoutSuffix bool) error { if !c.Multiple { - return g.genLogicInCompatibility(ctx, proto, cfg) + return g.genLogicInCompatibility(ctx, proto, cfg, withoutSuffix) } - return g.genLogicGroup(ctx, proto, cfg) + return g.genLogicGroup(ctx, proto, cfg, withoutSuffix) } func (g *Generator) genLogicInCompatibility(ctx DirContext, proto parser.Proto, - cfg *conf.Config) error { + cfg *conf.Config, withoutSuffix bool) error { dir := ctx.GetLogic() service := proto.Service[0].Service.Name for _, rpc := range proto.Service[0].RPC { - logicName := fmt.Sprintf("%sLogic", stringx.From(rpc.Name).ToCamel()) - logicFilename, err := format.FileNamingFormat(cfg.NamingFormat, rpc.Name+"_logic") + logicName := fmt.Sprintf("%s", stringx.From(rpc.Name).ToCamel()) + logicFilename, err := format.FileNamingFormat(cfg.NamingFormat, rpc.Name) + if !withoutSuffix { + logicName = fmt.Sprintf("%sLogic", stringx.From(rpc.Name).ToCamel()) + logicFilename, err = format.FileNamingFormat(cfg.NamingFormat, rpc.Name+"_logic") + } if err != nil { return err } filename := filepath.Join(dir.Filename, logicFilename+".go") - functions, err := g.genLogicFunction(service, proto.PbPackage, logicName, rpc) + functions, err := g.genLogicFunction(service, proto.PbPackage, logicName, rpc, withoutSuffix) if err != nil { return err } @@ -73,7 +77,7 @@ func (g *Generator) genLogicInCompatibility(ctx DirContext, proto parser.Proto, return nil } -func (g *Generator) genLogicGroup(ctx DirContext, proto parser.Proto, cfg *conf.Config) error { +func (g *Generator) genLogicGroup(ctx DirContext, proto parser.Proto, cfg *conf.Config, withoutSuffix bool) error { dir := ctx.GetLogic() for _, item := range proto.Service { serviceName := item.Name @@ -85,23 +89,31 @@ func (g *Generator) genLogicGroup(ctx DirContext, proto parser.Proto, cfg *conf. logicFilename string packageName string ) - - logicName = fmt.Sprintf("%sLogic", stringx.From(rpc.Name).ToCamel()) + logicName = fmt.Sprintf("%s", stringx.From(rpc.Name).ToCamel()) + if !withoutSuffix { + logicName = fmt.Sprintf("%sLogic", stringx.From(rpc.Name).ToCamel()) + } childPkg, err := dir.GetChildPackage(serviceName) if err != nil { return err } serviceDir := filepath.Base(childPkg) - nameJoin := fmt.Sprintf("%s_logic", serviceName) + nameJoin := fmt.Sprintf("%s", serviceName) + if !withoutSuffix { + nameJoin = fmt.Sprintf("%s_logic", serviceName) + } packageName = strings.ToLower(stringx.From(nameJoin).ToCamel()) - logicFilename, err = format.FileNamingFormat(cfg.NamingFormat, rpc.Name+"_logic") + logicFilename, err = format.FileNamingFormat(cfg.NamingFormat, rpc.Name) + if !withoutSuffix { + logicFilename, err = format.FileNamingFormat(cfg.NamingFormat, rpc.Name+"_logic") + } if err != nil { return err } filename = filepath.Join(dir.Filename, serviceDir, logicFilename+".go") - functions, err := g.genLogicFunction(serviceName, proto.PbPackage, logicName, rpc) + functions, err := g.genLogicFunction(serviceName, proto.PbPackage, logicName, rpc, withoutSuffix) if err != nil { return err } @@ -128,7 +140,7 @@ func (g *Generator) genLogicGroup(ctx DirContext, proto parser.Proto, cfg *conf. } func (g *Generator) genLogicFunction(serviceName, goPackage, logicName string, - rpc *parser.RPC) (string, + rpc *parser.RPC, withoutSuffix bool) (string, error) { functions := make([]string, 0) text, err := pathx.LoadTemplate(category, logicFuncTemplateFileFile, logicFunctionTemplate) @@ -137,8 +149,13 @@ func (g *Generator) genLogicFunction(serviceName, goPackage, logicName string, } comment := parser.GetComment(rpc.Doc()) - streamServer := fmt.Sprintf("%s.%s_%s%s", goPackage, parser.CamelCase(serviceName), - parser.CamelCase(rpc.Name), "Server") + streamServer := fmt.Sprintf("%s.%s_%s", goPackage, parser.CamelCase(serviceName), + parser.CamelCase(rpc.Name)) + if !withoutSuffix { + streamServer = fmt.Sprintf("%s.%s_%s%s", goPackage, parser.CamelCase(serviceName), + parser.CamelCase(rpc.Name), "Server") + } + buffer, err := util.With("fun").Parse(text).Execute(map[string]any{ "logicName": logicName, "method": parser.CamelCase(rpc.Name), diff --git a/tools/goctl/rpc/generator/genmain.go b/tools/goctl/rpc/generator/genmain.go index 0238153875fd..f6c0a388cb08 100644 --- a/tools/goctl/rpc/generator/genmain.go +++ b/tools/goctl/rpc/generator/genmain.go @@ -24,7 +24,7 @@ type MainServiceTemplateData struct { // GenMain generates the main file of the rpc service, which is an rpc service program call entry func (g *Generator) GenMain(ctx DirContext, proto parser.Proto, cfg *conf.Config, - c *ZRpcContext) error { + c *ZRpcContext, withoutSuffix bool) error { mainFilename, err := format.FileNamingFormat(cfg.NamingFormat, ctx.GetServiceName().Source()) if err != nil { return err @@ -51,8 +51,11 @@ func (g *Generator) GenMain(ctx DirContext, proto parser.Proto, cfg *conf.Config if err != nil { return err } + serverPkg = filepath.Base(childPkg) - serverPkg = filepath.Base(childPkg + "Server") + if !withoutSuffix { + serverPkg = filepath.Base(childPkg + "Server") + } remoteImport = fmt.Sprintf(`%s "%v"`, serverPkg, childPkg) } imports = append(imports, remoteImport) diff --git a/tools/goctl/rpc/generator/genserver.go b/tools/goctl/rpc/generator/genserver.go index 04c816bf7a7f..fcfc046adbd5 100644 --- a/tools/goctl/rpc/generator/genserver.go +++ b/tools/goctl/rpc/generator/genserver.go @@ -22,29 +22,38 @@ func (s *{{.server}}Server) {{.method}} ({{if .notStream}}ctx context.Context,{{ return l.{{.method}}({{if .hasReq}}in{{if .stream}} ,stream{{end}}{{else}}{{if .stream}}stream{{end}}{{end}}) } ` +const withoutSuffixFunctionTemplate = ` +{{if .hasComment}}{{.comment}}{{end}} +func (s *{{.server}}) {{.method}} ({{if .notStream}}ctx context.Context,{{if .hasReq}} in {{.request}}{{end}}{{else}}{{if .hasReq}} in {{.request}},{{end}}stream {{.streamBody}}{{end}}) ({{if .notStream}}{{.response}},{{end}}error) { + l := {{.logicPkg}}.New{{.logicName}}({{if .notStream}}ctx,{{else}}stream.Context(),{{end}}s.svcCtx) + return l.{{.method}}({{if .hasReq}}in{{if .stream}} ,stream{{end}}{{else}}{{if .stream}}stream{{end}}{{end}}) +} +` //go:embed server.tpl var serverTemplate string // GenServer generates rpc server file, which is an implementation of rpc server func (g *Generator) GenServer(ctx DirContext, proto parser.Proto, cfg *conf.Config, - c *ZRpcContext) error { + c *ZRpcContext, withoutSuffix bool) error { if !c.Multiple { - return g.genServerInCompatibility(ctx, proto, cfg, c) + return g.genServerInCompatibility(ctx, proto, cfg, c, withoutSuffix) } - return g.genServerGroup(ctx, proto, cfg) + return g.genServerGroup(ctx, proto, cfg, withoutSuffix) } -func (g *Generator) genServerGroup(ctx DirContext, proto parser.Proto, cfg *conf.Config) error { +func (g *Generator) genServerGroup(ctx DirContext, proto parser.Proto, cfg *conf.Config, withoutSuffix bool) error { dir := ctx.GetServer() for _, service := range proto.Service { var ( serverFile string logicImport string ) - - serverFilename, err := format.FileNamingFormat(cfg.NamingFormat, service.Name+"_server") + serverFilename, err := format.FileNamingFormat(cfg.NamingFormat, service.Name) + if !withoutSuffix { + serverFilename, err = format.FileNamingFormat(cfg.NamingFormat, service.Name+"_server") + } if err != nil { return err } @@ -64,14 +73,14 @@ func (g *Generator) genServerGroup(ctx DirContext, proto parser.Proto, cfg *conf serverFile = filepath.Join(dir.Filename, serverDir, serverFilename+".go") svcImport := fmt.Sprintf(`"%v"`, ctx.GetSvc().Package) - pbImport := fmt.Sprintf(`"%v"`, ctx.GetPb().Package) + pbImport := fmt.Sprintf(`"%v"`, ctx.GetPb().Package) //pb types imports := collection.NewSet() imports.AddStr(logicImport, svcImport, pbImport) head := util.GetHead(proto.Name) - funcList, err := g.genFunctions(proto.PbPackage, service, true) + funcList, err := g.genFunctions(proto.PbPackage, service, true, withoutSuffix) if err != nil { return err } @@ -88,15 +97,19 @@ func (g *Generator) genServerGroup(ctx DirContext, proto parser.Proto, cfg *conf break } } - + unimplementedServer := fmt.Sprintf("%s.Unimplemented%sServer", proto.PbPackage, + stringx.From(service.Name).ToCamel()) + if !withoutSuffix { + unimplementedServer = fmt.Sprintf("%s.Unimplemented%sServer", proto.PbPackage, + stringx.From(service.Name).ToCamel()) + } if err = util.With("server").GoFmt(true).Parse(text).SaveTo(map[string]any{ - "head": head, - "unimplementedServer": fmt.Sprintf("%s.Unimplemented%sServer", proto.PbPackage, - stringx.From(service.Name).ToCamel()), - "server": stringx.From(service.Name).ToCamel(), - "imports": strings.Join(imports.KeysStr(), pathx.NL), - "funcs": strings.Join(funcList, pathx.NL), - "notStream": notStream, + "head": head, + "unimplementedServer": unimplementedServer, + "server": stringx.From(service.Name).ToCamel(), + "imports": strings.Join(imports.KeysStr(), pathx.NL), + "funcs": strings.Join(funcList, pathx.NL), + "notStream": notStream, }, serverFile, true); err != nil { return err } @@ -105,7 +118,7 @@ func (g *Generator) genServerGroup(ctx DirContext, proto parser.Proto, cfg *conf } func (g *Generator) genServerInCompatibility(ctx DirContext, proto parser.Proto, - cfg *conf.Config, c *ZRpcContext) error { + cfg *conf.Config, c *ZRpcContext, withoutSuffix bool) error { dir := ctx.GetServer() logicImport := fmt.Sprintf(`"%v"`, ctx.GetLogic().Package) svcImport := fmt.Sprintf(`"%v"`, ctx.GetSvc().Package) @@ -116,13 +129,16 @@ func (g *Generator) genServerInCompatibility(ctx DirContext, proto parser.Proto, head := util.GetHead(proto.Name) service := proto.Service[0] - serverFilename, err := format.FileNamingFormat(cfg.NamingFormat, service.Name+"_server") + serverFilename, err := format.FileNamingFormat(cfg.NamingFormat, service.Name) + if !withoutSuffix { + serverFilename, err = format.FileNamingFormat(cfg.NamingFormat, service.Name+"_server") + } if err != nil { return err } serverFile := filepath.Join(dir.Filename, serverFilename+".go") - funcList, err := g.genFunctions(proto.PbPackage, service, false) + funcList, err := g.genFunctions(proto.PbPackage, service, false, withoutSuffix) if err != nil { return err } @@ -139,25 +155,33 @@ func (g *Generator) genServerInCompatibility(ctx DirContext, proto parser.Proto, break } } - + unimplementedServer := fmt.Sprintf("%s.Unimplemented%sServer", proto.PbPackage, + stringx.From(service.Name).ToCamel()) + if !withoutSuffix { + unimplementedServer = fmt.Sprintf("%s.Unimplemented%sServer", proto.PbPackage, + stringx.From(service.Name).ToCamel()) + } return util.With("server").GoFmt(true).Parse(text).SaveTo(map[string]any{ - "head": head, - "unimplementedServer": fmt.Sprintf("%s.Unimplemented%sServer", proto.PbPackage, - stringx.From(service.Name).ToCamel()), - "server": stringx.From(service.Name).ToCamel(), - "imports": strings.Join(imports.KeysStr(), pathx.NL), - "funcs": strings.Join(funcList, pathx.NL), - "notStream": notStream, + "head": head, + "unimplementedServer": unimplementedServer, + "server": stringx.From(service.Name).ToCamel(), + "imports": strings.Join(imports.KeysStr(), pathx.NL), + "funcs": strings.Join(funcList, pathx.NL), + "notStream": notStream, }, serverFile, true) } -func (g *Generator) genFunctions(goPackage string, service parser.Service, multiple bool) ([]string, error) { +func (g *Generator) genFunctions(goPackage string, service parser.Service, multiple, withoutSuffix bool) ([]string, error) { var ( functionList []string logicPkg string ) for _, rpc := range service.RPC { - text, err := pathx.LoadTemplate(category, serverFuncTemplateFile, functionTemplate) + _functionTemplate := functionTemplate + if !withoutSuffix { + _functionTemplate = withoutSuffixFunctionTemplate + } + text, err := pathx.LoadTemplate(category, serverFuncTemplateFile, _functionTemplate) if err != nil { return nil, err } @@ -165,16 +189,28 @@ func (g *Generator) genFunctions(goPackage string, service parser.Service, multi var logicName string if !multiple { logicPkg = "logic" - logicName = fmt.Sprintf("%sLogic", stringx.From(rpc.Name).ToCamel()) + logicName = fmt.Sprintf("%s", stringx.From(rpc.Name).ToCamel()) + if !withoutSuffix { + logicName = fmt.Sprintf("%sLogic", stringx.From(rpc.Name).ToCamel()) + } } else { - nameJoin := fmt.Sprintf("%s_logic", service.Name) + nameJoin := fmt.Sprintf("%s", service.Name) + logicName = fmt.Sprintf("%s", stringx.From(rpc.Name).ToCamel()) + if !withoutSuffix { + nameJoin = fmt.Sprintf("%s_logic", service.Name) + logicName = fmt.Sprintf("%sLogic", stringx.From(rpc.Name).ToCamel()) + } logicPkg = strings.ToLower(stringx.From(nameJoin).ToCamel()) - logicName = fmt.Sprintf("%sLogic", stringx.From(rpc.Name).ToCamel()) } comment := parser.GetComment(rpc.Doc()) - streamServer := fmt.Sprintf("%s.%s_%s%s", goPackage, parser.CamelCase(service.Name), - parser.CamelCase(rpc.Name), "Server") + streamServer := fmt.Sprintf("%s.%s_%s", goPackage, parser.CamelCase(service.Name), + parser.CamelCase(rpc.Name)) + if !withoutSuffix { + streamServer = fmt.Sprintf("%s.%s_%s%s", goPackage, parser.CamelCase(service.Name), + parser.CamelCase(rpc.Name), "Server") + } + buffer, err := util.With("func").Parse(text).Execute(map[string]any{ "server": stringx.From(service.Name).ToCamel(), "logicName": logicName, diff --git a/tools/goctl/rpc/generator/mkdir.go b/tools/goctl/rpc/generator/mkdir.go index 163f904a9f62..9cf69bafe9be 100644 --- a/tools/goctl/rpc/generator/mkdir.go +++ b/tools/goctl/rpc/generator/mkdir.go @@ -57,7 +57,7 @@ type ( } ) -func mkdir(ctx *ctx.ProjectContext, proto parser.Proto, conf *conf.Config, c *ZRpcContext) (DirContext, +func mkdir(ctx *ctx.ProjectContext, proto parser.Proto, conf *conf.Config, c *ZRpcContext, withoutSuffix bool) (DirContext, error) { inner := make(map[string]Dir) etcDir := filepath.Join(ctx.WorkDir, "etc") @@ -93,7 +93,11 @@ func mkdir(ctx *ctx.ProjectContext, proto parser.Proto, conf *conf.Config, c *ZR strings.ToLower(stringx.From(proto.Service[0].Name).ToCamel())) if strings.EqualFold(proto.Service[0].Name, filepath.Base(proto.GoPackage)) { var err error - clientDir, err = format.FileNamingFormat(conf.NamingFormat, proto.Service[0].Name+"_client") + clientDir, err = format.FileNamingFormat(conf.NamingFormat, proto.Service[0].Name) + + if !withoutSuffix { + clientDir, err = format.FileNamingFormat(conf.NamingFormat, proto.Service[0].Name+"_client") + } if err != nil { return nil, err } diff --git a/tools/goctl/rpc/generator/server.tpl b/tools/goctl/rpc/generator/server.tpl index 84a2f9c14dff..545454a84483 100644 --- a/tools/goctl/rpc/generator/server.tpl +++ b/tools/goctl/rpc/generator/server.tpl @@ -8,13 +8,13 @@ import ( {{.imports}} ) -type {{.server}}Server struct { +type {{.server}} struct { svcCtx *svc.ServiceContext {{.unimplementedServer}} } -func New{{.server}}Server(svcCtx *svc.ServiceContext) *{{.server}}Server { - return &{{.server}}Server{ +func New{{.server}}(svcCtx *svc.ServiceContext) *{{.server}} { + return &{{.server}}{ svcCtx: svcCtx, } }