forked from nytimes/openapi2proto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proto.go
174 lines (150 loc) · 5.03 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
package openapi2proto
import (
"bytes"
"fmt"
"log"
"regexp"
"strconv"
"strings"
"text/template"
)
// GenerateProto will attempt to generate an protobuf version 3
// schema from the given OpenAPI definition.
func GenerateProto(api *APIDefinition, annotate bool) ([]byte, error) {
// jam all the parameters into the normal 'definitions' for easier reference.
for name, param := range api.Parameters {
api.Definitions[name] = param
}
var out bytes.Buffer
data := struct {
*APIDefinition
Annotate bool
}{
api, annotate,
}
err := protoFileTmpl.Execute(&out, data)
if err != nil {
return nil, fmt.Errorf("unable to generate protobuf schema: %s", err)
}
return cleanSpacing(addImports(out.Bytes())), nil
}
const protoFileTmplStr = `syntax = "proto3";
{{ $defs := .Definitions }}{{ $annotate := .Annotate }}{{ if $annotate }}
import "google/api/annotations.proto";
{{ end }}
package {{ packageName .Info.Title }};
{{ range $path, $endpoint := .Paths }}
{{ $endpoint.ProtoMessages $path $defs }}
{{ end }}
{{ range $modelName, $model := $defs }}
{{ $model.ProtoMessage "" $modelName $defs counter -1 }}
{{ end }}{{ $basePath := .BasePath }}
service {{ serviceName .Info.Title }} {{"{"}}{{ range $path, $endpoint := .Paths }}
{{ $endpoint.ProtoEndpoints $annotate $basePath $path }}{{ end }}
}
`
const protoEndpointTmplStr = ` rpc {{ .Name }}({{ .RequestName }}) returns ({{ .ResponseName }}) {{"{"}}{{ if .Annotate }}
option (google.api.http) = {
{{ .Method }}: "{{ .Path }}"{{ if .IncludeBody }}
body: "{{ .BodyAttr }}"{{ end }}
};
{{ end }}{{"}"}}`
const protoMsgTmplStr = `{{ $i := counter }}{{ $defs := .Defs }}{{ $msgName := .Name }}{{ $depth := .Depth }}message {{ .Name }} {{"{"}}{{ range $propName, $prop := .Properties }}
{{ indent $depth }} {{ $prop.ProtoMessage $msgName $propName $defs $i $depth }};{{ end }}
{{ indent $depth }}}`
const protoEnumTmplStr = `{{ $i := zcounter }}{{ $depth := .Depth }}{{ $name := .Name }}enum {{ .Name }} {{"{"}}{{ range $index, $pName := .Enum }}
{{ indent $depth }} {{ toEnum $name $pName $depth }} = {{ inc $i }};{{ end }}
{{ indent $depth }}}`
var funcMap = template.FuncMap{
"inc": inc,
"counter": counter,
"zcounter": zcounter,
"indent": indent,
"toEnum": toEnum,
"packageName": packageName,
"serviceName": serviceName,
"pathMethodToName": pathMethodToName,
}
func packageName(t string) string {
return strings.ToLower(strings.Join(strings.Fields(t), ""))
}
func serviceName(t string) string {
var name string
for _, nme := range strings.Fields(t) {
name += strings.Title(nme)
}
return name + "Service"
}
func counter() *int {
i := 0
return &i
}
func zcounter() *int {
i := -1
return &i
}
func inc(i *int) int {
*i++
return *i
}
func indent(depth int) string {
var out string
for i := 0; i < depth; i++ {
out += " "
}
return out
}
func toEnum(name, enum string, depth int) string {
if strings.TrimSpace(enum) == "" {
enum = "empty"
}
e := enum
if _, err := strconv.Atoi(enum); err == nil || depth > 0 {
e = name + "_" + enum
}
e = strings.Replace(e, " & ", " AND ", -1)
e = strings.Replace(e, "&", "_AND_", -1)
e = strings.Replace(e, " ", "_", -1)
re := regexp.MustCompile(`[%\{\}\[\]()/\.'’-]`)
e = re.ReplaceAllString(e, "")
return strings.ToUpper(e)
}
var (
protoFileTmpl = template.Must(template.New("protoFile").Funcs(funcMap).Parse(protoFileTmplStr))
protoMsgTmpl = template.Must(template.New("protoMsg").Funcs(funcMap).Parse(protoMsgTmplStr))
protoEndpointTmpl = template.Must(template.New("protoEndpoint").Funcs(funcMap).Parse(protoEndpointTmplStr))
protoEnumTmpl = template.Must(template.New("protoEnum").Funcs(funcMap).Parse(protoEnumTmplStr))
)
func cleanSpacing(output []byte) []byte {
re := regexp.MustCompile(`}\n*message `)
output = re.ReplaceAll(output, []byte("}\n\nmessage "))
re = regexp.MustCompile(`}\n*enum `)
output = re.ReplaceAll(output, []byte("}\n\nenum "))
re = regexp.MustCompile(`;\n*message `)
output = re.ReplaceAll(output, []byte(";\n\nmessage "))
re = regexp.MustCompile(`}\n*service `)
return re.ReplaceAll(output, []byte("}\n\nservice "))
}
func addImports(output []byte) []byte {
if bytes.Contains(output, []byte("google.protobuf.Any")) {
output = bytes.Replace(output, []byte(`"proto3";`), []byte(`"proto3";
import "google/protobuf/any.proto";`), 1)
}
if bytes.Contains(output, []byte("google.protobuf.Empty")) {
output = bytes.Replace(output, []byte(`"proto3";`), []byte(`"proto3";
import "google/protobuf/empty.proto";`), 1)
}
if bytes.Contains(output, []byte("google.protobuf.NullValue")) {
output = bytes.Replace(output, []byte(`"proto3";`), []byte(`"proto3";
import "google/protobuf/struct.proto";`), 1)
}
match, err := regexp.Match("google.protobuf.(String|Bytes|Int.*|UInt.*|Float|Double)Value", output)
if err != nil {
log.Fatal("unable to find wrapper values: ", err)
}
if match {
output = bytes.Replace(output, []byte(`"proto3";`), []byte(`"proto3";
import "google/protobuf/wrappers.proto";`), 1)
}
return output
}