proto_generator.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. #! /usr/bin/env python
  2. # Copyright 2021 Google LLC
  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. Example usage:
  17. python FirebasePerformance/ProtoSupport/proto_generator.py \
  18. --nanopb \
  19. --protos_dir=FirebasePerformance/ProtoSupport/Protos/ \
  20. --pythonpath=~/Downloads/nanopb-0.3.9.8-macosx-x86/generator/ \
  21. --output_dir=FirebasePerformance/Sources//Protogen/ \
  22. --include=FirebasePerformance/ProtoSupport/Protos/
  23. """
  24. from __future__ import print_function
  25. import sys
  26. import argparse
  27. import os
  28. import os.path
  29. import re
  30. import subprocess
  31. OBJC_GENERATOR='nanopb_objc_generator.py'
  32. COPYRIGHT_NOTICE = '''
  33. /*
  34. * Copyright 2021 Google LLC
  35. *
  36. * Licensed under the Apache License, Version 2.0 (the "License");
  37. * you may not use this file except in compliance with the License.
  38. * You may obtain a copy of the License at
  39. *
  40. * http://www.apache.org/licenses/LICENSE-2.0
  41. *
  42. * Unless required by applicable law or agreed to in writing, software
  43. * distributed under the License is distributed on an "AS IS" BASIS,
  44. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  45. * See the License for the specific language governing permissions and
  46. * limitations under the License.
  47. */
  48. '''.lstrip()
  49. def main():
  50. parser = argparse.ArgumentParser(
  51. description='Generates proto messages.')
  52. parser.add_argument(
  53. '--nanopb', action='store_true',
  54. help='Generates nanopb messages.')
  55. parser.add_argument(
  56. '--objc', action='store_true',
  57. help='Generates Objective-C messages.')
  58. parser.add_argument(
  59. '--protos_dir',
  60. help='Source directory containing .proto files.')
  61. parser.add_argument(
  62. '--output_dir', '-d',
  63. help='Directory to write files; subdirectories will be created.')
  64. parser.add_argument(
  65. '--protoc', default='protoc',
  66. help='Location of the protoc executable')
  67. parser.add_argument(
  68. '--pythonpath',
  69. help='Location of the protoc python library.')
  70. parser.add_argument(
  71. '--include', '-I', action='append', default=[],
  72. help='Adds INCLUDE to the proto path.')
  73. args = parser.parse_args()
  74. if args.nanopb is None and args.objc is None:
  75. parser.print_help()
  76. sys.exit(1)
  77. if args.protos_dir is None:
  78. root_dir = os.path.abspath(os.path.dirname(__file__))
  79. args.protos_dir = os.path.join(root_dir, 'protos')
  80. if args.output_dir is None:
  81. root_dir = os.path.abspath(os.path.dirname(__file__))
  82. args.output_dir = os.path.join(root_dir, 'protogen-please-supply-an-outputdir')
  83. all_proto_files = collect_files(args.protos_dir, '.proto')
  84. if args.nanopb:
  85. NanopbGenerator(args, all_proto_files).run()
  86. proto_files = remove_well_known_protos(all_proto_files)
  87. if args.objc:
  88. ObjcProtobufGenerator(args, proto_files).run()
  89. class NanopbGenerator(object):
  90. """Builds and runs the nanopb plugin to protoc."""
  91. def __init__(self, args, proto_files):
  92. self.args = args
  93. self.proto_files = proto_files
  94. def run(self):
  95. """Performs the action of the generator."""
  96. nanopb_out = os.path.join(self.args.output_dir, 'nanopb')
  97. mkdir(nanopb_out)
  98. self.__run_generator(nanopb_out)
  99. sources = collect_files(nanopb_out, '.nanopb.h', '.nanopb.c')
  100. post_process_files(
  101. sources,
  102. add_copyright,
  103. nanopb_remove_extern_c,
  104. nanopb_rename_delete,
  105. nanopb_use_module_import
  106. )
  107. def __run_generator(self, out_dir):
  108. """Invokes protoc using the nanopb plugin."""
  109. cmd = protoc_command(self.args)
  110. gen = os.path.join(os.path.dirname(__file__), OBJC_GENERATOR)
  111. cmd.append('--plugin=protoc-gen-nanopb=%s' % gen)
  112. nanopb_flags = [
  113. '--extension=.nanopb',
  114. '--source-extension=.c',
  115. '--no-timestamp'
  116. ]
  117. nanopb_flags.extend(['-I%s' % path for path in self.args.include])
  118. cmd.append('--nanopb_out=%s:%s' % (' '.join(nanopb_flags), out_dir))
  119. cmd.extend(self.proto_files)
  120. run_protoc(self.args, cmd)
  121. def protoc_command(args):
  122. """Composes the initial protoc command-line including its include path."""
  123. cmd = [args.protoc]
  124. if args.include is not None:
  125. cmd.extend(['-I=%s' % path for path in args.include])
  126. return cmd
  127. def run_protoc(args, cmd):
  128. """Actually runs the given protoc command.
  129. Args:
  130. args: The command-line args (including pythonpath)
  131. cmd: The command to run expressed as a list of strings
  132. """
  133. kwargs = {}
  134. if args.pythonpath:
  135. env = os.environ.copy()
  136. old_path = env.get('PYTHONPATH')
  137. env['PYTHONPATH'] = os.path.expanduser(args.pythonpath)
  138. if old_path is not None:
  139. env['PYTHONPATH'] += os.pathsep + old_path
  140. kwargs['env'] = env
  141. try:
  142. print(subprocess.check_output(cmd, stderr=subprocess.STDOUT, **kwargs))
  143. except subprocess.CalledProcessError as error:
  144. print('command failed: ', ' '.join(cmd), '\nerror: ', error.output)
  145. def remove_well_known_protos(filenames):
  146. """Remove "well-known" protos for objc.
  147. On those platforms we get these for free as a part of the protobuf runtime.
  148. We only need them for nanopb.
  149. Args:
  150. filenames: A list of filenames, each naming a .proto file.
  151. Returns:
  152. The filenames with members of google/protobuf removed.
  153. """
  154. return [f for f in filenames if 'protos/google/protobuf/' not in f]
  155. def post_process_files(filenames, *processors):
  156. for filename in filenames:
  157. lines = []
  158. with open(filename, 'r') as fd:
  159. lines = fd.readlines()
  160. for processor in processors:
  161. lines = processor(lines)
  162. write_file(filename, lines)
  163. def write_file(filename, lines):
  164. mkdir(os.path.dirname(filename))
  165. with open(filename, 'w') as fd:
  166. fd.write(''.join(lines))
  167. def add_copyright(lines):
  168. """Adds a copyright notice to the lines."""
  169. result = [COPYRIGHT_NOTICE, '\n']
  170. result.extend(lines)
  171. return result
  172. def nanopb_remove_extern_c(lines):
  173. """Removes extern "C" directives from nanopb code.
  174. Args:
  175. lines: A nanobp-generated source file, split into lines.
  176. Returns:
  177. A list of strings, similar to the input but modified to remove extern "C".
  178. """
  179. result = []
  180. state = 'initial'
  181. for line in lines:
  182. if state == 'initial':
  183. if '#ifdef __cplusplus' in line:
  184. state = 'in-ifdef'
  185. continue
  186. result.append(line)
  187. elif state == 'in-ifdef':
  188. if '#endif' in line:
  189. state = 'initial'
  190. return result
  191. def nanopb_rename_delete(lines):
  192. """Renames a delete symbol to delete_.
  193. If a proto uses a field named 'delete', nanopb happily uses that in the
  194. message definition. Works fine for C; not so much for C++.
  195. Args:
  196. lines: The lines to fix.
  197. Returns:
  198. The lines, fixed.
  199. """
  200. delete_keyword = re.compile(r'\bdelete\b')
  201. return [delete_keyword.sub('delete_', line) for line in lines]
  202. def nanopb_use_module_import(lines):
  203. """Changes #include <pb.h> to include <nanopb/pb.h>""" # Don't let Copybara alter these lines.
  204. return [line.replace('#include <pb.h>', '{}include <nanopb/pb.h>'.format("#")) for line in lines]
  205. def strip_trailing_whitespace(lines):
  206. """Removes trailing whitespace from the given lines."""
  207. return [line.rstrip() + '\n' for line in lines]
  208. def objc_flatten_imports(lines):
  209. """Flattens the import statements for compatibility with CocoaPods."""
  210. long_import = re.compile(r'#import ".*/')
  211. return [long_import.sub('#import "', line) for line in lines]
  212. def objc_strip_extension_registry(lines):
  213. """Removes extensionRegistry methods from the classes."""
  214. skip = False
  215. result = []
  216. for line in lines:
  217. if '+ (GPBExtensionRegistry*)extensionRegistry {' in line:
  218. skip = True
  219. if not skip:
  220. result.append(line)
  221. elif line == '}\n':
  222. skip = False
  223. return result
  224. def collect_files(root_dir, *extensions):
  225. """Finds files with the given extensions in the root_dir.
  226. Args:
  227. root_dir: The directory from which to start traversing.
  228. *extensions: Filename extensions (including the leading dot) to find.
  229. Returns:
  230. A list of filenames, all starting with root_dir, that have one of the given
  231. extensions.
  232. """
  233. result = []
  234. for root, _, files in os.walk(root_dir):
  235. for basename in files:
  236. for ext in extensions:
  237. if basename.endswith(ext):
  238. filename = os.path.join(root, basename)
  239. result.append(filename)
  240. return result
  241. def mkdir(dirname):
  242. if not os.path.isdir(dirname):
  243. os.makedirs(dirname)
  244. if __name__ == '__main__':
  245. main()