Skip to content

Commit 8822002

Browse files
style: simplify and modernize (oapi-codegen#2305)
* style: simplify and modernize Signed-off-by: Gaiaz Iusipov <g.iusipov@gmail.com> * revert: adding compile-time checks Signed-off-by: Gaiaz Iusipov <g.iusipov@gmail.com> --------- Signed-off-by: Gaiaz Iusipov <g.iusipov@gmail.com> Co-authored-by: Marcin Romaszewicz <mromaszewicz@users.noreply.github.com>
1 parent e126f5a commit 8822002

19 files changed

Lines changed: 136 additions & 171 deletions

File tree

examples/authenticated-api/stdhttp/api/api.gen.go

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

examples/minimal-server/stdhttp/api/ping.gen.go

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

examples/petstore-expanded/stdhttp/api/petstore.gen.go

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

internal/test/issues/issue-1963/issue1963.gen.go

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

internal/test/issues/issue-2190/issue2190.gen.go

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

internal/test/issues/issue-2232/issue2232.gen.go

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

internal/test/strict-server/stdhttp/server.gen.go

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pkg/codegen/codegen.go

Lines changed: 19 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,11 @@ import (
2424
"go/scanner"
2525
"io"
2626
"io/fs"
27+
"maps"
2728
"net/http"
2829
"os"
2930
"runtime/debug"
31+
"slices"
3032
"sort"
3133
"strings"
3234
"text/template"
@@ -103,11 +105,8 @@ func constructImportMapping(importMapping map[string]string) importMap {
103105
)
104106

105107
{
106-
var packagePaths []string
107-
for _, packageName := range importMapping {
108-
packagePaths = append(packagePaths, packageName)
109-
}
110-
sort.Strings(packagePaths)
108+
packagePaths := slices.Collect(maps.Values(importMapping))
109+
slices.Sort(packagePaths)
111110

112111
for _, packagePath := range packagePaths {
113112
if _, ok := pathToImport[packagePath]; !ok && packagePath != importMappingCurrentPackage {
@@ -255,7 +254,7 @@ func Generate(spec *openapi3.T, opts Configuration) (string, error) {
255254
if err != nil {
256255
return "", fmt.Errorf("error getting type definition imports: %w", err)
257256
}
258-
MergeImports(xGoTypeImports, imprts)
257+
maps.Copy(xGoTypeImports, imprts)
259258
}
260259

261260
var serverURLsDefinitions string
@@ -626,11 +625,7 @@ func GenerateConstants(t *template.Template, ops []OperationDefinition) (string,
626625
}
627626
}
628627

629-
var providerNames []string
630-
for providerName := range providerNameMap {
631-
providerNames = append(providerNames, providerName)
632-
}
633-
628+
providerNames := slices.Collect(maps.Keys(providerNameMap))
634629
sort.Strings(providerNames)
635630

636631
constants.SecuritySchemeProviderNames = append(constants.SecuritySchemeProviderNames, providerNames...)
@@ -944,7 +939,7 @@ func resolvedNameForComponent(section, name string, contentType ...string) strin
944939
}
945940
if len(matches) > 0 {
946941
if len(matches) > 1 {
947-
sort.Strings(matches)
942+
slices.Sort(matches)
948943
}
949944
return globalState.resolvedNames[matches[0]]
950945
}
@@ -1243,14 +1238,14 @@ func OperationSchemaImports(s *Schema) (map[string]goImport, error) {
12431238
if err != nil {
12441239
return nil, err
12451240
}
1246-
MergeImports(res, imprts)
1241+
maps.Copy(res, imprts)
12471242
}
12481243

12491244
imprts, err := GoSchemaImports(&openapi3.SchemaRef{Value: s.OAPISchema})
12501245
if err != nil {
12511246
return nil, err
12521247
}
1253-
MergeImports(res, imprts)
1248+
maps.Copy(res, imprts)
12541249
return res, nil
12551250
}
12561251

@@ -1263,7 +1258,7 @@ func OperationImports(ops []OperationDefinition) (map[string]goImport, error) {
12631258
if err != nil {
12641259
return nil, err
12651260
}
1266-
MergeImports(res, imprts)
1261+
maps.Copy(res, imprts)
12671262
}
12681263
}
12691264

@@ -1272,7 +1267,7 @@ func OperationImports(ops []OperationDefinition) (map[string]goImport, error) {
12721267
if err != nil {
12731268
return nil, err
12741269
}
1275-
MergeImports(res, imprts)
1270+
maps.Copy(res, imprts)
12761271
}
12771272

12781273
for _, b := range op.Responses {
@@ -1281,7 +1276,7 @@ func OperationImports(ops []OperationDefinition) (map[string]goImport, error) {
12811276
if err != nil {
12821277
return nil, err
12831278
}
1284-
MergeImports(res, imprts)
1279+
maps.Copy(res, imprts)
12851280
}
12861281
}
12871282

@@ -1316,7 +1311,7 @@ func GetTypeDefinitionsImports(swagger *openapi3.T, excludeSchemas []string) (ma
13161311
}
13171312

13181313
for _, imprts := range []map[string]goImport{schemaImports, reqBodiesImports, responsesImports, parametersImports} {
1319-
MergeImports(res, imprts)
1314+
maps.Copy(res, imprts)
13201315
}
13211316
return res, nil
13221317
}
@@ -1343,14 +1338,14 @@ func GoSchemaImports(schemas ...*openapi3.SchemaRef) (map[string]goImport, error
13431338
if err != nil {
13441339
return nil, err
13451340
}
1346-
MergeImports(res, imprts)
1341+
maps.Copy(res, imprts)
13471342
}
13481343
} else if t.Is("array") {
13491344
imprts, err := GoSchemaImports(schemaVal.Items)
13501345
if err != nil {
13511346
return nil, err
13521347
}
1353-
MergeImports(res, imprts)
1348+
maps.Copy(res, imprts)
13541349
}
13551350
}
13561351
return res, nil
@@ -1371,7 +1366,7 @@ func GetSchemaImports(schemas map[string]*openapi3.SchemaRef, excludeSchemas []s
13711366
if err != nil {
13721367
return nil, err
13731368
}
1374-
MergeImports(res, imprts)
1369+
maps.Copy(res, imprts)
13751370
}
13761371
return res, nil
13771372
}
@@ -1389,7 +1384,7 @@ func GetRequestBodiesImports(bodies map[string]*openapi3.RequestBodyRef) (map[st
13891384
if err != nil {
13901385
return nil, err
13911386
}
1392-
MergeImports(res, imprts)
1387+
maps.Copy(res, imprts)
13931388
}
13941389
}
13951390
return res, nil
@@ -1408,7 +1403,7 @@ func GetResponsesImports(responses map[string]*openapi3.ResponseRef) (map[string
14081403
if err != nil {
14091404
return nil, err
14101405
}
1411-
MergeImports(res, imprts)
1406+
maps.Copy(res, imprts)
14121407
}
14131408
}
14141409
return res, nil
@@ -1424,7 +1419,7 @@ func GetParametersImports(params map[string]*openapi3.ParameterRef) (map[string]
14241419
if err != nil {
14251420
return nil, err
14261421
}
1427-
MergeImports(res, imprts)
1422+
maps.Copy(res, imprts)
14281423
}
14291424
return res, nil
14301425
}

pkg/codegen/gather.go

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
11
package codegen
22

33
import (
4+
"cmp"
45
"fmt"
5-
"sort"
6+
"slices"
67
"strings"
78

89
"github.com/getkin/kin-openapi/openapi3"
10+
911
"github.com/oapi-codegen/oapi-codegen/v2/pkg/util"
1012
)
1113

14+
var _ fmt.Stringer = (*SchemaPath)(nil)
15+
1216
// SchemaPath represents the document location of a schema, e.g.
1317
// ["components", "schemas", "Pet", "properties", "name"].
1418
type SchemaPath []string
@@ -18,6 +22,8 @@ func (sp SchemaPath) String() string {
1822
return strings.Join(sp, "/")
1923
}
2024

25+
var _ fmt.Stringer = (*SchemaContext)(nil)
26+
2127
// SchemaContext identifies where in the OpenAPI document a schema was found.
2228
type SchemaContext int
2329

@@ -82,13 +88,13 @@ func (sc SchemaContext) Suffix() string {
8288
// GatheredSchema represents a schema discovered during the gather pass,
8389
// along with its document location and context metadata.
8490
type GatheredSchema struct {
85-
Path SchemaPath
86-
Context SchemaContext
87-
Ref string // $ref string if this is a reference
88-
Schema *openapi3.Schema // The resolved schema value
89-
OperationID string // Enclosing operation's ID, if any
90-
ContentType string // Media type, if from request/response body
91-
StatusCode string // HTTP status code, if from a response
91+
Path SchemaPath
92+
Context SchemaContext
93+
Ref string // $ref string if this is a reference
94+
Schema *openapi3.Schema // The resolved schema value
95+
OperationID string // Enclosing operation's ID, if any
96+
ContentType string // Media type, if from request/response body
97+
StatusCode string // HTTP status code, if from a response
9298
ParamIndex int // Parameter index within an operation
9399
ComponentName string // The component name (e.g., "Bar" for components/schemas/Bar)
94100
GoNameOverride string // x-go-name override from the component or its parent container
@@ -105,11 +111,13 @@ func GatherSchemas(spec *openapi3.T, opts Configuration) []*GatheredSchema {
105111
var schemas []*GatheredSchema
106112

107113
if spec.Components != nil {
108-
schemas = append(schemas, gatherComponentSchemas(spec.Components)...)
109-
schemas = append(schemas, gatherComponentParameters(spec.Components)...)
110-
schemas = append(schemas, gatherComponentResponses(spec.Components)...)
111-
schemas = append(schemas, gatherComponentRequestBodies(spec.Components)...)
112-
schemas = append(schemas, gatherComponentHeaders(spec.Components)...)
114+
schemas = slices.Concat(
115+
gatherComponentSchemas(spec.Components),
116+
gatherComponentParameters(spec.Components),
117+
gatherComponentResponses(spec.Components),
118+
gatherComponentRequestBodies(spec.Components),
119+
gatherComponentHeaders(spec.Components),
120+
)
113121
}
114122

115123
// Gather client response wrapper types for operations that will generate
@@ -268,10 +276,8 @@ func gatherComponentHeaders(components *openapi3.Components) []*GatheredSchema {
268276
// `<OperationId>Response`. These don't correspond to a real schema in the
269277
// spec but they need names that don't collide with real types.
270278
func gatherClientResponseWrappers(spec *openapi3.T) []*GatheredSchema {
271-
var result []*GatheredSchema
272-
273279
if spec.Paths == nil {
274-
return result
280+
return nil
275281
}
276282

277283
// Collect all operations sorted for determinism
@@ -296,10 +302,11 @@ func gatherClientResponseWrappers(spec *openapi3.T) []*GatheredSchema {
296302
}
297303

298304
// Sort by operationID for determinism
299-
sort.Slice(ops, func(i, j int) bool {
300-
return ops[i].op.OperationID < ops[j].op.OperationID
305+
slices.SortFunc(ops, func(a, b opEntry) int {
306+
return cmp.Compare(a.op.OperationID, b.op.OperationID)
301307
})
302308

309+
result := make([]*GatheredSchema, 0, len(ops))
303310
for _, entry := range ops {
304311
result = append(result, &GatheredSchema{
305312
Path: SchemaPath{"paths", entry.path, entry.method, "x-client-response-wrapper"},

pkg/codegen/merge_schemas.go

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package codegen
33
import (
44
"errors"
55
"fmt"
6+
"maps"
67
"strings"
78

89
"github.com/getkin/kin-openapi/openapi3"
@@ -87,14 +88,10 @@ func mergeAllOf(allOf []*openapi3.SchemaRef) (openapi3.Schema, error) {
8788
func mergeOpenapiSchemas(s1, s2 openapi3.Schema, allOf bool) (openapi3.Schema, error) {
8889
var result openapi3.Schema
8990

90-
result.Extensions = make(map[string]any)
91-
for k, v := range s1.Extensions {
92-
result.Extensions[k] = v
93-
}
94-
for k, v := range s2.Extensions {
95-
// TODO: Check for collisions
96-
result.Extensions[k] = v
97-
}
91+
result.Extensions = make(map[string]any, len(s1.Extensions)+len(s2.Extensions))
92+
maps.Copy(result.Extensions, s1.Extensions)
93+
// TODO: Check for collisions
94+
maps.Copy(result.Extensions, s2.Extensions)
9895

9996
result.OneOf = append(s1.OneOf, s2.OneOf...)
10097

@@ -195,14 +192,10 @@ func mergeOpenapiSchemas(s1, s2 openapi3.Schema, allOf bool) (openapi3.Schema, e
195192
result.Required = append(s1.Required, s2.Required...)
196193

197194
// We merge all properties
198-
result.Properties = make(map[string]*openapi3.SchemaRef)
199-
for k, v := range s1.Properties {
200-
result.Properties[k] = v
201-
}
202-
for k, v := range s2.Properties {
203-
// TODO: detect conflicts
204-
result.Properties[k] = v
205-
}
195+
result.Properties = make(map[string]*openapi3.SchemaRef, len(s1.Properties)+len(s2.Properties))
196+
maps.Copy(result.Properties, s1.Properties)
197+
// TODO: detect conflicts
198+
maps.Copy(result.Properties, s2.Properties)
206199

207200
if isAdditionalPropertiesExplicitFalse(&s1) || isAdditionalPropertiesExplicitFalse(&s2) {
208201
result.WithoutAdditionalProperties()

0 commit comments

Comments
 (0)