protobuf.bzl 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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. if ctx.attr.javalite:
  291. java_out = "lite:%s" % srcjar.path
  292. else:
  293. java_out = srcjar
  294. args.add("--java_out", java_out)
  295. descriptors = depset(
  296. transitive = [dep.transitive_descriptor_sets for dep in deps],
  297. )
  298. args.add_joined(
  299. "--descriptor_set_in",
  300. descriptors,
  301. join_with = ctx.configuration.host_path_separator,
  302. )
  303. for dep in deps:
  304. if "." == dep.proto_source_root:
  305. args.add_all([src.path for src in dep.direct_sources])
  306. else:
  307. source_root = dep.proto_source_root
  308. offset = len(source_root) + 1 # + '/'.
  309. args.add_all([src.path[offset:] for src in dep.direct_sources])
  310. ctx.actions.run(
  311. executable = ctx.executable._protoc,
  312. inputs = descriptors,
  313. outputs = [srcjar],
  314. arguments = [args],
  315. use_default_shell_env = True,
  316. )
  317. return [
  318. DefaultInfo(
  319. files = depset([srcjar]),
  320. ),
  321. ]
  322. internal_gen_well_known_protos_java = rule(
  323. implementation = _internal_gen_well_known_protos_java_impl,
  324. attrs = {
  325. "deps": attr.label_list(
  326. mandatory = True,
  327. providers = [ProtoInfo],
  328. ),
  329. "javalite": attr.bool(
  330. default = False,
  331. ),
  332. "_protoc": attr.label(
  333. executable = True,
  334. cfg = "host",
  335. default = "@com_google_protobuf//:protoc",
  336. ),
  337. },
  338. )
  339. def internal_copied_filegroup(name, srcs, strip_prefix, dest, **kwargs):
  340. """Macro to copy files to a different directory and then create a filegroup.
  341. This is used by the //:protobuf_python py_proto_library target to work around
  342. an issue caused by Python source files that are part of the same Python
  343. package being in separate directories.
  344. Args:
  345. srcs: The source files to copy and add to the filegroup.
  346. strip_prefix: Path to the root of the files to copy.
  347. dest: The directory to copy the source files into.
  348. **kwargs: extra arguments that will be passesd to the filegroup.
  349. """
  350. outs = [_RelativeOutputPath(s, strip_prefix, dest) for s in srcs]
  351. native.genrule(
  352. name = name + "_genrule",
  353. srcs = srcs,
  354. outs = outs,
  355. cmd = " && ".join(
  356. ["cp $(location %s) $(location %s)" %
  357. (s, _RelativeOutputPath(s, strip_prefix, dest)) for s in srcs],
  358. ),
  359. )
  360. native.filegroup(
  361. name = name,
  362. srcs = outs,
  363. **kwargs
  364. )
  365. def py_proto_library(
  366. name,
  367. srcs = [],
  368. deps = [],
  369. py_libs = [],
  370. py_extra_srcs = [],
  371. include = None,
  372. default_runtime = "@com_google_protobuf//:protobuf_python",
  373. protoc = "@com_google_protobuf//:protoc",
  374. use_grpc_plugin = False,
  375. **kargs):
  376. """Bazel rule to create a Python protobuf library from proto source files
  377. NOTE: the rule is only an internal workaround to generate protos. The
  378. interface may change and the rule may be removed when bazel has introduced
  379. the native rule.
  380. Args:
  381. name: the name of the py_proto_library.
  382. srcs: the .proto files of the py_proto_library.
  383. deps: a list of dependency labels; must be py_proto_library.
  384. py_libs: a list of other py_library targets depended by the generated
  385. py_library.
  386. py_extra_srcs: extra source files that will be added to the output
  387. py_library. This attribute is used for internal bootstrapping.
  388. include: a string indicating the include path of the .proto files.
  389. default_runtime: the implicitly default runtime which will be depended on by
  390. the generated py_library target.
  391. protoc: the label of the protocol compiler to generate the sources.
  392. use_grpc_plugin: a flag to indicate whether to call the Python C++ plugin
  393. when processing the proto files.
  394. **kargs: other keyword arguments that are passed to py_library.
  395. """
  396. outs = _PyOuts(srcs, use_grpc_plugin)
  397. includes = []
  398. if include != None:
  399. includes = [include]
  400. grpc_python_plugin = None
  401. if use_grpc_plugin:
  402. grpc_python_plugin = "//external:grpc_python_plugin"
  403. # Note: Generated grpc code depends on Python grpc module. This dependency
  404. # is not explicitly listed in py_libs. Instead, host system is assumed to
  405. # have grpc installed.
  406. proto_gen(
  407. name = name + "_genproto",
  408. srcs = srcs,
  409. deps = [s + "_genproto" for s in deps],
  410. includes = includes,
  411. protoc = protoc,
  412. gen_py = 1,
  413. outs = outs,
  414. visibility = ["//visibility:public"],
  415. plugin = grpc_python_plugin,
  416. plugin_language = "grpc",
  417. )
  418. if default_runtime and not default_runtime in py_libs + deps:
  419. py_libs = py_libs + [default_runtime]
  420. py_library(
  421. name = name,
  422. srcs = outs + py_extra_srcs,
  423. deps = py_libs + deps,
  424. imports = includes,
  425. **kargs
  426. )
  427. def internal_protobuf_py_tests(
  428. name,
  429. modules = [],
  430. **kargs):
  431. """Bazel rules to create batch tests for protobuf internal.
  432. Args:
  433. name: the name of the rule.
  434. modules: a list of modules for tests. The macro will create a py_test for
  435. each of the parameter with the source "google/protobuf/%s.py"
  436. kargs: extra parameters that will be passed into the py_test.
  437. """
  438. for m in modules:
  439. s = "python/google/protobuf/internal/%s.py" % m
  440. py_test(
  441. name = "py_%s" % m,
  442. srcs = [s],
  443. main = s,
  444. **kargs
  445. )
  446. def check_protobuf_required_bazel_version():
  447. """For WORKSPACE files, to check the installed version of bazel.
  448. This ensures bazel supports our approach to proto_library() depending on a
  449. copied filegroup. (Fixed in bazel 0.5.4)
  450. """
  451. versions.check(minimum_bazel_version = "0.5.4")