build_protos.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. #! /usr/bin/env python
  2. # Copyright 2018 Google
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Generates and massages protocol buffer outputs.
  16. """
  17. from __future__ import print_function
  18. import sys
  19. import argparse
  20. import os
  21. import os.path
  22. import re
  23. import subprocess
  24. CPP_GENERATOR = 'nanopb_cpp_generator.py'
  25. COPYRIGHT_NOTICE = '''
  26. /*
  27. * Copyright 2018 Google
  28. *
  29. * Licensed under the Apache License, Version 2.0 (the "License");
  30. * you may not use this file except in compliance with the License.
  31. * You may obtain a copy of the License at
  32. *
  33. * http://www.apache.org/licenses/LICENSE-2.0
  34. *
  35. * Unless required by applicable law or agreed to in writing, software
  36. * distributed under the License is distributed on an "AS IS" BASIS,
  37. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  38. * See the License for the specific language governing permissions and
  39. * limitations under the License.
  40. */
  41. '''.lstrip()
  42. def main():
  43. parser = argparse.ArgumentParser(
  44. description='Generates proto messages.')
  45. parser.add_argument(
  46. '--nanopb', action='store_true',
  47. help='Generates nanopb messages.')
  48. parser.add_argument(
  49. '--cpp', action='store_true',
  50. help='Generates C++ libprotobuf messages.')
  51. parser.add_argument(
  52. '--objc', action='store_true',
  53. help='Generates Objective-C messages.')
  54. parser.add_argument(
  55. '--protos_dir',
  56. help='Source directory containing .proto files.')
  57. parser.add_argument(
  58. '--output_dir', '-d',
  59. help='Directory to write files; subdirectories will be created.')
  60. parser.add_argument(
  61. '--protoc', default='protoc',
  62. help='Location of the protoc executable')
  63. parser.add_argument(
  64. '--pythonpath',
  65. help='Location of the protoc python library.')
  66. parser.add_argument(
  67. '--include', '-I', action='append', default=[],
  68. help='Adds INCLUDE to the proto path.')
  69. args = parser.parse_args()
  70. if args.nanopb is None and args.cpp is None and args.objc is None:
  71. parser.print_help()
  72. sys.exit(1)
  73. if args.protos_dir is None:
  74. root_dir = os.path.abspath(os.path.dirname(__file__))
  75. args.protos_dir = os.path.join(root_dir, 'protos')
  76. if args.output_dir is None:
  77. args.output_dir = os.getcwd()
  78. all_proto_files = collect_files(args.protos_dir, '.proto')
  79. if args.nanopb:
  80. NanopbGenerator(args, all_proto_files).run()
  81. proto_files = remove_well_known_protos(all_proto_files)
  82. if args.cpp:
  83. CppProtobufGenerator(args, proto_files).run()
  84. if args.objc:
  85. ObjcProtobufGenerator(args, proto_files).run()
  86. class NanopbGenerator(object):
  87. """Builds and runs the nanopb plugin to protoc."""
  88. def __init__(self, args, proto_files):
  89. self.args = args
  90. self.proto_files = proto_files
  91. def run(self):
  92. """Performs the action of the generator."""
  93. nanopb_out = os.path.join(self.args.output_dir, 'nanopb')
  94. mkdir(nanopb_out)
  95. self.__run_generator(nanopb_out)
  96. sources = collect_files(nanopb_out, '.nanopb.h', '.nanopb.cc')
  97. post_process_files(
  98. sources,
  99. add_copyright,
  100. nanopb_remove_extern_c
  101. )
  102. def __run_generator(self, out_dir):
  103. """Invokes protoc using the nanopb plugin."""
  104. cmd = protoc_command(self.args)
  105. gen = os.path.join(os.path.dirname(__file__), CPP_GENERATOR)
  106. cmd.append('--plugin=protoc-gen-nanopb=%s' % gen)
  107. nanopb_flags = ' '.join([
  108. '--extension=.nanopb',
  109. '--source-extension=.cc',
  110. '--no-timestamp',
  111. # Make sure Nanopb finds the `.options` files. See
  112. # https://jpa.kapsi.fi/nanopb/docs/reference.html#defining-the-options-in-a-options-file
  113. # "...if your .proto is in a subdirectory, nanopb may have trouble
  114. # finding the associated .options file. A workaround is to specify
  115. # include path separately to the nanopb plugin"
  116. '-I' + self.args.protos_dir,
  117. ])
  118. cmd.append('--nanopb_out=%s:%s' % (nanopb_flags, out_dir))
  119. cmd.extend(self.proto_files)
  120. run_protoc(self.args, cmd)
  121. class ObjcProtobufGenerator(object):
  122. """Runs protoc for Objective-C."""
  123. def __init__(self, args, proto_files):
  124. self.args = args
  125. self.proto_files = proto_files
  126. def run(self):
  127. objc_out = os.path.join(self.args.output_dir, 'objc')
  128. mkdir(objc_out)
  129. self.__run_generator(objc_out)
  130. self.__stub_non_buildable_files(objc_out)
  131. sources = collect_files(objc_out, '.h', '.m')
  132. post_process_files(
  133. sources,
  134. add_copyright,
  135. strip_trailing_whitespace,
  136. objc_flatten_imports,
  137. objc_strip_extension_registry
  138. )
  139. def __run_generator(self, out_dir):
  140. """Invokes protoc using the objc plugin."""
  141. cmd = protoc_command(self.args)
  142. cmd.extend(['--objc_out=' + out_dir])
  143. cmd.extend(self.proto_files)
  144. run_protoc(self.args, cmd)
  145. def __stub_non_buildable_files(self, out_dir):
  146. """Stub out generated files that make no sense."""
  147. write_file(os.path.join(out_dir, 'google/api/Annotations.pbobjc.m'), [
  148. 'static int annotations_stub __attribute__((unused,used)) = 0;\n'
  149. ])
  150. write_file(os.path.join(out_dir, 'google/api/Annotations.pbobjc.h'), [
  151. '// Empty stub file\n'
  152. ])
  153. class CppProtobufGenerator(object):
  154. """Runs protoc for C++ libprotobuf (used in testing)."""
  155. def __init__(self, args, proto_files):
  156. self.args = args
  157. self.proto_files = proto_files
  158. def run(self):
  159. out_dir = os.path.join(self.args.output_dir, 'cpp')
  160. mkdir(out_dir)
  161. self.__run_generator(out_dir)
  162. sources = collect_files(out_dir, '.pb.h', '.pb.cc')
  163. # TODO(wilhuff): strip trailing whitespace?
  164. post_process_files(
  165. sources,
  166. add_copyright,
  167. cpp_rename_in,
  168. )
  169. def __run_generator(self, out_dir):
  170. """Invokes protoc using using the default C++ generator."""
  171. cmd = protoc_command(self.args)
  172. cmd.append('--cpp_out=' + out_dir)
  173. cmd.extend(self.proto_files)
  174. run_protoc(self.args, cmd)
  175. def protoc_command(args):
  176. """Composes the initial protoc command-line including its include path."""
  177. cmd = [args.protoc]
  178. if args.include is not None:
  179. cmd.extend(['-I%s' % path for path in args.include])
  180. return cmd
  181. def run_protoc(args, cmd):
  182. """Actually runs the given protoc command.
  183. Args:
  184. args: The command-line args (including pythonpath)
  185. cmd: The command to run expressed as a list of strings
  186. """
  187. kwargs = {}
  188. if args.pythonpath:
  189. env = os.environ.copy()
  190. old_path = env.get('PYTHONPATH')
  191. env['PYTHONPATH'] = args.pythonpath
  192. if old_path is not None:
  193. env['PYTHONPATH'] += os.pathsep + old_path
  194. kwargs['env'] = env
  195. subprocess.check_call(cmd, **kwargs)
  196. def remove_well_known_protos(filenames):
  197. """Remove "well-known" protos for objc and cpp.
  198. On those platforms we get these for free as a part of the protobuf runtime.
  199. We only need them for nanopb.
  200. Args:
  201. filenames: A list of filenames, each naming a .proto file.
  202. Returns:
  203. The filenames with members of google/protobuf removed.
  204. """
  205. return [f for f in filenames if 'protos/google/protobuf/' not in f]
  206. def post_process_files(filenames, *processors):
  207. for filename in filenames:
  208. lines = []
  209. with open(filename, 'r') as fd:
  210. lines = fd.readlines()
  211. for processor in processors:
  212. lines = processor(lines)
  213. write_file(filename, lines)
  214. def write_file(filename, lines):
  215. with open(filename, 'w') as fd:
  216. fd.write(''.join(lines))
  217. def add_copyright(lines):
  218. """Adds a copyright notice to the lines."""
  219. result = [COPYRIGHT_NOTICE, '\n']
  220. result.extend(lines)
  221. return result
  222. # TODO(varconst|wilhuff): move this to `nanopb_cpp_generator.py`.
  223. def nanopb_remove_extern_c(lines):
  224. """Removes extern "C" directives from nanopb code.
  225. Args:
  226. lines: A nanobp-generated source file, split into lines.
  227. Returns:
  228. A list of strings, similar to the input but modified to remove extern "C".
  229. """
  230. result = []
  231. state = 'initial'
  232. for line in lines:
  233. if state == 'initial':
  234. if '#ifdef __cplusplus' in line:
  235. state = 'in-ifdef'
  236. continue
  237. result.append(line)
  238. elif state == 'in-ifdef':
  239. if '#endif' in line:
  240. state = 'initial'
  241. return result
  242. def cpp_rename_in(lines):
  243. """Renames an IN symbol to IN_.
  244. If a proto uses a enum member named 'IN', protobuf happily uses that in the
  245. message definition. This conflicts with the IN parameter annotation macro in
  246. windows.h.
  247. Args:
  248. lines: The lines to fix.
  249. Returns:
  250. The lines, fixed.
  251. """
  252. in_macro = re.compile(r'\bIN\b')
  253. return [in_macro.sub('IN_', line) for line in lines]
  254. def strip_trailing_whitespace(lines):
  255. """Removes trailing whitespace from the given lines."""
  256. return [line.rstrip() + '\n' for line in lines]
  257. def objc_flatten_imports(lines):
  258. """Flattens the import statements for compatibility with CocoaPods."""
  259. long_import = re.compile(r'#import ".*/')
  260. return [long_import.sub('#import "', line) for line in lines]
  261. def objc_strip_extension_registry(lines):
  262. """Removes extensionRegistry methods from the classes."""
  263. skip = False
  264. result = []
  265. for line in lines:
  266. if '+ (GPBExtensionRegistry*)extensionRegistry {' in line:
  267. skip = True
  268. if not skip:
  269. result.append(line)
  270. elif line == '}\n':
  271. skip = False
  272. return result
  273. def collect_files(root_dir, *extensions):
  274. """Finds files with the given extensions in the root_dir.
  275. Args:
  276. root_dir: The directory from which to start traversing.
  277. *extensions: Filename extensions (including the leading dot) to find.
  278. Returns:
  279. A list of filenames, all starting with root_dir, that have one of the given
  280. extensions.
  281. """
  282. result = []
  283. for root, _, files in os.walk(root_dir):
  284. for basename in files:
  285. for ext in extensions:
  286. if basename.endswith(ext):
  287. filename = os.path.join(root, basename)
  288. result.append(filename)
  289. return result
  290. def mkdir(dirname):
  291. if not os.path.isdir(dirname):
  292. os.makedirs(dirname)
  293. if __name__ == '__main__':
  294. main()