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

fix(cmd/hz): unexpected generated model file path #1155

Open
wants to merge 7 commits into
base: develop
Choose a base branch
from
35 changes: 24 additions & 11 deletions cmd/hz/protobuf/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -290,27 +290,40 @@ func (plugin *Plugin) Handle(req *pluginpb.CodeGeneratorRequest, args *config.Ar
return nil
}

func gopkgIncluded(opt string, gopkg string) bool {
if strings.HasPrefix(opt, gopkg) {
return true
} else if strings.HasPrefix(opt, "/"+gopkg) {
return true
} else {
return false
}
}

func (plugin *Plugin) processOpt(opt string) string {
gopkg := plugin.Package
if !gopkgIncluded(opt, gopkg) {
if strings.HasPrefix(opt, "/") {
opt = gopkg + opt
} else {
opt = gopkg + "/" + opt
}
}
impt, _ := plugin.fixModelPathAndPackage(opt)
return impt
}

// fixGoPackage will update go_package to store all the model files in ${model_dir}
func (plugin *Plugin) fixGoPackage(req *pluginpb.CodeGeneratorRequest, pkgMap map[string]string, trimGoPackage string) {
gopkg := plugin.Package
for _, f := range req.ProtoFile {
if strings.HasPrefix(f.GetPackage(), "google.protobuf") {
continue
}
if len(trimGoPackage) != 0 && strings.HasPrefix(f.GetOptions().GetGoPackage(), trimGoPackage) {
*f.Options.GoPackage = strings.TrimPrefix(*f.Options.GoPackage, trimGoPackage)
}

opt := getGoPackage(f, pkgMap)
if !strings.Contains(opt, gopkg) {
if strings.HasPrefix(opt, "/") {
opt = gopkg + opt
} else {
opt = gopkg + "/" + opt
}
}
impt, _ := plugin.fixModelPathAndPackage(opt)
*f.Options.GoPackage = impt
*f.Options.GoPackage = plugin.processOpt(opt)
}
}

Expand Down
18 changes: 18 additions & 0 deletions cmd/hz/protobuf/plugin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,24 @@ func TestPlugin_Handle(t *testing.T) {
plu.recvWarningLogger()
}

func TestProcessOpt(t *testing.T) {
plu := &Plugin{}
plu.Package = "hello"
plu.ModelDir = meta.ModelDir
tests := [][]string{
{"a/b/c", "hello/biz/model/a/b/c"},
{"a/hello/c", "hello/biz/model/a/hello/c"},
{"biz/model/a/b/c", "hello/biz/model/a/b/c"},
{"hello/a/b/c", "hello/biz/model/a/b/c"},
{"hello/biz/model/a/hello/c", "hello/biz/model/a/hello/c"},
}
for _, test := range tests {
if result := plu.processOpt(test[0]); result != test[1] {
t.Fatalf("want go package: %s, but get: %s", test[1], result)
}
}
}

func TestFixModelPathAndPackage(t *testing.T) {
plu := &Plugin{}
plu.Package = "cloudwego/hertz"
Expand Down