-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathproto_generator.py
More file actions
238 lines (202 loc) · 8.64 KB
/
proto_generator.py
File metadata and controls
238 lines (202 loc) · 8.64 KB
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
"""
proto_generator.py - .proto 文件生成器
从 FileDescriptorProto 或 protobuf-c 结构体信息生成 .proto 文件
"""
from google.protobuf.descriptor_pb2 import (
FileDescriptorProto, DescriptorProto, FieldDescriptorProto,
EnumDescriptorProto, OneofDescriptorProto, ServiceDescriptorProto,
MethodDescriptorProto,
)
# protobuf wire type name mapping
FIELD_TYPE_NAMES = {
FieldDescriptorProto.TYPE_DOUBLE: 'double',
FieldDescriptorProto.TYPE_FLOAT: 'float',
FieldDescriptorProto.TYPE_INT64: 'int64',
FieldDescriptorProto.TYPE_UINT64: 'uint64',
FieldDescriptorProto.TYPE_INT32: 'int32',
FieldDescriptorProto.TYPE_FIXED64: 'fixed64',
FieldDescriptorProto.TYPE_FIXED32: 'fixed32',
FieldDescriptorProto.TYPE_BOOL: 'bool',
FieldDescriptorProto.TYPE_STRING: 'string',
FieldDescriptorProto.TYPE_GROUP: 'group',
FieldDescriptorProto.TYPE_MESSAGE: 'message',
FieldDescriptorProto.TYPE_BYTES: 'bytes',
FieldDescriptorProto.TYPE_UINT32: 'uint32',
FieldDescriptorProto.TYPE_ENUM: 'enum',
FieldDescriptorProto.TYPE_SFIXED32: 'sfixed32',
FieldDescriptorProto.TYPE_SFIXED64: 'sfixed64',
FieldDescriptorProto.TYPE_SINT32: 'sint32',
FieldDescriptorProto.TYPE_SINT64: 'sint64',
}
LABEL_NAMES = {
FieldDescriptorProto.LABEL_OPTIONAL: 'optional',
FieldDescriptorProto.LABEL_REQUIRED: 'required',
FieldDescriptorProto.LABEL_REPEATED: 'repeated',
}
# well-known proto files to skip
WELL_KNOWN_PROTOS = {
'google/protobuf/any.proto',
'google/protobuf/api.proto',
'google/protobuf/compiler/plugin.proto',
'google/protobuf/descriptor.proto',
'google/protobuf/duration.proto',
'google/protobuf/empty.proto',
'google/protobuf/field_mask.proto',
'google/protobuf/source_context.proto',
'google/protobuf/struct.proto',
'google/protobuf/timestamp.proto',
'google/protobuf/type.proto',
'google/protobuf/wrappers.proto',
'google/protobuf/cpp_features.proto',
'google/protobuf/java_features.proto',
'google/protobuf/go_features.proto',
}
def is_well_known(filename: str) -> bool:
"""判断是否为 protobuf well-known type"""
normalized = filename.replace('\\', '/')
return normalized in WELL_KNOWN_PROTOS or normalized.startswith('google/protobuf/')
class ProtoFileGenerator:
"""从 FileDescriptorProto 生成 .proto 文件内容"""
def __init__(self, fd: FileDescriptorProto, syntax: str = None):
self.fd = fd
# 自动推断 syntax
if syntax:
self.syntax = syntax
elif fd.HasField('syntax') and fd.syntax:
self.syntax = fd.syntax
else:
self.syntax = 'proto3'
def generate(self) -> str:
lines = []
lines.append(f'syntax = "{self.syntax}";')
lines.append('')
if self.fd.package:
lines.append(f'package {self.fd.package};')
lines.append('')
# imports
for dep in self.fd.dependency:
lines.append(f'import "{dep}";')
if self.fd.dependency:
lines.append('')
# options
opts = []
if self.fd.HasField('options'):
if self.fd.options.HasField('java_package'):
opts.append(f'option java_package = "{self.fd.options.java_package}";')
if self.fd.options.HasField('go_package'):
opts.append(f'option go_package = "{self.fd.options.go_package}";')
if opts:
lines.extend(opts)
lines.append('')
# enums (top-level)
for enum_desc in self.fd.enum_type:
lines.extend(self._gen_enum(enum_desc, 0))
lines.append('')
# messages
for msg_desc in self.fd.message_type:
lines.extend(self._gen_message(msg_desc, 0))
lines.append('')
# services
for svc_desc in self.fd.service:
lines.extend(self._gen_service(svc_desc, 0))
lines.append('')
return '\n'.join(lines)
def _indent(self, level: int) -> str:
return ' ' * level
def _gen_message(self, msg: DescriptorProto, level: int) -> list:
ind = self._indent(level)
lines = [f'{ind}message {msg.name} {{']
# nested enums
for enum_desc in msg.enum_type:
lines.extend(self._gen_enum(enum_desc, level + 1))
# nested messages
for nested in msg.nested_type:
# 跳过 map entry 类型
if nested.options and nested.options.map_entry:
continue
lines.extend(self._gen_message(nested, level + 1))
# oneofs
oneof_fields = {} # oneof_index -> [fields]
for field in msg.field:
if field.HasField('oneof_index'):
oneof_fields.setdefault(field.oneof_index, []).append(field)
# regular fields (non-oneof)
for field in msg.field:
if field.HasField('oneof_index'):
continue
lines.append(self._gen_field(field, level + 1))
# oneof declarations
for idx, oneof in enumerate(msg.oneof_decl):
fields = oneof_fields.get(idx, [])
ind2 = self._indent(level + 1)
lines.append(f'{ind2}oneof {oneof.name} {{')
for field in fields:
lines.append(self._gen_field(field, level + 2, in_oneof=True))
lines.append(f'{ind2}}}')
# map fields
for nested in msg.nested_type:
if nested.options and nested.options.map_entry:
key_field = None
value_field = None
for f in nested.field:
if f.number == 1:
key_field = f
elif f.number == 2:
value_field = f
if key_field and value_field:
ind2 = self._indent(level + 1)
key_type = self._field_type_name(key_field)
val_type = self._field_type_name(value_field)
# 找到引用这个 map 的 field
for field in msg.field:
if field.type_name.endswith(nested.name):
lines.append(f'{ind2}map<{key_type}, {val_type}> {field.name} = {field.number};')
# reserved
for rr in msg.reserved_range:
lines.append(f'{self._indent(level + 1)}reserved {rr.start} to {rr.end - 1};')
for rn in msg.reserved_name:
lines.append(f'{self._indent(level + 1)}reserved "{rn}";')
lines.append(f'{ind}}}')
return lines
def _gen_field(self, field: FieldDescriptorProto, level: int, in_oneof: bool = False) -> str:
ind = self._indent(level)
type_name = self._field_type_name(field)
label = ''
if not in_oneof:
if self.syntax == 'proto2':
label = LABEL_NAMES.get(field.label, '') + ' '
elif field.label == FieldDescriptorProto.LABEL_REPEATED:
label = 'repeated '
elif field.label == FieldDescriptorProto.LABEL_OPTIONAL and field.HasField('proto3_optional') and field.proto3_optional:
label = 'optional '
return f'{ind}{label}{type_name} {field.name} = {field.number};'
def _field_type_name(self, field: FieldDescriptorProto) -> str:
if field.type in (FieldDescriptorProto.TYPE_MESSAGE, FieldDescriptorProto.TYPE_ENUM):
# 使用 type_name, 去掉前缀的点
name = field.type_name
if name.startswith('.'):
name = name[1:]
return name
return FIELD_TYPE_NAMES.get(field.type, f'unknown_type_{field.type}')
def _gen_enum(self, enum: EnumDescriptorProto, level: int) -> list:
ind = self._indent(level)
lines = [f'{ind}enum {enum.name} {{']
for val in enum.value:
lines.append(f'{self._indent(level + 1)}{val.name} = {val.number};')
lines.append(f'{ind}}}')
return lines
def _gen_service(self, svc: ServiceDescriptorProto, level: int) -> list:
ind = self._indent(level)
lines = [f'{ind}service {svc.name} {{']
for method in svc.method:
input_type = method.input_type.lstrip('.')
output_type = method.output_type.lstrip('.')
cs = 'stream ' if method.client_streaming else ''
ss = 'stream ' if method.server_streaming else ''
lines.append(f'{self._indent(level + 1)}rpc {method.name} ({cs}{input_type}) returns ({ss}{output_type});')
lines.append(f'{ind}}}')
return lines
def fdproto_to_proto_string(fd: FileDescriptorProto) -> str:
"""快捷函数:FileDescriptorProto → .proto 文件内容"""
gen = ProtoFileGenerator(fd)
return gen.generate()