protobuf.bzl 13 KB

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