protobuf.bzl 12 KB

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