2016-12-15 15:28:57 +03:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2016-12-16 18:08:37 +03:00
|
|
|
"strings"
|
2016-12-15 15:28:57 +03:00
|
|
|
"text/template"
|
|
|
|
|
|
|
|
"github.com/Masterminds/sprig"
|
2016-12-20 13:31:46 +03:00
|
|
|
"github.com/huandu/xstrings"
|
2016-12-21 12:26:26 +03:00
|
|
|
|
|
|
|
"github.com/golang/protobuf/protoc-gen-go/descriptor"
|
2016-12-15 15:28:57 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
var ProtoHelpersFuncMap = template.FuncMap{
|
|
|
|
"string": func(i interface {
|
|
|
|
String() string
|
|
|
|
}) string {
|
|
|
|
return i.String()
|
|
|
|
},
|
|
|
|
"json": func(v interface{}) string {
|
|
|
|
a, _ := json.Marshal(v)
|
|
|
|
return string(a)
|
|
|
|
},
|
|
|
|
"prettyjson": func(v interface{}) string {
|
|
|
|
a, _ := json.MarshalIndent(v, "", " ")
|
|
|
|
return string(a)
|
|
|
|
},
|
2016-12-16 18:08:37 +03:00
|
|
|
"splitArray": func(sep string, s string) []string {
|
|
|
|
return strings.Split(s, sep)
|
|
|
|
},
|
|
|
|
"first": func(a []string) string {
|
2016-12-15 15:28:57 +03:00
|
|
|
return a[0]
|
|
|
|
},
|
2016-12-16 18:08:37 +03:00
|
|
|
"last": func(a []string) string {
|
2016-12-15 15:28:57 +03:00
|
|
|
return a[len(a)-1]
|
|
|
|
},
|
2016-12-19 17:43:38 +03:00
|
|
|
"upperFirst": func(s string) string {
|
|
|
|
return strings.ToUpper(s[:1]) + s[1:]
|
|
|
|
},
|
2016-12-16 18:08:37 +03:00
|
|
|
"lowerFirst": func(s string) string {
|
|
|
|
return strings.ToLower(s[:1]) + s[1:]
|
|
|
|
},
|
2016-12-20 13:31:46 +03:00
|
|
|
"camelCase": func(s string) string {
|
|
|
|
return xstrings.ToCamelCase(s)
|
|
|
|
},
|
|
|
|
"lowerCamelCase": func(s string) string {
|
|
|
|
cc := xstrings.ToCamelCase(s)
|
|
|
|
return strings.ToLower(cc[:1]) + cc[1:]
|
|
|
|
},
|
|
|
|
"snakeCase": func(s string) string {
|
|
|
|
return xstrings.ToSnakeCase(s)
|
|
|
|
},
|
|
|
|
"kebabCase": func(s string) string {
|
|
|
|
return strings.Replace(xstrings.ToSnakeCase(s), "_", "-", -1)
|
|
|
|
},
|
2016-12-21 12:26:26 +03:00
|
|
|
"getMessageType": getMessageType,
|
|
|
|
"isFieldMessage": isFieldMessage,
|
2016-12-15 15:28:57 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
for k, v := range sprig.TxtFuncMap() {
|
|
|
|
ProtoHelpersFuncMap[k] = v
|
|
|
|
}
|
|
|
|
}
|
2016-12-21 12:26:26 +03:00
|
|
|
|
|
|
|
func getMessageType(f *descriptor.FileDescriptorProto, name string) *descriptor.DescriptorProto {
|
|
|
|
for _, m := range f.MessageType {
|
|
|
|
// name usually contains the package name
|
|
|
|
if strings.HasSuffix(name, *m.Name) {
|
|
|
|
return m
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func isFieldMessage(f *descriptor.FieldDescriptorProto) bool {
|
|
|
|
if f.Type != nil && *f.Type == descriptor.FieldDescriptorProto_TYPE_MESSAGE {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
if f.TypeName != nil && (*f.TypeName)[0] == '.' {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|