protoc.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Philipp Bender, 2012
  4. # Matt Clarkson, 2012
  5. import re, os
  6. from waflib.Task import Task
  7. from waflib.TaskGen import extension
  8. from waflib import Errors, Context
  9. """
  10. A simple tool to integrate protocol buffers into your build system.
  11. Example for C++:
  12. def configure(conf):
  13. conf.load('compiler_cxx cxx protoc')
  14. def build(bld):
  15. bld(
  16. features = 'cxx cxxprogram'
  17. source = 'main.cpp file1.proto proto/file2.proto',
  18. includes = '. proto',
  19. target = 'executable')
  20. Example for Python:
  21. def configure(conf):
  22. conf.load('python protoc')
  23. def build(bld):
  24. bld(
  25. features = 'py'
  26. source = 'main.py file1.proto proto/file2.proto',
  27. protoc_includes = 'proto')
  28. Example for both Python and C++ at same time:
  29. def configure(conf):
  30. conf.load('cxx python protoc')
  31. def build(bld):
  32. bld(
  33. features = 'cxx py'
  34. source = 'file1.proto proto/file2.proto',
  35. protoc_includes = 'proto') # or includes
  36. Example for Java:
  37. def options(opt):
  38. opt.load('java')
  39. def configure(conf):
  40. conf.load('python java protoc')
  41. # Here you have to point to your protobuf-java JAR and have it in classpath
  42. conf.env.CLASSPATH_PROTOBUF = ['protobuf-java-2.5.0.jar']
  43. def build(bld):
  44. bld(
  45. features = 'javac protoc',
  46. name = 'pbjava',
  47. srcdir = 'inc/ src', # directories used by javac
  48. source = ['inc/message_inc.proto', 'inc/message.proto'],
  49. # source is used by protoc for .proto files
  50. use = 'PROTOBUF',
  51. protoc_includes = ['inc']) # for protoc to search dependencies
  52. Notes when using this tool:
  53. - protoc command line parsing is tricky.
  54. The generated files can be put in subfolders which depend on
  55. the order of the include paths.
  56. Try to be simple when creating task generators
  57. containing protoc stuff.
  58. """
  59. class protoc(Task):
  60. run_str = '${PROTOC} ${PROTOC_FL:PROTOC_FLAGS} ${PROTOC_ST:INCPATHS} ${PROTOC_ST:PROTOC_INCPATHS} ${SRC[0].bldpath()}'
  61. color = 'BLUE'
  62. ext_out = ['.h', 'pb.cc', '.py', '.java']
  63. def scan(self):
  64. """
  65. Scan .proto dependencies
  66. """
  67. node = self.inputs[0]
  68. nodes = []
  69. names = []
  70. seen = []
  71. search_nodes = []
  72. if not node:
  73. return (nodes, names)
  74. if 'cxx' in self.generator.features:
  75. search_nodes = self.generator.includes_nodes
  76. if 'py' in self.generator.features or 'javac' in self.generator.features:
  77. for incpath in getattr(self.generator, 'protoc_includes', []):
  78. search_nodes.append(self.generator.bld.path.find_node(incpath))
  79. def parse_node(node):
  80. if node in seen:
  81. return
  82. seen.append(node)
  83. code = node.read().splitlines()
  84. for line in code:
  85. m = re.search(r'^import\s+"(.*)";.*(//)?.*', line)
  86. if m:
  87. dep = m.groups()[0]
  88. for incnode in search_nodes:
  89. found = incnode.find_resource(dep)
  90. if found:
  91. nodes.append(found)
  92. parse_node(found)
  93. else:
  94. names.append(dep)
  95. parse_node(node)
  96. # Add also dependencies path to INCPATHS so protoc will find the included file
  97. for deppath in nodes:
  98. self.env.append_value('INCPATHS', deppath.parent.bldpath())
  99. return (nodes, names)
  100. @extension('.proto')
  101. def process_protoc(self, node):
  102. incdirs = []
  103. out_nodes = []
  104. protoc_flags = []
  105. # ensure PROTOC_FLAGS is a list; a copy is used below anyway
  106. self.env.PROTOC_FLAGS = self.to_list(self.env.PROTOC_FLAGS)
  107. if 'cxx' in self.features:
  108. cpp_node = node.change_ext('.pb.cc')
  109. hpp_node = node.change_ext('.pb.h')
  110. self.source.append(cpp_node)
  111. out_nodes.append(cpp_node)
  112. out_nodes.append(hpp_node)
  113. protoc_flags.append('--cpp_out=%s' % node.parent.get_bld().bldpath())
  114. if 'py' in self.features:
  115. py_node = node.change_ext('_pb2.py')
  116. self.source.append(py_node)
  117. out_nodes.append(py_node)
  118. protoc_flags.append('--python_out=%s' % node.parent.get_bld().bldpath())
  119. if 'javac' in self.features:
  120. pkgname, javapkg, javacn, nodename = None, None, None, None
  121. messages = []
  122. # .java file name is done with some rules depending on .proto file content:
  123. # -) package is either derived from option java_package if present
  124. # or from package directive
  125. # -) file name is either derived from option java_outer_classname if present
  126. # or the .proto file is converted to camelcase. If a message
  127. # is named the same then the behaviour depends on protoc version
  128. #
  129. # See also: https://developers.google.com/protocol-buffers/docs/reference/java-generated#invocation
  130. code = node.read().splitlines()
  131. for line in code:
  132. m = re.search(r'^package\s+(.*);', line)
  133. if m:
  134. pkgname = m.groups()[0]
  135. m = re.search(r'^option\s+(\S*)\s*=\s*"(\S*)";', line)
  136. if m:
  137. optname = m.groups()[0]
  138. if optname == 'java_package':
  139. javapkg = m.groups()[1]
  140. elif optname == 'java_outer_classname':
  141. javacn = m.groups()[1]
  142. if self.env.PROTOC_MAJOR > '2':
  143. m = re.search(r'^message\s+(\w*)\s*{*', line)
  144. if m:
  145. messages.append(m.groups()[0])
  146. if javapkg:
  147. nodename = javapkg
  148. elif pkgname:
  149. nodename = pkgname
  150. else:
  151. raise Errors.WafError('Cannot derive java name from protoc file')
  152. nodename = nodename.replace('.',os.sep) + os.sep
  153. if javacn:
  154. nodename += javacn + '.java'
  155. else:
  156. if self.env.PROTOC_MAJOR > '2' and node.abspath()[node.abspath().rfind(os.sep)+1:node.abspath().rfind('.')].title() in messages:
  157. nodename += node.abspath()[node.abspath().rfind(os.sep)+1:node.abspath().rfind('.')].title().replace('_','') + 'OuterClass.java'
  158. else:
  159. nodename += node.abspath()[node.abspath().rfind(os.sep)+1:node.abspath().rfind('.')].title().replace('_','') + '.java'
  160. java_node = node.parent.find_or_declare(nodename)
  161. out_nodes.append(java_node)
  162. protoc_flags.append('--java_out=%s' % node.parent.get_bld().bldpath())
  163. # Make javac get also pick java code generated in build
  164. if not node.parent.get_bld() in self.javac_task.srcdir:
  165. self.javac_task.srcdir.append(node.parent.get_bld())
  166. if not out_nodes:
  167. raise Errors.WafError('Feature %r not supported by protoc extra' % self.features)
  168. tsk = self.create_task('protoc', node, out_nodes)
  169. tsk.env.append_value('PROTOC_FLAGS', protoc_flags)
  170. if 'javac' in self.features:
  171. self.javac_task.set_run_after(tsk)
  172. # Instruct protoc where to search for .proto included files.
  173. # For C++ standard include files dirs are used,
  174. # but this doesn't apply to Python for example
  175. for incpath in getattr(self, 'protoc_includes', []):
  176. incdirs.append(self.path.find_node(incpath).bldpath())
  177. tsk.env.PROTOC_INCPATHS = incdirs
  178. # PR2115: protoc generates output of .proto files in nested
  179. # directories by canonicalizing paths. To avoid this we have to pass
  180. # as first include the full directory file of the .proto file
  181. tsk.env.prepend_value('INCPATHS', node.parent.bldpath())
  182. use = getattr(self, 'use', '')
  183. if not 'PROTOBUF' in use:
  184. self.use = self.to_list(use) + ['PROTOBUF']
  185. def configure(conf):
  186. conf.check_cfg(package='protobuf', uselib_store='PROTOBUF', args=['--cflags', '--libs'])
  187. conf.find_program('protoc', var='PROTOC')
  188. conf.start_msg('Checking for protoc version')
  189. protocver = conf.cmd_and_log(conf.env.PROTOC + ['--version'], output=Context.BOTH)
  190. protocver = ''.join(protocver).strip()[protocver[0].rfind(' ')+1:]
  191. conf.end_msg(protocver)
  192. conf.env.PROTOC_MAJOR = protocver[:protocver.find('.')]
  193. conf.env.PROTOC_ST = '-I%s'
  194. conf.env.PROTOC_FL = '%s'