Skip to content

Add new protoc-gen-alias command to allow backwards version compat #2921

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

Merged
merged 2 commits into from
May 15, 2024
Merged
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
5 changes: 5 additions & 0 deletions cmd/protoc-gen-alias/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
test: build
cd test && make clean test

build:
go install .
27 changes: 27 additions & 0 deletions cmd/protoc-gen-alias/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# protoc-gen-alias

`protoc-gen-alias` is a plugin for protoc which type alias for all messages, such that one protobuf definition can
be consumed from many Go packages

## Usage

Usage is typically through `buf`, but you can use directly.
See `test/Makefile` for example usage.

## Configuration

The plugin looks for a comment like `+cue-gen:Simple:versions:v1,v1alpha` on the package.
This will generate aliases to the current version, for all versions listed (the current version is ignored).

## Examples Of Generated Code

```go
// Code generated by protoc-gen-jsonshim. DO NOT EDIT.
type Simple = v1.Simple
type Simple_Name = v1.Simple_Name
type Simple_Number = v1.Simple_Number
type SimpleWithMap = v1.SimpleWithMap
type SimpleWithMap_Nested = v1.SimpleWithMap_Nested
type ReferencedMap = v1.ReferencedMap
type ImportedReference = v1.ImportedReference
```
107 changes: 107 additions & 0 deletions cmd/protoc-gen-alias/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// Copyright 2019 Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
"path/filepath"
"strings"

"google.golang.org/protobuf/compiler/protogen"
"google.golang.org/protobuf/types/descriptorpb"
)

func main() {
protogen.Options{}.Run(func(gen *protogen.Plugin) error {
for _, f := range gen.Files {
if !f.Generate {
continue
}
generateFile(gen, f)
}
return nil
})
}

func generateFile(gen *protogen.Plugin, file *protogen.File) {
ourVersion := filepath.Base(filepath.Dir(file.Desc.Path()))
var versions []string
for _, msg := range file.Messages {
for _, line := range strings.Split(msg.Comments.Leading.String(), "\n") {
// Looking for something like '// +cue-gen:Simple:versions:v1,v1alpha'
if strings.HasPrefix(line, "// +cue-gen:") {
items := strings.Split(line, ":")
if len(items) != 4 {
continue
}
if items[2] == "versions" {
for _, v := range strings.Split(items[3], ",") {
if v != ourVersion {
versions = append(versions, v)
}
}
}
}
}
}
if len(versions) == 0 {
return
}
base := filepath.Dir(filepath.Dir(file.Desc.Path()))
fnamePrefix := filepath.Base(file.GeneratedFilenamePrefix)
for _, aliasVersion := range versions {
filename := filepath.Join(base, aliasVersion, fnamePrefix+"_alias.gen.go")
p := gen.NewGeneratedFile(filename, file.GoImportPath)

p.P("// Code generated by protoc-gen-alias. DO NOT EDIT.")
p.P("package ", aliasVersion)
p.P(`import `, file.GoImportPath)
var processMessages func([]*protogen.Message)
var processEnums func([]*protogen.Enum)
var processOneofs func([]*protogen.Oneof)

processEnums = func(enums []*protogen.Enum) {
for _, e := range enums {
typeName := e.GoIdent.GoName
p.P(`type `, typeName, `= `, file.GoPackageName, ".", e.GoIdent)
for _, v := range e.Values {
p.P(`const `, v.GoIdent, " ", typeName, `= `, file.GoPackageName, ".", v.GoIdent)
}
}
}
processOneofs = func(oneofs []*protogen.Oneof) {
for _, e := range oneofs {
for _, f := range e.Fields {
p.P(`type `, f.GoIdent, `= `, file.GoPackageName, ".", f.GoIdent)
}
}
}
processMessages = func(messages []*protogen.Message) {
for _, message := range messages {
// skip maps in protos.
if message.Desc.Options().(*descriptorpb.MessageOptions).GetMapEntry() {
continue
}
typeName := message.GoIdent.GoName
p.P(`type `, typeName, "= ", file.GoPackageName, ".", message.GoIdent)
processMessages(message.Messages)
processEnums(message.Enums)
processOneofs(message.Oneofs)
}
}
processMessages(file.Messages)
processEnums(file.Enums)

}
}
21 changes: 21 additions & 0 deletions cmd/protoc-gen-alias/test/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@

go_package = istio.io/tools/cmd/protoc-gen-golang-jsonshim/test/generated

all: clean test

clean:
if [ -d "generated" ]; then rm -rf generated; fi

test: generate gobuild gotest

generate:
if [ ! -d "generated" ]; then mkdir generated; fi
protoc --go_out=. --go_opt=paths=source_relative \
--alias_out=. --alias_opt=paths=source_relative \
v1/*.proto

gobuild:
go build ./...

gotest:
go test .
65 changes: 65 additions & 0 deletions cmd/protoc-gen-alias/test/alias_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Copyright 2019 Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package test

import (
"testing"

"google.golang.org/protobuf/proto"

v1 "istio.io/tools/cmd/protoc-gen-alias/test/v1"
"istio.io/tools/cmd/protoc-gen-alias/test/v1alpha"
)

func TestSimpleCase(t *testing.T) {
concrete := &v1.Simple{
FieldA: 1,
FieldB: "test",
FieldC: &v1.Simple_Name{
Name: "test",
},
}
alias := &v1alpha.Simple{
FieldA: 1,
FieldB: "test",
FieldC: &v1alpha.Simple_Name{
Name: "test",
},
}
mixedAliasFirst := &v1alpha.Simple{
FieldA: 1,
FieldB: "test",
FieldC: &v1.Simple_Name{
Name: "test",
},
}
mixedConcreteFirst := &v1.Simple{
FieldA: 1,
FieldB: "test",
FieldC: &v1alpha.Simple_Name{
Name: "test",
},
}
// Test we can do proto operations
proto.Equal(concrete, alias)
proto.Equal(concrete, mixedConcreteFirst)
proto.Equal(concrete, mixedAliasFirst)
if proto.MessageName(mixedConcreteFirst).Name() != "Simple" {
t.Errorf("proto name should be Simple")
}
if proto.MessageName(mixedAliasFirst).Name() != "Simple" {
t.Errorf("proto name should be Simple")
}
}
Loading