protobuf.bzl 15 KB

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