Skip to content

Commit

Permalink
feat: deterministic proto writer
Browse files Browse the repository at this point in the history
since iteration of go maps are not deterministic, some sorting is required
to ensure a proper order.

non-deterministic ordering in proto files may lead to significant
unnescessary diffs if generated protos are checked in.
  • Loading branch information
toumorokoshi committed Sep 28, 2023
1 parent db05459 commit a5575d5
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 13 deletions.
24 changes: 12 additions & 12 deletions examples/bookstore.yaml.output.proto
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@ import "google/protobuf/empty.proto";

option go_package = "/bookstore";

message Author {
string path = 1;
}

message ReadAuthorRequest {
string path = 1;
}

message Book {
string path = 1;
}
Expand Down Expand Up @@ -54,15 +62,11 @@ message ListPublisherResponse {
repeated Publisher resources = 1;
}

message Author {
string path = 1;
}

message ReadAuthorRequest {
string path = 1;
}

service Bookstore {
rpc ReadAuthor ( ReadAuthorRequest ) returns ( Author ) {
option (google.api.http) = { get: "/{path=publisher/*/author/*}" };
}

rpc CreateBook ( CreateBookRequest ) returns ( Book ) {
option (google.api.http) = { post: "/{parent=publisher/*}/book" };
}
Expand Down Expand Up @@ -90,8 +94,4 @@ service Bookstore {
rpc ListPublisher ( ListPublisherRequest ) returns ( ListPublisherResponse ) {
option (google.api.http) = { get: "/publisher" };
}

rpc ReadAuthor ( ReadAuthorRequest ) returns ( Author ) {
option (google.api.http) = { get: "/{path=publisher/*/author/*}" };
}
}
16 changes: 15 additions & 1 deletion writer/proto/proto.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package proto
import (
"bytes"
"fmt"
"sort"
"strings"

"github.com/aep-dev/aepc/parser"
Expand Down Expand Up @@ -46,7 +47,7 @@ func WriteServiceToProto(ps *parser.ParsedService) ([]byte, error) {
fb.SetOptions(fo)
sb := builder.NewService(pServiceName)
fb.AddService(sb)
for _, r := range ps.ResourceByType {
for _, r := range getSortedResources(ps.ResourceByType) {
err := AddResource(r, fb, sb)
if err != nil {
return []byte{}, fmt.Errorf("adding resource %v failed: %w", r.Kind, err)
Expand All @@ -69,3 +70,16 @@ func toProtoServiceName(serviceName string) string {
parts := strings.SplitN(serviceName, ".", 2)
return capitalizer.String(parts[0])
}

func getSortedResources(prsByString map[string]*parser.ParsedResource) []*parser.ParsedResource {
keys := []string{}
for k := range prsByString {
keys = append(keys, k)
}
sort.Strings(keys)
resources := make([]*parser.ParsedResource, 0, len(keys))
for _, k := range keys {
resources = append(resources, prsByString[k])
}
return resources
}

0 comments on commit a5575d5

Please sign in to comment.