-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.go
377 lines (330 loc) · 11.7 KB
/
main.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
package main
import (
"bufio"
"flag"
"fmt"
"log"
"os"
"path"
"path/filepath"
"strings"
"github.com/go-openapi/loads"
"github.com/go-openapi/loads/fmts"
"github.com/go-openapi/spec"
"github.com/go-openapi/swag"
goclient "github.com/Clever/wag/v9/clients/go"
jsclient "github.com/Clever/wag/v9/clients/js"
"github.com/Clever/wag/v9/hardcoded"
"github.com/Clever/wag/v9/models"
"github.com/Clever/wag/v9/server"
"github.com/Clever/wag/v9/server/gendb"
"github.com/Clever/wag/v9/swagger"
"github.com/Clever/wag/v9/validation"
)
// config contains the configuration of command line flags and configuration derived from command line flags
type config struct {
clientLanguage *string
clientOnly *bool
dynamoOnly *bool
withTests *bool
outputPath *string
versionFlag *bool
swaggerFile *string
relativeDynamoPath *string
jsModulePath *string
goPackageName *string
dynamoPath string
goAbsolutePackagePath string
jsClientPath string
generateDynamo bool
generateGoClient bool
generateGoModels bool
generateJSClient bool
generateServer bool
generateTracing bool
}
var version string
func main() {
conf := config{
swaggerFile: flag.String("file", "swagger.yml", "the spec file to use"),
goPackageName: flag.String("go-package", "", "package of the generated go code"),
outputPath: flag.String("output-path", "", "relative output path of the generated go code"),
jsModulePath: flag.String("js-path", "", "path to put the js client"),
versionFlag: flag.Bool("version", false, "print the wag version and exit"),
clientOnly: flag.Bool("client-only", false, "only generate client code"),
clientLanguage: flag.String("client-language", "", "generate client code in specific language [go|js]"),
dynamoOnly: flag.Bool("dynamo-only", false, "only generate dynamo code"),
relativeDynamoPath: flag.String("dynamo-path", "", "path to generate dynamo code relative to go package path"),
withTests: flag.Bool("with-tests", false, "generate tests for the generated db code"),
}
flag.Parse()
if *conf.versionFlag {
fmt.Println(version)
os.Exit(0)
}
if err := conf.parse(); err != nil {
log.Fatalf(err.Error())
}
loads.AddLoader(fmts.YAMLMatcher, fmts.YAMLDoc)
doc, err := loads.Spec(*conf.swaggerFile)
if err != nil {
log.Fatalf("Error loading swagger file: %s", err)
}
swaggerSpec := *doc.Spec()
injectDefaultDefinitions(&swaggerSpec)
if err := validation.Validate(*doc, conf.generateJSClient); err != nil {
log.Fatalf("Swagger file not valid: %s", err)
}
err = swagger.ValidateResponses(swaggerSpec)
if err != nil {
log.Fatalf("Failed processing the swagger spec: %s", err)
}
if conf.generateGoModels {
if err := generateGoModels(*conf.goPackageName, conf.goAbsolutePackagePath, *conf.outputPath, swaggerSpec); err != nil {
log.Fatal(err.Error())
}
}
if conf.generateServer {
if err := generateServer(*conf.goPackageName, conf.goAbsolutePackagePath, *conf.outputPath, swaggerSpec); err != nil {
log.Fatal(err.Error())
}
}
if conf.generateTracing {
if err := generateTracing(conf.goAbsolutePackagePath, *conf.outputPath); err != nil {
log.Fatal(err.Error())
}
}
if conf.generateDynamo {
if err := generateDynamo(conf.dynamoPath, *conf.goPackageName, conf.goAbsolutePackagePath, *conf.relativeDynamoPath, *conf.outputPath, *conf.withTests, swaggerSpec); err != nil {
log.Fatal(err.Error())
}
}
if conf.generateGoClient {
if err := generateGoClient(*conf.goPackageName, conf.goAbsolutePackagePath, *conf.outputPath, swaggerSpec); err != nil {
log.Fatal(err.Error())
}
}
if conf.generateJSClient {
if err := generateJSClient(*conf.jsModulePath, swaggerSpec); err != nil {
log.Fatal(err.Error())
}
}
}
func generateGoModels(packageName, basePath, outputPath string, swaggerSpec spec.Swagger) error {
if err := prepareDir(filepath.Join(basePath, "models")); err != nil {
return err
}
if err := models.Generate(packageName, basePath, outputPath, swaggerSpec); err != nil {
return fmt.Errorf("Error generating models: %s", err)
}
return nil
}
func generateServer(goPackageName, basePath, outputPath string, swaggerSpec spec.Swagger) error {
if err := prepareDir(filepath.Join(basePath, "server")); err != nil {
return err
}
if err := server.Generate(goPackageName, basePath, outputPath, swaggerSpec); err != nil {
return fmt.Errorf("Failed to generate server: %s", err)
}
middlewareGenerator := swagger.Generator{BasePath: basePath}
middlewareGenerator.Write(hardcoded.MustAsset("../_hardcoded/middleware.go"))
if err := middlewareGenerator.WriteFile("server/middleware.go"); err != nil {
return fmt.Errorf("Failed to copy middleware.go: %s", err)
}
return nil
}
func generateTracing(basePath, outputPath string) error {
if err := prepareDir(filepath.Join(basePath, "servertracing")); err != nil {
return err
}
tracingGenerator := swagger.Generator{BasePath: basePath}
tracingGenerator.Write(hardcoded.MustAsset("../_hardcoded/tracing.go"))
if err := tracingGenerator.WriteFile("servertracing/tracing.go"); err != nil {
log.Fatalf("Failed to copy tracing.go: %s", err)
}
return nil
}
func generateDynamo(dynamoPath, goPackageName, basePath, relativeDynamoPath, OutputPath string, withTests bool, swaggerSpec spec.Swagger) error {
if err := prepareDir(dynamoPath); err != nil {
return err
}
if err := gendb.GenerateDB(goPackageName, basePath, OutputPath, withTests, &swaggerSpec, relativeDynamoPath); err != nil {
return fmt.Errorf("Failed to generate database: %s", err)
}
return nil
}
func generateGoClient(goPackageName, basePath, outputPath string, swaggerSpec spec.Swagger) error {
if err := prepareDir(filepath.Join(basePath, "client")); err != nil {
return err
}
if err := goclient.Generate(goPackageName, basePath, outputPath, swaggerSpec); err != nil {
return fmt.Errorf("Failed generating go client %s", err)
}
doerGenerator := swagger.Generator{BasePath: basePath}
doerGenerator.Write(hardcoded.MustAsset("../_hardcoded/doer.go"))
if err := doerGenerator.WriteFile("client/doer.go"); err != nil {
return fmt.Errorf("Failed to copy doer.go: %s", err)
}
return nil
}
func generateJSClient(jsModulePath string, swaggerSpec spec.Swagger) error {
if err := prepareDir(jsModulePath); err != nil {
return err
}
if err := jsclient.Generate(jsModulePath, swaggerSpec); err != nil {
return fmt.Errorf("Failed generating js client %s", err)
}
return nil
}
func prepareDir(dir string) error {
if err := os.RemoveAll(dir); err != nil {
return fmt.Errorf("Could not remove directory: %s, error :%s", dir, err)
}
if err := os.MkdirAll(dir, 0o700); err != nil {
if !os.IsExist(err.(*os.PathError)) {
return fmt.Errorf("Could not create directory: %s, error: %s", dir, err)
}
}
return nil
}
// parseCmdConfig determines the which code is generated and the location of the generated code
// from the command line arguments
func (c *config) parse() error {
if err := c.setGoPaths(swag.StringValue(c.outputPath), swag.StringValue(c.goPackageName)); err != nil {
return err
}
clientLanguage, jsModulePath := swag.StringValue(c.clientLanguage), swag.StringValue(c.jsModulePath)
if err := c.setGenerateFlags(clientLanguage, jsModulePath); err != nil {
return err
}
c.setGeneratedFilePaths()
return nil
}
func (c *config) setGenerateFlags(clientLanguage, jsModulePath string) error {
if swag.BoolValue(c.clientOnly) && swag.BoolValue(c.dynamoOnly) {
return fmt.Errorf("Cannot use -dynamo-only and -client-only together")
} else if swag.BoolValue(c.clientOnly) {
if err := c.setClientLanguage(clientLanguage, jsModulePath); err != nil {
return err
}
c.generateGoModels = c.generateGoClient
c.generateTracing = c.generateGoClient
} else if swag.BoolValue(c.dynamoOnly) {
c.generateDynamo = true
c.generateGoModels = true
c.generateGoClient = false
} else {
c.generateServer = true
c.generateDynamo = true
c.generateGoModels = true
c.generateTracing = true
if err := c.setClientLanguage(clientLanguage, jsModulePath); err != nil {
return err
}
}
return nil
}
// setGoPaths sets the golang package path and package name. Go repos using modules may have a
// package name differing from its package path.
func (c *config) setGoPaths(outputPath, goPackageName string) error {
// check if the repo uses modules
if modFile, err := os.Open("go.mod"); err != nil {
if _, ok := err.(*os.PathError); !ok {
return fmt.Errorf("Error checking if the repo contains a go.mod file: %s", err.Error())
}
if goPackageName == "" {
return fmt.Errorf("go-package is required")
}
// if the repo does not use modules, the package name is equivalent to the package path
c.goAbsolutePackagePath = filepath.Join(os.Getenv("GOPATH"), "src", goPackageName)
} else {
defer modFile.Close()
if "outputPath" == "" {
return fmt.Errorf("output-path is required")
}
absolutePath, err := filepath.Abs(outputPath)
if err != nil {
return fmt.Errorf("converting output-path to absolute path: %v", err)
}
c.goAbsolutePackagePath = absolutePath
*c.goPackageName = getModulePackageName(modFile, path.Clean(outputPath))
}
return nil
}
// setClientLanguage determines in which langues to generate the server client
func (c *config) setClientLanguage(clientLanguage, jsModulePath string) error {
if clientLanguage != "" {
if clientLanguage != "go" && clientLanguage != "js" {
return fmt.Errorf("client-language must be one of \"go\" or \"js\"")
}
switch clientLanguage {
case "go":
c.generateGoClient = true
c.generateJSClient = false
case "js":
c.generateGoClient = false
c.generateJSClient = true
default:
return fmt.Errorf("client-language must be one of \"go\" or \"js\"")
}
} else {
c.generateGoClient = true
c.generateJSClient = true
}
if c.generateJSClient && jsModulePath == "" {
return fmt.Errorf("js-path is required")
}
return nil
}
// setGeneratedFilePaths determines where to output the generated files.
func (c *config) setGeneratedFilePaths() {
const serverDir = "server"
if c.generateDynamo {
// set path of generated dynamo code if none specified
if swag.StringValue(c.relativeDynamoPath) == "" {
if c.generateServer {
c.relativeDynamoPath = swag.String(path.Join(serverDir, "db"))
} else {
c.relativeDynamoPath = swag.String("db")
}
}
c.dynamoPath = path.Join(c.goAbsolutePackagePath, *c.relativeDynamoPath)
}
}
// getModulePackageName gets the package name of the generated code
// Example: if packagePath = github.com/Clever/wag/v8/gen-go and the module name is github.com/Clever/wag/v8/v2
// the function will return github.com/Clever/wag/v8/v2/gen-go
// Example: if packagePath = github.com/Clever/wag/v8/gen-go and the module name is github.com/Clever/wag/v8
// the function will return github.com/Clever/wag/v8/gen-go
func getModulePackageName(modFile *os.File, outputPath string) string {
// read first line of module file
r := bufio.NewReader(modFile)
b, _, err := r.ReadLine()
if err != nil {
log.Fatalf("Error checking module name: %s", err.Error())
}
// parse module path
moduleName := strings.TrimPrefix(string(b), "module")
moduleName = strings.TrimSpace(moduleName)
return fmt.Sprintf("%v/%v", moduleName, outputPath)
}
// injectDefaultDefinitions injects default definitions
func injectDefaultDefinitions(swaggerSpec *spec.Swagger) {
swaggerSpec.Definitions["UnknownResponse"] = spec.Schema{
SchemaProps: spec.SchemaProps{
Type: spec.StringOrArray{"object"},
Properties: map[string]spec.Schema{
"statusCode": {
SchemaProps: spec.SchemaProps{
Type: spec.StringOrArray{"integer"},
},
},
"body": {
SchemaProps: spec.SchemaProps{
Type: spec.StringOrArray{"string"},
},
},
},
},
}
}