From 5f4b3f72a543b5193a40258738d08c4810cd178f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BE=E9=87=8C=28barry=29?= Date: Tue, 7 May 2024 12:12:08 +0800 Subject: [PATCH] Fix 240505 (#2) * fix: 2024-05-05 14:31:36 * fix: 2024-05-05 16:33:53 * fix: 2024-05-07 10:16:27 * fix: 2024-05-07 11:41:51 * fix: 2024-05-07 11:52:52 --- Makefile | 1 + cmd/format/fmt.go | 95 ++++++++++++++++ cmd/format/format.go | 10 +- cmd/{protobuild => format}/lint.go | 2 +- cmd/protobuild/cmd.go | 63 ++++++----- cmd/protobuild/config.go | 35 ------ cmd/protobuild/fmt.go | 104 ------------------ cmd/protobuild/yaml_types.go | 34 ++++++ cmd/protoc-gen-go-json/internal/template.go | 1 - .../internal/retag/extract.go | 4 +- cmd/protoc-gen-gotag/internal/retag/tagger.go | 1 - cmd/protoc-gen-retag/ast/ast.go | 4 +- cmd/protoc-gen-retag/ast/generator.go | 12 +- cmd/protoc-gen-retag/ast/parse_and_rewrite.go | 57 +++++----- cmd/protoc-gen-retag/example/example.pb.go | 2 +- cmd/protoc-gen-retag/example/example.proto | 68 ++++++------ cmd/protoc-gen-retag/main.go | 1 + go.mod | 5 +- go.sum | 9 +- internal/modutil/util.go | 16 +-- internal/plugin/plugin.go | 4 +- internal/protoc-gen-errors/main.go | 2 +- internal/protoc-gen-gorm/internal/field.go | 24 ++-- internal/protoc-gen-gorm/internal/mod.go | 58 +++++----- internal/protoc-gen-gorm/internal1/field.go | 24 ++-- internal/protoc-gen-gorm/internal1/mod.go | 42 ++++--- .../protoc-gen-gotag/internal/retag/ast.go | 4 +- .../internal/retag/generator.go | 10 +- .../internal/retag/rewrite.go | 5 +- internal/protoc-gen-gotag/main.go | 5 +- internal/protoc-gen-lava/internal/gensql.go | 2 +- internal/protoc-gen-lava/internal/lava.go | 52 ++++----- internal/protoc-gen-lava/internal/restapi.go | 4 +- internal/protoc-gen-lava/internal/version.go | 12 +- internal/protoc-gen-resty/internal/resty.go | 5 +- internal/protoc-gen-resty/internal/version.go | 6 +- internal/protoutil/gen.go | 12 +- internal/protoutil/name.go | 3 +- internal/shutil/shell.go | 2 +- internal/template/template.go | 8 +- internal/typex/cli.go | 10 +- .../protoc-gen-retag/example/example.pb.go | 4 +- pkg/protoc-gen-gorm/example/example_test.go | 8 +- proto/retag/retag.proto | 8 +- version/version.go | 4 +- 45 files changed, 412 insertions(+), 430 deletions(-) create mode 100644 cmd/format/fmt.go rename cmd/{protobuild => format}/lint.go (88%) delete mode 100644 cmd/protobuild/fmt.go create mode 100644 cmd/protobuild/yaml_types.go diff --git a/Makefile b/Makefile index 232e49c..97bdf64 100644 --- a/Makefile +++ b/Makefile @@ -21,6 +21,7 @@ build: vet: @go vet ./... + gofumpt -l -w -extra . generate: @go generate ./... diff --git a/cmd/format/fmt.go b/cmd/format/fmt.go new file mode 100644 index 0000000..c678c48 --- /dev/null +++ b/cmd/format/fmt.go @@ -0,0 +1,95 @@ +// Refer: https://github.com/emicklei/proto-contrib/tree/master/cmd/protofmt +// https://github.com/bufbuild/buf/blob/main/private/buf/bufformat/bufformat.go + +package format + +import ( + "bytes" + "io" + "io/ioutil" + "os" + + "github.com/emicklei/proto" + "github.com/emicklei/proto-contrib/pkg/protofmt" + "github.com/pubgo/funk/assert" +) + +var overwrite = false + +// func fmtCmd() *cli.Command { +// return &cli.Command{ +// Name: "fmt", +// Usage: "格式化protobuf文件", +// Flags: typex.Flags{&cli.BoolFlag{ +// Name: "overwrite", +// Usage: "write result to (source) file instead of stdout", +// Aliases: typex.Strs{"w"}, +// Value: overwrite, +// Destination: &overwrite, +// }}, +// Before: func(context *cli.Context) error { +// return parseConfig() +// }, +// Action: func(ctx *cli.Context) error { +// protoList := make(map[string]bool) + +// for i := range cfg.Root { +// if pathutil.IsNotExist(cfg.Root[i]) { +// logger.Info().Msgf("file %s not found", cfg.Root[i]) +// continue +// } + +// assert.Must(filepath.Walk(cfg.Root[i], func(path string, info fs.FileInfo, err error) error { +// if err != nil { +// return err +// } + +// if info.IsDir() { +// return nil +// } + +// if strings.HasSuffix(info.Name(), ".proto") { +// protoList[path] = true +// return nil +// } + +// return nil +// })) +// } + +// for name := range protoList { +// //_ = shutil.MustRun("clang-format", "-i", fmt.Sprintf("-style=google %s", name)) +// //readFormatWrite(name) +// format.Format(name) +// } + +// return nil +// }, +// } +// } + +func readFormatWrite(filename string) { + // open for read + file := assert.Must1(os.Open(filename)) + + // buffer before write + buf := new(bytes.Buffer) + format1(filename, file, buf) + + if overwrite { + // write back to input + assert.Must(ioutil.WriteFile(filename, buf.Bytes(), os.ModePerm)) + } else { + // write to stdout + buf.WriteString("\n================================================================================================\n") + assert.Must1(io.Copy(os.Stdout, bytes.NewReader(buf.Bytes()))) + + } +} + +func format1(filename string, input io.Reader, output io.Writer) { + parser := proto.NewParser(input) + parser.Filename(filename) + def := assert.Must1(parser.Parse()) + protofmt.NewFormatter(output, " ").Format(def) // 2 spaces +} diff --git a/cmd/format/format.go b/cmd/format/format.go index 2e51b0b..5e42818 100644 --- a/cmd/format/format.go +++ b/cmd/format/format.go @@ -2,19 +2,19 @@ package format import ( "bytes" + "os" + "github.com/bufbuild/protocompile/parser" "github.com/bufbuild/protocompile/reporter" "github.com/pubgo/funk/assert" - "os" ) // Format formats and writes the target module files into a read bucket. func Format(path string) { - var data = assert.Must1(os.ReadFile(path)) - fileNode, err := parser.Parse(path, bytes.NewBuffer(data), reporter.NewHandler(nil)) - assert.Must(err) + data := assert.Must1(os.ReadFile(path)) + fileNode := assert.Must1(parser.Parse(path, bytes.NewBuffer(data), reporter.NewHandler(nil))) var buf bytes.Buffer assert.Must(newFormatter(&buf, fileNode).Run()) - assert.Must(os.WriteFile(path, buf.Bytes(), 0644)) + assert.Must(os.WriteFile(path, buf.Bytes(), 0o644)) } diff --git a/cmd/protobuild/lint.go b/cmd/format/lint.go similarity index 88% rename from cmd/protobuild/lint.go rename to cmd/format/lint.go index 6a8bde8..a2362ec 100644 --- a/cmd/protobuild/lint.go +++ b/cmd/format/lint.go @@ -1,4 +1,4 @@ -package protobuild +package format // https://github.com/yoheimuta/protolint // clang-format -i -style=google role.proto diff --git a/cmd/protobuild/cmd.go b/cmd/protobuild/cmd.go index 8c4e5a8..62f3b78 100644 --- a/cmd/protobuild/cmd.go +++ b/cmd/protobuild/cmd.go @@ -38,7 +38,7 @@ var ( modPath = filepath.Join(os.Getenv("GOPATH"), "pkg", "mod") pwd = assert.Exit1(os.Getwd()) logger = log.GetLogger("proto-build") - //binPath = []string{os.ExpandEnv("$HOME/bin"), os.ExpandEnv("$HOME/.local/bin"), os.ExpandEnv("./bin")} + // binPath = []string{os.ExpandEnv("$HOME/bin"), os.ExpandEnv("$HOME/.local/bin"), os.ExpandEnv("./bin")} ) func parseConfig() error { @@ -80,7 +80,7 @@ func parseConfig() error { func Main() *cli.App { var force bool - var app = &cli.App{ + app := &cli.App{ Name: "protobuf build", Usage: "protobuf generation, configuration and management", Version: version.Version, @@ -94,6 +94,10 @@ func Main() *cli.App { }, }, Action: func(context *cli.Context) error { + if shutil.IsHelp() { + return nil + } + in := assert.Must1(io.ReadAll(os.Stdin)) req := &pluginpb.CodeGeneratorRequest{} assert.Must(proto.Unmarshal(in, req)) @@ -148,10 +152,9 @@ func Main() *cli.App { return nil }, Commands: cli.Commands{ - fmtCmd(), &cli.Command{ Name: "gen", - Usage: "编译protobuf文件", + Usage: "编译 protobuf 文件", Before: func(context *cli.Context) error { return parseConfig() }, @@ -159,7 +162,7 @@ func Main() *cli.App { defer recovery.Exit() var protoList sync.Map - var basePlugin = cfg.BasePlugin + basePlugin := cfg.BasePlugin for i := range cfg.Root { if pathutil.IsNotExist(cfg.Root[i]) { log.Printf("file %s not found", cfg.Root[i]) @@ -190,21 +193,21 @@ func Main() *cli.App { } protoList.Range(func(key, _ interface{}) bool { - var in = key.(string) + in := key.(string) - var data = "" - var base = fmt.Sprintf("protoc -I %s -I %s", cfg.Vendor, pwd) + data := "" + base := fmt.Sprintf("protoc -I %s -I %s", cfg.Vendor, pwd) logger.Info().Msgf("includes=%q", cfg.Includes) for i := range cfg.Includes { base += fmt.Sprintf(" -I %s", cfg.Includes[i]) } - var retagOut = "" - var retagOpt = "" + retagOut := "" + retagOpt := "" for i := range cfg.Plugins { - var plg = cfg.Plugins[i] + plg := cfg.Plugins[i] - var name = plg.Name + name := plg.Name // 指定plugin path if plg.Path != "" { @@ -213,11 +216,11 @@ func Main() *cli.App { data += fmt.Sprintf(" --plugin=protoc-gen-%s=%s", name, plg.Path) } - var out = func() string { + out := func() string { // https://github.com/pseudomuto/protoc-gen-doc // 目录特殊处理 if name == "doc" { - var out = filepath.Join(plg.Out, in) + out := filepath.Join(plg.Out, in) assert.Must(pathutil.IsNotExistMkDir(out)) return out } @@ -235,8 +238,8 @@ func Main() *cli.App { _ = pathutil.IsNotExistMkDir(out) - var opts = plg.Opt - var hasPath = func() bool { + opts := plg.Opt + hasPath := func() bool { for _, opt := range opts { if strings.HasPrefix(opt, "paths=") { return true @@ -245,7 +248,7 @@ func Main() *cli.App { return false } - var hasModule = func() bool { + hasModule := func() bool { for _, opt := range opts { if strings.HasPrefix(opt, "module=") { return true @@ -300,7 +303,7 @@ func Main() *cli.App { }, &cli.Command{ Name: "vendor", - Usage: "同步项目protobuf依赖到.proto中", + Usage: "同步项目 protobuf 依赖到 .proto 目录中", Before: func(context *cli.Context) error { return parseConfig() }, @@ -319,7 +322,7 @@ func Main() *cli.App { var changed bool // 解析go.mod并获取所有pkg版本 - var versions = modutil.LoadVersions() + versions := modutil.LoadVersions() for i, dep := range cfg.Depends { pathVersion := strings.SplitN(dep.Url, "@", 2) if len(pathVersion) == 2 { @@ -327,24 +330,24 @@ func Main() *cli.App { dep.Path = pathVersion[0] } - var url = os.ExpandEnv(dep.Url) + url := os.ExpandEnv(dep.Url) // url是本地目录, 不做检查 if pathutil.IsDir(url) { continue } - var v = strutil.FirstFnNotEmpty(func() string { + v := strutil.FirstFnNotEmpty(func() string { return versions[url] }, func() string { return generic.DePtr(dep.Version) }, func() string { // go.mod中version不存在, 并且protobuf.yaml也没有指定 // go pkg缓存 - var localPkg, err = os.ReadDir(filepath.Dir(filepath.Join(modPath, url))) + localPkg, err := os.ReadDir(filepath.Dir(filepath.Join(modPath, url))) assert.Must(err) - var _, name = filepath.Split(url) + _, name := filepath.Split(url) for j := range localPkg { if !localPkg[j].IsDir() { continue @@ -378,11 +381,11 @@ func Main() *cli.App { } var buf bytes.Buffer - var enc = yaml.NewEncoder(&buf) + enc := yaml.NewEncoder(&buf) enc.SetIndent(2) defer enc.Close() assert.Must(enc.Encode(cfg)) - assert.Must(os.WriteFile(protoCfg, buf.Bytes(), 0666)) + assert.Must(os.WriteFile(protoCfg, buf.Bytes(), 0o666)) if !changed && !cfg.changed && !force { fmt.Println("No changes") @@ -398,8 +401,8 @@ func Main() *cli.App { continue } - var url = os.ExpandEnv(dep.Url) - var v = generic.DePtr(dep.Version) + url := os.ExpandEnv(dep.Url) + v := generic.DePtr(dep.Version) // 加载版本 if v != "" { @@ -416,7 +419,7 @@ func Main() *cli.App { fmt.Println(url) url = assert.Must1(filepath.Abs(url)) - var newUrl = filepath.Join(cfg.Vendor, dep.Name) + newUrl := filepath.Join(cfg.Vendor, dep.Name) assert.Must(filepath.Walk(url, func(path string, info fs.FileInfo, err error) (gErr error) { if err != nil { return err @@ -437,7 +440,7 @@ func Main() *cli.App { return nil } - var newPath = filepath.Join(newUrl, strings.TrimPrefix(path, url)) + newPath := filepath.Join(newUrl, strings.TrimPrefix(path, url)) assert.Must(pathutil.IsNotExistMkDir(filepath.Dir(newPath))) assert.Must1(copyFile(newPath, path)) @@ -452,7 +455,7 @@ func Main() *cli.App { return app } -func copyFile(dstFilePath string, srcFilePath string) (written int64, err error) { +func copyFile(dstFilePath, srcFilePath string) (written int64, err error) { srcFile, err := os.Open(srcFilePath) defer srcFile.Close() assert.Must(err, "打开源文件错误", srcFilePath) diff --git a/cmd/protobuild/config.go b/cmd/protobuild/config.go index d6e4aaf..999686f 100644 --- a/cmd/protobuild/config.go +++ b/cmd/protobuild/config.go @@ -1,40 +1,5 @@ package protobuild -import ( - "fmt" - - "github.com/pubgo/funk/errors" - "gopkg.in/yaml.v3" -) - -var _ yaml.Unmarshaler = (*pluginOpts)(nil) - -type pluginOpts []string - -func (p *pluginOpts) UnmarshalYAML(value *yaml.Node) error { - if value.IsZero() { - return nil - } - - switch value.Kind { - case yaml.ScalarNode: - if value.Value != "" { - *p = []string{value.Value} - return nil - } - return nil - case yaml.SequenceNode: - var data []string - if err := value.Decode(&data); err != nil { - return err - } - *p = data - return nil - default: - return errors.New(fmt.Sprintf("yaml kind type error, data=%s", value.Value)) - } -} - type Cfg struct { Checksum string `yaml:"checksum,omitempty" hash:"-"` Vendor string `yaml:"vendor,omitempty"` diff --git a/cmd/protobuild/fmt.go b/cmd/protobuild/fmt.go deleted file mode 100644 index e66fc89..0000000 --- a/cmd/protobuild/fmt.go +++ /dev/null @@ -1,104 +0,0 @@ -// Refer: https://github.com/emicklei/proto-contrib/tree/master/cmd/protofmt -// https://github.com/bufbuild/buf/blob/main/private/buf/bufformat/bufformat.go - -package protobuild - -import ( - "bytes" - "io" - "io/fs" - "io/ioutil" - "os" - "path/filepath" - "strings" - - "github.com/emicklei/proto" - "github.com/emicklei/proto-contrib/pkg/protofmt" - "github.com/pubgo/funk/assert" - "github.com/pubgo/funk/pathutil" - "github.com/pubgo/protobuild/cmd/format" - "github.com/pubgo/protobuild/internal/typex" - "github.com/urfave/cli/v2" -) - -var ( - overwrite = false -) - -func fmtCmd() *cli.Command { - return &cli.Command{ - Name: "fmt", - Usage: "格式化protobuf文件", - Flags: typex.Flags{&cli.BoolFlag{ - Name: "overwrite", - Usage: "write result to (source) file instead of stdout", - Aliases: typex.Strs{"w"}, - Value: overwrite, - Destination: &overwrite, - }}, - Before: func(context *cli.Context) error { - return parseConfig() - }, - Action: func(ctx *cli.Context) error { - var protoList = make(map[string]bool) - - for i := range cfg.Root { - if pathutil.IsNotExist(cfg.Root[i]) { - logger.Info().Msgf("file %s not found", cfg.Root[i]) - continue - } - - assert.Must(filepath.Walk(cfg.Root[i], func(path string, info fs.FileInfo, err error) error { - if err != nil { - return err - } - - if info.IsDir() { - return nil - } - - if strings.HasSuffix(info.Name(), ".proto") { - protoList[path] = true - return nil - } - - return nil - })) - } - - for name := range protoList { - //_ = shutil.MustRun("clang-format", "-i", fmt.Sprintf("-style=google %s", name)) - //readFormatWrite(name) - format.Format(name) - } - - return nil - }, - } -} - -func readFormatWrite(filename string) { - // open for read - file := assert.Must1(os.Open(filename)) - - // buffer before write - buf := new(bytes.Buffer) - format1(filename, file, buf) - - if overwrite { - // write back to input - assert.Must(ioutil.WriteFile(filename, buf.Bytes(), os.ModePerm)) - } else { - // write to stdout - buf.WriteString("\n================================================================================================\n") - assert.Must1(io.Copy(os.Stdout, bytes.NewReader(buf.Bytes()))) - - } -} - -func format1(filename string, input io.Reader, output io.Writer) { - parser := proto.NewParser(input) - parser.Filename(filename) - def := assert.Must1(parser.Parse()) - protofmt.NewFormatter(output, " ").Format(def) // 2 spaces -} diff --git a/cmd/protobuild/yaml_types.go b/cmd/protobuild/yaml_types.go new file mode 100644 index 0000000..c9ccfdd --- /dev/null +++ b/cmd/protobuild/yaml_types.go @@ -0,0 +1,34 @@ +package protobuild + +import ( + "github.com/pubgo/funk/errors" + yaml "gopkg.in/yaml.v3" +) + +var _ yaml.Unmarshaler = (*pluginOpts)(nil) + +type pluginOpts []string + +func (p *pluginOpts) UnmarshalYAML(value *yaml.Node) error { + if value.IsZero() { + return nil + } + + switch value.Kind { + case yaml.ScalarNode: + if value.Value != "" { + *p = []string{value.Value} + return nil + } + return nil + case yaml.SequenceNode: + var data []string + if err := value.Decode(&data); err != nil { + return err + } + *p = data + return nil + default: + return errors.Format("yaml kind type error,kinf=%v data=%s", value.Kind, value.Value) + } +} diff --git a/cmd/protoc-gen-go-json/internal/template.go b/cmd/protoc-gen-go-json/internal/template.go index 447d390..0eaaec5 100644 --- a/cmd/protoc-gen-go-json/internal/template.go +++ b/cmd/protoc-gen-go-json/internal/template.go @@ -18,7 +18,6 @@ type Options struct { // This function is called with a param which contains the entire definition of a method. func ApplyTemplate(w io.Writer, f *protogen.File, opts Options) error { - if err := headerTemplate.Execute(w, tplHeader{ File: f, }); err != nil { diff --git a/cmd/protoc-gen-gotag/internal/retag/extract.go b/cmd/protoc-gen-gotag/internal/retag/extract.go index 0894164..9f7ac8f 100644 --- a/cmd/protoc-gen-gotag/internal/retag/extract.go +++ b/cmd/protoc-gen-gotag/internal/retag/extract.go @@ -65,7 +65,7 @@ func (v *tagExtractor) VisitOneOf(o pgs.OneOf) (pgs.Visitor, error) { return v, nil } - var tt = new(structtag.Tags) + tt := new(structtag.Tags) for _, tag := range tval { assert.Must(tt.Set(&structtag.Tag{Key: tag.Name, Name: tag.Value})) } @@ -108,7 +108,7 @@ func (v *tagExtractor) VisitField(f pgs.Field) (pgs.Visitor, error) { return v, nil } - var tt = new(structtag.Tags) + tt := new(structtag.Tags) for _, tag := range tval { assert.Must(tt.Set(&structtag.Tag{Key: tag.Name, Name: tag.Value})) } diff --git a/cmd/protoc-gen-gotag/internal/retag/tagger.go b/cmd/protoc-gen-gotag/internal/retag/tagger.go index 64430f9..f0fa0d2 100644 --- a/cmd/protoc-gen-gotag/internal/retag/tagger.go +++ b/cmd/protoc-gen-gotag/internal/retag/tagger.go @@ -35,7 +35,6 @@ func (m *mod) InitContext(c pgs.BuildContext) { func (*mod) Name() string { return "retag" } func (m *mod) Execute(targets map[string]pgs.File, packages map[string]pgs.Package) []pgs.Artifact { - xtv := m.Parameters().Str("xxx") xtv = strings.Replace(xtv, "+", ":", -1) diff --git a/cmd/protoc-gen-retag/ast/ast.go b/cmd/protoc-gen-retag/ast/ast.go index b4d120e..7868d86 100644 --- a/cmd/protoc-gen-retag/ast/ast.go +++ b/cmd/protoc-gen-retag/ast/ast.go @@ -81,7 +81,7 @@ func (g *GoFile) genDecl(node ast.Node) bool { } // Handle comment - //if c := tspec.Comment; c != nil && len(c.List) == 1 {} + // if c := tspec.Comment; c != nil && len(c.List) == 1 {} for _, field := range sExpr.Fields.List { fieldName := "" @@ -137,7 +137,7 @@ func (g *GoFile) genDecl(node ast.Node) bool { } // struct tags: protobuf, json, other tags ordered by ascii - var keys = []string{"protobuf", "json"} + keys := []string{"protobuf", "json"} keys = append(keys, strings_.SliceTrim(goTags.OrderKeys(), "protobuf", "json")...) newGoTag := goTags.SelectAstString(keys...) if newGoTag != goTagFieldValue { diff --git a/cmd/protoc-gen-retag/ast/generator.go b/cmd/protoc-gen-retag/ast/generator.go index 52eb35c..78ab418 100644 --- a/cmd/protoc-gen-retag/ast/generator.go +++ b/cmd/protoc-gen-retag/ast/generator.go @@ -16,9 +16,7 @@ import ( "google.golang.org/protobuf/types/pluginpb" ) -var ( - fileSet = token.NewFileSet() -) +var fileSet = token.NewFileSet() type Generator struct { // Ast goFiles to which this package contains. @@ -72,7 +70,7 @@ func (g *Generator) Generate() { ast.Inspect(file.astFile, file.genDecl) } - //if file.fileChanged { + // if file.fileChanged { // FIXME: always generate *.pb.go, to replace protoc-go, avoid "Tried to write the same file twice" { // PrintComment when file is changed by protoc-gen-go-tag. @@ -88,8 +86,8 @@ func (g *Generator) Generate() { } // fix Response will always be generated, so add a new generated file directly. - //content := buf.String() - //file.outerFile.Content = &content + // content := buf.String() + // file.outerFile.Content = &content _, err = g.protoGenerator.NewGeneratedFile(file.outerFile.GetName(), "").Write(buf.Bytes()) if err != nil { g.protoGenerator.Error(fmt.Errorf("failed to new generated file to rewrite: %w", err)) @@ -104,7 +102,7 @@ func PrintComment(file *ast.File) { return } var list ast.Comment - list.Text = "// Code generated by protoc-gen-go-tag. DO NOT EDIT." + list.Text = "// Code generated by protoc-gen-retag. DO NOT EDIT." if len(file.Comments) == 0 { file.Comments = []*ast.CommentGroup{{}} } diff --git a/cmd/protoc-gen-retag/ast/parse_and_rewrite.go b/cmd/protoc-gen-retag/ast/parse_and_rewrite.go index 4d72a5f..7794623 100644 --- a/cmd/protoc-gen-retag/ast/parse_and_rewrite.go +++ b/cmd/protoc-gen-retag/ast/parse_and_rewrite.go @@ -48,19 +48,19 @@ func WalkDescriptorProto(g *protogen.Plugin, dp *descriptorpb.DescriptorProto, t s.StructNameInGo = CamelCaseSlice(append(typeNames, CamelCase(dp.GetName()))) for _, field := range dp.GetField() { - var oneofS *StructInfo + var oneOfS *StructInfo if field.OneofIndex != nil { // Special Case: oneof - oneofS = &StructInfo{} - oneofS.StructNameInProto = field.GetName() - oneofS.StructNameInGo = CamelCaseSlice(append(typeNames, CamelCase(dp.GetName()), CamelCase(field.GetName()))) + oneOfS = &StructInfo{} + oneOfS.StructNameInProto = field.GetName() + oneOfS.StructNameInGo = CamelCaseSlice(append(typeNames, CamelCase(dp.GetName()), CamelCase(field.GetName()))) } - f := HandleFieldDescriptorProto(g, field) + f := HandleFieldDescriptorProto(field) if f != nil { - if oneofS != nil { - oneofS.FieldInfos = append(oneofS.FieldInfos, *f) - if len(oneofS.FieldInfos) > 0 { - ss = append(ss, *oneofS) + if oneOfS != nil { + oneOfS.FieldInfos = append(oneOfS.FieldInfos, *f) + if len(oneOfS.FieldInfos) > 0 { + ss = append(ss, *oneOfS) } } else { s.FieldInfos = append(s.FieldInfos, *f) @@ -71,25 +71,25 @@ func WalkDescriptorProto(g *protogen.Plugin, dp *descriptorpb.DescriptorProto, t typeNames = append(typeNames, CamelCase(dp.GetName())) for _, decl := range dp.GetOneofDecl() { - declS := HandleOneofDescriptorProto(g, decl, typeNames) - if declS != nil { - if decl.GetOptions() != nil { - v := proto.GetExtension(decl.GetOptions(), retagpb.E_OneofTags) - switch v := v.(type) { - case []*retagpb.Tag: - info := FieldInfo{FieldNameInProto: decl.GetName(), FieldNameInGo: CamelCase(decl.GetName())} - for i := range v { - tag := reflect.StructTag{} - tag.SetName(v[i].Name, v[i].Value) - info.FieldTag = append(info.FieldTag, tag) - } - - s.FieldInfos = append(s.FieldInfos, info) + declS := HandleOneOfDescriptorProto(decl, typeNames) + if declS == nil { + continue + } + + if decl.GetOptions() != nil { + v, ok := proto.GetExtension(decl.GetOptions(), retagpb.E_OneofTags).([]*retagpb.Tag) + if ok { + info := FieldInfo{FieldNameInProto: decl.GetName(), FieldNameInGo: CamelCase(decl.GetName())} + for i := range v { + tag := reflect.StructTag{} + tag.SetName(v[i].Name, v[i].Value) + info.FieldTag = append(info.FieldTag, tag) } + s.FieldInfos = append(s.FieldInfos, info) } - - ss = append(ss, *declS) } + + ss = append(ss, *declS) } if len(s.FieldInfos) > 0 { @@ -102,17 +102,18 @@ func WalkDescriptorProto(g *protogen.Plugin, dp *descriptorpb.DescriptorProto, t return ss } -func HandleOneofDescriptorProto(g *protogen.Plugin, dp *descriptorpb.OneofDescriptorProto, typeNames []string) *StructInfo { +func HandleOneOfDescriptorProto(dp *descriptorpb.OneofDescriptorProto, typeNames []string) *StructInfo { if dp == nil { return nil } + s := StructInfo{} s.StructNameInProto = dp.GetName() s.StructNameInGo = "is" + CamelCaseSlice(append(typeNames, CamelCase(dp.GetName()))) return &s } -func HandleFieldDescriptorProto(g *protogen.Plugin, field *descriptorpb.FieldDescriptorProto) *FieldInfo { +func HandleFieldDescriptorProto(field *descriptorpb.FieldDescriptorProto) *FieldInfo { if field.GetOptions() == nil { return nil } @@ -122,7 +123,7 @@ func HandleFieldDescriptorProto(g *protogen.Plugin, field *descriptorpb.FieldDes return nil } - var info = &FieldInfo{FieldNameInProto: field.GetName(), FieldNameInGo: CamelCase(field.GetName())} + info := &FieldInfo{FieldNameInProto: field.GetName(), FieldNameInGo: CamelCase(field.GetName())} for _, v := range tags { tag := reflect.StructTag{} tag.SetName(v.Name, v.Value) diff --git a/cmd/protoc-gen-retag/example/example.pb.go b/cmd/protoc-gen-retag/example/example.pb.go index 4297805..45be98f 100644 --- a/cmd/protoc-gen-retag/example/example.pb.go +++ b/cmd/protoc-gen-retag/example/example.pb.go @@ -2,7 +2,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.32.0 -// protoc v4.25.2 +// protoc v4.25.3 // source: cmd/protoc-gen-retag/example/example.proto package example diff --git a/cmd/protoc-gen-retag/example/example.proto b/cmd/protoc-gen-retag/example/example.proto index 5f51672..b8eced5 100644 --- a/cmd/protoc-gen-retag/example/example.proto +++ b/cmd/protoc-gen-retag/example/example.proto @@ -7,51 +7,51 @@ import "proto/retag/retag.proto"; option go_package = "github.com/pubgo/protobuild/pkg/protoc-gen-retag/example;example"; message Example { - string with_new_tags = 1 [ - (retag.tags) = {name:"graphql",value:"withNewTags,optional"} - ]; + string with_new_tags = 1 [ + (retag.tags) = {name: "graphql",value: "withNewTags,optional"} + ]; - string with_new_multiple = 2 [ - (retag.tags) = {name:"graphql",value:"withNewTags,optional"}, - (retag.tags) = {name:"xml",value:"multi,omitempty"} - ]; + string with_new_multiple = 2 [ + (retag.tags) = {name: "graphql",value: "withNewTags,optional"}, + (retag.tags) = {name: "xml",value: "multi,omitempty"} + ]; - string replace_default = 3 [ - (retag.tags) = {name:"json",value:"replacePrevious111"} - ] ; + string replace_default = 3 [ + (retag.tags) = {name: "json",value: "replacePrevious111"} + ]; - oneof one_of { - option (retag.oneof_tags) = {name:"graphql",value:"withNewTags,optional"}; - string a = 5 [(retag.tags) = {name:"json",value:"A111"}]; - int32 b_jk = 6 [(retag.tags) = {name:"json",value:"b_Jk1111"}]; - } + oneof one_of { + option (retag.oneof_tags) = {name: "graphql",value: "withNewTags,optional"}; + string a = 5 [(retag.tags) = {name: "json",value: "A111"}]; + int32 b_jk = 6 [(retag.tags) = {name: "json",value: "b_Jk1111"}]; + } - optional string ID = 4; + optional string ID = 4; - SecondMessage mm = 7; - optional SecondMessage mm2 = 8; + SecondMessage mm = 7; + optional SecondMessage mm2 = 8; } message SecondMessage { - string with_new_tags = 1 [(retag.tags) = {name:"graphql",value:"withNewTags,optional"}]; - string with_new_multiple = 2 [ - (retag.tags) = {name:"graphql",value:"withNewTags,optional"}, - (retag.tags) = {name:"xml",value:"multi,omitempty"} - ]; + string with_new_tags = 1 [(retag.tags) = {name: "graphql",value: "withNewTags,optional"}]; + string with_new_multiple = 2 [ + (retag.tags) = {name: "graphql",value: "withNewTags,optional"}, + (retag.tags) = {name: "xml",value: "multi,omitempty"} + ]; - string replace_default = 3 [(retag.tags) = {name:"json",value:"replacePrevious1111"}] ; + string replace_default = 3 [(retag.tags) = {name: "json",value: "replacePrevious1111"}]; } message ThirdExample { - message InnerExample { - string id = 1 [ - (retag.tags) = {name:"json",value:"yes111"}, - (retag.tags) = {name:"json",value:"yes222"} + message InnerExample { + string id = 1 [ + (retag.tags) = {name: "json",value: "yes111"}, + (retag.tags) = {name: "json",value: "yes222"} + ]; + int32 yes = 2 [(retag.tags) = {name: "json",value: "id111"}]; + } + + InnerExample inner_example = 1 [ + (retag.tags) = {name: "json",value: "inner1111"} ]; - int32 yes = 2 [(retag.tags) = {name:"json",value:"id111"}]; - } - - InnerExample inner_example = 1 [ - (retag.tags) = {name:"json",value:"inner1111"} - ]; } \ No newline at end of file diff --git a/cmd/protoc-gen-retag/main.go b/cmd/protoc-gen-retag/main.go index 7e04cb3..cf4a56c 100644 --- a/cmd/protoc-gen-retag/main.go +++ b/cmd/protoc-gen-retag/main.go @@ -1,4 +1,5 @@ // Note: 本项目主要思路和代码来源于protoc-gen-go-tag +// https://github.com/searKing/golang/tree/master/tools/protoc-gen-go-tag package main diff --git a/go.mod b/go.mod index faf071b..d1751c9 100644 --- a/go.mod +++ b/go.mod @@ -18,7 +18,6 @@ require ( github.com/searKing/golang/go v1.2.115 github.com/spf13/cast v1.5.0 github.com/urfave/cli/v2 v2.8.0 - github.com/urfave/cli/v3 v3.0.0-alpha8 github.com/yuin/goldmark v1.4.12 go.uber.org/multierr v1.11.0 golang.org/x/mod v0.14.0 @@ -30,7 +29,7 @@ require ( ) require ( - github.com/alecthomas/repr v0.2.0 // indirect + github.com/alecthomas/repr v0.4.0 // indirect github.com/antzucaro/matchr v0.0.0-20210222213004-b04723ef80f0 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect github.com/goccy/go-json v0.10.0 // indirect @@ -43,9 +42,9 @@ require ( github.com/rs/zerolog v1.29.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/spf13/afero v1.9.2 // indirect + github.com/stretchr/testify v1.8.4 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/valyala/fasttemplate v1.2.2 // indirect - github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect golang.org/x/exp v0.0.0-20231206192017-f3f8817b8deb // indirect golang.org/x/net v0.19.0 // indirect golang.org/x/sys v0.15.0 // indirect diff --git a/go.sum b/go.sum index d3a49c9..b58d7e9 100644 --- a/go.sum +++ b/go.sum @@ -38,8 +38,8 @@ cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3f dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= -github.com/alecthomas/repr v0.2.0 h1:HAzS41CIzNW5syS8Mf9UwXhNH1J9aix/BvDRf1Ml2Yk= -github.com/alecthomas/repr v0.2.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= +github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc= +github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= github.com/antzucaro/matchr v0.0.0-20210222213004-b04723ef80f0 h1:R/qAiUxFT3mNgQaNqJe0IVznjKRNm23ohAIh9lgtlzc= github.com/antzucaro/matchr v0.0.0-20210222213004-b04723ef80f0/go.mod h1:v3ZDlfVAL1OrkKHbGSFFK60k0/7hruHPDq2XMs9Gu6U= github.com/bufbuild/protocompile v0.5.1 h1:mixz5lJX4Hiz4FpqFREJHIXLfaLBntfaJv1h+/jS+Qg= @@ -204,16 +204,13 @@ github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81P github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/urfave/cli/v2 v2.8.0 h1:EZsAB20oRW4nHcB99TTL6PrXpBGIEujMEKdjwruY9KQ= github.com/urfave/cli/v2 v2.8.0/go.mod h1:TYFbtzt/azQoJOrGH5mDfZtS0jIkl/OeFwlRWPR9KRM= -github.com/urfave/cli/v3 v3.0.0-alpha8 h1:H+qxFPoCkGzdF8KUMs2fEOZl5io/1QySgUiGfar8occ= -github.com/urfave/cli/v3 v3.0.0-alpha8/go.mod h1:0kK/RUFHyh+yIKSfWxwheGndfnrvYSmYFVeKCh03ZUc= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= -github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU= -github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= diff --git a/internal/modutil/util.go b/internal/modutil/util.go index 693865c..74bc758 100644 --- a/internal/modutil/util.go +++ b/internal/modutil/util.go @@ -10,7 +10,7 @@ import ( "golang.org/x/mod/modfile" ) -func getFileByRecursion(file string, path string) string { +func getFileByRecursion(file, path string) string { filePath := filepath.Join(path, file) if pathutil.IsExist(filePath) { return filePath @@ -24,28 +24,28 @@ func getFileByRecursion(file string, path string) string { } func GoModPath() string { - var pwd = assert.Must1(os.Getwd()) + pwd := assert.Must1(os.Getwd()) return getFileByRecursion("go.mod", pwd) } func LoadVersions() map[string]string { - var path = GoModPath() + path := GoModPath() assert.Assert(path == "", "go.mod not exists") - var modBytes = assert.Must1(ioutil.ReadFile(path)) + modBytes := assert.Must1(ioutil.ReadFile(path)) - var a, err = modfile.Parse("in", modBytes, nil) + a, err := modfile.Parse("in", modBytes, nil) assert.Must(err, "go.mod 解析失败") - var versions = make(map[string]string) + versions := make(map[string]string) for i := range a.Require { - var mod = a.Require[i].Mod + mod := a.Require[i].Mod versions[mod.Path] = mod.Version } for i := range a.Replace { - var mod = a.Replace[i].New + mod := a.Replace[i].New versions[mod.Path] = mod.Version } diff --git a/internal/plugin/plugin.go b/internal/plugin/plugin.go index e03e5d7..099441c 100644 --- a/internal/plugin/plugin.go +++ b/internal/plugin/plugin.go @@ -2,7 +2,6 @@ package plugin import ( "bytes" - "github.com/golang/protobuf/protoc-gen-go/descriptor" "io" "io/ioutil" "log" @@ -10,6 +9,8 @@ import ( "os/exec" "strings" + "github.com/golang/protobuf/protoc-gen-go/descriptor" + "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/pluginpb" ) @@ -22,7 +23,6 @@ func StripParam(req *pluginpb.CodeGeneratorRequest, p string) { v := stripParam(*req.Parameter, p) req.Parameter = &v - } func stripParam(s, p string) string { diff --git a/internal/protoc-gen-errors/main.go b/internal/protoc-gen-errors/main.go index 6d92c3d..3911f38 100644 --- a/internal/protoc-gen-errors/main.go +++ b/internal/protoc-gen-errors/main.go @@ -21,7 +21,7 @@ func main() { originFiles = append(originFiles, gengo.GenerateFile(gen, f)) } - //ast.Rewrite(gen) + // ast.Rewrite(gen) for _, f := range originFiles { f.Skip() diff --git a/internal/protoc-gen-gorm/internal/field.go b/internal/protoc-gen-gorm/internal/field.go index c8b7b91..3a52ec2 100644 --- a/internal/protoc-gen-gorm/internal/field.go +++ b/internal/protoc-gen-gorm/internal/field.go @@ -15,13 +15,13 @@ import ( ) func NewField(field *protogen.Field, gen *protogen.Plugin) *Field { - var f = &Field{GoTag: make(map[string]string)} + f := &Field{GoTag: make(map[string]string)} f.IsList = field.Desc.IsList() f.IsOptional = field.Desc.HasOptionalKeyword() f.IsMap = field.Desc.IsMap() f.IsMessage = field.Message != nil - var tag, ok = gp.GetExtension(field.Desc.Options(), ormpb.E_Field).(*ormpb.GormTag) + tag, ok := gp.GetExtension(field.Desc.Options(), ormpb.E_Field).(*ormpb.GormTag) if !ok || tag != nil { f.tag = tag } @@ -87,7 +87,7 @@ type Field struct { } func getTags(field *protogen.Field) map[string]string { - var tagMap = map[string]string{"json": protoutil.Name(field.GoName).LowerSnakeCase().String()} + tagMap := map[string]string{"json": protoutil.Name(field.GoName).LowerSnakeCase().String()} if tags, ok := gp.GetExtension(field.Desc.Options(), retagpb.E_Tags).([]*retagpb.Tag); ok && tags != nil { for i := range tags { tagMap[tags[i].Name] = tags[i].Value @@ -97,7 +97,7 @@ func getTags(field *protogen.Field) map[string]string { } func (f *Field) genGormField() *jen.Statement { - var g = jen.Id(f.GoName) + g := jen.Id(f.GoName) if f.IsList { g = g.Index() } @@ -107,7 +107,7 @@ func (f *Field) genGormField() *jen.Statement { } if f.IsMessage { - var ormType = f.GoType + ormType := f.GoType switch f.Type { case "google.protobuf.Timestamp": if f.IsOptional { @@ -150,7 +150,7 @@ func (f *Field) genGormField() *jen.Statement { } func (f *Field) genGormCond() string { - var name = f.Name + name := f.Name if strings.HasSuffix(name, "_from") { name = strings.TrimSuffix(name, "_from") return fmt.Sprintf("%s >= ?", name) @@ -176,8 +176,8 @@ func (f *Field) genModel2Protobuf() *jen.Statement { switch f.Type { case "google.protobuf.Timestamp": if f.IsList || f.IsMap { - var v = jen.Op("*").Qual("google.golang.org/protobuf/types/known/timestamppb", "Timestamp") - var gen = jen.Id("x").Dot(f.GoName). + v := jen.Op("*").Qual("google.golang.org/protobuf/types/known/timestamppb", "Timestamp") + gen := jen.Id("x").Dot(f.GoName). Op("="). Make(generic.Ternary(f.IsMap, jen.Map(jen.Id(f.MapKeyType.GoName)), jen.Index()).Add(v), jen.Len(jen.Id("m").Dot(f.GoName))).Line() return gen.For( @@ -209,7 +209,7 @@ func (f *Field) genModel2Protobuf() *jen.Statement { }).Line() default: if f.IsList || f.IsMap { - var gen = jen.Id("x").Dot(f.GoName). + gen := jen.Id("x").Dot(f.GoName). Op("="). Make(generic.Ternary(f.IsList, jen.Index(), jen.Map(jen.Id(f.MapKeyType.GoName))).Op("*").Qual(string(f.GoType.GoImportPath), f.GoType.GoName), jen.Len(jen.Id("m").Dot(f.GoName))).Line() return gen.For( @@ -241,8 +241,8 @@ func (f *Field) genProtobuf2Model() *jen.Statement { switch f.Type { case "google.protobuf.Timestamp": if f.IsList || f.IsMap { - var v = jen.Qual("time", "Time") - var gen = jen.Id("m").Dot(f.GoName). + v := jen.Qual("time", "Time") + gen := jen.Id("m").Dot(f.GoName). Op("="). Make(generic.Ternary(f.IsMap, jen.Map(jen.Id(f.MapKeyType.GoName)), jen.Index()).Add(v), jen.Len(jen.Id("x").Dot(f.GoName))).Line() return gen.For( @@ -277,7 +277,7 @@ func (f *Field) genProtobuf2Model() *jen.Statement { }).Line() default: if f.IsList || f.IsMap { - var gen = jen.Id("m").Dot(f.GoName). + gen := jen.Id("m").Dot(f.GoName). Op("="). Make(generic.Ternary(f.IsList, jen.Index(), jen.Map(jen.Id(f.MapKeyType.GoName))).Op("*").Qual(string(f.GoType.GoImportPath), f.GoType.GoName+"Model"), jen.Len(jen.Id("x").Dot(f.GoName))).Line() return gen.For( diff --git a/internal/protoc-gen-gorm/internal/mod.go b/internal/protoc-gen-gorm/internal/mod.go index 2adafeb..c4ed3ac 100644 --- a/internal/protoc-gen-gorm/internal/mod.go +++ b/internal/protoc-gen-gorm/internal/mod.go @@ -49,7 +49,7 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated fields map[string]*Field } - var tables = make(map[string]*table) + tables := make(map[string]*table) for i := range file.Messages { m := file.Messages[i] @@ -57,12 +57,12 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated continue } - var opts, ok = gp.GetExtension(m.Desc.Options(), ormpb.E_Opts).(*ormpb.GormMessageOptions) + opts, ok := gp.GetExtension(m.Desc.Options(), ormpb.E_Opts).(*ormpb.GormMessageOptions) if !ok || opts == nil || !opts.Enabled { continue } - var tableName = string(m.Desc.Name()) + tableName := string(m.Desc.Name()) if opts.Table != "" { tableName = opts.Table } @@ -76,7 +76,7 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated } for j := range m.Fields { - var ff = NewField(m.Fields[j], gen) + ff := NewField(m.Fields[j], gen) tables[tableName].fields[ff.GoName] = ff if ff.tag != nil && ff.tag.Pk { @@ -101,26 +101,26 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated continue } - var name = protoutil.Name(srv.Desc.Name()).UpperCamelCase().String() + name := protoutil.Name(srv.Desc.Name()).UpperCamelCase().String() logger.Info().Msg(string(srv.Desc.FullName())) - var opts, ok = gp.GetExtension(srv.Desc.Options(), ormpb.E_Server).(*ormpb.GormMessageOptions) + opts, ok := gp.GetExtension(srv.Desc.Options(), ormpb.E_Server).(*ormpb.GormMessageOptions) if !ok || opts == nil || !opts.Service { continue } - var tb = tables[opts.Table] + tb := tables[opts.Table] if tb == nil { panic(fmt.Sprintf("table [%s] not found", opts.Table)) } - var srvName = fmt.Sprintf("%sGormHandler", name) + srvName := fmt.Sprintf("%sGormHandler", name) genFile.Add( jen.Type().Id(srvName).InterfaceFunc(func(g *jen.Group) { for j := range srv.Methods { - var m = srv.Methods[j] - var code = jen.Id(m.GoName). + m := srv.Methods[j] + code := jen.Id(m.GoName). Params( jen.Id("ctx").Qual("context", "Context"), jen.Id("req").Op("*").Id(m.Input.GoIdent.GoName), @@ -174,7 +174,7 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated ) for j := range srv.Methods { - var m = srv.Methods[j] + m := srv.Methods[j] logger.Info().Str("name", m.GoName). Msg("service method") @@ -200,19 +200,15 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated g.Var().Id("rsp").Op("=").New(jen.Id(m.Output.GoIdent.GoName)) if strings.HasPrefix(m.GoName, "Create") { - } if strings.HasPrefix(m.GoName, "Delete") { - } if strings.HasPrefix(m.GoName, "Update") { - } if strings.HasPrefix(m.GoName, "Get") { - } if strings.HasPrefix(m.GoName, "List") { @@ -229,19 +225,19 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated for i := range file.Messages { m := file.Messages[i] - var opts, ok = gp.GetExtension(m.Desc.Options(), ormpb.E_Opts).(*ormpb.GormMessageOptions) + opts, ok := gp.GetExtension(m.Desc.Options(), ormpb.E_Opts).(*ormpb.GormMessageOptions) if !ok || opts == nil || !opts.Enabled { continue } - var ormName = protoutil.Name(string(m.Desc.Name()) + "Model").UpperCamelCase().String() + ormName := protoutil.Name(string(m.Desc.Name()) + "Model").UpperCamelCase().String() logger.Info(). Str("orm", ormName). Msg(string(m.Desc.FullName())) - var tb = &table{fields: map[string]*Field{}, name: ormName} + tb := &table{fields: map[string]*Field{}, name: ormName} for j := range m.Fields { - var ff = NewField(m.Fields[j], gen) + ff := NewField(m.Fields[j], gen) tb.fields[ff.GoName] = ff if ff.tag != nil && ff.tag.Pk { tb.pkName = ff.Name @@ -252,15 +248,15 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated _gen := jen.Commentf("%s gen from %s.%s", ormName, string(m.GoIdent.GoImportPath), m.GoIdent.GoName).Line() _gen = _gen.Type().Id(ormName).StructFunc(func(group *jen.Group) { for j := range m.Fields { - var ff = NewField(m.Fields[j], gen) + ff := NewField(m.Fields[j], gen) group.Add(ff.genGormField()) } }).Line().Line() - var createModel = protoutil.Name(string(m.Desc.Name()) + "CreateModel").UpperCamelCase().String() + createModel := protoutil.Name(string(m.Desc.Name()) + "CreateModel").UpperCamelCase().String() _gen = _gen.Type().Id(createModel).StructFunc(func(group *jen.Group) { for j := range m.Fields { - var ff = NewField(m.Fields[j], gen) + ff := NewField(m.Fields[j], gen) if ff.tag == nil || (!ff.tag.AllowCreate && !ff.tag.AllowAll) { continue } @@ -269,10 +265,10 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated } }).Line().Line() - var updateModel = protoutil.Name(string(m.Desc.Name()) + "UpdateModel").UpperCamelCase().String() + updateModel := protoutil.Name(string(m.Desc.Name()) + "UpdateModel").UpperCamelCase().String() _gen = _gen.Type().Id(updateModel).StructFunc(func(group *jen.Group) { for j := range m.Fields { - var ff = NewField(m.Fields[j], gen) + ff := NewField(m.Fields[j], gen) if ff.tag == nil || (!ff.tag.AllowUpdate && !ff.tag.AllowAll) { continue } @@ -281,10 +277,10 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated } }).Line().Line() - var detailModel = protoutil.Name(string(m.Desc.Name()) + "DetailModel").UpperCamelCase().String() + detailModel := protoutil.Name(string(m.Desc.Name()) + "DetailModel").UpperCamelCase().String() _gen = _gen.Type().Id(detailModel).StructFunc(func(group *jen.Group) { for j := range m.Fields { - var ff = NewField(m.Fields[j], gen) + ff := NewField(m.Fields[j], gen) if ff.tag == nil || (!ff.tag.AllowDetail && !ff.tag.AllowAll) { continue } @@ -293,10 +289,10 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated } }).Line().Line() - var listModel = protoutil.Name(string(m.Desc.Name()) + "ListModel").UpperCamelCase().String() + listModel := protoutil.Name(string(m.Desc.Name()) + "ListModel").UpperCamelCase().String() _gen = _gen.Type().Id(listModel).StructFunc(func(group *jen.Group) { for j := range m.Fields { - var ff = NewField(m.Fields[j], gen) + ff := NewField(m.Fields[j], gen) if ff.tag == nil || (!ff.tag.AllowList && !ff.tag.AllowAll) { continue } @@ -305,7 +301,7 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated } }).Line().Line() - var tableName = string(m.Desc.Name()) + tableName := string(m.Desc.Name()) if opts.Table != "" { tableName = opts.Table } @@ -389,7 +385,7 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated g.Var().Id("x").Op("=").New(jen.Id(string(m.Desc.Name()))) for j := range m.Fields { - var ff = NewField(m.Fields[j], gen) + ff := NewField(m.Fields[j], gen) g.Add(ff.genModel2Protobuf()) } @@ -406,7 +402,7 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated g.Var().Id("m").Op("=").New(jen.Id(ormName)) for j := range m.Fields { - var ff = NewField(m.Fields[j], gen) + ff := NewField(m.Fields[j], gen) g.Add(ff.genProtobuf2Model()) } diff --git a/internal/protoc-gen-gorm/internal1/field.go b/internal/protoc-gen-gorm/internal1/field.go index da512e6..1622029 100644 --- a/internal/protoc-gen-gorm/internal1/field.go +++ b/internal/protoc-gen-gorm/internal1/field.go @@ -14,13 +14,13 @@ import ( ) func NewField(field *protogen.Field, gen *protogen.Plugin) *Field { - var f = &Field{GoTag: make(map[string]string)} + f := &Field{GoTag: make(map[string]string)} f.IsList = field.Desc.IsList() f.IsOptional = field.Desc.HasOptionalKeyword() f.IsMap = field.Desc.IsMap() f.IsMessage = field.Message != nil - var tag, ok = gp.GetExtension(field.Desc.Options(), ormpb.E_Tag).(*ormpb.GormTag) + tag, ok := gp.GetExtension(field.Desc.Options(), ormpb.E_Tag).(*ormpb.GormTag) if !ok || tag != nil { f.tag = tag } @@ -79,7 +79,7 @@ type Field struct { } func getTags(field *protogen.Field) map[string]string { - var tagMap = map[string]string{"json": protoutil.Name(field.GoName).LowerSnakeCase().String()} + tagMap := map[string]string{"json": protoutil.Name(field.GoName).LowerSnakeCase().String()} if tags, ok := gp.GetExtension(field.Desc.Options(), retagpb.E_Tags).([]*retagpb.Tag); ok && tags != nil { for i := range tags { tagMap[tags[i].Name] = tags[i].Value @@ -89,7 +89,7 @@ func getTags(field *protogen.Field) map[string]string { } func (f *Field) genGormField() *jen.Statement { - var g = jen.Id(f.GoName) + g := jen.Id(f.GoName) if f.IsList { g = g.Index() } @@ -99,7 +99,7 @@ func (f *Field) genGormField() *jen.Statement { } if f.IsMessage { - var ormType = f.GoType + ormType := f.GoType switch f.Type { case "google.protobuf.Timestamp": if f.IsOptional { @@ -142,7 +142,7 @@ func (f *Field) genGormField() *jen.Statement { } func (f *Field) genGormCond() string { - var name = f.Name + name := f.Name if strings.HasSuffix(name, "_from") { name = strings.TrimSuffix(name, "_from") return fmt.Sprintf("%s >= ?", name) @@ -168,8 +168,8 @@ func (f *Field) genModel2Protobuf() *jen.Statement { switch f.Type { case "google.protobuf.Timestamp": if f.IsList || f.IsMap { - var v = jen.Op("*").Qual("google.golang.org/protobuf/types/known/timestamppb", "Timestamp") - var gen = jen.Id("x").Dot(f.GoName). + v := jen.Op("*").Qual("google.golang.org/protobuf/types/known/timestamppb", "Timestamp") + gen := jen.Id("x").Dot(f.GoName). Op("="). Make(generic.Ternary(f.IsMap, jen.Map(jen.Id(f.MapKeyType.GoName)), jen.Index()).Add(v), jen.Len(jen.Id("m").Dot(f.GoName))).Line() return gen.For( @@ -201,7 +201,7 @@ func (f *Field) genModel2Protobuf() *jen.Statement { }).Line() default: if f.IsList || f.IsMap { - var gen = jen.Id("x").Dot(f.GoName). + gen := jen.Id("x").Dot(f.GoName). Op("="). Make(generic.Ternary(f.IsList, jen.Index(), jen.Map(jen.Id(f.MapKeyType.GoName))).Op("*").Qual(string(f.GoType.GoImportPath), f.GoType.GoName), jen.Len(jen.Id("m").Dot(f.GoName))).Line() return gen.For( @@ -233,8 +233,8 @@ func (f *Field) genProtobuf2Model() *jen.Statement { switch f.Type { case "google.protobuf.Timestamp": if f.IsList || f.IsMap { - var v = jen.Qual("time", "Time") - var gen = jen.Id("m").Dot(f.GoName). + v := jen.Qual("time", "Time") + gen := jen.Id("m").Dot(f.GoName). Op("="). Make(generic.Ternary(f.IsMap, jen.Map(jen.Id(f.MapKeyType.GoName)), jen.Index()).Add(v), jen.Len(jen.Id("x").Dot(f.GoName))).Line() return gen.For( @@ -269,7 +269,7 @@ func (f *Field) genProtobuf2Model() *jen.Statement { }).Line() default: if f.IsList || f.IsMap { - var gen = jen.Id("m").Dot(f.GoName). + gen := jen.Id("m").Dot(f.GoName). Op("="). Make(generic.Ternary(f.IsList, jen.Index(), jen.Map(jen.Id(f.MapKeyType.GoName))).Op("*").Qual(string(f.GoType.GoImportPath), f.GoType.GoName+"Model"), jen.Len(jen.Id("x").Dot(f.GoName))).Line() return gen.For( diff --git a/internal/protoc-gen-gorm/internal1/mod.go b/internal/protoc-gen-gorm/internal1/mod.go index 7cb5814..d0d2e26 100644 --- a/internal/protoc-gen-gorm/internal1/mod.go +++ b/internal/protoc-gen-gorm/internal1/mod.go @@ -49,7 +49,7 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated fields map[string]*Field } - var tables = make(map[string]*table) + tables := make(map[string]*table) for i := range file.Messages { m := file.Messages[i] @@ -57,12 +57,12 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated continue } - var opts, ok = gp.GetExtension(m.Desc.Options(), ormpb.E_Opts).(*ormpb.GormMessageOptions) + opts, ok := gp.GetExtension(m.Desc.Options(), ormpb.E_Opts).(*ormpb.GormMessageOptions) if !ok || opts == nil || !opts.Enabled { continue } - var tableName = string(m.Desc.Name()) + tableName := string(m.Desc.Name()) if opts.Table != "" { tableName = opts.Table } @@ -76,7 +76,7 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated } for j := range m.Fields { - var ff = NewField(m.Fields[j], gen) + ff := NewField(m.Fields[j], gen) tables[tableName].fields[ff.GoName] = ff if ff.tag != nil && ff.tag.Pk { @@ -98,26 +98,26 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated continue } - var name = protoutil.Name(srv.Desc.Name()).UpperCamelCase().String() + name := protoutil.Name(srv.Desc.Name()).UpperCamelCase().String() logger.Info(string(srv.Desc.FullName())) - var opts, ok = gp.GetExtension(srv.Desc.Options(), ormpb.E_Server).(*ormpb.GormMessageOptions) + opts, ok := gp.GetExtension(srv.Desc.Options(), ormpb.E_Server).(*ormpb.GormMessageOptions) if !ok || opts == nil || !opts.Service { continue } - var tb = tables[opts.Table] + tb := tables[opts.Table] if tb == nil { panic(fmt.Sprintf("table [%s] not found", opts.Table)) } - var srvName = fmt.Sprintf("%sGormHandler", name) + srvName := fmt.Sprintf("%sGormHandler", name) genFile.Add( jen.Type().Id(srvName).InterfaceFunc(func(g *jen.Group) { for j := range srv.Methods { - var m = srv.Methods[j] - var code = jen.Id(m.GoName). + m := srv.Methods[j] + code := jen.Id(m.GoName). Params( jen.Id("ctx").Qual("context", "Context"), jen.Id("req").Op("*").Id(m.Input.GoIdent.GoName), @@ -171,7 +171,7 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated ) for j := range srv.Methods { - var m = srv.Methods[j] + m := srv.Methods[j] logger.Info("service method", "name", m.GoName) @@ -196,19 +196,15 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated g.Var().Id("rsp").Op("=").New(jen.Id(m.Output.GoIdent.GoName)) if strings.HasPrefix(m.GoName, "Create") { - } if strings.HasPrefix(m.GoName, "Delete") { - } if strings.HasPrefix(m.GoName, "Update") { - } if strings.HasPrefix(m.GoName, "Get") { - } if strings.HasPrefix(m.GoName, "List") { @@ -225,17 +221,17 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated for i := range file.Messages { m := file.Messages[i] - var opts, ok = gp.GetExtension(m.Desc.Options(), ormpb.E_Opts).(*ormpb.GormMessageOptions) + opts, ok := gp.GetExtension(m.Desc.Options(), ormpb.E_Opts).(*ormpb.GormMessageOptions) if !ok || opts == nil || !opts.Enabled { continue } - var ormName = protoutil.Name(string(m.Desc.Name()) + "Model").UpperCamelCase().String() + ormName := protoutil.Name(string(m.Desc.Name()) + "Model").UpperCamelCase().String() logger.Info(string(m.Desc.FullName()), "orm", ormName) - var tb = &table{fields: map[string]*Field{}, name: ormName} + tb := &table{fields: map[string]*Field{}, name: ormName} for j := range m.Fields { - var ff = NewField(m.Fields[j], gen) + ff := NewField(m.Fields[j], gen) tb.fields[ff.GoName] = ff if ff.tag != nil && ff.tag.Pk { tb.pkName = ff.Name @@ -246,12 +242,12 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated _gen := jen.Commentf("%s gen from %s.%s", ormName, string(m.GoIdent.GoImportPath), m.GoIdent.GoName).Line() _gen = _gen.Type().Id(ormName).StructFunc(func(group *jen.Group) { for j := range m.Fields { - var ff = NewField(m.Fields[j], gen) + ff := NewField(m.Fields[j], gen) group.Add(ff.genGormField()) } }).Line().Line() - var tableName = string(m.Desc.Name()) + tableName := string(m.Desc.Name()) if opts.Table != "" { tableName = opts.Table } @@ -306,7 +302,7 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated g.Var().Id("x").Op("=").New(jen.Id(string(m.Desc.Name()))) for j := range m.Fields { - var ff = NewField(m.Fields[j], gen) + ff := NewField(m.Fields[j], gen) g.Add(ff.genModel2Protobuf()) } @@ -323,7 +319,7 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated g.Var().Id("m").Op("=").New(jen.Id(ormName)) for j := range m.Fields { - var ff = NewField(m.Fields[j], gen) + ff := NewField(m.Fields[j], gen) g.Add(ff.genProtobuf2Model()) } diff --git a/internal/protoc-gen-gotag/internal/retag/ast.go b/internal/protoc-gen-gotag/internal/retag/ast.go index 694099a..6a15715 100644 --- a/internal/protoc-gen-gotag/internal/retag/ast.go +++ b/internal/protoc-gen-gotag/internal/retag/ast.go @@ -78,7 +78,7 @@ func (g *GoFile) genDecl(node ast.Node) bool { } // Handle comment - //if c := tspec.Comment; c != nil && len(c.List) == 1 {} + // if c := tspec.Comment; c != nil && len(c.List) == 1 {} for _, field := range sExpr.Fields.List { fieldName := "" @@ -137,7 +137,7 @@ func (g *GoFile) genDecl(node ast.Node) bool { } // struct tags: protobuf, json, other tags ordered by ascii - var keys = []string{"protobuf", "json"} + keys := []string{"protobuf", "json"} keys = append(keys, strings_.SliceTrim(goTags.OrderKeys(), "protobuf", "json")...) newGoTag := goTags.SelectAstString(keys...) if newGoTag != goTagFieldValue { diff --git a/internal/protoc-gen-gotag/internal/retag/generator.go b/internal/protoc-gen-gotag/internal/retag/generator.go index 2750e0e..59bfd8f 100644 --- a/internal/protoc-gen-gotag/internal/retag/generator.go +++ b/internal/protoc-gen-gotag/internal/retag/generator.go @@ -12,9 +12,7 @@ import ( "google.golang.org/protobuf/types/pluginpb" ) -var ( - fset = token.NewFileSet() -) +var fset = token.NewFileSet() type Generator struct { // Ast goFiles to which this package contains. @@ -68,7 +66,7 @@ func (g *Generator) Generate() { ast.Inspect(file.astFile, file.genDecl) } - //if file.fileChanged { + // if file.fileChanged { // FIXME: always generate *.pb.go, to replace protoc-go, avoid "Tried to write the same file twice" { // PrintComment when file is changed by protoc-gen-go-tag. @@ -83,8 +81,8 @@ func (g *Generator) Generate() { } // fix Response will always be generated, so add a new generated file directly. - //content := buf.String() - //file.outerFile.Content = &content + // content := buf.String() + // file.outerFile.Content = &content _, err = g.protoGenerator.NewGeneratedFile(file.outerFile.GetName(), "").Write(buf.Bytes()) if err != nil { g.protoGenerator.Error(fmt.Errorf("failed to new generated file to rewrite: %w", err)) diff --git a/internal/protoc-gen-gotag/internal/retag/rewrite.go b/internal/protoc-gen-gotag/internal/retag/rewrite.go index c001890..197c73c 100644 --- a/internal/protoc-gen-gotag/internal/retag/rewrite.go +++ b/internal/protoc-gen-gotag/internal/retag/rewrite.go @@ -2,11 +2,12 @@ package retag import ( "fmt" + "reflect" + "github.com/pubgo/funk/generic" "google.golang.org/protobuf/compiler/protogen" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/descriptorpb" - "reflect" ) type FieldInfo struct { @@ -44,7 +45,7 @@ func WalkDescriptorProto(g *protogen.Plugin, dp *descriptorpb.DescriptorProto, t s.StructNameInProto = dp.GetName() s.StructNameInGo = CamelCaseSlice(append(typeNames, CamelCase(dp.GetName()))) - //typeNames := []string{s.StructNameInGo} + // typeNames := []string{s.StructNameInGo} for _, field := range dp.GetField() { if field.GetOptions() == nil { continue diff --git a/internal/protoc-gen-gotag/main.go b/internal/protoc-gen-gotag/main.go index 434add0..2caefc9 100644 --- a/internal/protoc-gen-gotag/main.go +++ b/internal/protoc-gen-gotag/main.go @@ -4,6 +4,7 @@ package main import ( "flag" + "github.com/pubgo/protobuild/internal/protoc-gen-gotag/internal/retag" gengo "google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo" @@ -11,9 +12,7 @@ import ( ) func main() { - var ( - flags flag.FlagSet - ) + var flags flag.FlagSet protogen.Options{ParamFunc: flags.Set}.Run(func(gen *protogen.Plugin) error { gen.SupportedFeatures = gengo.SupportedFeatures diff --git a/internal/protoc-gen-lava/internal/gensql.go b/internal/protoc-gen-lava/internal/gensql.go index 3e8119a..1e1ddd3 100644 --- a/internal/protoc-gen-lava/internal/gensql.go +++ b/internal/protoc-gen-lava/internal/gensql.go @@ -7,7 +7,7 @@ import ( func genSql(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service) { for _, mth := range service.Methods { - var opts = mth.Desc.Options() + opts := mth.Desc.Options() if !gp.HasExtension(opts, lava.E_Sqlx) { continue } diff --git a/internal/protoc-gen-lava/internal/lava.go b/internal/protoc-gen-lava/internal/lava.go index 4e15b21..08b4210 100644 --- a/internal/protoc-gen-lava/internal/lava.go +++ b/internal/protoc-gen-lava/internal/lava.go @@ -67,10 +67,10 @@ func generateFileContent(gen *protogen.Plugin, file *protogen.File, g *protogen. for _, service := range file.Services { genClient(gen, file, g, service) genRpcInfo(gen, file, g, service) - //genRestApiTest(gen, file, g, service) - //genRestRouter(gen, file, g, service) - //genGinRouter(gen, file, g, service) - //genSql(gen, file, g, service) + // genRestApiTest(gen, file, g, service) + // genRestRouter(gen, file, g, service) + // genGinRouter(gen, file, g, service) + // genSql(gen, file, g, service) } } @@ -82,39 +82,39 @@ func genClient(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedF } func genRpcInfo(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service) { - //g.P("func init(){") - //g.P("var mthList []", xgenCall("GrpcRestHandler")) + // g.P("func init(){") + // g.P("var mthList []", xgenCall("GrpcRestHandler")) var isGw bool for _, m := range service.Methods { - //g.P("mthList = append(mthList, ", xgenCall("GrpcRestHandler"), "{") - //g.P("Input: &", g.QualifiedGoIdent(m.Input.GoIdent), "{},") - //g.P("Output: &", g.QualifiedGoIdent(m.Output.GoIdent), "{},") - //g.P(fmt.Sprintf(`Service:"%s",`, service.Desc.FullName())) - //g.P(fmt.Sprintf(`Name:"%s",`, m.Desc.Name())) + // g.P("mthList = append(mthList, ", xgenCall("GrpcRestHandler"), "{") + // g.P("Input: &", g.QualifiedGoIdent(m.Input.GoIdent), "{},") + // g.P("Output: &", g.QualifiedGoIdent(m.Output.GoIdent), "{},") + // g.P(fmt.Sprintf(`Service:"%s",`, service.Desc.FullName())) + // g.P(fmt.Sprintf(`Name:"%s",`, m.Desc.Name())) - //var defaultUrl bool + // var defaultUrl bool hr, err := protoutil.ExtractAPIOptions(m.Desc) if err == nil && hr != nil { - //defaultUrl = true + // defaultUrl = true isGw = true - //var replacer = strings.NewReplacer(".", "/", "-", "/") - //hr = protoutil.DefaultAPIOptions(replacer.Replace(string(file.Desc.Package())), service.GoName, m.GoName) + // var replacer = strings.NewReplacer(".", "/", "-", "/") + // hr = protoutil.DefaultAPIOptions(replacer.Replace(string(file.Desc.Package())), service.GoName, m.GoName) } - //method, path := protoutil.ExtractHttpMethod(hr) - //g.P(fmt.Sprintf(`Method:"%s",`, method)) - //g.P(fmt.Sprintf(`Path:"%s",`, path)) - //g.P(fmt.Sprintf(`DefaultUrl:%v,`, defaultUrl)) - //g.P("ClientStream:", m.Desc.IsStreamingClient(), ",") - //g.P("ServerStream:", m.Desc.IsStreamingServer(), ",") - //g.P("})") - //g.P() + // method, path := protoutil.ExtractHttpMethod(hr) + // g.P(fmt.Sprintf(`Method:"%s",`, method)) + // g.P(fmt.Sprintf(`Path:"%s",`, path)) + // g.P(fmt.Sprintf(`DefaultUrl:%v,`, defaultUrl)) + // g.P("ClientStream:", m.Desc.IsStreamingClient(), ",") + // g.P("ServerStream:", m.Desc.IsStreamingServer(), ",") + // g.P("})") + // g.P() } // grpc - //g.P(xgenCall("Add"), "(Register", service.GoName, "Server, mthList)") - //g.P("}") - //g.P() + // g.P(xgenCall("Add"), "(Register", service.GoName, "Server, mthList)") + // g.P("}") + // g.P() if enableLava { if isGw { diff --git a/internal/protoc-gen-lava/internal/restapi.go b/internal/protoc-gen-lava/internal/restapi.go index 8a79dc7..5b74bb8 100644 --- a/internal/protoc-gen-lava/internal/restapi.go +++ b/internal/protoc-gen-lava/internal/restapi.go @@ -13,7 +13,7 @@ import ( // gen rest.http from protobuf func genRestApiTest(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service) { - var genPath = fmt.Sprintf("%s.%s.http", file.GoPackageName, service.GoName) + genPath := fmt.Sprintf("%s.%s.http", file.GoPackageName, service.GoName) var data []string for _, m := range service.Methods { @@ -32,7 +32,7 @@ func genRestApiTest(gen *protogen.Plugin, file *protogen.File, g *protogen.Gener data = append(data, fmt.Sprintf("Content-Type: application/json\n\n")) } assert.If(!utils.DirExists(testDir), "dir %s not found", testDir) - assert.Must(os.WriteFile(filepath.Join(testDir, genPath), []byte(strings.Join(data, "")), 0755)) + assert.Must(os.WriteFile(filepath.Join(testDir, genPath), []byte(strings.Join(data, "")), 0o755)) } //func genRestRouter(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service) { diff --git a/internal/protoc-gen-lava/internal/version.go b/internal/protoc-gen-lava/internal/version.go index 82ab5d4..321a2fa 100644 --- a/internal/protoc-gen-lava/internal/version.go +++ b/internal/protoc-gen-lava/internal/version.go @@ -4,11 +4,13 @@ import "flag" const version = "v0.1.0" -var path string -var testDir string -var genGin bool -var enableLava bool -var Flags flag.FlagSet +var ( + path string + testDir string + genGin bool + enableLava bool + Flags flag.FlagSet +) func init() { Flags.BoolVar(&genGin, "gin", false, "generate gin api") diff --git a/internal/protoc-gen-resty/internal/resty.go b/internal/protoc-gen-resty/internal/resty.go index 59a3cab..f080271 100644 --- a/internal/protoc-gen-resty/internal/resty.go +++ b/internal/protoc-gen-resty/internal/resty.go @@ -2,10 +2,11 @@ package internal import ( "fmt" - "github.com/pubgo/funk/errors" "net/http" "strings" + "github.com/pubgo/funk/errors" + "github.com/pubgo/funk/recovery" "github.com/pubgo/protobuild/internal/protoutil" "google.golang.org/protobuf/compiler/protogen" @@ -95,7 +96,7 @@ func genClientMethod(gen *protogen.Plugin, file *protogen.File, g *protogen.Gene service := method.Parent hr, err := protoutil.ExtractAPIOptions(method.Desc) if err != nil || hr == nil { - var replacer = strings.NewReplacer(".", "/", "-", "/") + replacer := strings.NewReplacer(".", "/", "-", "/") hr = protoutil.DefaultAPIOptions(replacer.Replace(string(file.Desc.Package())), service.GoName, method.GoName) } mth, path := protoutil.ExtractHttpMethod(hr) diff --git a/internal/protoc-gen-resty/internal/version.go b/internal/protoc-gen-resty/internal/version.go index 4c3958d..9718a70 100644 --- a/internal/protoc-gen-resty/internal/version.go +++ b/internal/protoc-gen-resty/internal/version.go @@ -1,6 +1,8 @@ package internal -var PathTag = "param" -var QueryTag = "query" +var ( + PathTag = "param" + QueryTag = "query" +) const version = "v0.1.0" diff --git a/internal/protoutil/gen.go b/internal/protoutil/gen.go index 8f573f9..5f8a44d 100644 --- a/internal/protoutil/gen.go +++ b/internal/protoutil/gen.go @@ -50,7 +50,7 @@ func Append(s *string, args ...string) { } func IsHelp() bool { - var arg = strings.TrimSpace(os.Args[len(os.Args)-1]) + arg := strings.TrimSpace(os.Args[len(os.Args)-1]) return arg == "--help" || arg == "-h" } @@ -207,7 +207,7 @@ func CamelCase(s string) string { // - method is POST // - path is "//" // - body should contain the serialized request message -func DefaultAPIOptions(pkg string, srv string, mth string) *options.HttpRule { +func DefaultAPIOptions(pkg, srv, mth string) *options.HttpRule { return &options.HttpRule{ Pattern: &options.HttpRule_Post{ Post: "/" + Camel2Case(fmt.Sprintf("%s/%s/%s", Camel2Case(pkg), Camel2Case(srv), Camel2Case(mth))), @@ -234,7 +234,7 @@ func ExtractAPIOptions(mth protoreflect.MethodDescriptor) (*options.HttpRule, er return opts, nil } -func ExtractHttpMethod(opts *options.HttpRule) (method string, path string) { +func ExtractHttpMethod(opts *options.HttpRule) (method, path string) { var ( httpMethod string pathTemplate string @@ -304,7 +304,7 @@ func trim(s string) string { } func Import(name string) func(id string) protogen.GoIdent { - var pkg = protogen.GoImportPath(name) + pkg := protogen.GoImportPath(name) return func(id string) protogen.GoIdent { return pkg.Ident(id) } @@ -327,7 +327,7 @@ func Template(tpl string, m pongo.Context) string { temp, err := pongo.FromString(strings.TrimSpace(tpl)) assert.Must(err) - var g = bytes.NewBuffer(nil) + g := bytes.NewBuffer(nil) assert.Must(temp.ExecuteWriter(m, g)) return g.String() } @@ -426,7 +426,7 @@ func httpPathsAdditionalBindings(m *descriptor.MethodDescriptorProto) []string { } var httpPaths []string - var optsAdditionalBindings = opts.GetAdditionalBindings() + optsAdditionalBindings := opts.GetAdditionalBindings() for _, optAdditionalBindings := range optsAdditionalBindings { switch t := optAdditionalBindings.Pattern.(type) { case *options.HttpRule_Get: diff --git a/internal/protoutil/name.go b/internal/protoutil/name.go index 0b21098..7df9a63 100644 --- a/internal/protoutil/name.go +++ b/internal/protoutil/name.go @@ -2,11 +2,10 @@ package protoutil import ( "bytes" + "path/filepath" "strings" "unicode" "unicode/utf8" - - "path/filepath" ) // A Name describes an identifier of an Entity (Message, Field, Enum, Service, diff --git a/internal/shutil/shell.go b/internal/shutil/shell.go index 6543010..99dbee7 100644 --- a/internal/shutil/shell.go +++ b/internal/shutil/shell.go @@ -35,7 +35,7 @@ func GoList() (string, error) { } func Shell(args ...string) *exec.Cmd { - var shell = strings.Join(args, " ") + shell := strings.Join(args, " ") cmd := exec.Command("/bin/sh", "-c", shell) cmd.Env = os.Environ() cmd.Stdout = os.Stdout diff --git a/internal/template/template.go b/internal/template/template.go index c82d43e..91d1eba 100644 --- a/internal/template/template.go +++ b/internal/template/template.go @@ -61,7 +61,7 @@ func main() { } if d.IsDir() { - return os.MkdirAll(filepath.Join(dstDir, name), 0700) + return os.MkdirAll(filepath.Join(dstDir, name), 0o700) } ext := filepath.Ext(name) @@ -84,7 +84,7 @@ func main() { return err } name := filepath.Join(dstDir, fpath) + ".html" - fi, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE, 0600) + fi, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE, 0o600) if err != nil { return err } @@ -99,12 +99,12 @@ func main() { } name := filepath.Join(dstDir, name) - err = os.MkdirAll(filepath.Dir(name), 0700) + err = os.MkdirAll(filepath.Dir(name), 0o700) if err != nil { return err } - dst, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE, 0600) + dst, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE, 0o600) if err != nil { return err } diff --git a/internal/typex/cli.go b/internal/typex/cli.go index c4375d0..b1cb67b 100644 --- a/internal/typex/cli.go +++ b/internal/typex/cli.go @@ -4,7 +4,9 @@ import ( "github.com/urfave/cli/v2" ) -type Strs = []string -type Flags = []cli.Flag -type Command = cli.Command -type Commands = []cli.Command +type ( + Strs = []string + Flags = []cli.Flag + Command = cli.Command + Commands = []cli.Command +) diff --git a/pkg/cmd/protoc-gen-retag/example/example.pb.go b/pkg/cmd/protoc-gen-retag/example/example.pb.go index 111c738..5b154a1 100644 --- a/pkg/cmd/protoc-gen-retag/example/example.pb.go +++ b/pkg/cmd/protoc-gen-retag/example/example.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.32.0 -// protoc v4.25.2 +// protoc-gen-go v1.33.0 +// protoc v4.25.3 // source: cmd/protoc-gen-retag/example/example.proto package example diff --git a/pkg/protoc-gen-gorm/example/example_test.go b/pkg/protoc-gen-gorm/example/example_test.go index 05b430f..d40dab3 100644 --- a/pkg/protoc-gen-gorm/example/example_test.go +++ b/pkg/protoc-gen-gorm/example/example_test.go @@ -12,8 +12,8 @@ import ( ) func TestName(t *testing.T) { - var pb = &Example{WithNewTags: "true", Test_5: timestamppb.New(time.Now().UTC())} - var dd, err = json.Marshal(pb) + pb := &Example{WithNewTags: "true", Test_5: timestamppb.New(time.Now().UTC())} + dd, err := json.Marshal(pb) assert.Must(err) // 2022-10-19T03:49:42.240649Z log.Print(string(dd)) @@ -40,10 +40,10 @@ func TestName(t *testing.T) { } func TestName2(t *testing.T) { - var req = new(AllSrvReq) + req := new(AllSrvReq) req.Req = append(req.Req, &Req{Req: &Req_Req1{}}) - var rsp = new(AllSrvRsp) + rsp := new(AllSrvRsp) for i := range rsp.Rsp { rsp.Rsp[i].GetRsp() } diff --git a/proto/retag/retag.proto b/proto/retag/retag.proto index ffd7b09..65dc9f8 100644 --- a/proto/retag/retag.proto +++ b/proto/retag/retag.proto @@ -7,15 +7,15 @@ import "google/protobuf/descriptor.proto"; option go_package = "github.com/pubgo/protobuild/pkg/retag;retagpb"; message Tag { - string name = 1; - string value = 2; + string name = 1; + string value = 2; } // Tags are applied at the field level extend google.protobuf.FieldOptions { - repeated Tag tags = 100000; + repeated Tag tags = 100000; } extend google.protobuf.OneofOptions { - repeated Tag oneof_tags = 100000; + repeated Tag oneof_tags = 100000; } \ No newline at end of file diff --git a/version/version.go b/version/version.go index 01f0b13..d4ca7d8 100644 --- a/version/version.go +++ b/version/version.go @@ -12,7 +12,5 @@ func init() { Version = "v0.0.1-dev" } - if _, err := ver.NewVersion(Version); err != nil { - assert.Exit(err, Version) - } + assert.Exit1(ver.NewVersion(Version)) }