-
Notifications
You must be signed in to change notification settings - Fork 13
/
main.go
548 lines (476 loc) · 15.8 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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
package cmd
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"time"
"github.com/solo-io/solo-kit/pkg/code-generator/schemagen"
"github.com/solo-io/solo-kit/pkg/code-generator/writer"
"github.com/solo-io/solo-kit/pkg/code-generator/metrics"
"github.com/golang/protobuf/protoc-gen-go/descriptor"
"github.com/rotisserie/eris"
"github.com/solo-io/anyvendor/anyvendor"
"github.com/solo-io/anyvendor/pkg/manager"
"github.com/solo-io/go-utils/log"
"github.com/solo-io/go-utils/stringutils"
code_generator "github.com/solo-io/solo-kit/pkg/code-generator"
"github.com/solo-io/solo-kit/pkg/code-generator/codegen"
"github.com/solo-io/solo-kit/pkg/code-generator/collector"
"github.com/solo-io/solo-kit/pkg/code-generator/docgen"
"github.com/solo-io/solo-kit/pkg/code-generator/docgen/options"
"github.com/solo-io/solo-kit/pkg/code-generator/model"
"github.com/solo-io/solo-kit/pkg/code-generator/parser"
"github.com/solo-io/solo-kit/pkg/code-generator/sk_anyvendor"
"github.com/solo-io/solo-kit/pkg/utils/modutils"
)
type DocsOptions = options.DocsOptions
const (
SkipMockGen = "SKIP_MOCK_GEN"
)
func Run(relativeRoot string, compileProtos bool, genDocs *DocsOptions, customImports, skipDirs []string) error {
return Generate(GenerateOptions{
RelativeRoot: relativeRoot,
CompileProtos: compileProtos,
GenDocs: genDocs,
CustomImports: customImports,
SkipDirs: skipDirs,
SkipGenMocks: os.Getenv(SkipMockGen) != "",
})
}
type RunFunc func() error
type GenerateOptions struct {
// Root of files to be compiled (will default to "." if not set)
RelativeRoot string
// // Root of package, necessary to find vendor (will default to $(go env GOMOD) if not set)
// ProjectRoot string
// compile protos found in project directories (dirs with solo-kit.json) and their subdirs
CompileProtos bool
// compile protos found in these directories. can also point directly to .proto files
CustomCompileProtos []string
// custom plugins
// each will append a <plugin>_out= directive to protoc command
CustomPlugins []string
GenDocs *DocsOptions
CustomImports []string
SkipDirs []string
// arguments for go_out=
CustomGoOutArgs []string
// skip generated mocks
SkipGenMocks bool
// skip generated tests
SkipGeneratedTests bool
/*
Represents the go package which this package would have been in the GOPATH
This allows it to be able to maintain compatibility with the old solo-kit
default: current github.com/solo-io/<current-folder>
for example: github.com/solo-io/solo-kit
*/
PackageName string
// config for anyvendor
ExternalImports *sk_anyvendor.Imports
ValidationSchemaOptions *schemagen.ValidationSchemaOptions
}
type Runner struct {
Opts GenerateOptions
// Relative root of solo-kit gen. Will be used as the root of all generation
RelativeRoot string
// Location to output all proto code gen, defaults to a temp dir
DescriptorOutDir string
// root of the go mod package
BaseDir string
// common import directories in which solo-kit should look for protos in the current package
CommonImports []string
}
func Generate(opts GenerateOptions) error {
metrics.NewAggregator()
// opts.SkipDirs = append(opts.SkipDirs, "vendor/")
workingRootRelative := opts.RelativeRoot
if workingRootRelative == "" {
workingRootRelative = "."
}
if filepath.IsAbs(workingRootRelative) {
return eris.Errorf("opts.RelativeRoot must be relative")
}
modBytes, err := modutils.GetCurrentModPackageFile()
modFileString := strings.TrimSpace(string(modBytes))
modPackageName, err := modutils.GetCurrentModPackageName(modFileString)
if err != nil {
return err
}
modPathString := filepath.Dir(modFileString)
if opts.PackageName == "" {
opts.PackageName = modPackageName
}
descriptorOutDir, err := ioutil.TempDir("", "")
if err != nil {
return err
}
defer os.Remove(descriptorOutDir)
commonImports, err := getCommonImports()
if err != nil {
return err
}
// copy over our protos to right path
r := Runner{
RelativeRoot: workingRootRelative,
Opts: opts,
BaseDir: modPathString,
DescriptorOutDir: descriptorOutDir,
CommonImports: commonImports,
}
if opts.ExternalImports == nil {
log.Warnf("ExternalImports is nil, therefore no protos will be vendored. This is not an error," +
"but will most likely lead to one.")
}
ctx := context.Background()
mgr, err := manager.NewManager(ctx, r.BaseDir)
if err != nil {
return err
}
if err := mgr.Ensure(ctx, opts.ExternalImports.ToAnyvendorConfig()); err != nil {
return err
}
// copy out generated code
err = r.Run()
if err != nil {
return err
}
/*
this is an extreme edge case, but an important one.
before attempting to copy over generated files we need to make sure that any files were generated at all.
solo-kit used to write directly into the GOPATH so this could never happen.
now however, in the case that solo-kit does not compile any protos, the following directory may never be created,
this is not technically an error, but a situation worth noting and logging
*/
outPath := filepath.Join(descriptorOutDir, r.Opts.PackageName)
if _, err := os.Stat(outPath); os.IsNotExist(err) {
log.Warnf("the filepath %s does not exist. this means that solo-kit did not compile any proto files."+
"this is not technically an error, but could be indicative of an incorrect setup.", outPath)
return nil
}
log.Printf("Copying relevant files from tmp directory: %s", descriptorOutDir)
if err := filepath.Walk(outPath, func(pbgoFile string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
if !(strings.HasSuffix(pbgoFile, ".go")) {
return nil
}
dest := strings.TrimPrefix(pbgoFile, filepath.Join(descriptorOutDir, r.Opts.PackageName))
dest = strings.TrimPrefix(dest, "/")
dir, _ := filepath.Split(dest)
os.MkdirAll(dir, 0755)
// copy
srcFile, err := os.Open(pbgoFile)
if err != nil {
return err
}
defer srcFile.Close()
dstFile, err := os.Create(dest)
if err != nil {
return err
}
defer dstFile.Close()
log.Debugf("copying %v -> %v", pbgoFile, dest)
_, err = io.Copy(dstFile, srcFile)
return err
}); err != nil {
return err
}
return metrics.Flush(os.Stdout)
}
func (r *Runner) Run() error {
defer metrics.MeasureElapsed("code-generator-runner", time.Now())
workingRootAbsolute, err := filepath.Abs(r.RelativeRoot)
if err != nil {
return err
}
// Creates a ProjectConfig from each of the 'solo-kit.json' files
// found in the directory tree rooted at 'workingRootAbsolute'.
// These files are vendored into the protodep.DefaultDepDir by protodep, and accessed from there.
// This root is the proper base directory to find only the roots which matter.
// This way solo-kit can be ran from a child directory with no repercussions.
projectConfigRoot := filepath.Join(r.BaseDir, anyvendor.DefaultDepDir, r.Opts.PackageName, strings.TrimPrefix(workingRootAbsolute, r.BaseDir))
projectConfigs, err := r.collectProjectsFromRoot(projectConfigRoot, r.Opts.SkipDirs)
if err != nil {
return err
}
log.Printf("collected projects: %v", func() []string {
var names []string
for _, project := range projectConfigs {
names = append(names, project.Name)
}
sort.Strings(names)
return names
}())
var customCompilePrefixes []string
for _, relativePath := range r.Opts.CustomCompileProtos {
if !strings.HasPrefix(relativePath, anyvendor.DefaultDepDir) {
relativePath = filepath.Join(anyvendor.DefaultDepDir, relativePath)
}
abs, err := filepath.Abs(relativePath)
if err != nil {
return err
}
customCompilePrefixes = append(customCompilePrefixes, abs)
}
// whether or not to do a regular go-proto generate while collecting descriptors
compileProto := func(protoFile string) bool {
for _, customCompilePrefix := range customCompilePrefixes {
if strings.HasPrefix(protoFile, customCompilePrefix) {
return true
}
}
if !r.Opts.CompileProtos {
return false
}
for _, proj := range projectConfigs {
if strings.HasPrefix(protoFile, filepath.Dir(proj.ProjectFile)) {
return true
}
}
return false
}
importsCollector := collector.NewCollector(r.Opts.CustomImports, r.CommonImports)
protocExecutor := &collector.DefaultProtocExecutor{
OutputDir: r.DescriptorOutDir,
ShouldCompileFile: compileProto,
CustomGoArgs: r.Opts.CustomGoOutArgs,
CustomPlugins: r.Opts.CustomPlugins,
}
descriptorCollector := collector.NewProtoCompiler(importsCollector, protocExecutor)
descriptors, err := descriptorCollector.CompileDescriptorsFromRoot(filepath.Join(r.BaseDir, anyvendor.DefaultDepDir), r.Opts.SkipDirs)
if err != nil {
return err
}
log.Debugf("collected descriptors: %v", func() []string {
var names []string
for _, desc := range descriptors {
names = append(names, desc.GetName())
}
names = stringutils.Unique(names)
sort.Strings(names)
return names
}())
var protoDescriptors []*descriptor.FileDescriptorProto
for _, projectConfig := range projectConfigs {
importedResources, err := r.importCustomResources(projectConfig.Imports)
if err != nil {
return err
}
projectConfig.CustomResources = append(projectConfig.CustomResources, importedResources...)
for _, desc := range descriptors {
if filepath.Dir(desc.ProtoFilePath) == filepath.Dir(projectConfig.ProjectFile) {
projectConfig.ProjectProtos = append(projectConfig.ProjectProtos, desc.GetName())
}
protoDescriptors = append(protoDescriptors, desc.FileDescriptorProto)
}
}
projectMap, err := parser.ProcessDescriptorsFromConfigs(projectConfigs, protoDescriptors)
if err != nil {
return err
}
for _, project := range projectMap {
log.Printf("Generating files for project: %s", project.String())
// Generate Files
generatedFiles, err := codegen.GenerateFiles(project, true, r.Opts.SkipGeneratedTests, project.ProjectConfig.GenKubeTypes)
if err != nil {
return err
}
split := strings.SplitAfterN(project.ProjectConfig.GoPackage, "/", filepathValidLength)
if len(split) < filepathValidLength {
return eris.Errorf("projectConfig.GoPackage is not valid, %s", project.ProjectConfig.GoPackage)
}
outDir := split[filepathValidLength-1]
fileWriter := &writer.DefaultFileWriter{
Root: outDir,
HeaderFromFilename: func(filename string) string {
if strings.HasSuffix(filename, ".go") {
return fmt.Sprintf("// %s\n\n", writer.DefaultFileHeader)
}
return writer.NoFileHeader
},
}
for _, file := range generatedFiles {
if err := fileWriter.WriteFile(file); err != nil {
return err
}
path := filepath.Join(outDir, file.Filename)
switch {
case strings.HasSuffix(file.Filename, ".sh"):
if out, err := exec.Command("chmod", "+x", filepath.Join(workingRootAbsolute, path)).CombinedOutput(); err != nil {
return eris.Wrapf(err, "chmod failed: %s", out)
}
case strings.HasSuffix(file.Filename, ".go"):
if out, err := exec.Command("gofmt", "-w", path).CombinedOutput(); err != nil {
return eris.Wrapf(err, "gofmt failed: %s", out)
}
if out, err := exec.Command("goimports", "-w", path).CombinedOutput(); err != nil {
return eris.Wrapf(err, "goimports failed: %s", out)
}
}
}
// Generate Docs
if err := docgen.WritePerProjectsDocs(project, r.Opts.GenDocs, workingRootAbsolute); err != nil {
return err
}
// Generate Mocks
// need to run after to make sure all resources have already been written
// Set this env var during tests so that mocks are not generated
if !r.Opts.SkipGenMocks {
if err := genMocks(generatedFiles, outDir, workingRootAbsolute); err != nil {
return err
}
}
// Generate OpenApi validation schemas
if err := schemagen.GenerateOpenApiValidationSchemas(project, r.Opts.ValidationSchemaOptions, importsCollector, workingRootAbsolute); err != nil {
return err
}
}
if err := docgen.WriteCrossProjectDocs(r.Opts.GenDocs, workingRootAbsolute, projectMap); err != nil {
return err
}
return nil
}
var (
validMockingInterfaces = []string{
"_client",
"_reconciler",
"_emitter",
"_event_loop",
}
invalidMockingInterface = []string{
"_simple_event_loop",
"_test",
}
)
func genMocks(code code_generator.Files, outDir, absoluteRoot string) error {
if err := os.MkdirAll(filepath.Join(outDir, "mocks"), os.ModePerm); err != nil {
return err
}
for _, file := range code {
if out, err := genMockForFile(file, outDir, absoluteRoot); err != nil {
return eris.Wrapf(err, "mockgen failed: %s", out)
}
}
return nil
}
func genMockForFile(file code_generator.File, outDir, absoluteRoot string) ([]byte, error) {
if containsAny(file.Filename, invalidMockingInterface) || !containsAny(file.Filename, validMockingInterfaces) {
return nil, nil
}
path := filepath.Join(outDir, file.Filename)
dest := filepath.Join(outDir, "mocks", file.Filename)
path = strings.Replace(path, absoluteRoot, ".", 1)
dest = strings.Replace(dest, absoluteRoot, ".", 1)
return exec.Command("mockgen", fmt.Sprintf("-source=%s", path), fmt.Sprintf("-destination=%s", dest), "-package=mocks").CombinedOutput()
}
func containsAny(str string, slice []string) bool {
for _, val := range slice {
if strings.Contains(str, val) {
return true
}
}
return false
}
func (r *Runner) collectProjectsFromRoot(root string, skipDirs []string) ([]*model.ProjectConfig, error) {
var projects []*model.ProjectConfig
if err := filepath.Walk(root, func(projectFile string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !strings.HasSuffix(projectFile, model.ProjectConfigFilename) {
return nil
}
for _, skip := range skipDirs {
skipRoot, err := filepath.Abs(skip)
if err != nil {
return err
}
if strings.HasPrefix(projectFile, skipRoot) {
log.Warnf("skipping detected project %v", projectFile)
return nil
}
}
project, err := model.LoadProjectConfig(projectFile)
if err != nil {
return err
}
projects = append(projects, &project)
return nil
}); err != nil {
return nil, err
}
return projects, nil
}
func getCommonImports() ([]string, error) {
var result []string
modPackageFile, err := modutils.GetCurrentModPackageFile()
if err != nil {
return nil, err
}
modPackageDir := filepath.Dir(modPackageFile)
for _, v := range commonImportStrings {
result = append(result, filepath.Join(modPackageDir, v))
}
return result, nil
}
var commonImportStrings = []string{
anyvendor.DefaultDepDir,
}
const (
filepathValidLength = 4
filepathWithVendorLength = filepathValidLength + 1
)
func (r *Runner) importCustomResources(imports []string) ([]model.CustomResourceConfig, error) {
var results []model.CustomResourceConfig
for _, imp := range imports {
imp = filepath.Join(anyvendor.DefaultDepDir, imp)
if !strings.HasSuffix(imp, model.ProjectConfigFilename) {
imp = filepath.Join(imp, model.ProjectConfigFilename)
}
byt, err := ioutil.ReadFile(imp)
if err != nil {
if !os.IsNotExist(err) {
return nil, err
}
/*
used to split file name up if check in vendor fails.
for example: vendor/github.com/solo-io/solo-kit/api/external/kubernetes/solo-kit.json
will become: [vendor/, github.com/, solo-io/, solo-kit/, api/external/kubernetes/solo-kit.json]
and the final member is the local path
*/
split := strings.SplitAfterN(imp, "/", filepathWithVendorLength)
if len(split) < filepathWithVendorLength {
return nil, eris.Errorf("filepath is not valid, %s", imp)
}
byt, err = ioutil.ReadFile(split[filepathWithVendorLength-1])
if err != nil {
return nil, err
}
}
var projectConfig model.ProjectConfig
err = json.Unmarshal(byt, &projectConfig)
if err != nil {
return nil, err
}
var customResources []model.CustomResourceConfig
for _, v := range projectConfig.CustomResources {
v.Package = projectConfig.GoPackage
v.Imported = true
customResources = append(customResources, v)
}
results = append(results, customResources...)
}
return results, nil
}