Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add message option to serialize as well known JSON type #739

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,14 @@ module github.com/gogo/protobuf
go 1.15

require (
github.com/golang/protobuf v1.5.2 // indirect
github.com/kisielk/errcheck v1.5.0 // indirect
github.com/kisielk/gotool v1.0.0 // indirect
golang.org/x/net v0.0.0-20211020060615-d418f374d309 // indirect
golang.org/x/sys v0.0.0-20211020174200-9d6173849985 // indirect
golang.org/x/text v0.3.7 // indirect
golang.org/x/tools v0.0.0-20210106214847-113979e3529a // indirect
google.golang.org/genproto v0.0.0-20211020151524-b7c3a969101a // indirect
google.golang.org/grpc v1.41.0 // indirect
google.golang.org/protobuf v1.27.1 // indirect
)
125 changes: 125 additions & 0 deletions go.sum

Large diffs are not rendered by default.

179 changes: 96 additions & 83 deletions gogoproto/gogo.pb.go

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions gogoproto/gogo.proto
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ extend google.protobuf.MessageOptions {

optional bool goproto_sizecache = 64034;
optional bool goproto_unkeyed = 64035;
optional string json_well_known_type = 64036;
}

extend google.protobuf.FieldOptions {
Expand Down
16 changes: 14 additions & 2 deletions gogoproto/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,10 @@

package gogoproto

import google_protobuf "github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
import proto "github.com/gogo/protobuf/proto"
import (
"github.com/gogo/protobuf/proto"
google_protobuf "github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
)

func IsEmbed(field *google_protobuf.FieldDescriptorProto) bool {
return proto.GetBoolExtension(field.Options, E_Embed, false)
Expand Down Expand Up @@ -147,6 +149,16 @@ func HasTypeDecl(file *google_protobuf.FileDescriptorProto, message *google_prot
return proto.GetBoolExtension(message.Options, E_Typedecl, proto.GetBoolExtension(file.Options, E_TypedeclAll, true))
}

func GetWellKnownType(message *google_protobuf.DescriptorProto) *string {
if message != nil && message.Options != nil {
v, err := proto.GetExtension(message.Options, E_JsonWellKnownType)
if err == nil && v.(*string) != nil {
return v.(*string)
}
}
return nil
}

func GetCustomType(field *google_protobuf.FieldDescriptorProto) string {
if field == nil {
return ""
Expand Down
126 changes: 126 additions & 0 deletions plugin/jsonwkt/jsonwkt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// Protocol Buffers for Go with Gadgets
//
// Copyright (c) 2013, The GoGo Authors. All rights reserved.
// http://github.com/gogo/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/*
This plugin will mark a generated type as "well known" to the gogo proto JSON marshaler/unmarshaler which will
serialize the value without the wrapper. This happens by default for google.protobuf.*Value message types.

# Without jsonwkt
message UUID {
string value = 1;
}

message MyType {
UUID user_uuid = 1;
}

MyType would be serialized to JSON as:

{
"user_uuid": {
"value": "8dfab8c2-7916-477f-bbd6-c9fc00dc4158"
}
}

# With jsonwkt
message UUID {
option (gogoproto.json_well_known_type) = "StringValue";
string value = 1;
}

message MyType {
UUID user_uuid = 1;
}

MyType would be serialized to JSON as:

{
"user_uuid": "8dfab8c2-7916-477f-bbd6-c9fc00dc4158"
}
*/

package jsonwkt

import (
"github.com/gogo/protobuf/gogoproto"
"github.com/gogo/protobuf/protoc-gen-gogo/generator"
)

var wellKnownTypes = map[string]bool{
"Duration": true,
"Timestamp": true,
"Value": true,
"ListValue": true,
"DoubleValue": true,
"FloatValue": true,
"Int64Value": true,
"UInt64Value": true,
"Int32Value": true,
"UInt32Value": true,
"BoolValue": true,
"StringValue": true,
"BytesValue": true,
}

type jsonwkt struct {
*generator.Generator
generator.PluginImports
}

func NewJsonWKT() *jsonwkt {
return &jsonwkt{}
}

func (p *jsonwkt) Name() string {
return "jsonwkt"
}

func (p *jsonwkt) Init(g *generator.Generator) {
p.Generator = g
}

func (p *jsonwkt) Generate(file *generator.FileDescriptor) {
p.PluginImports = generator.NewPluginImports(p.Generator)
for _, message := range file.Messages() {
wellKnownType := gogoproto.GetWellKnownType(message.DescriptorProto)
if wellKnownType == nil {
continue
}
if _, ok := wellKnownTypes[*wellKnownType]; !ok {
p.Generator.Fail("invalid json_well_known_type option %s", *wellKnownType)
continue
}

ccTypeName := generator.CamelCaseSlice(message.TypeName())
p.Generator.P("func (*", ccTypeName, `) XXX_WellKnownType() string { return "`, *wellKnownType, `" }`)
}
}

func init() {
generator.RegisterPlugin(NewJsonWKT())
}
79 changes: 79 additions & 0 deletions plugin/jsonwkt/jsonwkttest.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Protocol Buffers for Go with Gadgets
//
// Copyright (c) 2013, The GoGo Authors. All rights reserved.
// http://github.com/gogo/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package jsonwkt

import (
"github.com/gogo/protobuf/gogoproto"
"github.com/gogo/protobuf/plugin/testgen"
"github.com/gogo/protobuf/protoc-gen-gogo/generator"
)

type test struct {
*generator.Generator
}

func NewTest(g *generator.Generator) testgen.TestPlugin {
return &test{g}
}

func (p *test) Generate(imports generator.PluginImports, file *generator.FileDescriptor) bool {
used := false
randPkg := imports.NewImport("math/rand")
timePkg := imports.NewImport("time")
testingPkg := imports.NewImport("testing")
for _, message := range file.Messages() {
wellKnownType := gogoproto.GetWellKnownType(message.DescriptorProto)
if wellKnownType == nil {
continue
}

if gogoproto.HasTestGen(file.FileDescriptorProto, message.DescriptorProto) {
ccTypeName := generator.CamelCaseSlice(message.TypeName())
used = true
p.P(`func Test`, ccTypeName, `JsonWKT(t *`, testingPkg.Use(), `.T) {`)
p.In()
p.P(`popr := `, randPkg.Use(), `.New(`, randPkg.Use(), `.NewSource(`, timePkg.Use(), `.Now().UnixNano()))`)
p.P(`p := NewPopulated`, ccTypeName, `(popr, false)`)

p.P(`_, ok := interface{}(p).(interface { XXX_WellKnownType() string })`)
p.P(`if !ok {`)
p.In()
p.P(`t.Fatalf("Type `, ccTypeName, ` should implement XXX_WellKnownType but did not")`)
p.Out()
p.P(`}`)
p.Out()
p.P(`}`)
}
}
return used
}

func init() {
testgen.RegisterTestPlugin(NewTest)
}
4 changes: 2 additions & 2 deletions protoc-gen-gogo/generator/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ import (

"github.com/gogo/protobuf/gogoproto"
"github.com/gogo/protobuf/proto"
descriptor "github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
"github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
"github.com/gogo/protobuf/protoc-gen-gogo/generator/internal/remap"
plugin "github.com/gogo/protobuf/protoc-gen-gogo/plugin"
)
Expand Down Expand Up @@ -548,7 +548,7 @@ func (g *Generator) CommandLineParameters(parameter string) {
if pluginList == "none" {
pluginList = ""
}
gogoPluginNames := []string{"unmarshal", "unsafeunmarshaler", "union", "stringer", "size", "protosizer", "populate", "marshalto", "unsafemarshaler", "gostring", "face", "equal", "enumstringer", "embedcheck", "description", "defaultcheck", "oneofcheck", "compare"}
gogoPluginNames := []string{"unmarshal", "unsafeunmarshaler", "union", "stringer", "size", "protosizer", "populate", "marshalto", "unsafemarshaler", "gostring", "face", "equal", "enumstringer", "embedcheck", "description", "defaultcheck", "oneofcheck", "compare", "jsonwkt"}
pluginList = strings.Join(append(gogoPluginNames, pluginList), "+")
if pluginList != "" {
// Amend the set of plugins.
Expand Down
Loading