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
41 changes: 41 additions & 0 deletions _testdata/positive/embed_struct_aliases.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
openapi: 3.0.3
info:
title: Embed struct aliases
version: 1.0.0
paths:
/pets:
post:
operationId: createPet
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
application/x-www-form-urlencoded:
schema:
$ref: '#/components/schemas/Pet'
responses:
"200":
description: Existing pet
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
"201":
description: Created pet
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
components:
schemas:
Pet:
type: object
required: [name]
properties:
name:
type: string
maxLength: 10
tag:
type: string
3 changes: 3 additions & 0 deletions examples/ex_github/oas_json_gen.go

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

6 changes: 6 additions & 0 deletions examples/ex_openai_v2/oas_json_gen.go

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

4 changes: 4 additions & 0 deletions gen/_template/faker/faker_alias.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
func (s *{{ $.Name }}) SetFake() {
var unwrapped {{ $.AliasTo.Go }}
{{- template "faker/faker" elem $.AliasTo "unwrapped" }}
{{- if $.AliasEmbed }}
*s = {{ $.Go }}{unwrapped}
{{- else }}
*s = {{ $.Go }}(unwrapped)
{{- end }}
}
{{- end }}
1 change: 1 addition & 0 deletions gen/_template/json/decode.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ if err := d.Arr(func(d *jx.Decoder) error {
{{- if $t.NilSemantic.Null -}}
switch tt := d.Next(); tt {
case jx.Null:
{{ $.Var }} = nil
if err := d.Skip(); err != nil {
return err
}
Expand Down
10 changes: 9 additions & 1 deletion gen/_template/json/encoders_alias.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@
{{- $a := $.AliasTo }}
// Encode encodes {{ $.Name }} as json.
func (s {{ $.ReadOnlyReceiver }}) Encode(e *jx.Encoder) {
{{- if $a.DoPassByPointer }}
{{- if and $.AliasEmbed $a.DoPassByPointer }}
unwrapped := &s.{{ $a.Go }}
{{- else if $.AliasEmbed }}
unwrapped := s.{{ $a.Go }}
{{- else if $a.DoPassByPointer }}
unwrapped := (*{{ $a.Go }})(s)
{{- else }}
unwrapped := {{ $a.Go }}(s)
Expand All @@ -29,7 +33,11 @@ func (s *{{ $.Name }}) Decode(d *jx.Decoder) error {
}(); err != nil {
return errors.Wrap(err, "alias")
}
{{- if $.AliasEmbed }}
*s = {{ $.Go }}{unwrapped}
{{- else }}
*s = {{ $.Go }}(unwrapped)
{{- end }}
return nil
}

Expand Down
4 changes: 4 additions & 0 deletions gen/_template/request_decode.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,11 @@ func (s *{{ if $op.WebhookInfo }}Webhook{{ end }}Server) decode{{ $op.Name }}Req
{
var unwrapped {{ $t.AliasTo.Go -}}
{{ template "decode_form_request" elem $t.AliasTo "unwrapped" }}
{{- if $t.AliasEmbed }}
{{ $v }} = {{ $t.Go }}{unwrapped}
{{- else }}
{{ $v }} = {{ $t.Go }}(unwrapped)
{{- end }}
}
{{- else if $t.IsGeneric }}
{
Expand Down
6 changes: 6 additions & 0 deletions gen/_template/schema/alias.tmpl
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
{{- /*gotype: github.com/ogen-go/ogen/gen/ir.Type*/ -}}
{{- define "schema/alias" }}
{{- if $.AliasEmbed }}
type {{ $.Name }} struct {
{{ $.AliasTo.Go }}
}
{{- else }}
type {{ $.Name }} {{ $.AliasTo.Go }}
{{- end }}
{{ end }}
4 changes: 4 additions & 0 deletions gen/_template/uri/decode.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,11 @@
}(); err != nil {
return err
}
{{- if $t.AliasEmbed }}
{{ $var }} = {{ $t.Go }}{ {{- $tmpVar -}} }
{{- else }}
{{ $var }} = {{ $t.Go }}({{ $tmpVar }})
{{- end }}
return nil
{{- else if $t.IsGeneric }}
var {{ $tmpVar }} {{ $t.GenericOf.Go }}
Expand Down
4 changes: 4 additions & 0 deletions gen/_template/uri/encode.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@
{{ errorf "unexpected nil semantic %s" $t.NilSemantic }}
{{- end -}}
{{- else if $t.IsAlias }}
{{- if $t.AliasEmbed }}
if unwrapped := {{ $var }}.{{ $t.AliasTo.Go }}; true {
{{- else }}
if unwrapped := {{ $t.AliasTo.Go }}({{ $var }}); true {
{{- end }}
{{- template "uri/encode" elem $t.AliasTo "unwrapped" }}
}
return nil
Expand Down
6 changes: 5 additions & 1 deletion gen/_template/validators.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,11 @@ func (s {{ $t.ReadOnlyReceiver }}) Validate() error {
}
{{- else if $t.IsAlias }}
func (s {{ $t.ReadOnlyReceiver }}) Validate() error {
{{- if $t.DoPassByPointer }}
{{- if and $t.AliasEmbed $t.DoPassByPointer }}
alias := &s.{{ $t.AliasTo.Go }}
{{- else if $t.AliasEmbed }}
alias := s.{{ $t.AliasTo.Go }}
{{- else if $t.DoPassByPointer }}
alias := ({{ $t.AliasTo.ReadOnlyReceiver }})(s)
{{- else }}
alias := ({{ $t.AliasTo.Go }})(s)
Expand Down
7 changes: 7 additions & 0 deletions gen/features.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,12 @@ var (
"debug/example_tests",
`Enables example tests generation`,
}
SchemaEmbedStructAliases = Feature{
"schema/embed_struct_aliases",
`Generates aliases of object schemas as structs embedding the original type ` +
`(type Foo struct{ Bar }) instead of defined types (type Foo Bar), ` +
`so methods of the original type are promoted. Opt-in, since it changes generated API.`,
}
NamingCamelInitialisms = Feature{
"naming/camel_initialisms",
`Applies initialism rules (ID, URL, HTTP, ...) to camelCase identifiers, ` +
Expand Down Expand Up @@ -183,5 +189,6 @@ var AllFeatures = []Feature{
OgenOtel,
OgenUnimplemented,
DebugExampleTests,
SchemaEmbedStructAliases,
NamingCamelInitialisms,
}
13 changes: 13 additions & 0 deletions gen/gen_alias_embed.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package gen

import "github.com/ogen-go/ogen/gen/ir"

// embedStructAliases marks aliases of struct types to be generated as
// structs embedding the aliased type, so its methods are promoted.
func (g *Generator) embedStructAliases() {
for _, t := range g.tstorage.types {
if t.Kind == ir.KindAlias && t.AliasTo != nil && t.AliasTo.Kind == ir.KindStruct {
t.AliasEmbed = true
}
}
}
4 changes: 4 additions & 0 deletions gen/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,10 @@ func (g *Generator) makeIR(api *openapi.API) error {
return errors.Wrap(err, "operations")
}

if g.features.Has(SchemaEmbedStructAliases) {
g.embedStructAliases()
}

// Collect types that need Equal() and Hash() methods for complex uniqueItems validation
g.collectEqualitySpecs()

Expand Down
1 change: 1 addition & 0 deletions gen/ir/type.go
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ type Type struct {
Name string // only for struct, alias, interface, enum, stream, generic, map, sum
Primitive PrimitiveType // only for primitive, enum
AliasTo *Type // only for alias
AliasEmbed bool // only for alias: generate as struct embedding AliasTo
PointerTo *Type // only for pointer
SumOf []*Type // only for sum
SumSpec SumSpec // only for sum
Expand Down
4 changes: 4 additions & 0 deletions internal/integration/_config/embed_struct_aliases.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
generator:
features:
enable:
- "schema/embed_struct_aliases"
87 changes: 87 additions & 0 deletions internal/integration/embed_struct_aliases_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package integration

import (
"context"
"net/http/httptest"
"testing"

"github.com/go-faster/jx"
"github.com/stretchr/testify/require"

api "github.com/ogen-go/ogen/internal/integration/test_embed_struct_aliases"
)

// Methods of the aliased struct are promoted to the alias.
type petGetter interface {
GetName() string
GetTag() api.OptString
}

var (
_ petGetter = (*api.CreatePetApplicationJSON)(nil)
_ petGetter = (*api.CreatePetApplicationXWwwFormUrlencoded)(nil)
_ petGetter = (*api.CreatePetOK)(nil)
_ petGetter = (*api.CreatePetCreated)(nil)
)

type embedStructAliasesHandler struct{}

func (embedStructAliasesHandler) CreatePet(_ context.Context, req api.CreatePetReq) (api.CreatePetRes, error) {
switch req := req.(type) {
case *api.CreatePetApplicationJSON:
return &api.CreatePetOK{Pet: req.Pet}, nil
case *api.CreatePetApplicationXWwwFormUrlencoded:
return &api.CreatePetCreated{Pet: req.Pet}, nil
default:
panic("unreachable")
}
}

func TestEmbedStructAliases(t *testing.T) {
pet := api.Pet{Name: "Rex", Tag: api.NewOptString("dog")}

t.Run("JSON", func(t *testing.T) {
a := require.New(t)

v := api.CreatePetOK{Pet: pet}
e := jx.GetEncoder()
v.Encode(e)
a.JSONEq(`{"name":"Rex","tag":"dog"}`, e.String())

var got api.CreatePetOK
a.NoError(got.Decode(jx.DecodeBytes(e.Bytes())))
a.Equal(v, got)
a.Equal("Rex", got.GetName())
})

t.Run("Validate", func(t *testing.T) {
a := require.New(t)

a.NoError((&api.CreatePetApplicationJSON{Pet: pet}).Validate())
a.Error((&api.CreatePetApplicationJSON{Pet: api.Pet{Name: "TooLongName"}}).Validate())
})

t.Run("Server", func(t *testing.T) {
a := require.New(t)
ctx := context.Background()

srv, err := api.NewServer(embedStructAliasesHandler{})
a.NoError(err)
s := httptest.NewServer(srv)
t.Cleanup(s.Close)

client, err := api.NewClient(s.URL, api.WithClient(s.Client()))
a.NoError(err)

res, err := client.CreatePet(ctx, &api.CreatePetApplicationJSON{Pet: pet})
a.NoError(err)
a.Equal(&api.CreatePetOK{Pet: pet}, res)

res, err = client.CreatePet(ctx, &api.CreatePetApplicationXWwwFormUrlencoded{Pet: pet})
a.NoError(err)
a.Equal(&api.CreatePetCreated{Pet: pet}, res)

_, err = client.CreatePet(ctx, &api.CreatePetApplicationJSON{Pet: api.Pet{Name: "TooLongName"}})
a.Error(err)
})
}
1 change: 1 addition & 0 deletions internal/integration/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,4 @@ package integration
//go:generate go run ../../cmd/ogen -v --clean --target test_ref_overrides ../../_testdata/positive/ref_overrides.yml
//go:generate go run ../../cmd/ogen -v --clean --target test_response_header ../../_testdata/positive/response_header.yaml
//go:generate go run ../../cmd/ogen -v --clean --config _config/security_unsupported.yml --target test_security_unsupported ../../_testdata/positive/security_unsupported.yml
//go:generate go run ../../cmd/ogen -v --clean --config _config/embed_struct_aliases.yml --target test_embed_struct_aliases ../../_testdata/positive/embed_struct_aliases.yml
8 changes: 8 additions & 0 deletions internal/integration/json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,14 @@ func TestJSONArray(t *testing.T) {
})
}
})
t.Run("DecodeNullResetsValue", func(t *testing.T) {
value := api.ArrayTest{}
require.NoError(t, value.Decode(jx.DecodeStr(`{"required":[],"nullable_required":["old"]}`)))
require.Equal(t, []string{"old"}, value.NullableRequired)

require.NoError(t, value.Decode(jx.DecodeStr(`{"required":[],"nullable_required":null}`)))
require.Nil(t, value.NullableRequired)
})
t.Run("Encode", func(t *testing.T) {
for i, tc := range []struct {
Value api.ArrayTest
Expand Down
2 changes: 2 additions & 0 deletions internal/integration/sample_api/oas_json_gen.go

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

Loading
Loading