protobuf.bzl 17 KB

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