forked from rethinkdb/rethinkdb_rebirth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvert_protofile.py
211 lines (186 loc) · 6.94 KB
/
convert_protofile.py
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
# Copyright 2018-present RebirthDB
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy of the
# License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
#
# This file incorporates work covered by the following copyright:
#
# Copyright 2010-present, The Linux Foundation, portions copyright Google and
# others and used with permission or subject to their respective license
# agreements.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''
Take a .proto file as input and output the a definitions file for a
supported language: javascript, python, ruby
Usually the input file should be ../src/rdb_protocol/ql2.proto
'''
import os
import re
import sys
languageDefs = {
"python": {
"initialIndentLevel": 0,
"header": "# DO NOT EDIT\n# Autogenerated by %s\n" %
os.path.basename(__file__),
"separator": "",
"open": "\n%(tabs)sclass %(name)s:",
"value": "\n%(tabs)s%(name)s = %(value)s",
"empty": "pass",
"close": None,
"closeAlwaysNewLine": False,
"footer": "\n"
},
"ruby": {
"initialIndentLevel": 1,
"header": "# DO NOT EDIT\n# Autogenerated by %s\n\nmodule RethinkDB"
% os.path.basename(__file__),
"separator": "",
"open": "\n%(tabs)smodule %(name)s",
"value": "\n%(tabs)s%(name)s = %(value)s",
"empty": None,
"close": "end",
"closeAlwaysNewLine": True,
"footer": "\nend\n"
},
"javascript": {
"initialIndentLevel": 1,
"header":
"// DO NOT EDIT\n// Autogenerated by %s\n\nmodule.exports = {"
% os.path.basename(__file__),
"separator": ",",
"open": "\n%(tabs)s%(name)s: {",
"value": "\n%(tabs)s%(name)s: %(value)s",
"empty": None,
"close": "}",
"closeAlwaysNewLine": False,
"footer": "\n}\n"
}
}
def convertFile(inputFile, outputFile, language):
assert(inputFile is not None and hasattr(inputFile, 'read'))
assert(outputFile is not None and hasattr(outputFile, 'write'))
assert(language in languageDefs)
messageRegex = re.compile('\s*(message|enum) (?P<name>\w+) \{')
valueRegex = re.compile('\s*(?P<name>\w+)\s*=\s*(?P<value>\w+)')
endRegex = re.compile('\s*\}')
indentLevel = languageDefs[language]["initialIndentLevel"]
lastIndentLevel = languageDefs[language]["initialIndentLevel"] - 1
# -- write headers
outputFile.write(languageDefs[language]["header"])
# -- convert the body
levelHasContent = False
for line in inputFile:
# - open
match = messageRegex.match(line)
if match is not None:
if indentLevel == lastIndentLevel:
outputFile.write(languageDefs[language]["separator"])
if levelHasContent:
outputFile.write("\n" + "\t" * indentLevel)
outputFile.write(languageDefs[language]["open"] % {
'tabs': "\t" * indentLevel,
'name': match.group('name')
})
lastIndentLevel = indentLevel
indentLevel += 1
levelHasContent = False
continue
# - value
match = valueRegex.match(line)
if match is not None:
if indentLevel == lastIndentLevel:
outputFile.write(languageDefs[language]["separator"])
value = match.group('value')
if value.startswith('0x'):
value = int(value, 0)
outputFile.write(languageDefs[language]["value"] % {
'tabs': "\t" * indentLevel,
'name': match.group('name'),
'value': value,
})
lastIndentLevel = indentLevel
levelHasContent = True
continue
# - close
match = endRegex.match(line)
if match is not None:
if not levelHasContent and \
languageDefs[language]["empty"] is not None:
outputFile.write(
"\n" + "\t" * indentLevel +
languageDefs[language]["empty"]
)
lastIndentLevel = indentLevel
if languageDefs[language]["close"] is not None:
if indentLevel == lastIndentLevel or \
languageDefs[language]["closeAlwaysNewLine"] is True:
outputFile.write("\n" + "\t" * (indentLevel - 1))
outputFile.write(languageDefs[language]["close"])
indentLevel -= 1
lastIndentLevel = indentLevel
levelHasContent = True
# -- write footer
outputFile.write(languageDefs[language]["footer"])
if __name__ == '__main__':
import optparse
inputFile = sys.stdin
outputFile = sys.stdout
# -- parse input
parser = optparse.OptionParser()
parser.add_option(
"-l", "--language",
dest="language",
help="write output for language",
metavar="LANG",
choices=list(languageDefs.keys()),
default=None,
)
parser.add_option(
"-i", "--input-file",
dest="inputFile",
help="read from FILE (default STDIN)",
metavar="FILE",
default=None,
)
parser.add_option(
"-o", "--output-file",
dest="outputFile",
help="write to FILE (default STDOUT)",
metavar="FILE",
default=None,
)
(options, args) = parser.parse_args()
if options.language is None:
parser.error("A language option is required")
if options.inputFile is not None:
try:
inputFile = open(options.inputFile, 'r')
except Exception as e:
parser.error("Unable to open the given input file <<%s>>"
", got error: %s" % (inputFile, str(e)))
if options.outputFile is not None:
try:
outputFile = open(options.outputFile, 'w')
except Exception as e:
parser.error("Unable to open the given output file <<%s>>,"
" got error: %s" % (outputFile, str(e)))
convertFile(inputFile, outputFile, options.language)