Skip to content

Commit 63ae00d

Browse files
complete struct tag plugin
1 parent 57326b9 commit 63ae00d

File tree

10 files changed

+552
-0
lines changed

10 files changed

+552
-0
lines changed

Makefile

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
install:
2+
cd cmd/protoc-gen-structtag && go install && cd ..
3+
.PHONY: install

cmd/protoc-gen-structtag/main.go

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package main
2+
3+
import (
4+
"errors"
5+
"flag"
6+
7+
"google.golang.org/protobuf/compiler/protogen"
8+
)
9+
10+
var dbtag *string
11+
12+
func main() {
13+
var flags flag.FlagSet
14+
dbtag = flags.String("dbtag", "", "db tag to use for generated structs")
15+
16+
options := protogen.Options{
17+
ParamFunc: flags.Set,
18+
}
19+
options.Run(func(gen *protogen.Plugin) error {
20+
if *dbtag == "" {
21+
gen.Error(errors.New("dbtag must be set"))
22+
}
23+
for _, f := range gen.Files {
24+
if !f.Generate {
25+
continue
26+
}
27+
generateStructTags(gen, f)
28+
29+
}
30+
return nil
31+
})
32+
}
33+
34+
func generateStructTags(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile {
35+
filename := file.GeneratedFilenamePrefix + "_structtags.pb.go"
36+
g := gen.NewGeneratedFile(filename, file.GoImportPath)
37+
g.P("// Code generated by protoc-gen-go-structtags. DO NOT EDIT.")
38+
g.P()
39+
g.P("package ", file.GoPackageName)
40+
g.P()
41+
for _, message := range file.Messages {
42+
g.P("type ", message.GoIdent, " struct {")
43+
for _, field := range message.Fields {
44+
g.P(field.GoName, " ", field.Desc.Kind(), " `json:\"", field.Desc.Name(), "\" ", *dbtag, ":\"", field.Desc.Name(), "\"`")
45+
}
46+
g.P("}")
47+
}
48+
49+
return g
50+
}

example/Makefile

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
generate:
2+
protoc --go_out=pkg --go_opt=paths=source_relative --proto_path=proto \
3+
--structtag_out=internal --structtag_opt=paths=source_relative,dbtag=bun \
4+
proto/*.proto

example/go.mod

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module github.com/theluckiestsoul/protoc-gen-structtag/example
2+
3+
go 1.21.0

example/internal/entity_structtags.pb.go

Lines changed: 28 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)