-
Notifications
You must be signed in to change notification settings - Fork 98
/
handler-pb.go
287 lines (257 loc) · 10.2 KB
/
handler-pb.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package generate
import (
"errors"
"fmt"
"math/rand"
"strings"
"github.com/spf13/cobra"
"github.com/zhufuyi/sponge/pkg/gofile"
"github.com/zhufuyi/sponge/pkg/replacer"
"github.com/zhufuyi/sponge/pkg/sql2code"
"github.com/zhufuyi/sponge/pkg/sql2code/parser"
)
// HandlerPbCommand generate handler and protobuf code
func HandlerPbCommand() *cobra.Command {
var (
moduleName string // module name for go.mod
serverName string // server name
outPath string // output directory
dbTables string // table names
sqlArgs = sql2code.Args{
Package: "model",
JSONTag: true,
GormType: true,
IsWebProto: true,
}
suitedMonoRepo bool // whether the generated code is suitable for mono-repo
)
cmd := &cobra.Command{
Use: "handler-pb",
Short: "Generate handler and protobuf CRUD code based on sql",
Long: `generate handler and protobuf CRUD code based on sql.
Examples:
# generate handler and protobuf code.
sponge web handler-pb --module-name=yourModuleName --server-name=yourServerName --db-driver=mysql --db-dsn=root:123456@(192.168.3.37:3306)/test --db-table=user
# generate handler and protobuf code with multiple table names.
sponge web handler-pb --module-name=yourModuleName --server-name=yourServerName --db-driver=mysql --db-dsn=root:123456@(192.168.3.37:3306)/test --db-table=t1,t2
# generate handler and protobuf code and specify the server directory, Note: code generation will be canceled when the latest generated file already exists.
sponge web handler-pb --db-driver=mysql --db-dsn=root:123456@(192.168.3.37:3306)/test --db-table=user --out=./yourServerDir
`,
SilenceErrors: true,
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
mdName, srvName, smr := getNamesFromOutDir(outPath)
if mdName != "" {
moduleName = mdName
suitedMonoRepo = smr
} else if moduleName == "" {
return errors.New(`required flag(s) "module-name" not set, use "sponge web handler-pb -h" for help`)
}
if srvName != "" {
serverName = srvName
} else if serverName == "" {
return errors.New(`required flag(s) "server-name" not set, use "sponge web handler-pb -h" for help`)
}
serverName = convertServerName(serverName)
if suitedMonoRepo {
outPath = changeOutPath(outPath, serverName)
}
if sqlArgs.DBDriver == DBDriverMongodb {
sqlArgs.IsEmbed = false
}
tableNames := strings.Split(dbTables, ",")
for _, tableName := range tableNames {
if tableName == "" {
continue
}
sqlArgs.DBTable = tableName
codes, err := sql2code.Generate(&sqlArgs)
if err != nil {
return err
}
g := &handlerPbGenerator{
moduleName: moduleName,
serverName: serverName,
dbDriver: sqlArgs.DBDriver,
isEmbed: sqlArgs.IsEmbed,
codes: codes,
outPath: outPath,
suitedMonoRepo: suitedMonoRepo,
}
outPath, err = g.generateCode()
if err != nil {
return err
}
}
fmt.Printf(`
using help:
1. move the folders "api" and "internal" to your project code folder.
2. open a terminal and execute the command: make proto
3. compile and run service: make run
4. visit http://localhost:8080/apis/swagger/index.html in your browser, and test the http CRUD api.
`)
fmt.Printf("generate \"handler-pb\" code successfully, out = %s\n", outPath)
return nil
},
}
cmd.Flags().StringVarP(&moduleName, "module-name", "m", "", "module-name is the name of the module in the go.mod file")
//_ = cmd.MarkFlagRequired("module-name")
cmd.Flags().StringVarP(&serverName, "server-name", "s", "", "server name")
//_ = cmd.MarkFlagRequired("server-name")
cmd.Flags().StringVarP(&sqlArgs.DBDriver, "db-driver", "k", "mysql", "database driver, support mysql, mongodb, postgresql, tidb, sqlite")
cmd.Flags().StringVarP(&sqlArgs.DBDsn, "db-dsn", "d", "", "database content address, e.g. user:password@(host:port)/database. Note: if db-driver=sqlite, db-dsn must be a local sqlite db file, e.g. --db-dsn=/tmp/sponge_sqlite.db") //nolint
_ = cmd.MarkFlagRequired("db-dsn")
cmd.Flags().StringVarP(&dbTables, "db-table", "t", "", "table name, multiple names separated by commas")
_ = cmd.MarkFlagRequired("db-table")
cmd.Flags().BoolVarP(&sqlArgs.IsEmbed, "embed", "e", false, "whether to embed gorm.model struct")
cmd.Flags().BoolVarP(&suitedMonoRepo, "suited-mono-repo", "l", false, "whether the generated code is suitable for mono-repo")
cmd.Flags().IntVarP(&sqlArgs.JSONNamedType, "json-name-type", "j", 1, "json tags name type, 0:snake case, 1:camel case")
cmd.Flags().StringVarP(&outPath, "out", "o", "", "output directory, default is ./handler-pb_<time>,"+
" if you specify the directory where the web or microservice generated by sponge, the module-name and server-name flag can be ignored")
return cmd
}
type handlerPbGenerator struct {
moduleName string
serverName string
dbDriver string
isEmbed bool
codes map[string]string
outPath string
suitedMonoRepo bool
}
func (g *handlerPbGenerator) generateCode() (string, error) {
subTplName := "handler-pb"
r := Replacers[TplNameSponge]
if r == nil {
return "", errors.New("replacer is nil")
}
if g.serverName == "" {
g.serverName = g.moduleName
}
// setting up template information
subDirs := []string{"internal/model", "internal/cache", "internal/dao", "internal/ecode",
"internal/handler", "api/serverNameExample"} // only the specified subdirectory is processed, if empty or no subdirectory is specified, it means all files
ignoreDirs := []string{} // specify the directory in the subdirectory where processing is ignored
var ignoreFiles []string
switch strings.ToLower(g.dbDriver) {
case DBDriverMysql, DBDriverPostgresql, DBDriverTidb, DBDriverSqlite:
ignoreFiles = []string{ // specify the files in the subdirectory to be ignored for processing
"userExample.pb.go", "userExample.pb.validate.go", "userExample_grpc.pb.go", "userExample_router.pb.go", // api/serverNameExample
"systemCode_http.go", "systemCode_rpc.go", "userExample_rpc.go", // internal/ecode
"init.go", "init_test.go", "init.go.mgo", // internal/model
"doc.go", "cacheNameExample.go", "cacheNameExample_test.go", "cache/userExample.go.mgo", // internal/cache
"dao/userExample.go.mgo", // internal/dao
"handler/userExample.go", "handler/userExample.go.mgo", "handler/userExample_test.go", "handler/userExample_logic_test.go", "handler/userExample_logic.go.mgo", // internal/handler
}
case DBDriverMongodb:
ignoreFiles = []string{ // specify the files in the subdirectory to be ignored for processing
"userExample.pb.go", "userExample.pb.validate.go", "userExample_grpc.pb.go", "userExample_router.pb.go", // api/serverNameExample
"systemCode_http.go", "systemCode_rpc.go", "userExample_rpc.go", // internal/ecode
"init.go", "init_test.go", "init.go.mgo", // internal/model
"doc.go", "cacheNameExample.go", "cacheNameExample_test.go", "cache/userExample.go", "cache/userExample_test.go", // internal/cache
"dao/userExample_test.go", "dao/userExample.go", // internal/dao
"handler/userExample.go", "handler/userExample.go.mgo", "handler/userExample_test.go", "handler/userExample_logic_test.go", "handler/userExample_logic.go", // internal/handler
}
default:
return "", errors.New("unsupported db driver: " + g.dbDriver)
}
ignoreFiles = append(ignoreFiles, "handler/userExample.go.service")
r.SetSubDirsAndFiles(subDirs)
r.SetIgnoreSubDirs(ignoreDirs...)
r.SetIgnoreSubFiles(ignoreFiles...)
_ = r.SetOutputDir(g.outPath, subTplName)
fields := g.addFields(r)
r.SetReplacementFields(fields)
if err := r.SaveFiles(); err != nil {
return "", err
}
return r.GetOutputDir(), nil
}
func (g *handlerPbGenerator) addFields(r replacer.Replacer) []replacer.Field {
var fields []replacer.Field
fields = append(fields, deleteFieldsMark(r, modelFile, startMark, endMark)...)
fields = append(fields, deleteFieldsMark(r, daoFile, startMark, endMark)...)
fields = append(fields, deleteFieldsMark(r, daoMgoFile, startMark, endMark)...)
fields = append(fields, deleteFieldsMark(r, daoTestFile, startMark, endMark)...)
fields = append(fields, deleteFieldsMark(r, handlerLogicFile, startMark, endMark)...)
fields = append(fields, deleteFieldsMark(r, protoFile, startMark, endMark)...)
fields = append(fields, []replacer.Field{
{ // replace the contents of the model/userExample.go file
Old: modelFileMark,
New: g.codes[parser.CodeTypeModel],
},
{ // replace the contents of the dao/userExample.go file
Old: daoFileMark,
New: g.codes[parser.CodeTypeDAO],
},
{ // replace the contents of the handler/userExample_logic.go file
Old: embedTimeMark,
New: getEmbedTimeCode(g.isEmbed),
},
{ // replace the contents of the v1/userExample.proto file
Old: protoFileMark,
New: g.codes[parser.CodeTypeProto],
},
{
Old: selfPackageName + "/" + r.GetSourcePath(),
New: g.moduleName,
},
{
Old: "github.com/zhufuyi/sponge",
New: g.moduleName,
},
// replace directory name
{
Old: strings.Join([]string{"api", "serverNameExample", "v1"}, gofile.GetPathDelimiter()),
New: strings.Join([]string{"api", g.serverName, "v1"}, gofile.GetPathDelimiter()),
},
{
Old: "api/serverNameExample/v1",
New: fmt.Sprintf("api/%s/v1", g.serverName),
},
// Note: protobuf package no "-" signs allowed
{
Old: "api.serverNameExample.v1",
New: fmt.Sprintf("api.%s.v1", g.serverName),
},
{
Old: "userExampleNO = 1",
New: fmt.Sprintf("userExampleNO = %d", rand.Intn(99)+1),
},
{
Old: g.moduleName + "/pkg",
New: "github.com/zhufuyi/sponge/pkg",
},
{
Old: "userExample_logic.go.mgo",
New: "userExample.go",
},
{
Old: "userExample_logic.go",
New: "userExample.go",
},
{
Old: "userExample.go.mgo",
New: "userExample.go",
},
{
Old: "UserExamplePb",
New: "UserExample",
IsCaseSensitive: true,
},
{
Old: "serverNameExample",
New: g.serverName,
},
{
Old: "UserExample",
New: g.codes[parser.TableName],
IsCaseSensitive: true,
},
}...)
if g.suitedMonoRepo {
fs := SubServerCodeFields(r.GetOutputDir(), g.moduleName, g.serverName)
fields = append(fields, fs...)
}
return fields
}