From 7e8dc13992825da20f27188f733bf792c174be29 Mon Sep 17 00:00:00 2001 From: Young Xu Date: Sat, 6 Apr 2024 11:53:48 +0800 Subject: [PATCH] feat: new command pbf --- coco/main.go | 1 + coco_proto_format.go | 54 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 coco_proto_format.go diff --git a/coco/main.go b/coco/main.go index ee23a63..3faafd9 100644 --- a/coco/main.go +++ b/coco/main.go @@ -30,6 +30,7 @@ func init() { rootCmd.AddCommand(bootstrap.AddServiceCommand()) rootCmd.AddCommand(bootstrap.GenerateProtoFile()) rootCmd.AddCommand(bootstrap.InjectProtoFile()) + rootCmd.AddCommand(bootstrap.AddProtoFormat()) } func main() { diff --git a/coco_proto_format.go b/coco_proto_format.go new file mode 100644 index 0000000..c6b0bea --- /dev/null +++ b/coco_proto_format.go @@ -0,0 +1,54 @@ +package bootstrap + +import ( + "bytes" + "github.com/emicklei/proto" + "github.com/sirupsen/logrus" + "github.com/spf13/cobra" + "gitter.top/sync/proto-contrib/pkg/protofmt" + "os" +) + +func AddProtoFormat() *cobra.Command { + var protoFile string + cmd := &cobra.Command{ + Use: "pbf", + Short: "protobuf format", + PreRun: func(_ *cobra.Command, args []string) { + if protoFile == "" && len(args) != 0 { + protoFile = args[0] + } + stat, err := os.Stat(protoFile) + if err != nil { + logrus.Fatalf("read proto file %s failed: %v", protoFile, err) + return + } + if stat.IsDir() { + logrus.Fatalf("proto file can not be directory") + return + } + }, + Run: func(cmd *cobra.Command, args []string) { + file, err := os.Open(protoFile) + if err != nil { + logrus.Errorf("format proto file %s failed: %v", protoFile, err) + return + } + buf := new(bytes.Buffer) + parser := proto.NewParser(file) + parser.Filename(protoFile) + def, err := parser.Parse() + if err != nil { + logrus.Errorf("parse proto file %s failed: %v", protoFile, err) + return + } + protofmt.NewFormatter(buf, " ").Format(def) + if err := os.WriteFile(protoFile, buf.Bytes(), os.ModePerm); err != nil { + logrus.Errorf("write proto file %s failed: %v", protoFile, err) + return + } + }, + } + cmd.Flags().StringVar(&protoFile, "path", "", "proto file path") + return cmd +}