bootstrap/coco_inject.go

60 lines
1.4 KiB
Go

package bootstrap
import (
"os"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gitter.top/common/gobuf"
)
func InjectProtoFile() *cobra.Command {
var protoFile string
var tags []string
var tagStyle string
cmd := &cobra.Command{
Use: "inject",
Short: "inject pb.go file",
PreRun: func(_ *cobra.Command, _ []string) {
stat, err := os.Stat(protoFile)
if err != nil {
logrus.Errorf("read pb.go file %s failed: %v", protoFile, err)
return
}
if stat.IsDir() {
logrus.Errorf("proto file can not be directory")
return
}
},
Run: func(_ *cobra.Command, _ []string) {
var getStyle = func(style string) gobuf.TagValueStyle {
if style == "underline" {
return gobuf.Underline
}
if style == "lowercase" {
return gobuf.LowerCase
}
return gobuf.UpperCase
}
var inject = gobuf.NewInjectTag(protoFile)
for _, tag := range tags {
inject.WithTags(gobuf.InjectTagProps{
TagName: tag,
Style: getStyle(tagStyle),
})
}
if err := inject.Inject(); err != nil {
logrus.Errorf("inject %s file failed: %v", protoFile, err)
return
}
logrus.Infof("inject %s success", protoFile)
},
}
cmd.Flags().StringVar(&protoFile, "path", "", "pb.go file path")
cmd.Flags().StringVar(&tagStyle, "style", "underline", "tag value style, value underline|lowercase|uppercase")
cmd.Flags().StringSliceVar(&tags, "tags", []string{"bson"}, "inject tag field name")
return cmd
}