protobuf.bzl 16 KB

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