protobuf.bzl 13 KB

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