proto_generator.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. #! /usr/bin/env python
  2. # Copyright 2022 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 Crashlytics/ProtoSupport/build_protos.py \
  18. --nanopb \
  19. --protos_dir=Crashlytics/Classes/Protos/ \
  20. --pythonpath=~/Downloads/nanopb-0.3.9.2-macosx-x86/generator/ \
  21. --output_dir=Crashlytics/Protogen/
  22. """
  23. from __future__ import print_function
  24. from inspect import signature
  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 2022 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. parser.add_argument(
  74. '--include_prefix', '-p', action='append', default=[],
  75. help='Adds include_prefix to the <product>.nanopb.h include in .nanopb.c')
  76. args = parser.parse_args()
  77. if args.nanopb is None and args.objc is None:
  78. parser.print_help()
  79. sys.exit(1)
  80. if args.protos_dir is None:
  81. root_dir = os.path.abspath(os.path.dirname(__file__))
  82. args.protos_dir = os.path.join(root_dir, 'protos')
  83. if args.output_dir is None:
  84. root_dir = os.path.abspath(os.path.dirname(__file__))
  85. args.output_dir = os.path.join(root_dir, 'protogen-please-supply-an-outputdir')
  86. all_proto_files = collect_files(args.protos_dir, '.proto')
  87. if args.nanopb:
  88. NanopbGenerator(args, all_proto_files).run()
  89. proto_files = remove_well_known_protos(all_proto_files)
  90. if args.objc:
  91. ObjcProtobufGenerator(args, proto_files).run()
  92. class NanopbGenerator(object):
  93. """Builds and runs the nanopb plugin to protoc."""
  94. def __init__(self, args, proto_files):
  95. self.args = args
  96. self.proto_files = proto_files
  97. def run(self):
  98. """Performs the action of the generator."""
  99. nanopb_out = os.path.join(self.args.output_dir, 'nanopb')
  100. mkdir(nanopb_out)
  101. self.__run_generator(nanopb_out)
  102. sources = collect_files(nanopb_out, '.nanopb.h', '.nanopb.c')
  103. post_process_files(
  104. sources,
  105. add_copyright,
  106. nanopb_remove_extern_c,
  107. nanopb_rename_delete,
  108. nanopb_use_module_import,
  109. make_use_absolute_import(nanopb_out, self.args)
  110. )
  111. def __run_generator(self, out_dir):
  112. """Invokes protoc using the nanopb plugin."""
  113. cmd = protoc_command(self.args)
  114. gen = os.path.join(os.path.dirname(__file__), OBJC_GENERATOR)
  115. cmd.append('--plugin=protoc-gen-nanopb=%s' % gen)
  116. nanopb_flags = [
  117. '--extension=.nanopb',
  118. '--source-extension=.c',
  119. '--no-timestamp'
  120. ]
  121. nanopb_flags.extend(['-I%s' % path for path in self.args.include])
  122. cmd.append('--nanopb_out=%s:%s' % (' '.join(nanopb_flags), out_dir))
  123. cmd.extend(self.proto_files)
  124. run_protoc(self.args, cmd)
  125. def protoc_command(args):
  126. """Composes the initial protoc command-line including its include path."""
  127. cmd = [args.protoc]
  128. if args.include is not None:
  129. cmd.extend(['-I=%s' % path for path in args.include])
  130. return cmd
  131. def run_protoc(args, cmd):
  132. """Actually runs the given protoc command.
  133. Args:
  134. args: The command-line args (including pythonpath)
  135. cmd: The command to run expressed as a list of strings
  136. """
  137. kwargs = {}
  138. if args.pythonpath:
  139. env = os.environ.copy()
  140. old_path = env.get('PYTHONPATH')
  141. env['PYTHONPATH'] = os.path.expanduser(args.pythonpath)
  142. if old_path is not None:
  143. env['PYTHONPATH'] += os.pathsep + old_path
  144. kwargs['env'] = env
  145. try:
  146. outputString = subprocess.check_output(cmd, stderr=subprocess.STDOUT, **kwargs)
  147. print(outputString.decode("utf-8"))
  148. except subprocess.CalledProcessError as error:
  149. print('command failed: ', ' '.join(cmd), '\nerror: ', error.output)
  150. def remove_well_known_protos(filenames):
  151. """Remove "well-known" protos for objc.
  152. On those platforms we get these for free as a part of the protobuf runtime.
  153. We only need them for nanopb.
  154. Args:
  155. filenames: A list of filenames, each naming a .proto file.
  156. Returns:
  157. The filenames with members of google/protobuf removed.
  158. """
  159. return [f for f in filenames if 'protos/google/protobuf/' not in f]
  160. def post_process_files(filenames, *processors):
  161. for filename in filenames:
  162. lines = []
  163. with open(filename, 'r') as fd:
  164. lines = fd.readlines()
  165. for processor in processors:
  166. sig = signature(processor)
  167. if len(sig.parameters) == 1:
  168. lines = processor(lines)
  169. else:
  170. lines = processor(lines, filename)
  171. write_file(filename, lines)
  172. def write_file(filename, lines):
  173. mkdir(os.path.dirname(filename))
  174. with open(filename, 'w') as fd:
  175. fd.write(''.join(lines))
  176. def add_copyright(lines):
  177. """Adds a copyright notice to the lines."""
  178. if COPYRIGHT_NOTICE in lines:
  179. return lines
  180. result = [COPYRIGHT_NOTICE, '\n']
  181. result.extend(lines)
  182. return result
  183. def nanopb_remove_extern_c(lines):
  184. """Removes extern "C" directives from nanopb code.
  185. Args:
  186. lines: A nanobp-generated source file, split into lines.
  187. Returns:
  188. A list of strings, similar to the input but modified to remove extern "C".
  189. """
  190. result = []
  191. state = 'initial'
  192. for line in lines:
  193. if state == 'initial':
  194. if '#ifdef __cplusplus' in line:
  195. state = 'in-ifdef'
  196. continue
  197. result.append(line)
  198. elif state == 'in-ifdef':
  199. if '#endif' in line:
  200. state = 'initial'
  201. return result
  202. def nanopb_rename_delete(lines):
  203. """Renames a delete symbol to delete_.
  204. If a proto uses a field named 'delete', nanopb happily uses that in the
  205. message definition. Works fine for C; not so much for C++.
  206. Args:
  207. lines: The lines to fix.
  208. Returns:
  209. The lines, fixed.
  210. """
  211. delete_keyword = re.compile(r'\bdelete\b')
  212. return [delete_keyword.sub('delete_', line) for line in lines]
  213. def nanopb_use_module_import(lines):
  214. """Changes #include <pb.h> to include <nanopb/pb.h>""" # Don't let Copybara alter these lines.
  215. return [line.replace('#include <pb.h>', '{}include <nanopb/pb.h>'.format("#")) for line in lines]
  216. def make_use_absolute_import(nanopb_out, args):
  217. import_file = collect_files(nanopb_out, '.nanopb.h')[0]
  218. def nanopb_use_absolute_import(lines, filename):
  219. """Makes repo-relative imports
  220. #include "crashlytics.nanopb.h" =>
  221. #include "Crashlytics/Protogen/nanopb/crashlytics.nanopb.h"
  222. This only applies to .nanopb.c files because it causes errors if
  223. .nanopb.h files import other .nanopb.h files with full relative paths.
  224. """
  225. if ".h" in filename:
  226. return lines
  227. include_prefix = args.include_prefix[0]
  228. header = os.path.basename(import_file)
  229. return [line.replace('#include "{0}"'.format(header), '#include "{0}{1}"'.format(include_prefix, header)) for line in lines]
  230. return nanopb_use_absolute_import
  231. def strip_trailing_whitespace(lines):
  232. """Removes trailing whitespace from the given lines."""
  233. return [line.rstrip() + '\n' for line in lines]
  234. def objc_flatten_imports(lines):
  235. """Flattens the import statements for compatibility with CocoaPods."""
  236. long_import = re.compile(r'#import ".*/')
  237. return [long_import.sub('#import "', line) for line in lines]
  238. def objc_strip_extension_registry(lines):
  239. """Removes extensionRegistry methods from the classes."""
  240. skip = False
  241. result = []
  242. for line in lines:
  243. if '+ (GPBExtensionRegistry*)extensionRegistry {' in line:
  244. skip = True
  245. if not skip:
  246. result.append(line)
  247. elif line == '}\n':
  248. skip = False
  249. return result
  250. def collect_files(root_dir, *extensions):
  251. """Finds files with the given extensions in the root_dir.
  252. Args:
  253. root_dir: The directory from which to start traversing.
  254. *extensions: Filename extensions (including the leading dot) to find.
  255. Returns:
  256. A list of filenames, all starting with root_dir, that have one of the given
  257. extensions.
  258. """
  259. result = []
  260. for root, _, files in os.walk(root_dir):
  261. for basename in files:
  262. for ext in extensions:
  263. if basename.endswith(ext):
  264. filename = os.path.join(root, basename)
  265. result.append(filename)
  266. return result
  267. def mkdir(dirname):
  268. if not os.path.isdir(dirname):
  269. os.makedirs(dirname)
  270. if __name__ == '__main__':
  271. main()