protobuf.bzl 11 KB

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