Skip to content

Commit

Permalink
feat: format JSON output to stabilize its output
Browse files Browse the repository at this point in the history
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)
  • Loading branch information
radhus committed Aug 2, 2022
1 parent 28ea7fb commit 8de6957
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 13 deletions.
19 changes: 15 additions & 4 deletions cmd/protoc-gen-go-grpc-service-config/main.go
@@ -1,6 +1,7 @@
package main

import (
"bytes"
"encoding/json"
"flag"
"fmt"
Expand Down Expand Up @@ -80,6 +81,19 @@ func (p *plugin) generateFromProto() error {
if generatedPackages[file.Desc.Package()] {
return fmt.Errorf("package %s has multiple default_service_config annotations", file.Desc.Package())
}

jsonServiceConfig, err := protojson.MarshalOptions{
Multiline: true,
}.Marshal(defaultServiceConfig)
if err != nil {
return err
}

var formattedServiceConfig bytes.Buffer
if err := json.Indent(&formattedServiceConfig, jsonServiceConfig, "", " "); err != nil {
return err
}

generatedPackages[file.Desc.Package()] = true
g := p.gen.NewGeneratedFile(
filepath.Dir(file.GeneratedFilenamePrefix)+
Expand All @@ -92,10 +106,7 @@ func (p *plugin) generateFromProto() error {
g.P()
g.P("// DefaultServiceConfig is the default service config for all services in the package.")
g.P("// Source: ", file.Desc.Path(), ".")
g.P("const DefaultServiceConfig = `", protojson.MarshalOptions{
Multiline: true,
Indent: " ",
}.Format(defaultServiceConfig), "`")
g.P("const DefaultServiceConfig = `", formattedServiceConfig.String(), "`")
}
return nil
}
Expand Down

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

0 comments on commit 8de6957

Please sign in to comment.