Skip to content

Commit

Permalink
Merge pull request #186 from wubin1989/main
Browse files Browse the repository at this point in the history
some optimization to cli
  • Loading branch information
wubin1989 authored Jan 15, 2024
2 parents c91864c + a6bf1b9 commit 0299d90
Show file tree
Hide file tree
Showing 17 changed files with 126 additions and 49 deletions.
30 changes: 30 additions & 0 deletions app.yml.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
example:
db:
driver: mysql
dsn: root:1234@tcp(127.0.0.1:3306)/tutorial?charset=utf8mb4&parseTime=True&loc=Local
log:
level: info
slow-threshold: 200ms
ignore-record-not-found-error: false
parameterized-queries: false
mysql:
skip-initialize-with-version: false
default-string-size: 0
disable-with-returning: false
disable-datetime-precision: false
dont-support-rename-index: false
dont-support-rename-column: false
dont-support-for-share-clause: false
dont-support-null-as-default-value: false
dont-support-rename-column-unique: false
postgres:
prefer-simple-protocol: false
without-returning: false
pool:
max-idle-conns: 2
max-open-conns: -1
conn-max-lifetime: ""
conn-max-idle-time: ""
biz:
api:
secret: "my_secret"
2 changes: 1 addition & 1 deletion cmd/internal/openapi/v3/codegen/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ import (
v3 "github.com/unionj-cloud/go-doudou/v2/toolkit/openapi/v3"
)
//go:generate go-doudou svc http -c
//go:generate go-doudou svc http
//go:generate go-doudou svc grpc
{{ range $i, $c := .Meta.Comments }}
Expand Down
51 changes: 30 additions & 21 deletions cmd/internal/svc/codegen/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,53 +3,60 @@ package codegen
import (
"github.com/sirupsen/logrus"
"github.com/unionj-cloud/go-doudou/v2/cmd/internal/templates"
"github.com/unionj-cloud/go-doudou/v2/toolkit/astutils"
"github.com/unionj-cloud/go-doudou/v2/version"
"os"
"path/filepath"
"strings"
"text/template"
)

var configTmpl = templates.EditableHeaderTmpl + `package config
import (
"github.com/kelseyhightower/envconfig"
"github.com/unionj-cloud/go-doudou/v2/framework/config"
"github.com/unionj-cloud/go-doudou/v2/toolkit/errorx"
)
type Config struct {
BizConf BizConf
}
var G_Config *Config
type BizConf struct {
ApiSecret string ` + "`" + `split_words:"true"` + "`" + `
type Config struct {
Biz struct {
ApiSecret string ` + "`" + `split_words:"true"` + "`" + `
}
config.Config
}
func LoadFromEnv() *Config {
var bizConf BizConf
err := envconfig.Process("biz", &bizConf)
func init() {
var conf Config
err := envconfig.Process("{{.ServiceName}}", &conf)
if err != nil {
errorx.Panic("Error processing environment variables")
}
return &Config{
BizConf: bizConf,
}
G_Config = &conf
}
func LoadFromEnv() *Config {
return G_Config
}
`

//GenConfig generates config file
func GenConfig(dir string) {
// GenConfig generates config file
func GenConfig(dir string, ic astutils.InterfaceCollector) {
var (
err error
configfile string
f *os.File
tpl *template.Template
configDir string
err error
configfile string
f *os.File
tpl *template.Template
configDir string
serviceName string
)
configDir = filepath.Join(dir, "config")
if err = os.MkdirAll(configDir, os.ModePerm); err != nil {
panic(err)
}

serviceName = strings.ToLower(ic.Interfaces[0].Name)
configfile = filepath.Join(configDir, "config.go")
if _, err = os.Stat(configfile); os.IsNotExist(err) {
if f, err = os.Create(configfile); err != nil {
Expand All @@ -58,9 +65,11 @@ func GenConfig(dir string) {
defer f.Close()
tpl, _ = template.New("config.go.tmpl").Parse(configTmpl)
_ = tpl.Execute(f, struct {
Version string
Version string
ServiceName string
}{
Version: version.Release,
Version: version.Release,
ServiceName: serviceName,
})
} else {
logrus.Warnf("file %s already exists", configfile)
Expand Down
7 changes: 5 additions & 2 deletions cmd/internal/svc/codegen/config_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package codegen

import (
"github.com/unionj-cloud/go-doudou/v2/toolkit/astutils"
"os"
"path/filepath"
"testing"
Expand All @@ -12,9 +13,11 @@ func TestGenConfig(t *testing.T) {
dir := testDir + "config"
InitSvc(dir)
defer os.RemoveAll(dir)
GenConfig(dir)
var ic astutils.InterfaceCollector
GenConfig(dir, ic)
}

func TestGenConfig1(t *testing.T) {
GenConfig(filepath.Join(testDir))
var ic astutils.InterfaceCollector
GenConfig(filepath.Join(testDir), ic)
}
27 changes: 16 additions & 11 deletions cmd/internal/svc/codegen/database/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ type AbstractBaseGenerator struct {
Env string
impl IOrmGenerator
runner executils.Runner
ConfigPackage string
}

func (b *AbstractBaseGenerator) fix() {
Expand Down Expand Up @@ -103,6 +104,14 @@ func (b *AbstractBaseGenerator) Initialize(conf OrmGeneratorConfig) {
}

func (b *AbstractBaseGenerator) GenService() {
b.dto()
b.svcGo()

validate.DataType(b.Dir)
ic := astutils.BuildInterfaceCollector(filepath.Join(b.Dir, "svc.go"), astutils.ExprString)
validate.RestApi(b.Dir, ic)

serviceName := ic.Interfaces[0].Name
envfile := filepath.Join(b.Dir, ".env")
if _, err := os.Stat(envfile); err != nil {
fileutils.CreateIfNotExists(envfile, false)
Expand All @@ -112,24 +121,20 @@ func (b *AbstractBaseGenerator) GenService() {
panic(err)
}
envContent := string(envSource)
if !strings.Contains(envContent, "GDD_DB_DRIVER") {
envContent += fmt.Sprintf(`GDD_DB_DRIVER=%s`, b.Driver)
if !strings.Contains(envContent, strings.ToUpper(serviceName)+"_DB_DRIVER") {
envContent += fmt.Sprintf(`%s_DB_DRIVER=%s`, strings.ToUpper(serviceName), b.Driver)
envContent += constants.LineBreak
}
if !strings.Contains(envContent, "GDD_DB_DSN") {
envContent += fmt.Sprintf(`GDD_DB_DSN=%s`, b.Dsn)
if !strings.Contains(envContent, strings.ToUpper(serviceName)+"_DB_DSN") {
envContent += fmt.Sprintf(`%s_DB_DSN=%s`, strings.ToUpper(serviceName), b.Dsn)
envContent += constants.LineBreak
}
ioutil.WriteFile(envfile, []byte(envContent), os.ModePerm)

b.dto()
b.svcGo()

validate.DataType(b.Dir)
ic := astutils.BuildInterfaceCollector(filepath.Join(b.Dir, "svc.go"), astutils.ExprString)
validate.RestApi(b.Dir, ic)
codegen.GenConfig(b.Dir, ic)

codegen.GenConfig(b.Dir)
cfgPkg := astutils.GetPkgPath(filepath.Join(b.Dir, "config"))
b.g.ConfigPackage = cfgPkg

b.orm()
b.svcImplGo()
Expand Down
2 changes: 1 addition & 1 deletion cmd/internal/svc/codegen/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
)

func genHttp(dir string, ic astutils.InterfaceCollector, caseConvertor func(string) string) {
GenConfig(dir)
GenConfig(dir, ic)
GenHttpMiddleware(dir)
GenHttpHandler(dir, ic, 0)
GenHttpHandlerImpl(dir, ic, GenHttpHandlerImplConfig{
Expand Down
2 changes: 1 addition & 1 deletion cmd/internal/svc/codegen/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import (
"{{.DtoPackage}}"
)
//go:generate go-doudou svc http -c
//go:generate go-doudou svc http
//go:generate go-doudou svc grpc
type {{.SvcName}} interface {
Expand Down
13 changes: 13 additions & 0 deletions cmd/internal/svc/codegen/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,19 @@ var mainTmpl = templates.EditableHeaderTmpl + `package main
import (
"github.com/unionj-cloud/go-doudou/v2/framework/rest"
{{.ServiceAlias}} "{{.ServicePackage}}"
{{- if .QueryPackage}}
"{{.QueryPackage}}"
"github.com/unionj-cloud/go-doudou/v2/framework/database"
{{- end}}
"{{.ConfigPackage}}"
"{{.HttpPackage}}"
)
func main() {
conf := config.LoadFromEnv()
{{- if .QueryPackage}}
query.SetDefault(database.NewDb(conf.Config))
{{- end}}
svc := {{.ServiceAlias}}.New{{.SvcName}}(conf)
handler := httpsrv.New{{.SvcName}}Handler(svc)
srv := rest.NewRestServer()
Expand Down Expand Up @@ -52,6 +59,10 @@ func GenMain(dir string, ic astutils.InterfaceCollector) {
servicePkg := astutils.GetPkgPath(dir)
cfgPkg := astutils.GetPkgPath(filepath.Join(dir, "config"))
httpsrvPkg := astutils.GetPkgPath(filepath.Join(dir, "transport", "httpsrv"))
var queryPkg string
if _, err := Stat(filepath.Join(dir, "query")); err == nil {
queryPkg = astutils.GetPkgPath(filepath.Join(dir, "query"))
}

if f, err = Create(mainfile); err != nil {
panic(err)
Expand All @@ -68,13 +79,15 @@ func GenMain(dir string, ic astutils.InterfaceCollector) {
SvcName string
ServiceAlias string
Version string
QueryPackage string
}{
ServicePackage: servicePkg,
ConfigPackage: cfgPkg,
HttpPackage: httpsrvPkg,
SvcName: svcName,
ServiceAlias: alias,
Version: version.Release,
QueryPackage: queryPkg,
}); err != nil {
panic(err)
}
Expand Down
4 changes: 2 additions & 2 deletions cmd/internal/svc/svc.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ func (receiver *Svc) Http() {
ic := astutils.BuildInterfaceCollector(filepath.Join(dir, "svc.go"), astutils.ExprString)
validate.RestApi(dir, ic)

codegen.GenConfig(dir)
codegen.GenConfig(dir, ic)
codegen.GenHttpMiddleware(dir)

codegen.GenMain(dir, ic)
Expand Down Expand Up @@ -514,7 +514,7 @@ func (receiver *Svc) Grpc() {
validate.DataType(dir)
ic := astutils.BuildInterfaceCollector(filepath.Join(dir, "svc.go"), astutils.ExprString)
validate.GrpcApi(dir, ic, receiver.http2grpc)
codegen.GenConfig(dir)
codegen.GenConfig(dir, ic)
parser.ParseDtoGrpc(dir, receiver.protoGenerator, "dto")
grpcSvc, protoFile := codegen.GenGrpcProto(dir, ic, receiver.protoGenerator)
// protoc --proto_path=. --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative transport/grpc/helloworld.proto
Expand Down
2 changes: 1 addition & 1 deletion cmd/internal/templates/mainmain.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func main() {
}
defer func() {
if r := recover(); r != nil {
zlogger.Info().Msgf("Recovered. Error:\n", r)
zlogger.Info().Msgf("Recovered. Error: %v\n", r)
}
for _, v := range plugin.GetServicePlugins() {
v.Close()
Expand Down
3 changes: 2 additions & 1 deletion cmd/internal/templates/mainmodule.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/unionj-cloud/go-doudou/v2/framework/grpcx"
"github.com/unionj-cloud/go-doudou/v2/framework/plugin"
"github.com/unionj-cloud/go-doudou/v2/framework/rest"
"github.com/unionj-cloud/go-doudou/v2/toolkit/zlogger"
_ "{{.PluginPackage}}"
)
Expand All @@ -17,7 +18,7 @@ func main() {
}
defer func() {
if r := recover(); r != nil {
zlogger.Info().Msgf("Recovered. Error:\n", r)
zlogger.Info().Msgf("Recovered. Error: %v\n", r)
}
for _, v := range plugin.GetServicePlugins() {
v.Close()
Expand Down
2 changes: 2 additions & 0 deletions toolkit/gormgen/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ type Config struct {
fieldJSONTagNS func(columnName string) (tagContent string)

modelOpts []ModelOpt

ConfigPackage string
}

// WithOpts set global model options
Expand Down
8 changes: 7 additions & 1 deletion toolkit/gormgen/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -786,7 +786,13 @@ func (g *Generator) generateModelFile() error {
errChan <- err
return
}
err = t.Execute(&buf, data)
err = t.Execute(&buf, struct {
*generate.QueryStructMeta
ConfigPackage string
}{
QueryStructMeta: data,
ConfigPackage: g.ConfigPackage,
})
if err != nil {
errChan <- err
return
Expand Down
14 changes: 13 additions & 1 deletion toolkit/gormgen/internal/template/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ const Model = NotEditMark + `
package {{.StructInfo.Package}}
import (
"{{.ConfigPackage}}"
"fmt"
"github.com/unionj-cloud/go-doudou/v2/toolkit/stringutils"
"encoding/json"
"time"
Expand All @@ -14,7 +18,15 @@ import (
{{range .ImportPkgPaths}}{{.}} ` + "\n" + `{{end}}
)
{{if .TableName -}}const TableName{{.ModelStructName}} = "{{.TableName}}"{{- end}}
{{if .TableName -}}var TableName{{.ModelStructName}} string{{- end}}
func init() {
if stringutils.IsNotEmpty(config.G_Config.Db.Name) {
TableName{{.ModelStructName}} = fmt.Sprintf("%s.{{.TableName}}", config.G_Config.Db.Name)
} else {
TableName{{.ModelStructName}} = "{{.TableName}}"
}
}
// {{.ModelStructName}} {{.StructComment}}
type {{.ModelStructName}} struct {
Expand Down
2 changes: 1 addition & 1 deletion toolkit/gormgen/internal/template/svc.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
v3 "github.com/unionj-cloud/go-doudou/v2/toolkit/openapi/v3"
)
//go:generate go-doudou svc http -c
//go:generate go-doudou svc http
//go:generate go-doudou svc grpc
type {{.InterfaceName}} interface {
Expand Down
4 changes: 0 additions & 4 deletions toolkit/gormgen/internal/template/svcimpl.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,6 @@ package service
import ()
func init() {
query.SetDefault(database.Db)
}
var _ {{.InterfaceName}} = (*{{.InterfaceName}}Impl)(nil)
type {{.InterfaceName}}Impl struct {
Expand Down
2 changes: 1 addition & 1 deletion version/version.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package version

const Release = "v2.2.8"
const Release = "v2.2.9"

0 comments on commit 0299d90

Please sign in to comment.