protobuf.bzl 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. # -*- mode: python; -*- PYTHON-PREPROCESSING-REQUIRED
  2. def _GetPath(ctx, path):
  3. if ctx.label.workspace_root:
  4. return ctx.label.workspace_root + '/' + path
  5. else:
  6. return path
  7. def _GenDir(ctx):
  8. if not ctx.attr.includes:
  9. return ctx.label.workspace_root
  10. if not ctx.attr.includes[0]:
  11. return _GetPath(ctx, ctx.label.package)
  12. if not ctx.label.package:
  13. return _GetPath(ctx, ctx.attr.includes[0])
  14. return _GetPath(ctx, ctx.label.package + '/' + ctx.attr.includes[0])
  15. def _CcOuts(srcs, use_grpc_plugin=False):
  16. ret = [s[:-len(".proto")] + ".pb.h" for s in srcs] + \
  17. [s[:-len(".proto")] + ".pb.cc" for s in srcs]
  18. if use_grpc_plugin:
  19. ret += [s[:-len(".proto")] + ".grpc.pb.h" for s in srcs] + \
  20. [s[:-len(".proto")] + ".grpc.pb.cc" for s in srcs]
  21. return ret
  22. def _PyOuts(srcs):
  23. return [s[:-len(".proto")] + "_pb2.py" for s in srcs]
  24. def _RelativeOutputPath(path, include, dest=""):
  25. if include == None:
  26. return path
  27. if not path.startswith(include):
  28. fail("Include path %s isn't part of the path %s." % (include, path))
  29. if include and include[-1] != '/':
  30. include = include + '/'
  31. if dest and dest[-1] != '/':
  32. dest = dest + '/'
  33. path = path[len(include):]
  34. return dest + path
  35. def _proto_gen_impl(ctx):
  36. """General implementation for generating protos"""
  37. srcs = ctx.files.srcs
  38. deps = []
  39. deps += ctx.files.srcs
  40. gen_dir = _GenDir(ctx)
  41. if gen_dir:
  42. import_flags = ["-I" + gen_dir, "-I" + ctx.var["GENDIR"] + "/" + gen_dir]
  43. else:
  44. import_flags = ["-I."]
  45. for dep in ctx.attr.deps:
  46. import_flags += dep.proto.import_flags
  47. deps += dep.proto.deps
  48. args = []
  49. if ctx.attr.gen_cc:
  50. args += ["--cpp_out=" + ctx.var["GENDIR"] + "/" + gen_dir]
  51. if ctx.attr.gen_py:
  52. args += ["--python_out=" + ctx.var["GENDIR"] + "/" + gen_dir]
  53. if ctx.executable.grpc_cpp_plugin:
  54. args += ["--plugin=protoc-gen-grpc=" + ctx.executable.grpc_cpp_plugin.path]
  55. args += ["--grpc_out=" + ctx.var["GENDIR"] + "/" + gen_dir]
  56. if args:
  57. ctx.action(
  58. inputs=srcs + deps,
  59. outputs=ctx.outputs.outs,
  60. arguments=args + import_flags + [s.path for s in srcs],
  61. executable=ctx.executable.protoc,
  62. )
  63. return struct(
  64. proto=struct(
  65. srcs=srcs,
  66. import_flags=import_flags,
  67. deps=deps,
  68. ),
  69. )
  70. _proto_gen = rule(
  71. attrs = {
  72. "srcs": attr.label_list(allow_files = True),
  73. "deps": attr.label_list(providers = ["proto"]),
  74. "includes": attr.string_list(),
  75. "protoc": attr.label(
  76. cfg = HOST_CFG,
  77. executable = True,
  78. single_file = True,
  79. mandatory = True,
  80. ),
  81. "grpc_cpp_plugin": attr.label(
  82. cfg = HOST_CFG,
  83. executable = True,
  84. single_file = True,
  85. ),
  86. "gen_cc": attr.bool(),
  87. "gen_py": attr.bool(),
  88. "outs": attr.output_list(),
  89. },
  90. output_to_genfiles = True,
  91. implementation = _proto_gen_impl,
  92. )
  93. def cc_proto_library(
  94. name,
  95. srcs=[],
  96. deps=[],
  97. cc_libs=[],
  98. include=None,
  99. protoc="//:protoc",
  100. internal_bootstrap_hack=False,
  101. use_grpc_plugin=False,
  102. default_runtime="//:protobuf",
  103. **kargs):
  104. """Bazel rule to create a C++ protobuf library from proto source files
  105. NOTE: the rule is only an internal workaround to generate protos. The
  106. interface may change and the rule may be removed when bazel has introduced
  107. the native rule.
  108. Args:
  109. name: the name of the cc_proto_library.
  110. srcs: the .proto files of the cc_proto_library.
  111. deps: a list of dependency labels; must be cc_proto_library.
  112. cc_libs: a list of other cc_library targets depended by the generated
  113. cc_library.
  114. include: a string indicating the include path of the .proto files.
  115. protoc: the label of the protocol compiler to generate the sources.
  116. internal_bootstrap_hack: a flag indicate the cc_proto_library is used only
  117. for bootstraping. When it is set to True, no files will be generated.
  118. The rule will simply be a provider for .proto files, so that other
  119. cc_proto_library can depend on it.
  120. use_grpc_plugin: a flag to indicate whether to call the grpc C++ plugin
  121. when processing the proto files.
  122. default_runtime: the implicitly default runtime which will be depended on by
  123. the generated cc_library target.
  124. **kargs: other keyword arguments that are passed to cc_library.
  125. """
  126. includes = []
  127. if include != None:
  128. includes = [include]
  129. if internal_bootstrap_hack:
  130. # For pre-checked-in generated files, we add the internal_bootstrap_hack
  131. # which will skip the codegen action.
  132. _proto_gen(
  133. name=name + "_genproto",
  134. srcs=srcs,
  135. deps=[s + "_genproto" for s in deps],
  136. includes=includes,
  137. protoc=protoc,
  138. visibility=["//visibility:public"],
  139. )
  140. # An empty cc_library to make rule dependency consistent.
  141. native.cc_library(
  142. name=name,
  143. **kargs)
  144. return
  145. grpc_cpp_plugin = None
  146. if use_grpc_plugin:
  147. grpc_cpp_plugin = "//external:grpc_cpp_plugin"
  148. outs = _CcOuts(srcs, use_grpc_plugin)
  149. _proto_gen(
  150. name=name + "_genproto",
  151. srcs=srcs,
  152. deps=[s + "_genproto" for s in deps],
  153. includes=includes,
  154. protoc=protoc,
  155. grpc_cpp_plugin=grpc_cpp_plugin,
  156. gen_cc=1,
  157. outs=outs,
  158. visibility=["//visibility:public"],
  159. )
  160. if default_runtime and not default_runtime in cc_libs:
  161. cc_libs += [default_runtime]
  162. if use_grpc_plugin:
  163. cc_libs += ["//external:grpc_lib"]
  164. native.cc_library(
  165. name=name,
  166. srcs=outs,
  167. deps=cc_libs + deps,
  168. includes=includes,
  169. **kargs)
  170. def internal_gen_well_known_protos_java(srcs):
  171. """Bazel rule to generate the gen_well_known_protos_java genrule
  172. Args:
  173. srcs: the well known protos
  174. """
  175. root = Label("%s//protobuf_java" % (REPOSITORY_NAME)).workspace_root
  176. if root == "":
  177. include = " -Isrc "
  178. else:
  179. include = " -I%s/src " % root
  180. native.genrule(
  181. name = "gen_well_known_protos_java",
  182. srcs = srcs,
  183. outs = [
  184. "wellknown.srcjar",
  185. ],
  186. cmd = "$(location :protoc) --java_out=$(@D)/wellknown.jar" +
  187. " %s $(SRCS) " % include +
  188. " && mv $(@D)/wellknown.jar $(@D)/wellknown.srcjar",
  189. tools = [":protoc"],
  190. )
  191. def internal_copied_filegroup(name, srcs, strip_prefix, dest, **kwargs):
  192. """Macro to copy files to a different directory and then create a filegroup.
  193. This is used by the //:protobuf_python py_proto_library target to work around
  194. an issue caused by Python source files that are part of the same Python
  195. package being in separate directories.
  196. Args:
  197. srcs: The source files to copy and add to the filegroup.
  198. strip_prefix: Path to the root of the files to copy.
  199. dest: The directory to copy the source files into.
  200. **kwargs: extra arguments that will be passesd to the filegroup.
  201. """
  202. outs = [_RelativeOutputPath(s, strip_prefix, dest) for s in srcs]
  203. native.genrule(
  204. name = name + "_genrule",
  205. srcs = srcs,
  206. outs = outs,
  207. cmd = " && ".join(
  208. ["cp $(location %s) $(location %s)" %
  209. (s, _RelativeOutputPath(s, strip_prefix, dest)) for s in srcs]),
  210. )
  211. native.filegroup(
  212. name = name,
  213. srcs = outs,
  214. **kwargs)
  215. def py_proto_library(
  216. name,
  217. srcs=[],
  218. deps=[],
  219. py_libs=[],
  220. py_extra_srcs=[],
  221. include=None,
  222. default_runtime="//:protobuf_python",
  223. protoc="//:protoc",
  224. **kargs):
  225. """Bazel rule to create a Python protobuf library from proto source files
  226. NOTE: the rule is only an internal workaround to generate protos. The
  227. interface may change and the rule may be removed when bazel has introduced
  228. the native rule.
  229. Args:
  230. name: the name of the py_proto_library.
  231. srcs: the .proto files of the py_proto_library.
  232. deps: a list of dependency labels; must be py_proto_library.
  233. py_libs: a list of other py_library targets depended by the generated
  234. py_library.
  235. py_extra_srcs: extra source files that will be added to the output
  236. py_library. This attribute is used for internal bootstrapping.
  237. include: a string indicating the include path of the .proto files.
  238. default_runtime: the implicitly default runtime which will be depended on by
  239. the generated py_library target.
  240. protoc: the label of the protocol compiler to generate the sources.
  241. **kargs: other keyword arguments that are passed to cc_library.
  242. """
  243. outs = _PyOuts(srcs)
  244. includes = []
  245. if include != None:
  246. includes = [include]
  247. _proto_gen(
  248. name=name + "_genproto",
  249. srcs=srcs,
  250. deps=[s + "_genproto" for s in deps],
  251. includes=includes,
  252. protoc=protoc,
  253. gen_py=1,
  254. outs=outs,
  255. visibility=["//visibility:public"],
  256. )
  257. if default_runtime and not default_runtime in py_libs + deps:
  258. py_libs += [default_runtime]
  259. native.py_library(
  260. name=name,
  261. srcs=outs+py_extra_srcs,
  262. deps=py_libs+deps,
  263. imports=includes,
  264. **kargs)
  265. def internal_protobuf_py_tests(
  266. name,
  267. modules=[],
  268. **kargs):
  269. """Bazel rules to create batch tests for protobuf internal.
  270. Args:
  271. name: the name of the rule.
  272. modules: a list of modules for tests. The macro will create a py_test for
  273. each of the parameter with the source "google/protobuf/%s.py"
  274. kargs: extra parameters that will be passed into the py_test.
  275. """
  276. for m in modules:
  277. s = "python/google/protobuf/internal/%s.py" % m
  278. native.py_test(
  279. name="py_%s" % m,
  280. srcs=[s],
  281. main=s,
  282. **kargs)