protobuf.bzl 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. load("@rules_cc//cc:defs.bzl", "cc_library")
  2. load("@rules_python//python:defs.bzl", "py_library", "py_test")
  3. def _GetPath(ctx, path):
  4. if ctx.label.workspace_root:
  5. return ctx.label.workspace_root + "/" + path
  6. else:
  7. return path
  8. def _IsNewExternal(ctx):
  9. # Bazel 0.4.4 and older have genfiles paths that look like:
  10. # bazel-out/local-fastbuild/genfiles/external/repo/foo
  11. # After the exec root rearrangement, they look like:
  12. # ../repo/bazel-out/local-fastbuild/genfiles/foo
  13. return ctx.label.workspace_root.startswith("../")
  14. def _GenDir(ctx):
  15. if _IsNewExternal(ctx):
  16. # We are using the fact that Bazel 0.4.4+ provides repository-relative paths
  17. # for ctx.genfiles_dir.
  18. return ctx.genfiles_dir.path + (
  19. "/" + ctx.attr.includes[0] if ctx.attr.includes and ctx.attr.includes[0] else ""
  20. )
  21. # This means that we're either in the old version OR the new version in the local repo.
  22. # Either way, appending the source path to the genfiles dir works.
  23. return ctx.var["GENDIR"] + "/" + _SourceDir(ctx)
  24. def _SourceDir(ctx):
  25. if not ctx.attr.includes:
  26. return ctx.label.workspace_root
  27. if not ctx.attr.includes[0]:
  28. return _GetPath(ctx, ctx.label.package)
  29. if not ctx.label.package:
  30. return _GetPath(ctx, ctx.attr.includes[0])
  31. return _GetPath(ctx, ctx.label.package + "/" + ctx.attr.includes[0])
  32. def _CcHdrs(srcs, use_grpc_plugin = False):
  33. ret = [s[:-len(".proto")] + ".pb.h" for s in srcs]
  34. if use_grpc_plugin:
  35. ret += [s[:-len(".proto")] + ".grpc.pb.h" for s in srcs]
  36. return ret
  37. def _CcSrcs(srcs, use_grpc_plugin = False):
  38. ret = [s[:-len(".proto")] + ".pb.cc" for s in srcs]
  39. if use_grpc_plugin:
  40. ret += [s[:-len(".proto")] + ".grpc.pb.cc" for s in srcs]
  41. return ret
  42. def _CcOuts(srcs, use_grpc_plugin = False):
  43. return _CcHdrs(srcs, use_grpc_plugin) + _CcSrcs(srcs, use_grpc_plugin)
  44. def _PyOuts(srcs):
  45. return [s[:-len(".proto")] + "_pb2.py" for s in srcs]
  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.actions.run(
  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. "outs": attr.output_list(),
  110. "gen_cc": attr.bool(),
  111. "gen_py": attr.bool(),
  112. "includes": attr.string_list(),
  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. "protoc": attr.label(
  121. cfg = "host",
  122. executable = True,
  123. allow_single_file = True,
  124. mandatory = True,
  125. ),
  126. "deps": attr.label_list(providers = ["proto"]),
  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 = "//:protoc",
  156. internal_bootstrap_hack = False,
  157. use_grpc_plugin = False,
  158. default_runtime = "//: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. cc_library(
  198. name = name,
  199. **kargs
  200. )
  201. return
  202. grpc_cpp_plugin = None
  203. if use_grpc_plugin:
  204. grpc_cpp_plugin = "//external:grpc_cpp_plugin"
  205. gen_srcs = _CcSrcs(srcs, use_grpc_plugin)
  206. gen_hdrs = _CcHdrs(srcs, use_grpc_plugin)
  207. outs = gen_srcs + gen_hdrs
  208. proto_gen(
  209. name = name + "_genproto",
  210. srcs = srcs,
  211. deps = [s + "_genproto" for s in deps],
  212. includes = includes,
  213. protoc = protoc,
  214. plugin = grpc_cpp_plugin,
  215. plugin_language = "grpc",
  216. gen_cc = 1,
  217. outs = outs,
  218. visibility = ["//visibility:public"],
  219. )
  220. if default_runtime and not default_runtime in cc_libs:
  221. cc_libs = cc_libs + [default_runtime]
  222. if use_grpc_plugin:
  223. cc_libs = cc_libs + ["//external:grpc_lib"]
  224. cc_library(
  225. name = name,
  226. srcs = gen_srcs,
  227. hdrs = gen_hdrs,
  228. deps = cc_libs + deps,
  229. includes = includes,
  230. **kargs
  231. )
  232. def internal_gen_well_known_protos_java(srcs):
  233. """Bazel rule to generate the gen_well_known_protos_java genrule
  234. Args:
  235. srcs: the well known protos
  236. """
  237. root = Label("%s//protobuf_java" % (native.repository_name())).workspace_root
  238. pkg = native.package_name() + "/" if native.package_name() else ""
  239. if root == "":
  240. include = " -I%ssrc " % pkg
  241. else:
  242. include = " -I%s/%ssrc " % (root, pkg)
  243. native.genrule(
  244. name = "gen_well_known_protos_java",
  245. srcs = srcs,
  246. outs = [
  247. "wellknown.srcjar",
  248. ],
  249. cmd = "$(location :protoc) --java_out=$(@D)/wellknown.jar" +
  250. " %s $(SRCS) " % include +
  251. " && mv $(@D)/wellknown.jar $(@D)/wellknown.srcjar",
  252. tools = [":protoc"],
  253. )
  254. def internal_copied_filegroup(name, srcs, strip_prefix, dest, **kwargs):
  255. """Macro to copy files to a different directory and then create a filegroup.
  256. This is used by the //:protobuf_python py_proto_library target to work around
  257. an issue caused by Python source files that are part of the same Python
  258. package being in separate directories.
  259. Args:
  260. srcs: The source files to copy and add to the filegroup.
  261. strip_prefix: Path to the root of the files to copy.
  262. dest: The directory to copy the source files into.
  263. **kwargs: extra arguments that will be passesd to the filegroup.
  264. """
  265. outs = [_RelativeOutputPath(s, strip_prefix, dest) for s in srcs]
  266. native.genrule(
  267. name = name + "_genrule",
  268. srcs = srcs,
  269. outs = outs,
  270. cmd = " && ".join(
  271. ["cp $(location %s) $(location %s)" %
  272. (s, _RelativeOutputPath(s, strip_prefix, dest)) for s in srcs],
  273. ),
  274. )
  275. native.filegroup(
  276. name = name,
  277. srcs = outs,
  278. **kwargs
  279. )
  280. def py_proto_library(
  281. name,
  282. srcs = [],
  283. deps = [],
  284. py_libs = [],
  285. py_extra_srcs = [],
  286. include = None,
  287. default_runtime = "//:protobuf_python",
  288. protoc = "//:protoc",
  289. use_grpc_plugin = False,
  290. **kargs):
  291. """Bazel rule to create a Python protobuf library from proto source files
  292. NOTE: the rule is only an internal workaround to generate protos. The
  293. interface may change and the rule may be removed when bazel has introduced
  294. the native rule.
  295. Args:
  296. name: the name of the py_proto_library.
  297. srcs: the .proto files of the py_proto_library.
  298. deps: a list of dependency labels; must be py_proto_library.
  299. py_libs: a list of other py_library targets depended by the generated
  300. py_library.
  301. py_extra_srcs: extra source files that will be added to the output
  302. py_library. This attribute is used for internal bootstrapping.
  303. include: a string indicating the include path of the .proto files.
  304. default_runtime: the implicitly default runtime which will be depended on by
  305. the generated py_library target.
  306. protoc: the label of the protocol compiler to generate the sources.
  307. use_grpc_plugin: a flag to indicate whether to call the Python C++ plugin
  308. when processing the proto files.
  309. **kargs: other keyword arguments that are passed to cc_library.
  310. """
  311. outs = _PyOuts(srcs)
  312. includes = []
  313. if include != None:
  314. includes = [include]
  315. grpc_python_plugin = None
  316. if use_grpc_plugin:
  317. grpc_python_plugin = "//external:grpc_python_plugin"
  318. # Note: Generated grpc code depends on Python grpc module. This dependency
  319. # is not explicitly listed in py_libs. Instead, host system is assumed to
  320. # have grpc installed.
  321. proto_gen(
  322. name = name + "_genproto",
  323. srcs = srcs,
  324. deps = [s + "_genproto" for s in deps],
  325. includes = includes,
  326. protoc = protoc,
  327. gen_py = 1,
  328. outs = outs,
  329. visibility = ["//visibility:public"],
  330. plugin = grpc_python_plugin,
  331. plugin_language = "grpc",
  332. )
  333. if default_runtime and not default_runtime in py_libs + deps:
  334. py_libs = py_libs + [default_runtime]
  335. py_library(
  336. name = name,
  337. srcs = outs + py_extra_srcs,
  338. deps = py_libs + deps,
  339. imports = includes,
  340. **kargs
  341. )
  342. def internal_protobuf_py_tests(
  343. name,
  344. modules = [],
  345. **kargs):
  346. """Bazel rules to create batch tests for protobuf internal.
  347. Args:
  348. name: the name of the rule.
  349. modules: a list of modules for tests. The macro will create a py_test for
  350. each of the parameter with the source "google/protobuf/%s.py"
  351. kargs: extra parameters that will be passed into the py_test.
  352. """
  353. for m in modules:
  354. s = "python/google/protobuf/internal/%s.py" % m
  355. py_test(
  356. name = "py_%s" % m,
  357. srcs = [s],
  358. main = s,
  359. **kargs
  360. )