protobuf.bzl 16 KB

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