Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 42 additions & 2 deletions codegen/internal/generator/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,14 @@ type clientModel struct {
FieldName string
Package string
Methods []operationModel
Nested bool
Children []childClient
AccessPath string
}

type childClient struct {
ClassName string
AccessorName string
}

// operationModel stores the derived metadata for one OpenAPI operation.
Expand Down Expand Up @@ -147,6 +155,10 @@ func buildModel(doc *v3.Document, params Params) (sdkModel, error) {
}
}
groups := map[string][]operationModel{}
parents, err := readResourceParents(doc)
if err != nil {
return sdkModel{}, err
}
if doc.Paths != nil && doc.Paths.PathItems != nil && doc.Paths.PathItems.Len() > 0 {
for path, item := range doc.Paths.PathItems.FromOldest() {
if item == nil {
Expand All @@ -163,6 +175,12 @@ func buildModel(doc *v3.Document, params Params) (sdkModel, error) {
opModel := convertOperation(method, path, item, operation, resolver)
tag := opModel.TagName
groups[tag] = append(groups[tag], opModel)
for parent := parents[tag].tag; parent != ""; parent = parents[parent].tag {
if _, exists := groups[parent]; exists {
break
}
groups[parent] = nil
}
}
}
}
Expand Down Expand Up @@ -198,15 +216,37 @@ func buildModel(doc *v3.Document, params Params) (sdkModel, error) {
className += suffix
}

clients = append(clients, clientModel{
client := clientModel{
TagName: tag,
TagDescriptionLines: tagDescriptions[tag],
ClassName: className,
AccessorName: accessor,
FieldName: fieldName,
Package: params.clientPackage(),
Methods: ops,
})
}
if parent := parents[tag]; parent.tag != "" {
client.Nested = true
client.AccessorName = camelCase(parent.label, "client")
}
clients = append(clients, client)
}
byTag := make(map[string]*clientModel, len(clients))
for i := range clients {
byTag[clients[i].TagName] = &clients[i]
}
for i := range clients {
client := &clients[i]
path := client.AccessorName + "()"
for ancestor := parents[client.TagName].tag; ancestor != ""; ancestor = parents[ancestor].tag {
path = byTag[ancestor].AccessorName + "()." + path
}
client.AccessPath = path
if parent := byTag[parents[client.TagName].tag]; parent != nil {
parent.Children = append(parent.Children, childClient{
ClassName: client.ClassName, AccessorName: client.AccessorName,
})
}
}

schemas := buildSchemas(doc, params, resolver)
Expand Down
26 changes: 19 additions & 7 deletions codegen/internal/generator/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"os"
"path/filepath"
"slices"
"sort"
"strconv"
"strings"
Expand Down Expand Up @@ -162,19 +163,26 @@ type operationTemplateData struct {
// clientTemplateData contains the data required to render a single client
// class.
type clientTemplateData struct {
Package string
ClassName string
TagName string
Children []childClient
Package string
ClassName string
TagName string
TagDescriptionLines []string
Imports []string
Operations []operationTemplateData
QueryStructs []*parameterGroupModel
HeaderStructs []*parameterGroupModel
Imports []string
Operations []operationTemplateData
QueryStructs []*parameterGroupModel
HeaderStructs []*parameterGroupModel
}

// prepareClientTemplateData converts an internal client model into a richer
// structure that is easier for templates to consume.
func prepareClientTemplateData(client clientModel, className string, async bool) clientTemplateData {
children := slices.Clone(client.Children)
if async {
for i := range children {
children[i].ClassName = asyncClientClassName(children[i].ClassName)
}
}
importSet := map[string]struct{}{
"com.sumup.sdk.core.ApiClient": {},
"com.sumup.sdk.core.ApiException": {},
Expand Down Expand Up @@ -318,6 +326,7 @@ func prepareClientTemplateData(client clientModel, className string, async bool)
sort.Strings(imports)

return clientTemplateData{
Children: children,
Package: client.Package,
ClassName: className,
TagName: client.TagName,
Expand All @@ -339,6 +348,9 @@ func prepareSumUpClientData(model sdkModel, className string, async bool) map[st
}
clientInfos := make([]map[string]string, 0, len(model.Clients))
for _, client := range model.Clients {
if client.Nested {
continue
}
clientClass := client.ClassName
if async {
clientClass = asyncClientClassName(clientClass)
Expand Down
2 changes: 1 addition & 1 deletion codegen/internal/generator/samples.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ func (r javaSampleRenderer) render(client clientModel, operation operationModel,
}

className := pascalCase(operation.OperationID+" "+example.name, "Sample")
call := "client." + client.AccessorName + "()." + operation.MethodName + "("
call := "client." + client.AccessPath + "." + operation.MethodName + "("
if len(args) > 0 {
call += "\n"
for i, arg := range args {
Expand Down
60 changes: 60 additions & 0 deletions codegen/internal/generator/tag_hierarchy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package generator

import (
"cmp"
"fmt"

v3 "github.com/pb33f/libopenapi/datamodel/high/v3"
)

type resourceParent struct {
tag string
label string
}

func readResourceParents(doc *v3.Document) (map[string]resourceParent, error) {
if doc.Extensions == nil {
return nil, nil
}
node, ok := doc.Extensions.Get("x-tagGroups")
if !ok {
return nil, nil
}
var groups []struct {
Name string `yaml:"name"`
Tags []string `yaml:"tags"`
}
if err := node.Decode(&groups); err != nil {
return nil, fmt.Errorf("decode x-tagGroups: %w", err)
}
labels := make(map[string]string, len(doc.Tags))
for _, tag := range doc.Tags {
var displayName string
if tag.Extensions != nil {
if label, ok := tag.Extensions.Get("x-displayName"); ok {
if err := label.Decode(&displayName); err != nil {
return nil, fmt.Errorf("decode x-displayName for %s: %w", tag.Name, err)
}
}
}
labels[tag.Name] = cmp.Or(displayName, tag.Name)
}
parents := map[string]resourceParent{}
for _, group := range groups {
if labels[group.Name] == "" {
continue
}
for _, child := range group.Tags {
if child == group.Name || labels[child] == "" || parents[child].tag != "" {
continue
}
for ancestor := group.Name; ancestor != ""; ancestor = parents[ancestor].tag {
if ancestor == child {
return nil, fmt.Errorf("tag hierarchy contains a cycle at %s", child)
}
}
parents[child] = resourceParent{tag: group.Name, label: labels[child]}
}
}
return parents, nil
}
64 changes: 64 additions & 0 deletions codegen/internal/generator/tag_hierarchy_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package generator

import (
"testing"

"github.com/pb33f/libopenapi"
)

func TestNestedReaderResources(t *testing.T) {
t.Parallel()

doc, err := libopenapi.NewDocument([]byte(`
openapi: 3.1.0
info: {title: Readers, version: 1.0.0}
tags:
- name: Readers
- name: ReaderCheckouts
x-displayName: Checkouts
x-tagGroups:
- name: Readers
tags: [ReaderCheckouts]
paths:
/readers/checkouts:
get:
operationId: ListReaders
tags: [Readers]
responses:
'204': {description: OK}
post:
operationId: CreateReaderCheckout
tags: [ReaderCheckouts]
x-codegen: {method_name: create}
responses:
'204': {description: OK}
components: {schemas: {}}
`))
if err != nil {
t.Fatal(err)
}
model, err := doc.BuildV3Model()
if err != nil {
t.Fatal(err)
}

sdk, err := buildModel(&model.Model, Params{BasePackage: "com.sumup.sdk"})
if err != nil {
t.Fatal(err)
}
for _, client := range sdk.Clients {
switch client.TagName {
case "Readers":
if len(client.Children) != 1 || client.Children[0].AccessorName != "checkouts" || len(client.Methods) != 1 || client.Methods[0].MethodName != "listReaders" {
t.Fatalf("expected Checkouts and the parent operation: %+v", client)
}
case "ReaderCheckouts":
if client.AccessPath != "readers().checkouts()" || len(client.Methods) != 1 || client.Methods[0].MethodName != "create" {
t.Fatalf("expected only the checkout operation on the nested client: %+v", client)
}
}
}
if len(sdk.Clients) != 2 {
t.Fatalf("expected two clients, got %d", len(sdk.Clients))
}
}
13 changes: 13 additions & 0 deletions codegen/internal/generator/templates/client.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ import {{ . }};
*/
public final class {{ .ClassName }} {
private final ApiClient apiClient;
{{- range .Children }}
private final {{ .ClassName }} {{ .AccessorName }};
{{- end }}

/**
* Creates a new {{ .ClassName }} instance backed by the provided ApiClient.
Expand All @@ -23,7 +26,17 @@ public final class {{ .ClassName }} {
*/
public {{ .ClassName }}(ApiClient apiClient) {
this.apiClient = Objects.requireNonNull(apiClient, "apiClient");
{{- range .Children }}
this.{{ .AccessorName }} = new {{ .ClassName }}(apiClient);
{{- end }}
}
{{- range .Children }}

/** @return the {{ .AccessorName }} client. */
public {{ .ClassName }} {{ .AccessorName }}() {
return {{ .AccessorName }};
}
{{- end }}

{{- range .Operations }}
{{- $reqDecl := join .RequiredParamDecls ", " -}}
Expand Down
13 changes: 13 additions & 0 deletions codegen/internal/generator/templates/client_async.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ import {{ . }};
*/
public final class {{ .ClassName }} {
private final ApiClient apiClient;
{{- range .Children }}
private final {{ .ClassName }} {{ .AccessorName }};
{{- end }}

/**
* Creates a new {{ .ClassName }} instance backed by the provided ApiClient.
Expand All @@ -23,7 +26,17 @@ public final class {{ .ClassName }} {
*/
public {{ .ClassName }}(ApiClient apiClient) {
this.apiClient = Objects.requireNonNull(apiClient, "apiClient");
{{- range .Children }}
this.{{ .AccessorName }} = new {{ .ClassName }}(apiClient);
{{- end }}
}
{{- range .Children }}

/** @return the {{ .AccessorName }} client. */
public {{ .ClassName }} {{ .AccessorName }}() {
return {{ .AccessorName }};
}
{{- end }}

{{- range .Operations }}
{{- $reqDecl := join .RequiredParamDecls ", " -}}
Expand Down
Loading