Skip to content

Commit

Permalink
refactor(generate): split generating of code into two parts
Browse files Browse the repository at this point in the history
Before both filtering of which services to generate AIP tests for
and the actual rendering of the code happened in one loop.

This commit separate its into two parts:
- Collect relevant services that tests can be generated for
- Generate code for the collected services
  • Loading branch information
thall committed Oct 11, 2024
1 parent 42a18b1 commit bb1b3d1
Showing 1 changed file with 41 additions and 6 deletions.
47 changes: 41 additions & 6 deletions internal/plugin/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,32 @@ const (

func Generate(plugin *protogen.Plugin) error {
plugin.SupportedFeatures |= 1 // proto3 optional
files, err := collectServices(plugin)
if err != nil {
return err
}
return generate(plugin, files)
}

type File struct {
*protogen.File
services []serviceGenerator
}

// collectServices collects valid services to generate AIP test code for.
func collectServices(
plugin *protogen.Plugin,
) ([]File, error) {
pkgResources := findResourcesPerPackage(plugin)
result := make([]File, 0, 10)
for _, file := range plugin.Files {
if len(file.Services) == 0 || !file.Generate {
continue
}
filename := fmt.Sprintf("%s_%s", file.GeneratedFilenamePrefix, fileSuffix)
f := plugin.NewGeneratedFile(filename, file.GoImportPath)
writeHeader(file, f)
f.Skip()

f := File{
File: file,
services: make([]serviceGenerator, 0, 10),
}
for _, service := range file.Services {
resources := pkgResources[file.Desc.Package()]
if len(resources) == 0 {
Expand All @@ -48,7 +64,7 @@ func Generate(plugin *protogen.Plugin) error {
rs = append(rs, serviceResource.descriptor)
m, err := protogenMessage(plugin, serviceResource.message.FullName())
if err != nil {
return err
return nil, err
}
ms = append(ms, m)
}
Expand All @@ -57,6 +73,18 @@ func Generate(plugin *protogen.Plugin) error {
resources: rs,
messages: ms,
}
f.services = append(f.services, generator)
}
result = append(result, f)
}
return result, nil
}

func generate(plugin *protogen.Plugin, files []File) error {
for _, file := range files {
f := createServiceTestFile(plugin, file)
f.Skip()
for _, generator := range file.services {
if err := generator.Generate(f); err != nil {
return err
}
Expand All @@ -66,6 +94,13 @@ func Generate(plugin *protogen.Plugin) error {
return nil
}

func createServiceTestFile(plugin *protogen.Plugin, file File) *protogen.GeneratedFile {
filename := fmt.Sprintf("%s_%s", file.GeneratedFilenamePrefix, fileSuffix)
f := plugin.NewGeneratedFile(filename, file.GoImportPath)
writeHeader(file.File, f)
return f
}

func writeHeader(file *protogen.File, f *protogen.GeneratedFile) {
f.P("// Code generated by protoc-gen-go-aip-test. DO NOT EDIT.")
f.P()
Expand Down

0 comments on commit bb1b3d1

Please sign in to comment.