Skip to content

Commit ea3c6b7

Browse files
committed
feat: format JSON output to stabilize its output
protojson doesn't guarantee stable JSON output, and deliberately introduce minor differences in output to prevent the illusion of this, see [1]. As this tool generates code, we'd like to keep the output as stable as possible, use the advice in [1] and [2] (at the end) and run the generated JSON through a formatter before including it in the generated code. This also changes from using the error ignoring Format() function to Marshal(). [1]: https://developers.google.com/protocol-buffers/docs/reference/go/faq#unstable-json [2]: golang/protobuf#1121 (comment)
1 parent 28ea7fb commit ea3c6b7

File tree

2 files changed

+24
-13
lines changed

2 files changed

+24
-13
lines changed

cmd/protoc-gen-go-grpc-service-config/main.go

+15-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package main
22

33
import (
4+
"bytes"
45
"encoding/json"
56
"flag"
67
"fmt"
@@ -80,6 +81,19 @@ func (p *plugin) generateFromProto() error {
8081
if generatedPackages[file.Desc.Package()] {
8182
return fmt.Errorf("package %s has multiple default_service_config annotations", file.Desc.Package())
8283
}
84+
85+
jsonServiceConfig, err := protojson.MarshalOptions{
86+
Multiline: true,
87+
}.Marshal(defaultServiceConfig)
88+
if err != nil {
89+
return err
90+
}
91+
92+
var formattedServiceConfig bytes.Buffer
93+
if err := json.Indent(&formattedServiceConfig, jsonServiceConfig, "", " "); err != nil {
94+
return err
95+
}
96+
8397
generatedPackages[file.Desc.Package()] = true
8498
g := p.gen.NewGeneratedFile(
8599
filepath.Dir(file.GeneratedFilenamePrefix)+
@@ -92,10 +106,7 @@ func (p *plugin) generateFromProto() error {
92106
g.P()
93107
g.P("// DefaultServiceConfig is the default service config for all services in the package.")
94108
g.P("// Source: ", file.Desc.Path(), ".")
95-
g.P("const DefaultServiceConfig = `", protojson.MarshalOptions{
96-
Multiline: true,
97-
Indent: " ",
98-
}.Format(defaultServiceConfig), "`")
109+
g.P("const DefaultServiceConfig = `", formattedServiceConfig.String(), "`")
99110
}
100111
return nil
101112
}

internal/gen/proto/einride/serviceconfig/example/v1/example_grpc_service_config.pb.go

+9-9
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)