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
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ module github.com/deepmap/oapi-codegen

require (
github.com/apapsch/go-jsonmerge/v2 v2.0.0
github.com/getkin/kin-openapi v0.112.0
github.com/getkin/kin-openapi v0.114.0
github.com/gin-gonic/gin v1.8.2
github.com/go-chi/chi/v5 v5.0.8
github.com/golangci/lint-1 v0.0.0-20181222135242-d2cdd8c08219
Expand Down Expand Up @@ -45,6 +45,7 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
github.com/pelletier/go-toml/v2 v2.0.6 // indirect
github.com/perimeterx/marshmallow v1.1.4 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/objx v0.5.0 // indirect
Expand Down
8 changes: 6 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.0-20210816181553-5444fa50b93d/go.mod h1:tmAIfUFEirG/Y8jhZ9M+h36obRZAk/1fcSpXwAVlfqE=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 h1:YLtO71vCjJRCBcrPMtQ9nqBsqpA1m5sE92cU+pd5Mcc=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeCxkaw7y45JueMRL4DIyJDKs=
github.com/getkin/kin-openapi v0.112.0 h1:lnLXx3bAG53EJVI4E/w0N8i1Y/vUZUEsnrXkgnfn7/Y=
github.com/getkin/kin-openapi v0.112.0/go.mod h1:QtwUNt0PAAgIIBEvFWYfB7dfngxtAaqCX1zYHMZDeK8=
github.com/getkin/kin-openapi v0.114.0 h1:ar7QiJpDdlR+zSyPjrLf8mNnpoFP/lI90XcywMCFNe8=
github.com/getkin/kin-openapi v0.114.0/go.mod h1:l5e9PaFUo9fyLJCPGQeXI2ML8c3P8BHOEV2VaAVf/pc=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.8.2 h1:UzKToD9/PoFj/V4rvlKqTRKnQYyz8Sc1MJlv4JHPtvY=
Expand All @@ -31,6 +31,8 @@ github.com/go-playground/universal-translator v0.18.0 h1:82dyy6p4OuJq4/CByFNOn/j
github.com/go-playground/universal-translator v0.18.0/go.mod h1:UvRDBj+xPUEGrFYl+lu/H90nyDXpg0fqeB/AQUGNTVA=
github.com/go-playground/validator/v10 v10.11.1 h1:prmOlTVv+YjZjmRmNSF3VmspqJIxJWXmqUsHwfTRRkQ=
github.com/go-playground/validator/v10 v10.11.1/go.mod h1:i+3WkQ1FvaUjjxh1kSvIA4dMGDBiPU55YFDl0WbKdWU=
github.com/go-test/deep v1.0.8 h1:TDsG77qcSprGbC6vTN8OuXp5g+J+b5Pcguhf7Zt61VM=
github.com/go-test/deep v1.0.8/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE=
github.com/goccy/go-json v0.9.7/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/goccy/go-json v0.9.11 h1:/pAaQDLHEoCq/5FFmSKBswWmK6H0e8g4159Kc/X/nqk=
github.com/goccy/go-json v0.9.11/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
Expand Down Expand Up @@ -102,6 +104,8 @@ github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwd
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/pelletier/go-toml/v2 v2.0.6 h1:nrzqCb7j9cDFj2coyLNLaZuJTLjWjlaz6nvTvIwycIU=
github.com/pelletier/go-toml/v2 v2.0.6/go.mod h1:eumQOmlWiOPt5WriQQqoM5y18pDHwha2N+QD+EUNTek=
github.com/perimeterx/marshmallow v1.1.4 h1:pZLDH9RjlLGGorbXhcaQLhfuV0pFMNfPO55FuFkxqLw=
github.com/perimeterx/marshmallow v1.1.4/go.mod h1:dsXbUu8CRzfYP5a87xpp0xq9S3u0Vchtcl8we9tYaXw=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
Expand Down
4 changes: 2 additions & 2 deletions internal/test/components/components.gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions internal/test/components/components.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ components:
additionalProperties:
$ref: '#/components/schemas/SchemaObject'
OneOfObject1:
description: oneOf with references and no disciminator
description: oneOf with references and no discriminator
oneOf:
- $ref: '#/components/schemas/OneOfVariant1'
- $ref: '#/components/schemas/OneOfVariant2'
Expand Down Expand Up @@ -244,7 +244,7 @@ components:
- $ref: '#/components/schemas/OneOfVariant2'
- $ref: '#/components/schemas/OneOfVariant3'
OneOfObject5:
description: oneOf with disciminator but no mapping
description: oneOf with discriminator but no mapping
oneOf:
- $ref: '#/components/schemas/OneOfVariant4'
- $ref: '#/components/schemas/OneOfVariant5'
Expand Down
12 changes: 6 additions & 6 deletions internal/test/issues/issue-grab_import_names/issue.gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

52 changes: 31 additions & 21 deletions pkg/codegen/codegen.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,9 +201,12 @@ func Generate(spec *openapi3.T, opts Configuration) (string, error) {

var strictServerOut string
if opts.Generate.Strict {
responses, err := GenerateResponseDefinitions("", spec.Components.Responses)
if err != nil {
return "", fmt.Errorf("error generation response definitions for schema: %w", err)
var responses []ResponseDefinition
if spec.Components != nil {
responses, err = GenerateResponseDefinitions("", spec.Components.Responses)
if err != nil {
return "", fmt.Errorf("error generation response definitions for schema: %w", err)
}
}
strictServerResponses, err := GenerateStrictResponses(t, responses)
if err != nil {
Expand Down Expand Up @@ -339,28 +342,31 @@ func Generate(spec *openapi3.T, opts Configuration) (string, error) {
}

func GenerateTypeDefinitions(t *template.Template, swagger *openapi3.T, ops []OperationDefinition, excludeSchemas []string) (string, error) {
schemaTypes, err := GenerateTypesForSchemas(t, swagger.Components.Schemas, excludeSchemas)
if err != nil {
return "", fmt.Errorf("error generating Go types for component schemas: %w", err)
}
var allTypes []TypeDefinition
if swagger.Components != nil {
schemaTypes, err := GenerateTypesForSchemas(t, swagger.Components.Schemas, excludeSchemas)
if err != nil {
return "", fmt.Errorf("error generating Go types for component schemas: %w", err)
}

paramTypes, err := GenerateTypesForParameters(t, swagger.Components.Parameters)
if err != nil {
return "", fmt.Errorf("error generating Go types for component parameters: %w", err)
}
allTypes := append(schemaTypes, paramTypes...)
paramTypes, err := GenerateTypesForParameters(t, swagger.Components.Parameters)
if err != nil {
return "", fmt.Errorf("error generating Go types for component parameters: %w", err)
}
allTypes = append(schemaTypes, paramTypes...)

responseTypes, err := GenerateTypesForResponses(t, swagger.Components.Responses)
if err != nil {
return "", fmt.Errorf("error generating Go types for component responses: %w", err)
}
allTypes = append(allTypes, responseTypes...)
responseTypes, err := GenerateTypesForResponses(t, swagger.Components.Responses)
if err != nil {
return "", fmt.Errorf("error generating Go types for component responses: %w", err)
}
allTypes = append(allTypes, responseTypes...)

bodyTypes, err := GenerateTypesForRequestBodies(t, swagger.Components.RequestBodies)
if err != nil {
return "", fmt.Errorf("error generating Go types for component request bodies: %w", err)
bodyTypes, err := GenerateTypesForRequestBodies(t, swagger.Components.RequestBodies)
if err != nil {
return "", fmt.Errorf("error generating Go types for component request bodies: %w", err)
}
allTypes = append(allTypes, bodyTypes...)
}
allTypes = append(allTypes, bodyTypes...)

// Go through all operations, and add their types to allTypes, so that we can
// scan all of them for enums. Operation definitions are handled differently
Expand Down Expand Up @@ -893,6 +899,10 @@ func OperationImports(ops []OperationDefinition) (map[string]goImport, error) {

func GetTypeDefinitionsImports(swagger *openapi3.T, excludeSchemas []string) (map[string]goImport, error) {
res := map[string]goImport{}
if swagger.Components == nil {
return res, nil
}

schemaImports, err := GetSchemaImports(swagger.Components.Schemas, excludeSchemas)
if err != nil {
return nil, err
Expand Down
48 changes: 19 additions & 29 deletions pkg/codegen/extension.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package codegen

import (
"encoding/json"
"fmt"
)

Expand All @@ -22,15 +21,10 @@ const (
)

func extString(extPropValue interface{}) (string, error) {
raw, ok := extPropValue.(json.RawMessage)
str, ok := extPropValue.(string)
if !ok {
return "", fmt.Errorf("failed to convert type: %T", extPropValue)
}
var str string
if err := json.Unmarshal(raw, &str); err != nil {
return "", fmt.Errorf("failed to unmarshal json: %w", err)
}

return str, nil
}
func extTypeName(extPropValue interface{}) (string, error) {
Expand All @@ -42,53 +36,49 @@ func extParseGoFieldName(extPropValue interface{}) (string, error) {
}

func extParseOmitEmpty(extPropValue interface{}) (bool, error) {
raw, ok := extPropValue.(json.RawMessage)
omitEmpty, ok := extPropValue.(bool)
if !ok {
return false, fmt.Errorf("failed to convert type: %T", extPropValue)
}

var omitEmpty bool
if err := json.Unmarshal(raw, &omitEmpty); err != nil {
return false, fmt.Errorf("failed to unmarshal json: %w", err)
}

return omitEmpty, nil
}

func extExtraTags(extPropValue interface{}) (map[string]string, error) {
raw, ok := extPropValue.(json.RawMessage)
tagsI, ok := extPropValue.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("failed to convert type: %T", extPropValue)
}
var tags map[string]string
if err := json.Unmarshal(raw, &tags); err != nil {
return nil, fmt.Errorf("failed to unmarshal json: %w", err)
tags := make(map[string]string, len(tagsI))
for k, v := range tagsI {
vs, ok := v.(string)
if !ok {
return nil, fmt.Errorf("failed to convert type: %T", v)
}
tags[k] = vs
}
return tags, nil
}

func extParseGoJsonIgnore(extPropValue interface{}) (bool, error) {
raw, ok := extPropValue.(json.RawMessage)
goJsonIgnore, ok := extPropValue.(bool)
if !ok {
return false, fmt.Errorf("failed to convert type: %T", extPropValue)
}

var goJsonIgnore bool
if err := json.Unmarshal(raw, &goJsonIgnore); err != nil {
return false, fmt.Errorf("failed to unmarshal json: %w", err)
}

return goJsonIgnore, nil
}

func extParseEnumVarNames(extPropValue interface{}) ([]string, error) {
raw, ok := extPropValue.(json.RawMessage)
namesI, ok := extPropValue.([]interface{})
if !ok {
return nil, fmt.Errorf("failed to convert type: %T", extPropValue)
}
var names []string
if err := json.Unmarshal(raw, &names); err != nil {
return nil, fmt.Errorf("failed to unmarshal json: %w", err)
names := make([]string, len(namesI))
for i, v := range namesI {
vs, ok := v.(string)
if !ok {
return nil, fmt.Errorf("failed to convert type: %T", v)
}
names[i] = vs
}
return names, nil
}
16 changes: 11 additions & 5 deletions pkg/codegen/extension_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (

func Test_extTypeName(t *testing.T) {
type args struct {
extPropValue interface{}
extPropValue json.RawMessage
}
tests := []struct {
name string
Expand All @@ -24,21 +24,27 @@ func Test_extTypeName(t *testing.T) {
wantErr: false,
},
{
name: "type conversion error",
name: "nil conversion error",
args: args{nil},
want: "",
wantErr: true,
},
{
name: "json unmarshal error",
args: args{json.RawMessage("invalid json format")},
name: "type conversion error",
args: args{json.RawMessage(`12`)},
want: "",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := extTypeName(tt.args.extPropValue)
// kin-openapi no longer returns these as RawMessage
var extPropValue interface{}
if tt.args.extPropValue != nil {
err := json.Unmarshal(tt.args.extPropValue, &extPropValue)
assert.NoError(t, err)
}
got, err := extTypeName(extPropValue)
if tt.wantErr {
assert.Error(t, err)
return
Expand Down
8 changes: 4 additions & 4 deletions pkg/codegen/merge_schemas.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,11 +212,11 @@ func mergeOpenapiSchemas(s1, s2 openapi3.Schema, allOf bool) (openapi3.Schema, e
if SchemaHasAdditionalProperties(&s1) && SchemaHasAdditionalProperties(&s2) {
return openapi3.Schema{}, errors.New("merging two schemas with additional properties, this is unhandled")
}
if s1.AdditionalProperties != nil {
result.AdditionalProperties = s1.AdditionalProperties
if s1.AdditionalProperties.Schema != nil {
result.AdditionalProperties.Schema = s1.AdditionalProperties.Schema
}
if s2.AdditionalProperties != nil {
result.AdditionalProperties = s2.AdditionalProperties
if s2.AdditionalProperties.Schema != nil {
result.AdditionalProperties.Schema = s2.AdditionalProperties.Schema
}

// Allow discriminators for allOf merges, but disallow for one/anyOfs.
Expand Down
16 changes: 8 additions & 8 deletions pkg/codegen/operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,8 @@ func (pd ParameterDefinition) GoVariableName() string {

func (pd ParameterDefinition) GoName() string {
goName := pd.ParamName
if _, ok := pd.Spec.ExtensionProps.Extensions[extGoName]; ok {
if extGoFieldName, err := extParseGoFieldName(pd.Spec.ExtensionProps.Extensions[extGoName]); err == nil {
if _, ok := pd.Spec.Extensions[extGoName]; ok {
if extGoFieldName, err := extParseGoFieldName(pd.Spec.Extensions[extGoName]); err == nil {
goName = extGoFieldName
}
}
Expand Down Expand Up @@ -825,12 +825,12 @@ func GenerateParamsTypes(op OperationDefinition) []TypeDefinition {
})
}
prop := Property{
Description: param.Spec.Description,
JsonFieldName: param.ParamName,
Required: param.Required,
Schema: pSchema,
NeedsFormTag: param.Style() == "form",
ExtensionProps: &param.Spec.ExtensionProps,
Description: param.Spec.Description,
JsonFieldName: param.ParamName,
Required: param.Required,
Schema: pSchema,
NeedsFormTag: param.Style() == "form",
Extensions: param.Spec.Extensions,
}
s.Properties = append(s.Properties, prop)
}
Expand Down
8 changes: 6 additions & 2 deletions pkg/codegen/prune.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func walkSwagger(swagger *openapi3.T, doFn func(RefWrapper) (bool, error)) error
}
}

_ = walkComponents(&swagger.Components, doFn)
_ = walkComponents(swagger.Components, doFn)

return nil
}
Expand Down Expand Up @@ -144,7 +144,7 @@ func walkSchemaRef(ref *openapi3.SchemaRef, doFn func(RefWrapper) (bool, error))
_ = walkSchemaRef(ref, doFn)
}

_ = walkSchemaRef(ref.Value.AdditionalProperties, doFn)
_ = walkSchemaRef(ref.Value.AdditionalProperties.Schema, doFn)

return nil
}
Expand Down Expand Up @@ -392,6 +392,10 @@ func findComponentRefs(swagger *openapi3.T) []string {
}

func removeOrphanedComponents(swagger *openapi3.T, refs []string) int {
if swagger.Components == nil {
return 0
}

countRemoved := 0

for key := range swagger.Components.Schemas {
Expand Down
Loading