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

feat(hz): remove tag #811

Merged
merged 2 commits into from
Jul 18, 2023
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
3 changes: 2 additions & 1 deletion _typos.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@ referer = "referer"
HeaderReferer = "HeaderReferer"
expectedReferer = "expectedReferer"
Referer = "Referer"
O_WRONLY = "O_WRONLY"
O_WRONLY = "O_WRONLY"
WRONLY = "WRONLY"
5 changes: 5 additions & 0 deletions cmd/hz/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ func Init() *cli.App {
unsetOmitemptyFlag := cli.BoolFlag{Name: "unset_omitempty", Usage: "Remove 'omitempty' tag for generated struct.", Destination: &globalArgs.UnsetOmitempty}
protoCamelJSONTag := cli.BoolFlag{Name: "pb_camel_json_tag", Usage: "Convert Name style for json tag to camel(Only works protobuf).", Destination: &globalArgs.ProtobufCamelJSONTag}
snakeNameFlag := cli.BoolFlag{Name: "snake_tag", Usage: "Use snake_case style naming for tags. (Only works for 'form', 'query', 'json')", Destination: &globalArgs.SnakeName}
rmTagFlag := cli.StringSliceFlag{Name: "rm_tag", Usage: "Remove the specified tag"}
customLayout := cli.StringFlag{Name: "customize_layout", Usage: "Specify the path for layout template.", Destination: &globalArgs.CustomizeLayout}
customLayoutData := cli.StringFlag{Name: "customize_layout_data_path", Usage: "Specify the path for layout template render data.", Destination: &globalArgs.CustomizeLayoutData}
customPackage := cli.StringFlag{Name: "customize_package", Usage: "Specify the path for package template.", Destination: &globalArgs.CustomizePackage}
Expand Down Expand Up @@ -230,6 +231,7 @@ func Init() *cli.App {
&unsetOmitemptyFlag,
&protoCamelJSONTag,
&snakeNameFlag,
&rmTagFlag,
&excludeFilesFlag,
&customLayout,
&customLayoutData,
Expand Down Expand Up @@ -263,6 +265,7 @@ func Init() *cli.App {
&unsetOmitemptyFlag,
&protoCamelJSONTag,
&snakeNameFlag,
&rmTagFlag,
&excludeFilesFlag,
&customPackage,
&handlerByMethod,
Expand All @@ -289,6 +292,7 @@ func Init() *cli.App {
&unsetOmitemptyFlag,
&protoCamelJSONTag,
&snakeNameFlag,
&rmTagFlag,
&excludeFilesFlag,
},
Action: Model,
Expand All @@ -315,6 +319,7 @@ func Init() *cli.App {
&unsetOmitemptyFlag,
&protoCamelJSONTag,
&snakeNameFlag,
&rmTagFlag,
&excludeFilesFlag,
&customLayout,
&customLayoutData,
Expand Down
2 changes: 2 additions & 0 deletions cmd/hz/config/argument.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ type Argument struct {
ProtobufPlugins []string
ThriftPlugins []string
SnakeName bool
RmTags []string
Excludes []string
NoRecurse bool
HandlerByMethod bool
Expand Down Expand Up @@ -121,6 +122,7 @@ func (arg *Argument) parseStringSlice(c *cli.Context) {
arg.ProtocOptions = c.StringSlice("protoc")
arg.ThriftPlugins = c.StringSlice("thrift-plugins")
arg.ProtobufPlugins = c.StringSlice("protoc-plugins")
arg.RmTags = c.StringSlice("rm_tag")
}

func (arg *Argument) UpdateByManifest(m *meta.Manifest) {
Expand Down
40 changes: 31 additions & 9 deletions cmd/hz/protobuf/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,22 @@ type Plugin struct {
ModelDir string
UseDir string
IdlClientDir string
RmTags RemoveTags
PkgMap map[string]string
logger *logs.StdLogger
}

type RemoveTags []string

func (rm *RemoveTags) Exist(tag string) bool {
for _, rmTag := range *rm {
if rmTag == tag {
return true
}
}
return false
}

func (plugin *Plugin) Run() int {
plugin.setLogger()
args := &config.Argument{}
Expand Down Expand Up @@ -192,6 +204,7 @@ func (plugin *Plugin) Handle(req *pluginpb.CodeGeneratorRequest, args *config.Ar
opts := protogen.Options{}
gen, err := opts.New(req)
plugin.Plugin = gen
plugin.RmTags = args.RmTags
if err != nil {
return fmt.Errorf("new protoc plugin failed: %s", err.Error())
}
Expand Down Expand Up @@ -322,7 +335,6 @@ func (plugin *Plugin) fixModelPathAndPackage(pkg string) (impt, path string) {
func (plugin *Plugin) GenerateFiles(pluginPb *protogen.Plugin) error {
idl := pluginPb.Request.FileToGenerate[len(pluginPb.Request.FileToGenerate)-1]
pluginPb.SupportedFeatures = gengo.SupportedFeatures

for _, f := range pluginPb.Files {
if f.Proto.GetName() == idl {
err := plugin.GenerateFile(pluginPb, f)
Expand Down Expand Up @@ -358,15 +370,15 @@ func (plugin *Plugin) GenerateFile(gen *protogen.Plugin, f *protogen.File) error
if len(plugin.UseDir) != 0 {
return nil
}
file, err := generateFile(gen, f)
file, err := generateFile(gen, f, plugin.RmTags)
if err != nil || file == nil {
return fmt.Errorf("generate file %s failed: %s", f.Proto.GetName(), err.Error())
}
return nil
}

// generateFile generates the contents of a .pb.go file.
func generateFile(gen *protogen.Plugin, file *protogen.File) (*protogen.GeneratedFile, error) {
func generateFile(gen *protogen.Plugin, file *protogen.File, rmTags RemoveTags) (*protogen.GeneratedFile, error) {
filename := file.GeneratedFilenamePrefix + ".pb.go"
g := gen.NewGeneratedFile(filename, file.GoImportPath)
f := newFileInfo(file)
Expand Down Expand Up @@ -398,7 +410,7 @@ func generateFile(gen *protogen.Plugin, file *protogen.File) (*protogen.Generate
}
var err error
for _, message := range f.allMessages {
err = genMessage(g, f, message)
err = genMessage(g, f, message, rmTags)
if err != nil {
return nil, err
}
Expand All @@ -410,7 +422,7 @@ func generateFile(gen *protogen.Plugin, file *protogen.File) (*protogen.Generate
return g, nil
}

func genMessage(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo) error {
func genMessage(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo, rmTags RemoveTags) error {
if m.Desc.IsMapEntry() {
return nil
}
Expand All @@ -421,7 +433,7 @@ func genMessage(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo) error {
m.Desc.Options().(*descriptorpb.MessageOptions).GetDeprecated())
g.P(leadingComments,
"type ", m.GoIdent, " struct {")
err := genMessageFields(g, f, m)
err := genMessageFields(g, f, m, rmTags)
if err != nil {
return err
}
Expand All @@ -435,20 +447,20 @@ func genMessage(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo) error {
return nil
}

func genMessageFields(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo) error {
func genMessageFields(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo, rmTags RemoveTags) error {
sf := f.allMessageFieldsByPtr[m]
genMessageInternalFields(g, f, m, sf)
var err error
for _, field := range m.Fields {
err = genMessageField(g, f, m, field, sf)
err = genMessageField(g, f, m, field, sf, rmTags)
if err != nil {
return err
}
}
return nil
}

func genMessageField(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo, field *protogen.Field, sf *structFields) error {
func genMessageField(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo, field *protogen.Field, sf *structFields, rmTags RemoveTags) error {
if oneof := field.Oneof; oneof != nil && !oneof.Desc.IsSynthetic() {
// It would be a bit simpler to iterate over the oneofs below,
// but generating the field here keeps the contents of the Go
Expand Down Expand Up @@ -506,6 +518,16 @@ func genMessageField(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo, fie
tags = append(tags, gotrackTags...)
}

if len(rmTags) > 0 {
tmp := structTags{}
for _, tag := range tags {
if !rmTags.Exist(tag[0]) {
tmp = append(tmp, tag)
}
}
tags = tmp
}

name := field.GoName
if field.Desc.IsWeak() {
name = WeakFieldPrefix_goname + name
Expand Down
13 changes: 10 additions & 3 deletions cmd/hz/thrift/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ type Plugin struct {
req *thriftgo_plugin.Request
args *config.Argument
logger *logs.StdLogger
rmTags []string
}

func (plugin *Plugin) Run() int {
Expand Down Expand Up @@ -74,6 +75,7 @@ func (plugin *Plugin) Run() int {
logs.Errorf("parse args failed: %s", err.Error())
return meta.PluginError
}
plugin.rmTags = args.RmTags
if args.CmdType == meta.CmdModel {
res, err := plugin.GetResponse(nil, args.OutDir)
if err != nil {
Expand Down Expand Up @@ -334,7 +336,7 @@ func (plugin *Plugin) InsertTag() ([]*thriftgo_plugin.Generated, error) {
stName := st.GetName()
for _, f := range st.Fields {
fieldName := f.GetName()
tagString, err := getTagString(f)
tagString, err := getTagString(f, plugin.rmTags)
if err != nil {
return nil, err
}
Expand All @@ -360,7 +362,7 @@ func (plugin *Plugin) InsertTag() ([]*thriftgo_plugin.Generated, error) {
stName := st.GetName()
for _, f := range st.Fields {
fieldName := f.GetName()
tagString, err := getTagString(f)
tagString, err := getTagString(f, plugin.rmTags)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -400,7 +402,7 @@ func (plugin *Plugin) GetResponse(files []generator.File, outputDir string) (*th
}, nil
}

func getTagString(f *parser.Field) (string, error) {
func getTagString(f *parser.Field, rmTags []string) (string, error) {
field := model.Field{}
err := injectTags(f, &field, true, false)
if err != nil {
Expand All @@ -412,6 +414,11 @@ func getTagString(f *parser.Field) (string, error) {
disableTag = true
}
}

for _, rmTag := range rmTags {
field.Tags.Remove(rmTag)
}

var tagString string
tags := field.Tags
for idx, tag := range tags {
Expand Down