From 1feb5d677b2309bffcbff87d8d0a62d3d4cd6615 Mon Sep 17 00:00:00 2001 From: luruichao <110596971+chaoranz758@users.noreply.github.com> Date: Mon, 9 Oct 2023 11:04:47 +0800 Subject: [PATCH] optimize: consts (#87) --- cmd/dynamic/cmd.go | 11 ++-- cmd/dynamic/common.go | 22 +++---- cmd/dynamic/db.go | 27 +++++---- cmd/static/client_flags.go | 21 +++---- cmd/static/cmd.go | 16 +++-- cmd/static/model_flags.go | 27 +++++---- cmd/static/server_flags.go | 23 ++++---- config/argument.go | 70 ++-------------------- config/client.go | 11 ++-- config/fallback.go | 15 ++--- config/model.go | 29 ++++----- config/server.go | 19 +++--- meta/version.go | 1 + pkg/client/check.go | 17 +++--- pkg/client/client.go | 5 +- pkg/client/hz.go | 26 ++++---- pkg/client/kitex.go | 8 +-- pkg/common/kx_registry/registry.go | 13 ++-- pkg/consts/const.go | 95 +++++++++++++++++++++++++++++- pkg/fallback/fallback.go | 5 +- pkg/model/model.go | 3 +- pkg/server/check.go | 12 ++-- pkg/server/hz.go | 26 ++++---- pkg/server/kitex.go | 16 ++--- pkg/server/server.go | 5 +- tpl/init.go | 11 ++-- 26 files changed, 288 insertions(+), 246 deletions(-) diff --git a/cmd/dynamic/cmd.go b/cmd/dynamic/cmd.go index bf751ea9..4ac35d53 100644 --- a/cmd/dynamic/cmd.go +++ b/cmd/dynamic/cmd.go @@ -23,6 +23,7 @@ import ( "github.com/cloudwego/cwgo/config" "github.com/cloudwego/cwgo/pkg/client" "github.com/cloudwego/cwgo/pkg/common/utils" + "github.com/cloudwego/cwgo/pkg/consts" "github.com/cloudwego/cwgo/pkg/model" "github.com/cloudwego/cwgo/pkg/server" "github.com/cloudwego/hertz/cmd/hz/meta" @@ -31,10 +32,10 @@ import ( var generateType = []*survey.Question{ { - Name: "type", + Name: consts.ServiceType, Prompt: &survey.MultiSelect{ Message: "Select generate type", - Options: []string{Server, Client, DB}, + Options: []string{consts.Server, consts.Client, consts.DB}, }, Validate: survey.Required, }, @@ -54,7 +55,7 @@ func Terminal(*cli.Context) error { cfg := &dfConfig{} // ask whether generate server project - if _, ok := typeMap[Server]; ok { + if _, ok := typeMap[consts.Server]; ok { sa := config.NewServerArgument() err = survey.Ask(commonQuestion(), sa.CommonParam) if err != nil { @@ -88,7 +89,7 @@ func Terminal(*cli.Context) error { num := &cNum{} // ask whether generate client project - if _, ok := typeMap[Client]; ok { + if _, ok := typeMap[consts.Client]; ok { err = survey.Ask(clientNum, num) if err != nil { return err @@ -130,7 +131,7 @@ func Terminal(*cli.Context) error { } // ask whether generate db project - if _, ok := typeMap[DB]; ok { + if _, ok := typeMap[consts.DB]; ok { da := config.NewModelArgument() err = survey.Ask(dbConfig, da) if err != nil { diff --git a/cmd/dynamic/common.go b/cmd/dynamic/common.go index c95719c2..4a5c257a 100644 --- a/cmd/dynamic/common.go +++ b/cmd/dynamic/common.go @@ -16,27 +16,21 @@ package dynamic import ( "github.com/AlecAivazis/survey/v2" - "github.com/cloudwego/cwgo/config" -) - -const ( - Server = "server" - Client = "client" - DB = "db" + "github.com/cloudwego/cwgo/pkg/consts" ) func commonQuestion() []*survey.Question { return []*survey.Question{ { - Name: "type", + Name: consts.ServiceType, Prompt: &survey.Select{ Message: "Select service type", - Options: []string{"RPC", "HTTP"}, + Options: []string{consts.RPC, consts.HTTP}, }, Validate: survey.Required, }, { - Name: "service", + Name: consts.Service, Prompt: &survey.Input{ Message: "Please input service name", }, @@ -76,7 +70,7 @@ func defaultConfig() []*survey.Question { func protoSearch() []*survey.Question { return []*survey.Question{{ - Name: "proto_search_path", + Name: consts.ProtoSearchPath, Prompt: &survey.Input{ Message: "Please input proto search path if exists, space as separator", }, @@ -86,7 +80,7 @@ func protoSearch() []*survey.Question { func customConfig() []*survey.Question { return []*survey.Question{ { - Name: "pass", + Name: consts.Pass, Prompt: &survey.Input{ Message: "Please input custom param", }, @@ -97,10 +91,10 @@ func customConfig() []*survey.Question { func registryConfig() []*survey.Question { return []*survey.Question{ { - Name: "registry", + Name: consts.Registry, Prompt: &survey.Select{ Message: "Please select a registry", - Options: []string{config.Zk, config.Polaris, config.Etcd, config.Nacos}, + Options: []string{consts.Zk, consts.Polaris, consts.Etcd, consts.Nacos}, }, Validate: survey.Required, }, diff --git a/cmd/dynamic/db.go b/cmd/dynamic/db.go index e5583b4e..5ae56647 100644 --- a/cmd/dynamic/db.go +++ b/cmd/dynamic/db.go @@ -20,6 +20,7 @@ import ( "github.com/cloudwego/cwgo/config" "github.com/cloudwego/cwgo/pkg/common/utils" + "github.com/cloudwego/cwgo/pkg/consts" "github.com/AlecAivazis/survey/v2" "github.com/AlecAivazis/survey/v2/core" @@ -27,10 +28,10 @@ import ( var dbConfig = []*survey.Question{ { - Name: "type", + Name: consts.ServiceType, Prompt: &survey.Select{ Message: "Select db type", - Options: []string{"MySQL", "SQLServer", "SQLite", "PostgreSQL"}, + Options: []string{string(consts.MySQL), string(consts.SQLServer), string(consts.Sqlite), string(consts.Postgres)}, }, Validate: survey.Required, Transform: func(ans interface{}) (newAns interface{}) { @@ -54,7 +55,7 @@ type ps struct { var pass = []*survey.Question{ { - Name: "pass", + Name: consts.Pass, Prompt: &survey.Input{ Message: "Please input custom param", }, @@ -63,17 +64,17 @@ var pass = []*survey.Question{ func parsePass(da *config.ModelArgument, pass string) error { f := flag.NewFlagSet("", flag.ContinueOnError) - f.StringVar(&da.OutPath, config.OutDir, "biz/dal/query", "") - f.StringVar(&da.OutFile, config.OutFile, "gen.go", "") - f.BoolVar(&da.WithUnitTest, config.UnitTest, false, "") - f.BoolVar(&da.OnlyModel, config.OnlyModel, false, "") - f.StringVar(&da.ModelPkgName, config.ModelPkgName, "", "") - f.BoolVar(&da.FieldNullable, config.Nullable, false, "") - f.BoolVar(&da.FieldSignable, config.Signable, false, "") - f.BoolVar(&da.FieldWithTypeTag, config.TypeTag, false, "") - f.BoolVar(&da.FieldWithIndexTag, config.IndexTag, false, "") + f.StringVar(&da.OutPath, consts.OutDir, consts.DefaultDbOutDir, "") + f.StringVar(&da.OutFile, consts.OutFile, consts.DefaultDbOutFile, "") + f.BoolVar(&da.WithUnitTest, consts.UnitTest, false, "") + f.BoolVar(&da.OnlyModel, consts.OnlyModel, false, "") + f.StringVar(&da.ModelPkgName, consts.ModelPkgName, "", "") + f.BoolVar(&da.FieldNullable, consts.Nullable, false, "") + f.BoolVar(&da.FieldSignable, consts.Signable, false, "") + f.BoolVar(&da.FieldWithTypeTag, consts.TypeTag, false, "") + f.BoolVar(&da.FieldWithIndexTag, consts.IndexTag, false, "") var tables utils.FlagStringSlice - f.Var(&tables, config.Tables, "") + f.Var(&tables, consts.Tables, "") if err := f.Parse(utils.StringSliceSpilt([]string{pass})); err != nil { return err } diff --git a/cmd/static/client_flags.go b/cmd/static/client_flags.go index 5112fdca..2ac6b7c0 100644 --- a/cmd/static/client_flags.go +++ b/cmd/static/client_flags.go @@ -18,21 +18,22 @@ package static import ( "github.com/cloudwego/cwgo/config" + "github.com/cloudwego/cwgo/pkg/consts" "github.com/urfave/cli/v2" ) func clientFlags() []cli.Flag { globalArgs := config.GetGlobalArgs() return []cli.Flag{ - &cli.StringFlag{Name: config.Service, Usage: "Specify the service name.", Destination: &globalArgs.ClientArgument.Service}, - &cli.StringFlag{Name: config.ServiceType, Usage: "Specify the generate type. (RPC or HTTP)", Value: config.RPC}, - &cli.StringFlag{Name: config.Module, Aliases: []string{"mod"}, Usage: "Specify the Go module name to generate go.mod.", Destination: &globalArgs.ClientArgument.GoMod}, - &cli.StringFlag{Name: config.IDLPath, Usage: "Specify the IDL file path. (.thrift or .proto)", Destination: &globalArgs.ClientArgument.IdlPath}, - &cli.StringFlag{Name: config.OutDir, Aliases: []string{"o"}, Usage: "Specify the output path.", Destination: &globalArgs.ClientArgument.OutDir}, - &cli.StringFlag{Name: config.Template, Usage: "Specify the output path. Currently cwgo supports git templates, such as `--template https://github.com/***/cwgo_template.git`", Destination: &globalArgs.ClientArgument.Template}, - &cli.StringFlag{Name: config.Registry, Usage: "Specify the registry, default is None"}, - &cli.StringSliceFlag{Name: config.ProtoSearchPath, Aliases: []string{"I"}, Usage: "Add an IDL search path for includes. (Valid only if idl is protobuf)"}, - &cli.StringSliceFlag{Name: config.Pass, Usage: "pass param to hz or kitex"}, - &cli.BoolFlag{Name: config.Verbose, Usage: "Turn on verbose mode."}, + &cli.StringFlag{Name: consts.Service, Usage: "Specify the service name.", Destination: &globalArgs.ClientArgument.Service}, + &cli.StringFlag{Name: consts.ServiceType, Usage: "Specify the generate type. (RPC or HTTP)", Value: consts.RPC}, + &cli.StringFlag{Name: consts.Module, Aliases: []string{"mod"}, Usage: "Specify the Go module name to generate go.mod.", Destination: &globalArgs.ClientArgument.GoMod}, + &cli.StringFlag{Name: consts.IDLPath, Usage: "Specify the IDL file path. (.thrift or .proto)", Destination: &globalArgs.ClientArgument.IdlPath}, + &cli.StringFlag{Name: consts.OutDir, Aliases: []string{"o"}, Usage: "Specify the output path.", Destination: &globalArgs.ClientArgument.OutDir}, + &cli.StringFlag{Name: consts.Template, Usage: "Specify the output path. Currently cwgo supports git templates, such as `--template https://github.com/***/cwgo_template.git`", Destination: &globalArgs.ClientArgument.Template}, + &cli.StringFlag{Name: consts.Registry, Usage: "Specify the registry, default is None"}, + &cli.StringSliceFlag{Name: consts.ProtoSearchPath, Aliases: []string{"I"}, Usage: "Add an IDL search path for includes. (Valid only if idl is protobuf)"}, + &cli.StringSliceFlag{Name: consts.Pass, Usage: "pass param to hz or kitex"}, + &cli.BoolFlag{Name: consts.Verbose, Usage: "Turn on verbose mode."}, } } diff --git a/cmd/static/cmd.go b/cmd/static/cmd.go index 88300ffd..a2bf7472 100644 --- a/cmd/static/cmd.go +++ b/cmd/static/cmd.go @@ -21,6 +21,7 @@ import ( "github.com/cloudwego/cwgo/config" "github.com/cloudwego/cwgo/meta" "github.com/cloudwego/cwgo/pkg/client" + "github.com/cloudwego/cwgo/pkg/consts" "github.com/cloudwego/cwgo/pkg/fallback" "github.com/cloudwego/cwgo/pkg/model" "github.com/cloudwego/cwgo/pkg/server" @@ -32,11 +33,11 @@ func Init() *cli.App { verboseFlag := cli.BoolFlag{Name: "verbose,vv", Usage: "turn on verbose mode"} app := cli.NewApp() - app.Name = "cwgo" - app.Usage = "All in one tools for CloudWeGo" + app.Name = meta.Name + app.Usage = AppUsage app.Version = meta.Version // The default separator for multiple parameters is modified to ";" - app.SliceFlagSeparator = ";" + app.SliceFlagSeparator = consts.Comma // global flags app.Flags = []cli.Flag{ @@ -87,8 +88,8 @@ func Init() *cli.App { }, }, { - Name: "fallback", - Usage: "fallback to hz or kitex", + Name: FallbackName, + Usage: FallbackUsage, Action: func(c *cli.Context) error { if err := globalArgs.FallbackArgument.ParseCli(c); err != nil { return err @@ -101,6 +102,8 @@ func Init() *cli.App { } const ( + AppUsage = "All in one tools for CloudWeGo" + ServerName = "server" ServerUsage = `generate RPC or HTTP server @@ -133,4 +136,7 @@ Examples: InitName = "init" InitUsage = `interactive terminals provide a more user-friendly experience for generating code` + + FallbackName = "fallback" + FallbackUsage = "fallback to hz or kitex" ) diff --git a/cmd/static/model_flags.go b/cmd/static/model_flags.go index 4f8feb77..8f7e90e3 100644 --- a/cmd/static/model_flags.go +++ b/cmd/static/model_flags.go @@ -21,32 +21,33 @@ import ( "strings" "github.com/cloudwego/cwgo/config" + "github.com/cloudwego/cwgo/pkg/consts" "github.com/urfave/cli/v2" ) func modelFlags() []cli.Flag { return []cli.Flag{ - &cli.StringFlag{Name: config.DSN, Usage: "Specify the database source name. (https://gorm.io/docs/connecting_to_the_database.html)", Value: "", DefaultText: "", Action: func(context *cli.Context, s string) error { + &cli.StringFlag{Name: consts.DSN, Usage: "Specify the database source name. (https://gorm.io/docs/connecting_to_the_database.html)", Value: "", DefaultText: "", Action: func(context *cli.Context, s string) error { if len(s) == 0 { return fmt.Errorf("dsn cannot be empty") } return nil }}, - &cli.StringFlag{Name: config.DBType, Usage: "Specify database type. (mysql or sqlserver or sqlite or postgres)", Value: "mysql", DefaultText: "mysql", Action: func(context *cli.Context, s string) error { - if _, ok := config.OpenTypeFuncMap[config.DataBaseType(strings.ToLower(s))]; !ok { + &cli.StringFlag{Name: consts.DBType, Usage: "Specify database type. (mysql or sqlserver or sqlite or postgres)", Value: string(consts.MySQL), DefaultText: string(consts.MySQL), Action: func(context *cli.Context, s string) error { + if _, ok := config.OpenTypeFuncMap[consts.DataBaseType(strings.ToLower(s))]; !ok { return fmt.Errorf("unknow db type %s (support mysql || postgres || sqlite || sqlserver for now)", s) } return nil }}, - &cli.StringFlag{Name: config.OutDir, Usage: "Specify output directory", Value: "biz/dal/query", DefaultText: "biz/dao/query"}, - &cli.StringFlag{Name: config.OutFile, Usage: "Specify output filename", Value: "gen.go", DefaultText: "gen.go"}, - &cli.StringSliceFlag{Name: config.Tables, Usage: "Specify databases tables"}, - &cli.BoolFlag{Name: config.UnitTest, Usage: "Specify generate unit test", Value: false, DefaultText: "false"}, - &cli.BoolFlag{Name: config.OnlyModel, Usage: "Specify only generate model code", Value: false, DefaultText: "false"}, - &cli.StringFlag{Name: config.ModelPkgName, Usage: "Specify model package name", Value: "", DefaultText: ""}, - &cli.BoolFlag{Name: config.Nullable, Usage: "Specify generate with pointer when field is nullable", Value: false, DefaultText: "false"}, - &cli.BoolFlag{Name: config.Signable, Usage: "Specify detect integer field's unsigned type, adjust generated data type", Value: false, DefaultText: "false"}, - &cli.BoolFlag{Name: config.TypeTag, Usage: "Specify generate field with gorm column type tag", Value: false, DefaultText: "false"}, - &cli.BoolFlag{Name: config.IndexTag, Usage: "Specify generate field with gorm index tag", Value: false, DefaultText: "false"}, + &cli.StringFlag{Name: consts.OutDir, Usage: "Specify output directory", Value: consts.DefaultDbOutDir, DefaultText: consts.DefaultDbOutDir}, + &cli.StringFlag{Name: consts.OutFile, Usage: "Specify output filename", Value: consts.DefaultDbOutFile, DefaultText: consts.DefaultDbOutFile}, + &cli.StringSliceFlag{Name: consts.Tables, Usage: "Specify databases tables"}, + &cli.BoolFlag{Name: consts.UnitTest, Usage: "Specify generate unit test", Value: false, DefaultText: "false"}, + &cli.BoolFlag{Name: consts.OnlyModel, Usage: "Specify only generate model code", Value: false, DefaultText: "false"}, + &cli.StringFlag{Name: consts.ModelPkgName, Usage: "Specify model package name", Value: "", DefaultText: ""}, + &cli.BoolFlag{Name: consts.Nullable, Usage: "Specify generate with pointer when field is nullable", Value: false, DefaultText: "false"}, + &cli.BoolFlag{Name: consts.Signable, Usage: "Specify detect integer field's unsigned type, adjust generated data type", Value: false, DefaultText: "false"}, + &cli.BoolFlag{Name: consts.TypeTag, Usage: "Specify generate field with gorm column type tag", Value: false, DefaultText: "false"}, + &cli.BoolFlag{Name: consts.IndexTag, Usage: "Specify generate field with gorm index tag", Value: false, DefaultText: "false"}, } } diff --git a/cmd/static/server_flags.go b/cmd/static/server_flags.go index 372cb523..3ca6f680 100644 --- a/cmd/static/server_flags.go +++ b/cmd/static/server_flags.go @@ -18,22 +18,23 @@ package static import ( "github.com/cloudwego/cwgo/config" + "github.com/cloudwego/cwgo/pkg/consts" "github.com/urfave/cli/v2" ) func serverFlags() []cli.Flag { globalArgs := config.GetGlobalArgs() return []cli.Flag{ - &cli.StringFlag{Name: config.Service, Usage: "Specify the service name.", Destination: &globalArgs.ServerArgument.Service}, - &cli.StringFlag{Name: config.ServiceType, Usage: "Specify the generate type. (RPC or HTTP)", Value: config.RPC}, - &cli.StringFlag{Name: config.Module, Aliases: []string{"mod"}, Usage: "Specify the Go module name to generate go.mod.", Destination: &globalArgs.ServerArgument.GoMod}, - &cli.StringFlag{Name: config.IDLPath, Usage: "Specify the IDL file path. (.thrift or .proto)", Destination: &globalArgs.ServerArgument.IdlPath}, - &cli.StringFlag{Name: config.OutDir, Value: ".", Aliases: []string{"o"}, Usage: "Specify the output path. Currently cwgo supports git templates, such as `--template https://github.com/***/cwgo_template.git`.", Destination: &globalArgs.ServerArgument.OutDir}, - &cli.StringFlag{Name: config.Template, Usage: "Specify the layout template.", Destination: &globalArgs.ServerArgument.Template}, - &cli.StringFlag{Name: config.Registry, Usage: "Specify the registry, default is None."}, - &cli.StringSliceFlag{Name: config.ProtoSearchPath, Aliases: []string{"I"}, Usage: "Add an IDL search path for includes."}, - &cli.StringSliceFlag{Name: config.Pass, Usage: "Pass param to hz or Kitex."}, - &cli.BoolFlag{Name: config.Verbose, Usage: "Turn on verbose mode."}, - &cli.BoolFlag{Name: config.HexTag, Usage: "Add HTTP listen for Kitex.", Destination: &globalArgs.Hex}, + &cli.StringFlag{Name: consts.Service, Usage: "Specify the service name.", Destination: &globalArgs.ServerArgument.Service}, + &cli.StringFlag{Name: consts.ServiceType, Usage: "Specify the generate type. (RPC or HTTP)", Value: consts.RPC}, + &cli.StringFlag{Name: consts.Module, Aliases: []string{"mod"}, Usage: "Specify the Go module name to generate go.mod.", Destination: &globalArgs.ServerArgument.GoMod}, + &cli.StringFlag{Name: consts.IDLPath, Usage: "Specify the IDL file path. (.thrift or .proto)", Destination: &globalArgs.ServerArgument.IdlPath}, + &cli.StringFlag{Name: consts.OutDir, Value: ".", Aliases: []string{"o"}, Usage: "Specify the output path. Currently cwgo supports git templates, such as `--template https://github.com/***/cwgo_template.git`.", Destination: &globalArgs.ServerArgument.OutDir}, + &cli.StringFlag{Name: consts.Template, Usage: "Specify the layout template.", Destination: &globalArgs.ServerArgument.Template}, + &cli.StringFlag{Name: consts.Registry, Usage: "Specify the registry, default is None."}, + &cli.StringSliceFlag{Name: consts.ProtoSearchPath, Aliases: []string{"I"}, Usage: "Add an IDL search path for includes."}, + &cli.StringSliceFlag{Name: consts.Pass, Usage: "Pass param to hz or Kitex."}, + &cli.BoolFlag{Name: consts.Verbose, Usage: "Turn on verbose mode."}, + &cli.BoolFlag{Name: consts.HexTag, Usage: "Add HTTP listen for Kitex.", Destination: &globalArgs.Hex}, } } diff --git a/config/argument.go b/config/argument.go index 4c72bc85..76d4ef1f 100644 --- a/config/argument.go +++ b/config/argument.go @@ -17,6 +17,7 @@ package config import ( + "github.com/cloudwego/cwgo/pkg/consts" "gorm.io/driver/mysql" "gorm.io/driver/postgres" "gorm.io/driver/sqlite" @@ -48,70 +49,11 @@ func NewArgument() *Argument { } } -const ( - RPC = "RPC" - HTTP = "HTTP" -) - -const ( - Standard = "standard" -) - -const ( - Zk = "ZK" - Nacos = "NACOS" - Etcd = "ETCD" - Polaris = "POLARIS" -) - -type DataBaseType string - -const ( - MySQL DataBaseType = "mysql" - SQLServer DataBaseType = "sqlserver" - Sqlite DataBaseType = "sqlite" - Postgres DataBaseType = "postgres" -) - type DialectorFunc func(string) gorm.Dialector -var OpenTypeFuncMap = map[DataBaseType]DialectorFunc{ - MySQL: mysql.Open, - SQLServer: sqlserver.Open, - Sqlite: sqlite.Open, - Postgres: postgres.Open, +var OpenTypeFuncMap = map[consts.DataBaseType]DialectorFunc{ + consts.MySQL: mysql.Open, + consts.SQLServer: sqlserver.Open, + consts.Sqlite: sqlite.Open, + consts.Postgres: postgres.Open, } - -type ToolType string - -const ( - Hz ToolType = "hz" - Kitex ToolType = "kitex" -) - -const ( - OutDir = "out_dir" - Verbose = "verbose" - Template = "template" - - Service = "service" - ServiceType = "type" - Module = "module" - IDLPath = "idl" - Registry = "registry" - Pass = "pass" - ProtoSearchPath = "proto_search_path" - - DSN = "dsn" - DBType = "db_type" - Tables = "tables" - OnlyModel = "only_model" - OutFile = "out_file" - UnitTest = "unittest" - ModelPkgName = "model_pkg" - Nullable = "nullable" - Signable = "signable" - IndexTag = "index_tag" - TypeTag = "type_tag" - HexTag = "hex" -) diff --git a/config/client.go b/config/client.go index c1596273..7c751240 100644 --- a/config/client.go +++ b/config/client.go @@ -19,6 +19,7 @@ package config import ( "strings" + "github.com/cloudwego/cwgo/pkg/consts" "github.com/urfave/cli/v2" ) @@ -44,10 +45,10 @@ func NewClientArgument() *ClientArgument { } func (c *ClientArgument) ParseCli(ctx *cli.Context) error { - c.Type = strings.ToUpper(ctx.String(ServiceType)) - c.Registry = strings.ToUpper(ctx.String(Registry)) - c.Verbose = ctx.Bool(Verbose) - c.SliceParam.ProtoSearchPath = ctx.StringSlice(ProtoSearchPath) - c.SliceParam.Pass = ctx.StringSlice(Pass) + c.Type = strings.ToUpper(ctx.String(consts.ServiceType)) + c.Registry = strings.ToUpper(ctx.String(consts.Registry)) + c.Verbose = ctx.Bool(consts.Verbose) + c.SliceParam.ProtoSearchPath = ctx.StringSlice(consts.ProtoSearchPath) + c.SliceParam.Pass = ctx.StringSlice(consts.Pass) return nil } diff --git a/config/fallback.go b/config/fallback.go index 1838e7ba..2cb2bfb6 100644 --- a/config/fallback.go +++ b/config/fallback.go @@ -19,11 +19,12 @@ package config import ( "fmt" + "github.com/cloudwego/cwgo/pkg/consts" "github.com/urfave/cli/v2" ) type FallbackArgument struct { - ToolType ToolType + ToolType consts.ToolType Args []string } @@ -37,12 +38,12 @@ func (c *FallbackArgument) ParseCli(ctx *cli.Context) error { return fmt.Errorf("please input tool type") } - c.ToolType = ToolType(args[0]) - switch ToolType(args[0]) { - case Hz: - c.ToolType = Hz - case Kitex: - c.ToolType = Kitex + c.ToolType = consts.ToolType(args[0]) + switch consts.ToolType(args[0]) { + case consts.Hz: + c.ToolType = consts.Hz + case consts.KitexTool: + c.ToolType = consts.KitexTool default: return fmt.Errorf("tool type is not supported") } diff --git a/config/model.go b/config/model.go index 6040f03d..c39b739f 100644 --- a/config/model.go +++ b/config/model.go @@ -19,6 +19,7 @@ package config import ( "strings" + "github.com/cloudwego/cwgo/pkg/consts" "github.com/urfave/cli/v2" ) @@ -39,23 +40,23 @@ type ModelArgument struct { func NewModelArgument() *ModelArgument { return &ModelArgument{ - OutPath: "biz/dal/query", - OutFile: "gen.go", + OutPath: consts.DefaultDbOutDir, + OutFile: consts.DefaultDbOutFile, } } func (c *ModelArgument) ParseCli(ctx *cli.Context) error { - c.DSN = ctx.String(DSN) - c.Type = strings.ToLower(ctx.String(DBType)) - c.Tables = ctx.StringSlice(Tables) - c.OnlyModel = ctx.Bool(OnlyModel) - c.OutPath = ctx.String(OutDir) - c.OutFile = ctx.String(OutFile) - c.WithUnitTest = ctx.Bool(UnitTest) - c.ModelPkgName = ctx.String(ModelPkgName) - c.FieldNullable = ctx.Bool(Nullable) - c.FieldSignable = ctx.Bool(Signable) - c.FieldWithIndexTag = ctx.Bool(IndexTag) - c.FieldWithTypeTag = ctx.Bool(TypeTag) + c.DSN = ctx.String(consts.DSN) + c.Type = strings.ToLower(ctx.String(consts.DBType)) + c.Tables = ctx.StringSlice(consts.Tables) + c.OnlyModel = ctx.Bool(consts.OnlyModel) + c.OutPath = ctx.String(consts.OutDir) + c.OutFile = ctx.String(consts.OutFile) + c.WithUnitTest = ctx.Bool(consts.UnitTest) + c.ModelPkgName = ctx.String(consts.ModelPkgName) + c.FieldNullable = ctx.Bool(consts.Nullable) + c.FieldSignable = ctx.Bool(consts.Signable) + c.FieldWithIndexTag = ctx.Bool(consts.IndexTag) + c.FieldWithTypeTag = ctx.Bool(consts.TypeTag) return nil } diff --git a/config/server.go b/config/server.go index ba6a63b1..c671a8f5 100644 --- a/config/server.go +++ b/config/server.go @@ -19,6 +19,7 @@ package config import ( "strings" + "github.com/cloudwego/cwgo/pkg/consts" "github.com/urfave/cli/v2" ) @@ -54,20 +55,20 @@ func NewServerArgument() *ServerArgument { } func (s *ServerArgument) ParseCli(ctx *cli.Context) error { - s.Type = strings.ToUpper(ctx.String(ServiceType)) - s.Registry = strings.ToUpper(ctx.String(Registry)) - s.Verbose = ctx.Bool(Verbose) - s.SliceParam.ProtoSearchPath = ctx.StringSlice(ProtoSearchPath) - s.SliceParam.Pass = ctx.StringSlice(Pass) + s.Type = strings.ToUpper(ctx.String(consts.ServiceType)) + s.Registry = strings.ToUpper(ctx.String(consts.Registry)) + s.Verbose = ctx.Bool(consts.Verbose) + s.SliceParam.ProtoSearchPath = ctx.StringSlice(consts.ProtoSearchPath) + s.SliceParam.Pass = ctx.StringSlice(consts.Pass) return nil } func (s *SliceParam) WriteAnswer(name string, value interface{}) error { - if name == Pass { - s.Pass = strings.Split(value.(string), " ") + if name == consts.Pass { + s.Pass = strings.Split(value.(string), consts.BlackSpace) } - if name == ProtoSearchPath { - s.ProtoSearchPath = strings.Split(value.(string), " ") + if name == consts.ProtoSearchPath { + s.ProtoSearchPath = strings.Split(value.(string), consts.BlackSpace) } return nil } diff --git a/meta/version.go b/meta/version.go index c89439d0..1df7441e 100644 --- a/meta/version.go +++ b/meta/version.go @@ -17,5 +17,6 @@ package meta const ( + Name = "cwgo" Version = "v0.0.1" ) diff --git a/pkg/client/check.go b/pkg/client/check.go index 0e96ca35..f1058fe5 100644 --- a/pkg/client/check.go +++ b/pkg/client/check.go @@ -24,19 +24,20 @@ import ( "strings" "github.com/cloudwego/cwgo/config" + "github.com/cloudwego/cwgo/pkg/consts" "github.com/cloudwego/hertz/cmd/hz/util" ) func check(ca *config.ClientArgument) error { - if ca.Type != config.RPC && ca.Type != config.HTTP { + if ca.Type != consts.RPC && ca.Type != consts.HTTP { return errors.New("generate type not supported") } if ca.Registry != "" && - ca.Registry != config.Zk && - ca.Registry != config.Nacos && - ca.Registry != config.Etcd && - ca.Registry != config.Polaris { + ca.Registry != consts.Zk && + ca.Registry != consts.Nacos && + ca.Registry != consts.Etcd && + ca.Registry != consts.Polaris { return errors.New("unsupported registry") } @@ -51,8 +52,8 @@ func check(ca *config.ClientArgument) error { } ca.Cwd = dir if ca.OutDir == "" { - if strings.ToUpper(ca.Type) == config.HTTP { - ca.OutDir = "biz/http" + if strings.ToUpper(ca.Type) == consts.HTTP { + ca.OutDir = consts.DefaultHZClientDir } else { ca.OutDir = dir } @@ -71,7 +72,7 @@ func check(ca *config.ClientArgument) error { } ca.GoPath = gopath - ca.GoSrc = filepath.Join(gopath, "src") + ca.GoSrc = filepath.Join(gopath, consts.Src) // Generate the project under gopath, use the relative path as the package name if strings.HasPrefix(ca.Cwd, ca.GoSrc) { diff --git a/pkg/client/client.go b/pkg/client/client.go index 4695c806..5ad61e63 100644 --- a/pkg/client/client.go +++ b/pkg/client/client.go @@ -22,6 +22,7 @@ import ( "strings" "github.com/cloudwego/cwgo/pkg/common/kx_registry" + "github.com/cloudwego/cwgo/pkg/consts" "github.com/cloudwego/cwgo/pkg/common/utils" kargs "github.com/cloudwego/kitex/tool/cmd/kitex/args" @@ -45,7 +46,7 @@ func Client(c *config.ClientArgument) error { return err } switch c.Type { - case config.RPC: + case consts.RPC: var args kargs.Arguments log.Verbose = c.Verbose err = convertKitexArgs(c, &args) @@ -69,7 +70,7 @@ func Client(c *config.ClientArgument) error { os.Exit(1) } replaceThriftVersion(&args) - case config.HTTP: + case consts.HTTP: args := hzConfig.NewArgument() utils.SetHzVerboseLog(c.Verbose) err = convertHzArgument(c, args) diff --git a/pkg/client/hz.go b/pkg/client/hz.go index 0c552427..79dc6ca8 100644 --- a/pkg/client/hz.go +++ b/pkg/client/hz.go @@ -25,15 +25,11 @@ import ( "github.com/cloudwego/cwgo/config" "github.com/cloudwego/cwgo/pkg/common/utils" + "github.com/cloudwego/cwgo/pkg/consts" "github.com/cloudwego/cwgo/tpl" hzConfig "github.com/cloudwego/hertz/cmd/hz/config" ) -const ( - layoutFile = "layout.yaml" - packageLayoutFile = "package.yaml" -) - func convertHzArgument(ca *config.ClientArgument, hzArgument *hzConfig.Argument) (err error) { // Common commands abPath, err := filepath.Abs(ca.IdlPath) @@ -41,8 +37,8 @@ func convertHzArgument(ca *config.ClientArgument, hzArgument *hzConfig.Argument) return fmt.Errorf("idl path %s is not absolute", ca.IdlPath) } - if strings.HasSuffix(ca.Template, ".git") { - err = utils.GitClone(ca.Template, path.Join(tpl.HertzDir, "client")) + if strings.HasSuffix(ca.Template, consts.SuffixGit) { + err = utils.GitClone(ca.Template, path.Join(tpl.HertzDir, consts.Client)) if err != nil { return err } @@ -50,16 +46,16 @@ func convertHzArgument(ca *config.ClientArgument, hzArgument *hzConfig.Argument) if err != nil { return err } - gitPath = path.Join(tpl.HertzDir, "client", gitPath) - hzArgument.CustomizeLayout = path.Join(gitPath, layoutFile) - hzArgument.CustomizePackage = path.Join(gitPath, packageLayoutFile) + gitPath = path.Join(tpl.HertzDir, consts.Client, gitPath) + hzArgument.CustomizeLayout = path.Join(gitPath, consts.LayoutFile) + hzArgument.CustomizePackage = path.Join(gitPath, consts.PackageLayoutFile) } else { if len(ca.Template) != 0 { - hzArgument.CustomizeLayout = path.Join(ca.Template, layoutFile) - hzArgument.CustomizePackage = path.Join(ca.Template, packageLayoutFile) + hzArgument.CustomizeLayout = path.Join(ca.Template, consts.LayoutFile) + hzArgument.CustomizePackage = path.Join(ca.Template, consts.PackageLayoutFile) } else { - hzArgument.CustomizeLayout = path.Join(tpl.HertzDir, "client", config.Standard, layoutFile) - hzArgument.CustomizePackage = path.Join(tpl.HertzDir, "client", config.Standard, packageLayoutFile) + hzArgument.CustomizeLayout = path.Join(tpl.HertzDir, consts.Client, consts.Standard, consts.LayoutFile) + hzArgument.CustomizePackage = path.Join(tpl.HertzDir, consts.Client, consts.Standard, consts.PackageLayoutFile) } } @@ -82,7 +78,7 @@ func convertHzArgument(ca *config.ClientArgument, hzArgument *hzConfig.Argument) // specific commands from -pass param f := flag.NewFlagSet("", flag.ContinueOnError) f.StringVar(&hzArgument.HandlerDir, "handler_dir", "", "") - f.StringVar(&hzArgument.ModelDir, "model_dir", "hertz_gen", "") + f.StringVar(&hzArgument.ModelDir, "model_dir", consts.DefaultHZModelDir, "") f.StringVar(&hzArgument.ClientDir, "client_dir", ca.OutDir, "") f.StringVar(&hzArgument.Use, "use", "", "") f.StringVar(&hzArgument.BaseDomain, "base_domain", "", "") diff --git a/pkg/client/kitex.go b/pkg/client/kitex.go index aab49a9f..b98bee92 100644 --- a/pkg/client/kitex.go +++ b/pkg/client/kitex.go @@ -95,8 +95,8 @@ Flags: kitexArgument.GenerateMain = false // Non-standard template - if strings.HasSuffix(sa.Template, ".git") { - err = utils.GitClone(sa.Template, path.Join(tpl.KitexDir, "client")) + if strings.HasSuffix(sa.Template, consts.SuffixGit) { + err = utils.GitClone(sa.Template, path.Join(tpl.KitexDir, consts.Client)) if err != nil { return err } @@ -104,13 +104,13 @@ Flags: if err != nil { return err } - gitPath = path.Join(tpl.KitexDir, "client", gitPath) + gitPath = path.Join(tpl.KitexDir, consts.Client, gitPath) kitexArgument.TemplateDir = gitPath } else { if len(sa.Template) != 0 { kitexArgument.TemplateDir = sa.Template } else { - kitexArgument.TemplateDir = path.Join(tpl.KitexDir, "client", config.Standard) + kitexArgument.TemplateDir = path.Join(tpl.KitexDir, consts.Client, consts.Standard) } } diff --git a/pkg/common/kx_registry/registry.go b/pkg/common/kx_registry/registry.go index b473e262..c1d64a94 100644 --- a/pkg/common/kx_registry/registry.go +++ b/pkg/common/kx_registry/registry.go @@ -20,6 +20,7 @@ import ( "path" "github.com/cloudwego/cwgo/config" + "github.com/cloudwego/cwgo/pkg/consts" "github.com/cloudwego/cwgo/tpl" "github.com/cloudwego/kitex/tool/internal_pkg/generator" ) @@ -36,7 +37,7 @@ func HandleRegistry(ca *config.CommonParam, dir string) { importPath := []string{ca.GoMod + "/conf", "github.com/cloudwego/kitex/pkg/klog"} switch ca.Registry { - case config.Etcd: + case consts.Etcd: te.Dependencies["github.com/kitex-contrib/registry-etcd"] = "etcd" te.ExtendServer = &generator.APIExtension{ ImportPaths: append(importPath, "github.com/kitex-contrib/registry-etcd", "github.com/cloudwego/kitex/pkg/rpcinfo"), @@ -46,7 +47,7 @@ func HandleRegistry(ca *config.CommonParam, dir string) { ImportPaths: append(importPath, "github.com/kitex-contrib/registry-etcd"), ExtendOption: etcdClient, } - case config.Zk: + case consts.Zk: te.Dependencies["github.com/kitex-contrib/registry-zookeeper/registry"] = "zkregistry" te.Dependencies["github.com/kitex-contrib/registry-zookeeper/resolver"] = "zkresolver" te.Dependencies["time"] = "time" @@ -58,7 +59,7 @@ func HandleRegistry(ca *config.CommonParam, dir string) { ImportPaths: append(importPath, "github.com/kitex-contrib/registry-zookeeper/resolver", "time"), ExtendOption: zkClient, } - case config.Polaris: + case consts.Polaris: te.Dependencies["github.com/kitex-contrib/registry-polaris"] = "polaris" te.Dependencies["github.com/cloudwego/kitex/pkg/registry"] = "registry" te.ExtendServer = &generator.APIExtension{ @@ -69,7 +70,7 @@ func HandleRegistry(ca *config.CommonParam, dir string) { ImportPaths: []string{"github.com/cloudwego/kitex/pkg/registry", "github.com/kitex-contrib/registry-polaris", "github.com/cloudwego/kitex/pkg/klog"}, ExtendOption: fmt.Sprintf(polarisClient, ca.Service), } - case config.Nacos: + case consts.Nacos: te.Dependencies["github.com/kitex-contrib/registry-nacos/registry"] = "registry" te.Dependencies["github.com/kitex-contrib/registry-nacos/resolver"] = "resolver" te.ExtendServer = &generator.APIExtension{ @@ -85,12 +86,12 @@ func HandleRegistry(ca *config.CommonParam, dir string) { return } - path := path.Join(dir, tpl.KitexExtension) + path := path.Join(dir, consts.KitexExtensionYaml) te.ToYAMLFile(path) } func RemoveExtension() { - path := tpl.KitexDir + tpl.KitexExtension + path := tpl.KitexDir + consts.KitexExtensionYaml os.RemoveAll(path) } diff --git a/pkg/consts/const.go b/pkg/consts/const.go index e0f32e39..6fff1c1c 100644 --- a/pkg/consts/const.go +++ b/pkg/consts/const.go @@ -18,6 +18,22 @@ package consts import "runtime" +const ( + Kitex = "kitex" + Hertz = "hertz" +) + +const ( + RPC = "RPC" + HTTP = "HTTP" +) + +const ( + Server = "server" + Client = "client" + DB = "db" +) + const Protobuf = "protobuf" // SysType is the running program's operating system type @@ -26,6 +42,81 @@ const SysType = runtime.GOOS const WindowsOS = "windows" const ( - Slash = "/" - BackSlash = "\\" + Slash = "/" + BackSlash = "\\" + BlackSpace = " " + Comma = ";" +) + +// Package Name +const ( + Src = "src" + DefaultHZModelDir = "hertz_gen" + DefaultHZClientDir = "biz/http" + DefaultKitexModelDir = "kitex_gen" + DefaultDbOutDir = "biz/dal/query" + Standard = "standard" +) + +// File Name +const ( + KitexExtensionYaml = "extensions.yaml" + LayoutFile = "layout.yaml" + PackageLayoutFile = "package.yaml" + SuffixGit = ".git" + DefaultDbOutFile = "gen.go" + Main = "main.go" +) + +// Registration Center +const ( + Zk = "ZK" + Nacos = "NACOS" + Etcd = "ETCD" + Polaris = "POLARIS" +) + +type DataBaseType string + +// DataBase Name +const ( + MySQL DataBaseType = "mysql" + SQLServer DataBaseType = "sqlserver" + Sqlite DataBaseType = "sqlite" + Postgres DataBaseType = "postgres" +) + +type ToolType string + +// Tool Name +const ( + Hz ToolType = "hz" + KitexTool ToolType = "kitex" +) + +const ( + OutDir = "out_dir" + Verbose = "verbose" + Template = "template" + + Service = "service" + ServiceType = "type" + Module = "module" + IDLPath = "idl" + Registry = "registry" + Pass = "pass" + ProtoSearchPath = "proto_search_path" + + DSN = "dsn" + DBType = "db_type" + Tables = "tables" + OnlyModel = "only_model" + OutFile = "out_file" + UnitTest = "unittest" + ModelPkgName = "model_pkg" + Nullable = "nullable" + Signable = "signable" + IndexTag = "index_tag" + TypeTag = "type_tag" + HexTag = "hex" ) diff --git a/pkg/fallback/fallback.go b/pkg/fallback/fallback.go index ab8b3de4..6c7a9cb6 100644 --- a/pkg/fallback/fallback.go +++ b/pkg/fallback/fallback.go @@ -22,6 +22,7 @@ import ( "strings" "github.com/cloudwego/cwgo/config" + "github.com/cloudwego/cwgo/pkg/consts" "github.com/cloudwego/hertz/cmd/hz/app" "github.com/cloudwego/hertz/cmd/hz/util/logs" "github.com/cloudwego/kitex" @@ -31,7 +32,7 @@ import ( func Fallback(c *config.FallbackArgument) error { switch c.ToolType { - case config.Kitex: + case consts.KitexTool: os.Args = c.Args var args kargs.Arguments args.ParseArgs(kitex.Version) @@ -48,7 +49,7 @@ func Fallback(c *config.FallbackArgument) error { } os.Exit(1) } - case config.Hz: + case consts.Hz: os.Args = c.Args defer func() { logs.Flush() diff --git a/pkg/model/model.go b/pkg/model/model.go index 2ab757b8..f50d2a17 100644 --- a/pkg/model/model.go +++ b/pkg/model/model.go @@ -20,13 +20,14 @@ import ( "fmt" "github.com/cloudwego/cwgo/config" + "github.com/cloudwego/cwgo/pkg/consts" "gorm.io/gen" "gorm.io/gorm" ) func Model(c *config.ModelArgument) error { - dialector := config.OpenTypeFuncMap[config.DataBaseType(c.Type)] + dialector := config.OpenTypeFuncMap[consts.DataBaseType(c.Type)] db, err := gorm.Open(dialector(c.DSN)) if err != nil { return err diff --git a/pkg/server/check.go b/pkg/server/check.go index 043929ba..6b42cd61 100644 --- a/pkg/server/check.go +++ b/pkg/server/check.go @@ -30,15 +30,15 @@ import ( ) func check(sa *config.ServerArgument) error { - if sa.Type != config.RPC && sa.Type != config.HTTP { + if sa.Type != consts.RPC && sa.Type != consts.HTTP { return errors.New("generate type not supported") } if sa.Registry != "" && - sa.Registry != config.Zk && - sa.Registry != config.Nacos && - sa.Registry != config.Etcd && - sa.Registry != config.Polaris { + sa.Registry != consts.Zk && + sa.Registry != consts.Nacos && + sa.Registry != consts.Etcd && + sa.Registry != consts.Polaris { return errors.New("unsupported registry") } @@ -69,7 +69,7 @@ func check(sa *config.ServerArgument) error { } sa.GoPath = gopath - sa.GoSrc = filepath.Join(gopath, "src") + sa.GoSrc = filepath.Join(gopath, consts.Src) // Generate the project under gopath, use the relative path as the package name if strings.HasPrefix(sa.Cwd, sa.GoSrc) { diff --git a/pkg/server/hz.go b/pkg/server/hz.go index 4b45265a..39a6ea95 100644 --- a/pkg/server/hz.go +++ b/pkg/server/hz.go @@ -25,15 +25,11 @@ import ( "github.com/cloudwego/cwgo/config" "github.com/cloudwego/cwgo/pkg/common/utils" + "github.com/cloudwego/cwgo/pkg/consts" "github.com/cloudwego/cwgo/tpl" hzConfig "github.com/cloudwego/hertz/cmd/hz/config" ) -const ( - layoutFile = "layout.yaml" - packageLayoutFile = "package.yaml" -) - func convertHzArgument(sa *config.ServerArgument, hzArgument *hzConfig.Argument) (err error) { // Common commands abPath, err := filepath.Abs(sa.IdlPath) @@ -41,8 +37,8 @@ func convertHzArgument(sa *config.ServerArgument, hzArgument *hzConfig.Argument) return fmt.Errorf("idl path %s is not absolute", sa.IdlPath) } - if strings.HasSuffix(sa.Template, ".git") { - err = utils.GitClone(sa.Template, path.Join(tpl.HertzDir, "server")) + if strings.HasSuffix(sa.Template, consts.SuffixGit) { + err = utils.GitClone(sa.Template, path.Join(tpl.HertzDir, consts.Server)) if err != nil { return err } @@ -50,16 +46,16 @@ func convertHzArgument(sa *config.ServerArgument, hzArgument *hzConfig.Argument) if err != nil { return err } - gitPath = path.Join(tpl.HertzDir, "server", gitPath) - hzArgument.CustomizeLayout = path.Join(gitPath, layoutFile) - hzArgument.CustomizePackage = path.Join(gitPath, packageLayoutFile) + gitPath = path.Join(tpl.HertzDir, consts.Server, gitPath) + hzArgument.CustomizeLayout = path.Join(gitPath, consts.LayoutFile) + hzArgument.CustomizePackage = path.Join(gitPath, consts.PackageLayoutFile) } else { if len(sa.Template) != 0 { - hzArgument.CustomizeLayout = path.Join(sa.Template, layoutFile) - hzArgument.CustomizePackage = path.Join(sa.Template, packageLayoutFile) + hzArgument.CustomizeLayout = path.Join(sa.Template, consts.LayoutFile) + hzArgument.CustomizePackage = path.Join(sa.Template, consts.PackageLayoutFile) } else { - hzArgument.CustomizeLayout = path.Join(tpl.HertzDir, "server", config.Standard, layoutFile) - hzArgument.CustomizePackage = path.Join(tpl.HertzDir, "server", config.Standard, packageLayoutFile) + hzArgument.CustomizeLayout = path.Join(tpl.HertzDir, consts.Server, consts.Standard, consts.LayoutFile) + hzArgument.CustomizePackage = path.Join(tpl.HertzDir, consts.Server, consts.Standard, consts.PackageLayoutFile) } } @@ -82,7 +78,7 @@ func convertHzArgument(sa *config.ServerArgument, hzArgument *hzConfig.Argument) // specific commands from -pass param f := flag.NewFlagSet("", flag.ContinueOnError) handlerDir := f.String("handler_dir", "", "") - modelDir := f.String("model_dir", "hertz_gen", "") + modelDir := f.String("model_dir", consts.DefaultHZModelDir, "") routerDir := f.String("router_dir", "", "") use := f.String("use", "", "") var excludeFile, thriftgo, protoc, thriftPlugins, protocPlugins utils.FlagStringSlice diff --git a/pkg/server/kitex.go b/pkg/server/kitex.go index fd7245a1..13b19659 100644 --- a/pkg/server/kitex.go +++ b/pkg/server/kitex.go @@ -101,8 +101,8 @@ Flags: } // Non-standard template - if strings.HasSuffix(sa.Template, ".git") { - err = utils.GitClone(sa.Template, path.Join(tpl.KitexDir, "server")) + if strings.HasSuffix(sa.Template, consts.SuffixGit) { + err = utils.GitClone(sa.Template, path.Join(tpl.KitexDir, consts.Server)) if err != nil { return err } @@ -110,13 +110,13 @@ Flags: if err != nil { return err } - gitPath = path.Join(tpl.KitexDir, "server", gitPath) + gitPath = path.Join(tpl.KitexDir, consts.Server, gitPath) kitexArgument.TemplateDir = gitPath } else { if len(sa.Template) != 0 { kitexArgument.TemplateDir = sa.Template } else { - kitexArgument.TemplateDir = path.Join(tpl.KitexDir, "server", config.Standard) + kitexArgument.TemplateDir = path.Join(tpl.KitexDir, consts.Server, consts.Standard) } } @@ -241,8 +241,8 @@ func hzArgsForHex(c *config.ServerArgument) (*hzConfig.Argument, error) { hzArgs.CmdType = meta.CmdUpdate // update command is enough for hex // these options are aligned with the kitex hzArgs.ThriftOptions = append(hzArgs.ThriftOptions, "naming_style=golint", "ignore_initialisms", "gen_setter", "gen_deep_equal", "compatible_names", "frugal_tag") - hzArgs.ModelDir = "kitex_gen" - if hzArgs.CustomizePackage == path.Join(tpl.HertzDir, "server", config.Standard, packageLayoutFile) { + hzArgs.ModelDir = consts.DefaultKitexModelDir + if hzArgs.CustomizePackage == path.Join(tpl.HertzDir, consts.Server, consts.Standard, consts.PackageLayoutFile) { hzArgs.CustomizePackage = "" // disable the default hertz template for hex } return hzArgs, nil @@ -358,7 +358,7 @@ func init() { } func addHexOptions() error { - filePath := "main.go" + filePath := consts.Main content, err := os.ReadFile(filePath) if err != nil { return err @@ -378,7 +378,7 @@ func addHexOptions() error { if !found { return nil } - outputFile, err := os.Create("main.go") + outputFile, err := os.Create(consts.Main) if err != nil { return err } diff --git a/pkg/server/server.go b/pkg/server/server.go index b84b5e53..d8d8d0cf 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -26,6 +26,7 @@ import ( "github.com/cloudwego/cwgo/config" "github.com/cloudwego/cwgo/pkg/common/kx_registry" "github.com/cloudwego/cwgo/pkg/common/utils" + "github.com/cloudwego/cwgo/pkg/consts" "github.com/cloudwego/hertz/cmd/hz/app" hzConfig "github.com/cloudwego/hertz/cmd/hz/config" "github.com/cloudwego/hertz/cmd/hz/meta" @@ -44,7 +45,7 @@ func Server(c *config.ServerArgument) error { } switch c.Type { - case config.RPC: + case consts.RPC: var args kargs.Arguments log.Verbose = c.Verbose err = convertKitexArgs(c, &args) @@ -85,7 +86,7 @@ func Server(c *config.ServerArgument) error { } } replaceThriftVersion(&args) - case config.HTTP: + case consts.HTTP: args := hzConfig.NewArgument() utils.SetHzVerboseLog(c.Verbose) err = convertHzArgument(c, args) diff --git a/tpl/init.go b/tpl/init.go index f6eb0a18..631b2b40 100644 --- a/tpl/init.go +++ b/tpl/init.go @@ -20,6 +20,8 @@ import ( "embed" "os" "path" + + "github.com/cloudwego/cwgo/pkg/consts" ) //go:embed kitex @@ -29,9 +31,8 @@ var kitexTpl embed.FS var hertzTpl embed.FS var ( - KitexDir = path.Join(os.TempDir(), "kitex") - HertzDir = path.Join(os.TempDir(), "hertz") - KitexExtension = "extensions.yaml" + KitexDir = path.Join(os.TempDir(), consts.Kitex) + HertzDir = path.Join(os.TempDir(), consts.Hertz) ) func Init() { @@ -39,8 +40,8 @@ func Init() { os.RemoveAll(HertzDir) os.Mkdir(KitexDir, 0o755) os.Mkdir(HertzDir, 0o755) - initDir(kitexTpl, "kitex", KitexDir) - initDir(hertzTpl, "hertz", HertzDir) + initDir(kitexTpl, consts.Kitex, KitexDir) + initDir(hertzTpl, consts.Hertz, HertzDir) } func initDir(fs embed.FS, srcDir, dstDir string) {