forked from asynkron/protoactor-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proto.go
91 lines (76 loc) · 2.24 KB
/
proto.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"bytes"
"strings"
google_protobuf "github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
)
// ProtoFile reprpesents a parsed proto file
type ProtoFile struct {
PackageName string
Namespace string
Messages []*ProtoMessage
Services []*ProtoService
}
// ProtoMessage represents a parsed message in a proto file
type ProtoMessage struct {
Name string
PascalName string
}
// ProtoService represents a parsed service in a proto file
type ProtoService struct {
Name string
PascalName string
Methods []*ProtoMethod
}
// ProtoMethod represents a parsed method in a proto service
type ProtoMethod struct {
Name string
PascalName string
InputStream bool
Input *ProtoMessage
OutputStream bool
Output *ProtoMessage
}
//ProtoAst transforms a FileDescriptor to an AST that can be used for code generation
func ProtoAst(file *google_protobuf.FileDescriptorProto) *ProtoFile {
pkg := &ProtoFile{}
pkg.PackageName = file.GetPackage()
pkg.Namespace = file.Options.GetCsharpNamespace()
messages := make(map[string]*ProtoMessage)
for _, message := range file.GetMessageType() {
m := &ProtoMessage{}
m.Name = message.GetName()
m.PascalName = MakeFirstLowerCase(m.Name)
pkg.Messages = append(pkg.Messages, m)
messages[m.Name] = m
}
for _, service := range file.GetService() {
s := &ProtoService{}
s.Name = service.GetName()
s.PascalName = MakeFirstLowerCase(s.Name)
pkg.Services = append(pkg.Services, s)
for _, method := range service.GetMethod() {
m := &ProtoMethod{}
m.Name = method.GetName()
m.PascalName = MakeFirstLowerCase(m.Name)
// m.InputStream = *method.ClientStreaming
// m.OutputStream = *method.ServerStreaming
input := removePackagePrefix(method.GetInputType(), pkg.PackageName)
output := removePackagePrefix(method.GetOutputType(), pkg.PackageName)
m.Input = messages[input]
m.Output = messages[output]
s.Methods = append(s.Methods, m)
}
}
return pkg
}
// MakeFirstLowerCase makes the first character in a string lower case
func MakeFirstLowerCase(s string) string {
if len(s) < 2 {
return strings.ToLower(s)
}
bts := []byte(s)
lc := bytes.ToLower([]byte{bts[0]})
rest := bts[1:]
return string(bytes.Join([][]byte{lc, rest}, nil))
}