Skip to content

Commit

Permalink
Fix field order in yaml generated OAS file (#3084)
Browse files Browse the repository at this point in the history
Today, the field order in swagger.json files is consistent with
the actual order of fields in the .proto messages.
(i.e. not by protobuf index/tag and not alphabetically sorted, but
actually in the same order inside the protobuf)

However, in swagger.yaml files the order becomes alphabetical due to
automatic map[string]interface{} ordering in yaml marshaling.
This gives less control over generated documentation (Redoc) from
those yaml files.

This commit uses yaml.Node introduces in yaml.v3 to keep the same
field order in yaml generated files as well.
  • Loading branch information
same-id committed Dec 21, 2022
1 parent 7542c08 commit 8dc2584
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions protoc-gen-openapiv2/internal/genopenapi/types.go
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"

"github.com/grpc-ecosystem/grpc-gateway/v2/internal/descriptor"
"gopkg.in/yaml.v3"
)

type param struct {
Expand Down Expand Up @@ -259,13 +260,23 @@ type keyVal struct {
type openapiSchemaObjectProperties []keyVal

func (p openapiSchemaObjectProperties) MarshalYAML() (interface{}, error) {
m := make(map[string]interface{}, len(p))

for _, v := range p {
m[v.Key] = v.Value
n := yaml.Node{
Kind: yaml.MappingNode,
Content: make([]*yaml.Node, len(p)*2),
}

return m, nil
for i, v := range p {
keyNode := yaml.Node{}
if err := keyNode.Encode(v.Key); err != nil {
return nil, err
}
valueNode := yaml.Node{}
if err := valueNode.Encode(v.Value); err != nil {
return nil, err
}
n.Content[i*2+0] = &keyNode
n.Content[i*2+1] = &valueNode
}
return n, nil
}

func (op openapiSchemaObjectProperties) MarshalJSON() ([]byte, error) {
Expand Down

0 comments on commit 8dc2584

Please sign in to comment.