Skip to content

Commit 8dc2584

Browse files
authored
Fix field order in yaml generated OAS file (#3084)
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.
1 parent 7542c08 commit 8dc2584

File tree

1 file changed

+17
-6
lines changed
  • protoc-gen-openapiv2/internal/genopenapi

1 file changed

+17
-6
lines changed

protoc-gen-openapiv2/internal/genopenapi/types.go

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"fmt"
77

88
"github.com/grpc-ecosystem/grpc-gateway/v2/internal/descriptor"
9+
"gopkg.in/yaml.v3"
910
)
1011

1112
type param struct {
@@ -259,13 +260,23 @@ type keyVal struct {
259260
type openapiSchemaObjectProperties []keyVal
260261

261262
func (p openapiSchemaObjectProperties) MarshalYAML() (interface{}, error) {
262-
m := make(map[string]interface{}, len(p))
263-
264-
for _, v := range p {
265-
m[v.Key] = v.Value
263+
n := yaml.Node{
264+
Kind: yaml.MappingNode,
265+
Content: make([]*yaml.Node, len(p)*2),
266266
}
267-
268-
return m, nil
267+
for i, v := range p {
268+
keyNode := yaml.Node{}
269+
if err := keyNode.Encode(v.Key); err != nil {
270+
return nil, err
271+
}
272+
valueNode := yaml.Node{}
273+
if err := valueNode.Encode(v.Value); err != nil {
274+
return nil, err
275+
}
276+
n.Content[i*2+0] = &keyNode
277+
n.Content[i*2+1] = &valueNode
278+
}
279+
return n, nil
269280
}
270281

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

0 commit comments

Comments
 (0)