Compare commits

...

14 Commits

Author SHA1 Message Date
5d13b84c7a add micro.codec.Frame special type handling
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-08-31 20:39:56 +03:00
ee4d83458f fix tag for nested messages
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-08-31 19:40:20 +03:00
dd62c380f2 lint fixes
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-08-20 23:03:11 +03:00
e4f2867419 update
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-08-17 00:58:23 +03:00
c5f68efd4c update with never micro-proto
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-08-17 00:10:01 +03:00
140c5fb90a update to latest micro-protoc
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-08-16 23:34:32 +03:00
b4231422b3 add ServiceName variable
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-07-14 13:49:37 +03:00
dd872a03b3 use plain struct for endpoints
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-06-23 00:23:38 +03:00
0e902b1022 update
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-06-22 01:34:46 +03:00
81bbbf55e6 change name, add comment
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-06-22 01:34:06 +03:00
c6caa0d3ac tag fix
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-05-18 14:03:21 +03:00
5ecc4986dd dont tag if tag_path is empty
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-05-11 09:07:12 +03:00
9ed1ca9a89 add info to readme
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-05-08 12:53:14 +03:00
805b52cf8d add tags example
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-05-08 12:46:02 +03:00
13 changed files with 152 additions and 70 deletions

View File

@@ -1,4 +1,4 @@
# `protoc-gen-micro`
# `protoc-gen-go-micro`
protobuf plugin to generate helper code for micro framework
A generic **code**/script/data generator based on [Protobuf](https://developers.google.com/protocol-buffers/).
@@ -15,11 +15,12 @@ $> protoc --micro_out=debug=true,components="micro|http":. input.proto
| Option | Default Value | Accepted Values | Description
|-----------------------|---------------|---------------------------|-----------------------
| `tag_path` | `.` | `any local path` | path contains generated protobuf code that needs to be tagged
| `debug`               | *false*       | `true` or `false` | if *true*, `protoc` will generate a more verbose output
| `components` | `micro` | `micro rpc http chi gorilla` | some values cant coexists like gorilla/chi or rpc/http, values must be concatinated with pipe symbol
| `components` | `micro` | `micro rpc http chi gorilla client server` | some values can't coexists like gorilla/chi or rpc/http, values must be concatinated with pipe symbol
## Install
* Install the **go** compiler and tools from https://golang.org/doc/install
* Install **protoc-gen-go**: `go get google.golang.org/protobuf/cmd/protoc-gen-go`
* Install **protoc-gen-micro**: `go get github.com/unistack-org/protoc-gen-micro/v3`
* Install **protoc-gen-go-micro**: `go get github.com/unistack-org/protoc-gen-go-micro/v3`

39
ast.go
View File

@@ -15,17 +15,9 @@ import (
"google.golang.org/protobuf/proto"
)
var (
astFields = make(map[string]map[string]map[string]*structtag.Tags) // map proto file with proto message ast struct
)
var astFields = make(map[string]map[string]map[string]*structtag.Tags) // map proto file with proto message ast struct
func (g *Generator) astGenerate(plugin *protogen.Plugin) error {
for _, file := range plugin.Files {
if !file.Generate {
continue
}
for _, message := range file.Messages {
func (g *Generator) astFill(file *protogen.File, message *protogen.Message) error {
for _, field := range message.Fields {
if field.Desc.Options() == nil {
continue
@@ -41,7 +33,10 @@ func (g *Generator) astGenerate(plugin *protogen.Plugin) error {
if !ok {
mp = make(map[string]map[string]*structtag.Tags)
}
nmp := make(map[string]*structtag.Tags)
nmp, ok := mp[message.GoIdent.GoName]
if !ok {
nmp = make(map[string]*structtag.Tags)
}
tags, err := structtag.Parse(opts.(string))
if err != nil {
return err
@@ -51,6 +46,28 @@ func (g *Generator) astGenerate(plugin *protogen.Plugin) error {
astFields[fpath] = mp
}
}
for _, nmessage := range message.Messages {
if err := g.astFill(file, nmessage); err != nil {
return err
}
}
return nil
}
func (g *Generator) astGenerate(plugin *protogen.Plugin) error {
if g.tagPath == "" {
return nil
}
for _, file := range plugin.Files {
if !file.Generate {
continue
}
for _, message := range file.Messages {
if err := g.astFill(file, message); err != nil {
return err
}
}
}

4
chi.go
View File

@@ -30,7 +30,9 @@ func (g *Generator) chiGenerate(component string, plugin *protogen.Plugin) error
}
gfile := plugin.NewGeneratedFile(gname, path)
gfile.P("// Code generated by protoc-gen-micro")
gfile.P("// Code generated by protoc-gen-go-micro. DO NOT EDIT.")
gfile.P("// protoc-gen-go-micro version: " + versionComment)
gfile.P()
gfile.P("package ", file.GoPackageName)
gfile.P()

44
example/example.proto Normal file
View File

@@ -0,0 +1,44 @@
syntax = "proto3";
package example;
option go_package = "github.com/unistack-org/protoc-gen-go-micro/v3/example;examplepb";
import "tag/tag.proto";
import "api/annotations.proto";
import "openapiv2/annotations.proto";
import "google/protobuf/wrappers.proto";
service Example {
rpc Call(CallReq) returns (CallRsp) {
option (micro.openapiv2.openapiv2_operation) = {
operation_id: "Call";
responses: {
key: "default";
value: {
description: "Error response";
schema: {
json_schema: {
ref: ".example.Error";
}
}
}
}
};
option (micro.api.http) = { post: "/v1/example/call/{name}"; body: "*"; };
option (micro.api.micro_method) = { timeout: 5; };
};
};
message CallReq {
string name = 1 [(micro.tag.tags) = "xml:\",attr\"" ];
string req = 2;
};
message CallRsp {
string rsp = 2;
};
message Error {
string msg = 1;
};

8
go.mod
View File

@@ -1,12 +1,10 @@
module github.com/unistack-org/protoc-gen-micro/v3
module github.com/unistack-org/protoc-gen-go-micro/v3
go 1.16
require (
github.com/fatih/structtag v1.2.0
github.com/unistack-org/micro-proto v0.0.2
github.com/unistack-org/micro-proto v0.0.8
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
google.golang.org/protobuf v1.26.0
google.golang.org/protobuf v1.27.1
)
//replace github.com/unistack-org/micro-proto => ../micro-proto

8
go.sum
View File

@@ -26,8 +26,8 @@ github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/unistack-org/micro-proto v0.0.2 h1:mL1ZPRGPCWJOiMBiJrkk8Y513rPrJmhJWxyLceckAXU=
github.com/unistack-org/micro-proto v0.0.2/go.mod h1:GYO53DWmeldRIo90cAdQx8bLr/WJMxW62W4ja74p1Ac=
github.com/unistack-org/micro-proto v0.0.8 h1:g4UZGQGeYGI3CFJtjuEm47aouYPviG8SDhSifl0831w=
github.com/unistack-org/micro-proto v0.0.8/go.mod h1:GYO53DWmeldRIo90cAdQx8bLr/WJMxW62W4ja74p1Ac=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
@@ -69,7 +69,7 @@ google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0 h1:bxAC2xTBsZGibn2RTntX0oH50xLsqy1OxA9tTL3p/lk=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ=
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=

View File

@@ -30,7 +30,9 @@ func (g *Generator) gorillaGenerate(component string, plugin *protogen.Plugin) e
}
gfile := plugin.NewGeneratedFile(gname, path)
gfile.P("// Code generated by protoc-gen-micro")
gfile.P("// Code generated by protoc-gen-go-micro. DO NOT EDIT.")
gfile.P("// protoc-gen-go-micro version: " + versionComment)
gfile.P()
gfile.P("package ", file.GoPackageName)
gfile.P()

View File

@@ -20,13 +20,16 @@ func (g *Generator) httpGenerate(component string, plugin *protogen.Plugin, genC
}
gfile := plugin.NewGeneratedFile(gname, path)
gfile.P("// Code generated by protoc-gen-micro")
gfile.P("// Code generated by protoc-gen-go-micro. DO NOT EDIT.")
gfile.P("// protoc-gen-go-micro version: " + versionComment)
gfile.P("// source: ", file.Proto.GetName())
gfile.P()
gfile.P("package ", file.GoPackageName)
gfile.P()
gfile.Import(contextPackage)
gfile.Import(microApiPackage)
if genClient {
gfile.Import(microClientPackage)
gfile.Import(microClientHttpPackage)

View File

@@ -13,7 +13,7 @@ var (
flagDebug = flag.Bool("debug", false, "")
flagStandalone = flag.Bool("standalone", false, "")
flagComponents = flag.String("components", "micro|rpc|http|client|server", "")
flagTagPath = flag.String("tag_path", ".", "")
flagTagPath = flag.String("tag_path", "", "")
)
func main() {

View File

@@ -21,8 +21,10 @@ func (g *Generator) microGenerate(component string, plugin *protogen.Plugin, gen
}
gfile := plugin.NewGeneratedFile(gname, path)
gfile.P("// Code generated by protoc-gen-micro")
gfile.P("// Code generated by protoc-gen-go-micro. DO NOT EDIT.")
gfile.P("// protoc-gen-go-micro version: " + versionComment)
gfile.P("// source: ", file.Proto.GetName())
gfile.P()
gfile.P("package ", file.GoPackageName)
gfile.P()

4
rpc.go
View File

@@ -20,8 +20,10 @@ func (g *Generator) rpcGenerate(component string, plugin *protogen.Plugin, genCl
}
gfile := plugin.NewGeneratedFile(gname, path)
gfile.P("// Code generated by protoc-gen-micro")
gfile.P("// Code generated by protoc-gen-go-micro. DO NOT EDIT.")
gfile.P("// protoc-gen-go-micro version: " + versionComment)
gfile.P("// source: ", file.Proto.GetName())
gfile.P()
gfile.P("package ", file.GoPackageName)
gfile.P()

35
util.go
View File

@@ -10,8 +10,7 @@ import (
"google.golang.org/protobuf/proto"
)
var (
httpMethodMap = map[string]string{
var httpMethodMap = map[string]string{
"GET": "MethodGet",
"HEAD": "MethodHead",
"POST": "MethodPost",
@@ -22,7 +21,6 @@ var (
"OPTIONS": "MethodOptions",
"TRACE": "MethodTrace",
}
)
func unexport(s string) string {
return strings.ToLower(s[:1]) + s[1:]
@@ -55,14 +53,18 @@ func generateServiceClientMethods(gfile *protogen.GeneratedFile, service *protog
opts := proto.GetExtension(method.Desc.Options(), openapiv2_options.E_Openapiv2Operation)
if opts != nil {
r := opts.(*openapiv2_options.Operation)
gfile.P("errmap := make(map[string]interface{}, ", len(r.Responses), ")")
for code, response := range r.Responses {
if response.Schema != nil && response.Schema.JsonSchema != nil {
ref := response.Schema.JsonSchema.Ref
gfile.P("errmap := make(map[string]interface{}, ", len(r.Responses.ResponseCode), ")")
for _, rsp := range r.Responses.ResponseCode {
if schema := rsp.Value.GetJsonReference(); schema != nil {
ref := schema.XRef
if strings.HasPrefix(ref, "."+string(service.Desc.ParentFile().Package())+".") {
ref = strings.TrimPrefix(ref, "."+string(service.Desc.ParentFile().Package())+".")
}
gfile.P(`errmap["`, code, `"] = &`, ref, "{}")
if ref == "micro.codec.Frame" {
gfile.P(`errmap["`, rsp.Name, `"] = &`, microCodecPackage.Ident("Frame"), "{}")
} else {
gfile.P(`errmap["`, rsp.Name, `"] = &`, ref, "{}")
}
}
}
}
@@ -284,8 +286,8 @@ func generateServiceRegister(gfile *protogen.GeneratedFile, service *protogen.Se
gfile.P("}")
gfile.P("h := &", unexport(serviceName), "Server{sh}")
gfile.P("var nopts []", microServerPackage.Ident("HandlerOption"))
gfile.P("for _, endpoint := range New", serviceName, "Endpoints() {")
gfile.P("nopts = append(nopts, ", microApiPackage.Ident("WithEndpoint"), "(endpoint))")
gfile.P("for _, endpoint := range ", serviceName, "Endpoints {")
gfile.P("nopts = append(nopts, ", microApiPackage.Ident("WithEndpoint"), "(&endpoint))")
gfile.P("}")
gfile.P("return s.Handle(s.NewHandler(&", serviceName, "{h}, append(nopts, opts...)...))")
gfile.P("}")
@@ -448,8 +450,10 @@ func generateServiceServerStreamInterface(gfile *protogen.GeneratedFile, service
func generateServiceEndpoints(gfile *protogen.GeneratedFile, service *protogen.Service) {
serviceName := service.GoName
gfile.P("func New", serviceName, "Endpoints() []*", microApiPackage.Ident("Endpoint"), " {")
gfile.P("return []*", microApiPackage.Ident("Endpoint"), "{")
gfile.P("var (")
gfile.P(serviceName, "Name", "=", `"`, serviceName, `"`)
gfile.P()
gfile.P(serviceName, "Endpoints", "=", "[]", microApiPackage.Ident("Endpoint"), "{")
for _, method := range service.Methods {
if method.Desc.Options() == nil {
continue
@@ -457,13 +461,18 @@ func generateServiceEndpoints(gfile *protogen.GeneratedFile, service *protogen.S
if proto.HasExtension(method.Desc.Options(), api_options.E_Http) {
endpoints, streaming := generateEndpoints(method)
for _, endpoint := range endpoints {
gfile.P("&", microApiPackage.Ident("Endpoint"), "{")
gfile.P("{")
generateEndpoint(gfile, serviceName, method.GoName, endpoint, streaming)
gfile.P("},")
}
}
}
gfile.P("}")
gfile.P(")")
gfile.P()
gfile.P("func New", serviceName, "Endpoints()", "[]", microApiPackage.Ident("Endpoint"), "{")
gfile.P("return ", serviceName, "Endpoints")
gfile.P("}")
gfile.P()
}

View File

@@ -15,6 +15,8 @@ var (
microClientPackage = protogen.GoImportPath("github.com/unistack-org/micro/v3/client")
microServerPackage = protogen.GoImportPath("github.com/unistack-org/micro/v3/server")
microClientHttpPackage = protogen.GoImportPath("github.com/unistack-org/micro-client-http/v3")
microCodecPackage = protogen.GoImportPath("github.com/unistack-org/micro/v3/codec")
timePackage = protogen.GoImportPath("time")
deprecationComment = "// Deprecated: Do not use."
versionComment = "v3.4.2"
)