-
Notifications
You must be signed in to change notification settings - Fork 5
/
codegen.go
73 lines (61 loc) · 1.93 KB
/
codegen.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
package retries
import (
"fmt"
"path/filepath"
"github.com/blueprint-uservices/blueprint/plugins/golang"
"github.com/blueprint-uservices/blueprint/plugins/golang/gocode"
"github.com/blueprint-uservices/blueprint/plugins/golang/gogen"
"golang.org/x/exp/slog"
)
// code generation function called from the ir.go file.
func generateClient(builder golang.ModuleBuilder, wrapped *gocode.ServiceInterface, outputPackage string, Max int64) error {
pkg, err := builder.CreatePackage(outputPackage)
if err != nil {
return err
}
client := clientArgs{
Package: pkg,
Service: wrapped,
Name: wrapped.BaseName + "_RetrierClient",
Max: Max,
Imports: gogen.NewImports(pkg.Name),
}
client.Imports.AddPackages("context")
slog.Info(fmt.Sprintf("Generating %v/%v", client.Package.PackageName, wrapped.BaseName+"_RetrierClient"))
outputFile := filepath.Join(client.Package.Path, wrapped.BaseName+"_RetrierClient.go")
return gogen.ExecuteTemplateToFile("Retries", clientTemplate, client, outputFile)
}
type clientArgs struct {
Package golang.PackageInfo
Service *gocode.ServiceInterface
Name string
Max int64
Imports *gogen.Imports
}
var clientTemplate = `// Blueprint: Auto-generated by Retries Plugin
package {{.Package.ShortName}}
{{.Imports}}
type {{.Name}} struct {
Client {{.Imports.NameOf .Service.UserType}}
MaxTries int
}
func New_{{.Name}} (ctx context.Context, client {{.Imports.NameOf .Service.UserType}}) (*{{.Name}}, error) {
handler := &{{.Name}}{}
handler.Client = client
handler.MaxTries = {{.Max}}
return handler, nil
}
{{$service := .Service.Name -}}
{{$receiver := .Name -}}
{{ range $_, $f := .Service.Methods }}
func (client *{{$receiver}}) {{$f.Name -}} ({{ArgVarsAndTypes $f "ctx context.Context"}}) ({{RetVarsAndTypes $f "err error"}}) {
for i := 0; i < client.MaxTries; i++ {
{{RetVars $f "err"}} = client.Client.{{$f.Name}}({{ArgVars $f "ctx"}})
if err == nil {
return
}
}
return
}
{{end}}
`