build_protos.py 10 KB

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