protobuf.bzl 16 KB

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