Skip to content

Commit

Permalink
refactor: 重构protoc-gen-bot,使用自定义bot信息拓展代替注释
Browse files Browse the repository at this point in the history
  • Loading branch information
TBXark committed Nov 7, 2024
1 parent 7ca34b1 commit 6fdce96
Show file tree
Hide file tree
Showing 19 changed files with 202 additions and 91 deletions.
79 changes: 44 additions & 35 deletions api/bot/v1/counter.pb.go

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

9 changes: 9 additions & 0 deletions api/bot/v1/counter_bot.pb.go

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

2 changes: 2 additions & 0 deletions buf.gen.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ managed:
module: buf.build/googleapis/googleapis
- file_option: go_package_prefix
module: buf.build/bufbuild/protovalidate
- file_option: go_package_prefix
module: buf.build/tbxark/options
override:
- file_option: go_package_prefix
value: github.com/tbxark/sphere/api
Expand Down
3 changes: 3 additions & 0 deletions buf.lock
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,6 @@ deps:
- name: buf.build/googleapis/googleapis
commit: f52d4f76a8434cc5966798b1d3b4f110
digest: b5:5e634ff0ee118aea188b3e9c13ad7d285a192ef6c591bc20ff5a3360438d6ca310cfe9d663b20d60e1daa21789add35b919eac84e8e94a4d576e83a50dd2d62c
- name: buf.build/tbxark/options
commit: b9c75f30527e461897d205bf47c88916
digest: b5:2663950590d5f1f8e255b8e612178132d6d36c6997dedfc2a33f0d948134787a569a5ace992ae66ef5a7591ff4d76083ece1f7884aeb083afae39f47957f9633
1 change: 1 addition & 0 deletions buf.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ modules:
deps:
- buf.build/googleapis/googleapis
- buf.build/bufbuild/protovalidate
- buf.build/tbxark/options
lint:
use:
- STANDARD
Expand Down
34 changes: 25 additions & 9 deletions contrib/protoc-gen-bot/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,33 @@ go install github.com/tbxark/sphere/contrib/protoc-gen-bot@latest

## Usage

Add `// @bot` to the comment of the service, and the bot will generate the code.
Add `tbxark.options.options` to the rpc method, and set the key to `bot`, You can also add extra options to the method.

```proto
syntax = "proto3";
package helloworld;
// @bot
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
service CounterService {
rpc Start(StartRequest) returns (StartResponse) {
option (tbxark.options.options) = {
key: "bot"
};
}
rpc Counter(CounterRequest) returns (CounterResponse) {
option (tbxark.options.options) = {
key: "bot",
extra: [
{
key: "command",
value: "count",
},
{
key: "callback_query",
value: "count",
}
]
};
}
rpc Unknown(UnknownRequest) returns (UnknownResponse);
}
...
```
```

44 changes: 25 additions & 19 deletions contrib/protoc-gen-bot/bot.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
package main

import (
"buf.build/gen/go/tbxark/options/protocolbuffers/go/tbxark/options"
"google.golang.org/protobuf/compiler/protogen"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/descriptorpb"
"regexp"
"strings"
)

const deprecationComment = "// Deprecated: Do not use."

const botAnnotationKey = "bot"

const (
contextPackage = protogen.GoImportPath("context")
)
Expand Down Expand Up @@ -43,6 +45,7 @@ func generateFileContent(gen *protogen.Plugin, file *protogen.File, g *protogen.
g.P("var _ = new(", conf.client.pkg.Ident(conf.client.model), ")")
g.P("var _ = new(", conf.update.pkg.Ident(conf.update.model), ")")
g.P("var _ = new(", conf.message.pkg.Ident(conf.message.model), ")")
g.P("var _ = new(", conf.extra.pkg.Ident(conf.extra.model), ")")
g.P()
for _, service := range file.Services {
genService(gen, file, g, service, conf)
Expand All @@ -60,14 +63,14 @@ func genService(_ *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFi
ServiceName: string(service.Desc.FullName()),
Metadata: file.Desc.Path(),

ClientType: g.QualifiedGoIdent(conf.client.pkg.Ident(conf.client.model)),
UpdateType: g.QualifiedGoIdent(conf.update.pkg.Ident(conf.update.model)),
MessageType: g.QualifiedGoIdent(conf.message.pkg.Ident(conf.message.model)),
ClientType: g.QualifiedGoIdent(conf.client.pkg.Ident(conf.client.model)),
UpdateType: g.QualifiedGoIdent(conf.update.pkg.Ident(conf.update.model)),
MessageType: g.QualifiedGoIdent(conf.message.pkg.Ident(conf.message.model)),
NewExtraDataFunc: g.QualifiedGoIdent(conf.extra.pkg.Ident("New" + conf.extra.model)),
}
allEnable := isBotEnable(service.Comments.Leading.String())
for _, method := range service.Methods {
enable := allEnable || isBotEnable(method.Comments.Leading.String())
if !enable {
rule := extractBotRule(method)
if rule == nil {
continue
}
sd.Methods = append(sd.Methods, &methodDesc{
Expand All @@ -77,6 +80,7 @@ func genService(_ *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFi
Request: method.Input.GoIdent.GoName,
Reply: method.Output.GoIdent.GoName,
Comment: method.Comments.Leading.String(),
Extra: rule.Extra,
})
methodSets[method.GoName] += 1
}
Expand All @@ -85,27 +89,29 @@ func genService(_ *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFi
}
}

var botTagsMatchRegexp = regexp.MustCompile(` *//+ *@bot`)

func hasBotRule(services []*protogen.Service) bool {
for _, service := range services {
if isBotEnable(service.Comments.Leading.String()) {
return true
}
for _, method := range service.Methods {
if isBotEnable(method.Comments.Leading.String()) {
if extractBotRule(method) != nil {
return true
}
}
}
return false
}

func isBotEnable(comment string) bool {
for _, line := range strings.Split(comment, "\n") {
if botTagsMatchRegexp.MatchString(line) {
return true
func extractBotRule(method *protogen.Method) *options.KeyValuePair {
if method.Desc.IsStreamingClient() || method.Desc.IsStreamingServer() {
return nil
}
rules, ok := proto.GetExtension(method.Desc.Options(), options.E_Options).([]*options.KeyValuePair)
if rules == nil || !ok {
return nil
}
for _, rule := range rules {
if rule.GetKey() == botAnnotationKey {
return rule
}
}
return false
return nil
}
2 changes: 2 additions & 0 deletions contrib/protoc-gen-bot/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@ module github.com/tbxark/sphere/contrib/protoc-gen-bot
go 1.23.2

require google.golang.org/protobuf v1.35.1

require buf.build/gen/go/tbxark/options/protocolbuffers/go v1.35.1-20241107024543-7afe4060470a.1 // indirect
4 changes: 4 additions & 0 deletions contrib/protoc-gen-bot/go.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
buf.build/gen/go/tbxark/annotations/protocolbuffers/go v1.35.1-20241107015316-f9e8a079932f.1 h1:oJzuiHXixdey4MQiUOI7iSqK9TG5RLM9c/N3SBNK2Do=
buf.build/gen/go/tbxark/annotations/protocolbuffers/go v1.35.1-20241107015316-f9e8a079932f.1/go.mod h1:A4xXdK2m6JCD2DnPI6dMxTzmvWX9Ojoe2JT4DKMgULI=
buf.build/gen/go/tbxark/options/protocolbuffers/go v1.35.1-20241107024543-7afe4060470a.1 h1:34ZELl67BIA/McOR+Cm0dD0K8DpCOBYD3qRxAcf4WHY=
buf.build/gen/go/tbxark/options/protocolbuffers/go v1.35.1-20241107024543-7afe4060470a.1/go.mod h1:c2hH3HNH5YrpugKZYpI7gS+wpeDYBBi6Ex66Q+XOyEg=
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=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
Expand Down
21 changes: 16 additions & 5 deletions contrib/protoc-gen-bot/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,19 @@ import (
)

var (
showVersion = flag.Bool("version", false, "print the version and exit")
updatePackage = flag.String("update_package", "github.com/go-telegram/bot/models", "update package")
updateModel = flag.String("update_model", "Update", "update model")
showVersion = flag.Bool("version", false, "print the version and exit")

updatePackage = flag.String("update_package", "github.com/go-telegram/bot/models", "update package")
updateModel = flag.String("update_model", "Update", "update model")

messagePackage = flag.String("message_package", "github.com/tbxark/sphere/pkg/telegram", "message package")
messageModel = flag.String("message_model", "Message", "message model")
clientPackage = flag.String("bot_package", "github.com/go-telegram/bot", "bot package")
clientModel = flag.String("bot_model", "Bot", "bot model")

clientPackage = flag.String("bot_package", "github.com/go-telegram/bot", "bot package")
clientModel = flag.String("bot_model", "Bot", "bot model")

extraDataPackage = flag.String("extra_data_package", "github.com/tbxark/sphere/pkg/telegram", "extra data package")
extraDataModel = flag.String("extra_data_model", "MethodExtraData", "extra data model")
)

type Package struct {
Expand All @@ -27,6 +33,7 @@ type Config struct {
update Package
message Package
client Package
extra Package
}

func main() {
Expand All @@ -48,6 +55,10 @@ func main() {
pkg: protogen.GoImportPath(*clientPackage),
model: *clientModel,
},
extra: Package{
pkg: protogen.GoImportPath(*extraDataPackage),
model: *extraDataModel,
},
}
protogen.Options{
ParamFunc: flag.CommandLine.Set,
Expand Down
10 changes: 7 additions & 3 deletions contrib/protoc-gen-bot/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@ type serviceDesc struct {
Methods []*methodDesc
MethodSets map[string]*methodDesc

ClientType string
UpdateType string
MessageType string
ClientType string
UpdateType string
MessageType string
NewExtraDataFunc string
}

type methodDesc struct {
Expand All @@ -30,6 +31,9 @@ type methodDesc struct {
Request string
Reply string
Comment string

// bot_rule
Extra map[string]string
}

func (s *serviceDesc) execute() string {
Expand Down
10 changes: 10 additions & 0 deletions contrib/protoc-gen-bot/template.go.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,21 @@
{{$clientType := .ClientType}}
{{$updateType := .UpdateType}}
{{$messageType := .MessageType}}
{{$newExtraDataFunc := .NewExtraDataFunc}}

{{- range .MethodSets}}
const BotHandler{{$svrType}}{{.OriginalName}} = "/{{$svrName}}/{{.OriginalName}}"
{{- end}}

{{- range .MethodSets}}
{{- if .Extra}}
var ExtraData{{$svrType}}{{.Name}} = {{$newExtraDataFunc}}(map[string]string{
{{- range $key, $value := .Extra}}
"{{$key}}": "{{$value}}",
{{- end}}
})
{{- end}}
{{- end}}

type {{.ServiceType}}Server interface {
{{- range .MethodSets}}
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ go 1.23.0

require (
buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.35.1-20240920164238-5a7b106cbb87.1
buf.build/gen/go/tbxark/options/protocolbuffers/go v1.35.1-20241107024543-7afe4060470a.1
entgo.io/ent v0.14.1
github.com/alitto/pond/v2 v2.0.4
github.com/bufbuild/protovalidate-go v0.7.2
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ ariga.io/atlas v0.28.1 h1:cNE0FYmoYs1u4KF+FGnp2on1srhM6FDpjaCgL7Rd8/c=
ariga.io/atlas v0.28.1/go.mod h1:LOOp18LCL9r+VifvVlJqgYJwYl271rrXD9/wIyzJ8sw=
buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.35.1-20240920164238-5a7b106cbb87.1 h1:9wP6ZZYWnF2Z0TxmII7m3XNykxnP4/w8oXeth6ekcRI=
buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.35.1-20240920164238-5a7b106cbb87.1/go.mod h1:Duw/9JoXkXIydyASnLYIiufkzySThoqavOsF+IihqvM=
buf.build/gen/go/tbxark/options/protocolbuffers/go v1.35.1-20241107024543-7afe4060470a.1 h1:34ZELl67BIA/McOR+Cm0dD0K8DpCOBYD3qRxAcf4WHY=
buf.build/gen/go/tbxark/options/protocolbuffers/go v1.35.1-20241107024543-7afe4060470a.1/go.mod h1:c2hH3HNH5YrpugKZYpI7gS+wpeDYBBi6Ex66Q+XOyEg=
entgo.io/ent v0.14.1 h1:fUERL506Pqr92EPHJqr8EYxbPioflJo6PudkrEA8a/s=
entgo.io/ent v0.14.1/go.mod h1:MH6XLG0KXpkcDQhKiHfANZSzR55TJyPL5IGNpI8wpco=
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
Expand Down
Loading

0 comments on commit 6fdce96

Please sign in to comment.