protobuf.bzl 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. def _GetPath(ctx, path):
  2. if ctx.label.workspace_root:
  3. return ctx.label.workspace_root + '/' + path
  4. else:
  5. return path
  6. def _IsNewExternal(ctx):
  7. # Bazel 0.4.4 and older have genfiles paths that look like:
  8. # bazel-out/local-fastbuild/genfiles/external/repo/foo
  9. # After the exec root rearrangement, they look like:
  10. # ../repo/bazel-out/local-fastbuild/genfiles/foo
  11. return ctx.label.workspace_root.startswith("../")
  12. def _GenDir(ctx):
  13. if _IsNewExternal(ctx):
  14. # We are using the fact that Bazel 0.4.4+ provides repository-relative paths
  15. # for ctx.genfiles_dir.
  16. return ctx.genfiles_dir.path + (
  17. "/" + ctx.attr.includes[0] if ctx.attr.includes and ctx.attr.includes[0] else "")
  18. # This means that we're either in the old version OR the new version in the local repo.
  19. # Either way, appending the source path to the genfiles dir works.
  20. return ctx.var["GENDIR"] + "/" + _SourceDir(ctx)
  21. def _SourceDir(ctx):
  22. if not ctx.attr.includes:
  23. return ctx.label.workspace_root
  24. if not ctx.attr.includes[0]:
  25. return _GetPath(ctx, ctx.label.package)
  26. if not ctx.label.package:
  27. return _GetPath(ctx, ctx.attr.includes[0])
  28. return _GetPath(ctx, ctx.label.package + '/' + ctx.attr.includes[0])
  29. def _CcHdrs(srcs, use_grpc_plugin=False):
  30. ret = [s[:-len(".proto")] + ".pb.h" for s in srcs]
  31. if use_grpc_plugin:
  32. ret += [s[:-len(".proto")] + ".grpc.pb.h" for s in srcs]
  33. return ret
  34. def _CcSrcs(srcs, use_grpc_plugin=False):
  35. ret = [s[:-len(".proto")] + ".pb.cc" for s in srcs]
  36. if use_grpc_plugin:
  37. ret += [s[:-len(".proto")] + ".grpc.pb.cc" for s in srcs]
  38. return ret
  39. def _CcOuts(srcs, use_grpc_plugin=False):
  40. return _CcHdrs(srcs, use_grpc_plugin) + _CcSrcs(srcs, use_grpc_plugin)
  41. def _PyOuts(srcs):
  42. return [s[:-len(".proto")] + "_pb2.py" for s in srcs]
  43. def _RelativeOutputPath(path, include, dest=""):
  44. if include == None:
  45. return path
  46. if not path.startswith(include):
  47. fail("Include path %s isn't part of the path %s." % (include, path))
  48. if include and include[-1] != '/':
  49. include = include + '/'
  50. if dest and dest[-1] != '/':
  51. dest = dest + '/'
  52. path = path[len(include):]
  53. return dest + path
  54. def _proto_gen_impl(ctx):
  55. """General implementation for generating protos"""
  56. srcs = ctx.files.srcs
  57. deps = []
  58. deps += ctx.files.srcs
  59. source_dir = _SourceDir(ctx)
  60. gen_dir = _GenDir(ctx)
  61. if source_dir:
  62. import_flags = ["-I" + source_dir, "-I" + gen_dir]
  63. else:
  64. import_flags = ["-I."]
  65. for dep in ctx.attr.deps:
  66. import_flags += dep.proto.import_flags
  67. deps += dep.proto.deps
  68. args = []
  69. if ctx.attr.gen_cc:
  70. args += ["--cpp_out=" + gen_dir]
  71. if ctx.attr.gen_py:
  72. args += ["--python_out=" + gen_dir]
  73. inputs = srcs + deps
  74. if ctx.executable.plugin:
  75. plugin = ctx.executable.plugin
  76. lang = ctx.attr.plugin_language
  77. if not lang and plugin.basename.startswith('protoc-gen-'):
  78. lang = plugin.basename[len('protoc-gen-'):]
  79. if not lang:
  80. fail("cannot infer the target language of plugin", "plugin_language")
  81. outdir = gen_dir
  82. if ctx.attr.plugin_options:
  83. outdir = ",".join(ctx.attr.plugin_options) + ":" + outdir
  84. args += ["--plugin=protoc-gen-%s=%s" % (lang, plugin.path)]
  85. args += ["--%s_out=%s" % (lang, outdir)]
  86. inputs += [plugin]
  87. if args:
  88. ctx.action(
  89. inputs=inputs,
  90. outputs=ctx.outputs.outs,
  91. arguments=args + import_flags + [s.path for s in srcs],
  92. executable=ctx.executable.protoc,
  93. mnemonic="ProtoCompile",
  94. )
  95. return struct(
  96. proto=struct(
  97. srcs=srcs,
  98. import_flags=import_flags,
  99. deps=deps,
  100. ),
  101. )
  102. proto_gen = rule(
  103. attrs = {
  104. "srcs": attr.label_list(allow_files = True),
  105. "deps": attr.label_list(providers = ["proto"]),
  106. "includes": attr.string_list(),
  107. "protoc": attr.label(
  108. cfg = "host",
  109. executable = True,
  110. single_file = True,
  111. mandatory = True,
  112. ),
  113. "plugin": attr.label(
  114. cfg = "host",
  115. allow_files = True,
  116. executable = True,
  117. ),
  118. "plugin_language": attr.string(),
  119. "plugin_options": attr.string_list(),
  120. "gen_cc": attr.bool(),
  121. "gen_py": attr.bool(),
  122. "outs": attr.output_list(),
  123. },
  124. output_to_genfiles = True,
  125. implementation = _proto_gen_impl,
  126. )
  127. """Generates codes from Protocol Buffers definitions.
  128. This rule helps you to implement Skylark macros specific to the target
  129. language. You should prefer more specific `cc_proto_library `,
  130. `py_proto_library` and others unless you are adding such wrapper macros.
  131. Args:
  132. srcs: Protocol Buffers definition files (.proto) to run the protocol compiler
  133. against.
  134. deps: a list of dependency labels; must be other proto libraries.
  135. includes: a list of include paths to .proto files.
  136. protoc: the label of the protocol compiler to generate the sources.
  137. plugin: the label of the protocol compiler plugin to be passed to the protocol
  138. compiler.
  139. plugin_language: the language of the generated sources
  140. plugin_options: a list of options to be passed to the plugin
  141. gen_cc: generates C++ sources in addition to the ones from the plugin.
  142. gen_py: generates Python sources in addition to the ones from the plugin.
  143. outs: a list of labels of the expected outputs from the protocol compiler.
  144. """
  145. def cc_proto_library(
  146. name,
  147. srcs=[],
  148. deps=[],
  149. cc_libs=[],
  150. include=None,
  151. protoc="//:protoc",
  152. internal_bootstrap_hack=False,
  153. use_grpc_plugin=False,
  154. default_runtime="//:protobuf",
  155. **kargs):
  156. """Bazel rule to create a C++ protobuf library from proto source files
  157. NOTE: the rule is only an internal workaround to generate protos. The
  158. interface may change and the rule may be removed when bazel has introduced
  159. the native rule.
  160. Args:
  161. name: the name of the cc_proto_library.
  162. srcs: the .proto files of the cc_proto_library.
  163. deps: a list of dependency labels; must be cc_proto_library.
  164. cc_libs: a list of other cc_library targets depended by the generated
  165. cc_library.
  166. include: a string indicating the include path of the .proto files.
  167. protoc: the label of the protocol compiler to generate the sources.
  168. internal_bootstrap_hack: a flag indicate the cc_proto_library is used only
  169. for bootstraping. When it is set to True, no files will be generated.
  170. The rule will simply be a provider for .proto files, so that other
  171. cc_proto_library can depend on it.
  172. use_grpc_plugin: a flag to indicate whether to call the grpc C++ plugin
  173. when processing the proto files.
  174. default_runtime: the implicitly default runtime which will be depended on by
  175. the generated cc_library target.
  176. **kargs: other keyword arguments that are passed to cc_library.
  177. """
  178. includes = []
  179. if include != None:
  180. includes = [include]
  181. if internal_bootstrap_hack:
  182. # For pre-checked-in generated files, we add the internal_bootstrap_hack
  183. # which will skip the codegen action.
  184. proto_gen(
  185. name=name + "_genproto",
  186. srcs=srcs,
  187. deps=[s + "_genproto" for s in deps],
  188. includes=includes,
  189. protoc=protoc,
  190. visibility=["//visibility:public"],
  191. )
  192. # An empty cc_library to make rule dependency consistent.
  193. native.cc_library(
  194. name=name,
  195. **kargs)
  196. return
  197. grpc_cpp_plugin = None
  198. if use_grpc_plugin:
  199. grpc_cpp_plugin = "//external:grpc_cpp_plugin"
  200. gen_srcs = _CcSrcs(srcs, use_grpc_plugin)
  201. gen_hdrs = _CcHdrs(srcs, use_grpc_plugin)
  202. outs = gen_srcs + gen_hdrs
  203. proto_gen(
  204. name=name + "_genproto",
  205. srcs=srcs,
  206. deps=[s + "_genproto" for s in deps],
  207. includes=includes,
  208. protoc=protoc,
  209. plugin=grpc_cpp_plugin,
  210. plugin_language="grpc",
  211. gen_cc=1,
  212. outs=outs,
  213. visibility=["//visibility:public"],
  214. )
  215. if default_runtime and not default_runtime in cc_libs:
  216. cc_libs += [default_runtime]
  217. if use_grpc_plugin:
  218. cc_libs += ["//external:grpc_lib"]
  219. native.cc_library(
  220. name=name,
  221. srcs=gen_srcs,
  222. hdrs=gen_hdrs,
  223. deps=cc_libs + deps,
  224. includes=includes,
  225. **kargs)
  226. def internal_gen_well_known_protos_java(srcs):
  227. """Bazel rule to generate the gen_well_known_protos_java genrule
  228. Args:
  229. srcs: the well known protos
  230. """
  231. root = Label("%s//protobuf_java" % (REPOSITORY_NAME)).workspace_root
  232. pkg = PACKAGE_NAME + "/" if PACKAGE_NAME else ""
  233. if root == "":
  234. include = " -I%ssrc " % pkg
  235. else:
  236. include = " -I%s/%ssrc " % (root, pkg)
  237. native.genrule(
  238. name = "gen_well_known_protos_java",
  239. srcs = srcs,
  240. outs = [
  241. "wellknown.srcjar",
  242. ],
  243. cmd = "$(location :protoc) --java_out=$(@D)/wellknown.jar" +
  244. " %s $(SRCS) " % include +
  245. " && mv $(@D)/wellknown.jar $(@D)/wellknown.srcjar",
  246. tools = [":protoc"],
  247. )
  248. def internal_copied_filegroup(name, srcs, strip_prefix, dest, **kwargs):
  249. """Macro to copy files to a different directory and then create a filegroup.
  250. This is used by the //:protobuf_python py_proto_library target to work around
  251. an issue caused by Python source files that are part of the same Python
  252. package being in separate directories.
  253. Args:
  254. srcs: The source files to copy and add to the filegroup.
  255. strip_prefix: Path to the root of the files to copy.
  256. dest: The directory to copy the source files into.
  257. **kwargs: extra arguments that will be passesd to the filegroup.
  258. """
  259. outs = [_RelativeOutputPath(s, strip_prefix, dest) for s in srcs]
  260. native.genrule(
  261. name = name + "_genrule",
  262. srcs = srcs,
  263. outs = outs,
  264. cmd = " && ".join(
  265. ["cp $(location %s) $(location %s)" %
  266. (s, _RelativeOutputPath(s, strip_prefix, dest)) for s in srcs]),
  267. )
  268. native.filegroup(
  269. name = name,
  270. srcs = outs,
  271. **kwargs)
  272. def py_proto_library(
  273. name,
  274. srcs=[],
  275. deps=[],
  276. py_libs=[],
  277. py_extra_srcs=[],
  278. include=None,
  279. default_runtime="//:protobuf_python",
  280. protoc="//:protoc",
  281. use_grpc_plugin=False,
  282. **kargs):
  283. """Bazel rule to create a Python protobuf library from proto source files
  284. NOTE: the rule is only an internal workaround to generate protos. The
  285. interface may change and the rule may be removed when bazel has introduced
  286. the native rule.
  287. Args:
  288. name: the name of the py_proto_library.
  289. srcs: the .proto files of the py_proto_library.
  290. deps: a list of dependency labels; must be py_proto_library.
  291. py_libs: a list of other py_library targets depended by the generated
  292. py_library.
  293. py_extra_srcs: extra source files that will be added to the output
  294. py_library. This attribute is used for internal bootstrapping.
  295. include: a string indicating the include path of the .proto files.
  296. default_runtime: the implicitly default runtime which will be depended on by
  297. the generated py_library target.
  298. protoc: the label of the protocol compiler to generate the sources.
  299. use_grpc_plugin: a flag to indicate whether to call the Python C++ plugin
  300. when processing the proto files.
  301. **kargs: other keyword arguments that are passed to cc_library.
  302. """
  303. outs = _PyOuts(srcs)
  304. includes = []
  305. if include != None:
  306. includes = [include]
  307. grpc_python_plugin = None
  308. if use_grpc_plugin:
  309. grpc_python_plugin = "//external:grpc_python_plugin"
  310. # Note: Generated grpc code depends on Python grpc module. This dependency
  311. # is not explicitly listed in py_libs. Instead, host system is assumed to
  312. # have grpc installed.
  313. proto_gen(
  314. name=name + "_genproto",
  315. srcs=srcs,
  316. deps=[s + "_genproto" for s in deps],
  317. includes=includes,
  318. protoc=protoc,
  319. gen_py=1,
  320. outs=outs,
  321. visibility=["//visibility:public"],
  322. plugin=grpc_python_plugin,
  323. plugin_language="grpc"
  324. )
  325. if default_runtime and not default_runtime in py_libs + deps:
  326. py_libs += [default_runtime]
  327. native.py_library(
  328. name=name,
  329. srcs=outs+py_extra_srcs,
  330. deps=py_libs+deps,
  331. imports=includes,
  332. **kargs)
  333. def internal_protobuf_py_tests(
  334. name,
  335. modules=[],
  336. **kargs):
  337. """Bazel rules to create batch tests for protobuf internal.
  338. Args:
  339. name: the name of the rule.
  340. modules: a list of modules for tests. The macro will create a py_test for
  341. each of the parameter with the source "google/protobuf/%s.py"
  342. kargs: extra parameters that will be passed into the py_test.
  343. """
  344. for m in modules:
  345. s = "python/google/protobuf/internal/%s.py" % m
  346. native.py_test(
  347. name="py_%s" % m,
  348. srcs=[s],
  349. main=s,
  350. **kargs)