Debian Codegraph @

bazel/python_rules.bzl

raw
1 # Copyright 2021 The gRPC Authors
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 """Generates and compiles Python gRPC stubs from proto_library rules."""
15
16 load("@rules_proto//proto:defs.bzl", "ProtoInfo")
17 load(
18 "//bazel:protobuf.bzl",
19 "declare_out_files",
20 "get_include_directory",
21 "get_out_dir",
22 "get_plugin_args",
23 "get_proto_arguments",
24 "get_staged_proto_file",
25 "includes_from_deps",
26 "is_well_known",
27 "protos_from_context",
28 )
29
30 _GENERATED_PROTO_FORMAT = "{}_pb2.py"
31 _GENERATED_GRPC_PROTO_FORMAT = "{}_pb2_grpc.py"
32
33 PyProtoInfo = provider(
34 "The Python outputs from the Protobuf compiler.",
35 fields = {
36 "py_info": "A PyInfo provider for the generated code.",
37 "generated_py_srcs": "The direct (not transitive) generated Python source files.",
38 },
39 )
40
41 def _merge_pyinfos(pyinfos):
42 return PyInfo(
43 transitive_sources = depset(transitive = [p.transitive_sources for p in pyinfos]),
44 imports = depset(transitive = [p.imports for p in pyinfos]),
45 )
46
47 def _gen_py_aspect_impl(target, context):
48 # Early return for well-known protos.
49 if is_well_known(str(context.label)):
50 return [
51 PyProtoInfo(py_info = context.attr._protobuf_library[PyInfo]),
52 ]
53
54 protos = []
55 for p in target[ProtoInfo].direct_sources:
56 protos.append(get_staged_proto_file(target.label, context, p))
57
58 includes = depset(direct = protos, transitive = [target[ProtoInfo].transitive_imports])
59 out_files = declare_out_files(protos, context, _GENERATED_PROTO_FORMAT)
60 generated_py_srcs = out_files
61
62 tools = [context.executable._protoc]
63
64 out_dir = get_out_dir(protos, context)
65
66 arguments = ([
67 "--python_out={}".format(out_dir.path),
68 ] + [
69 "--proto_path={}".format(get_include_directory(i))
70 for i in includes.to_list()
71 ] + [
72 "--proto_path={}".format(context.genfiles_dir.path),
73 ])
74
75 arguments += get_proto_arguments(protos, context.genfiles_dir.path)
76
77 context.actions.run(
78 inputs = protos + includes.to_list(),
79 tools = tools,
80 outputs = out_files,
81 executable = context.executable._protoc,
82 arguments = arguments,
83 mnemonic = "ProtocInvocation",
84 )
85
86 imports = []
87 if out_dir.import_path:
88 imports.append("{}/{}".format(context.workspace_name, out_dir.import_path))
89
90 py_info = PyInfo(transitive_sources = depset(direct = out_files), imports = depset(direct = imports))
91 return PyProtoInfo(
92 py_info = _merge_pyinfos(
93 [
94 py_info,
95 context.attr._protobuf_library[PyInfo],
96 ] + [dep[PyProtoInfo].py_info for dep in context.rule.attr.deps],
97 ),
98 generated_py_srcs = generated_py_srcs,
99 )
100
101 _gen_py_aspect = aspect(
102 implementation = _gen_py_aspect_impl,
103 attr_aspects = ["deps"],
104 fragments = ["py"],
105 attrs = {
106 "_protoc": attr.label(
107 default = Label("//external:protocol_compiler"),
108 providers = ["files_to_run"],
109 executable = True,
110 cfg = "host",
111 ),
112 "_protobuf_library": attr.label(
113 default = Label("@com_google_protobuf//:protobuf_python"),
114 providers = [PyInfo],
115 ),
116 },
117 )
118
119 def _generate_py_impl(context):
120 if (len(context.attr.deps) != 1):
121 fail("Can only compile a single proto at a time.")
122
123 py_sources = []
124
125 # If the proto_library this rule *directly* depends on is in another
126 # package, then we generate .py files to import them in this package. This
127 # behavior is needed to allow rearranging of import paths to make Bazel
128 # outputs align with native python workflows.
129 #
130 # Note that this approach is vulnerable to protoc defining __all__ or other
131 # symbols with __ prefixes that need to be directly imported. Since these
132 # names are likely to be reserved for private APIs, the risk is minimal.
133 if context.label.package != context.attr.deps[0].label.package:
134 for py_src in context.attr.deps[0][PyProtoInfo].generated_py_srcs:
135 reimport_py_file = context.actions.declare_file(py_src.basename)
136 py_sources.append(reimport_py_file)
137 import_line = "from %s import *" % py_src.short_path.replace("/", ".")[:-len(".py")]
138 context.actions.write(reimport_py_file, import_line)
139
140 # Collect output PyInfo provider.
141 imports = [context.label.package + "/" + i for i in context.attr.imports]
142 py_info = PyInfo(transitive_sources = depset(direct = py_sources), imports = depset(direct = imports))
143 out_pyinfo = _merge_pyinfos([py_info, context.attr.deps[0][PyProtoInfo].py_info])
144
145 runfiles = context.runfiles(files = out_pyinfo.transitive_sources.to_list()).merge(context.attr._protobuf_library[DefaultInfo].data_runfiles)
146 return [
147 DefaultInfo(
148 files = out_pyinfo.transitive_sources,
149 runfiles = runfiles,
150 ),
151 out_pyinfo,
152 ]
153
154 py_proto_library = rule(
155 attrs = {
156 "deps": attr.label_list(
157 mandatory = True,
158 allow_empty = False,
159 providers = [ProtoInfo],
160 aspects = [_gen_py_aspect],
161 ),
162 "_protoc": attr.label(
163 default = Label("//external:protocol_compiler"),
164 providers = ["files_to_run"],
165 executable = True,
166 cfg = "host",
167 ),
168 "_protobuf_library": attr.label(
169 default = Label("@com_google_protobuf//:protobuf_python"),
170 providers = [PyInfo],
171 ),
172 "imports": attr.string_list(),
173 },
174 implementation = _generate_py_impl,
175 )
176
177 def _generate_pb2_grpc_src_impl(context):
178 protos = protos_from_context(context)
179 includes = includes_from_deps(context.attr.deps)
180 out_files = declare_out_files(protos, context, _GENERATED_GRPC_PROTO_FORMAT)
181
182 plugin_flags = ["grpc_2_0"] + context.attr.strip_prefixes
183
184 arguments = []
185 tools = [context.executable._protoc, context.executable._grpc_plugin]
186 out_dir = get_out_dir(protos, context)
187 arguments += get_plugin_args(
188 context.executable._grpc_plugin,
189 plugin_flags,
190 out_dir.path,
191 False,
192 )
193
194 arguments += [
195 "--proto_path={}".format(get_include_directory(i))
196 for i in includes
197 ]
198 arguments.append("--proto_path={}".format(context.genfiles_dir.path))
199 arguments += get_proto_arguments(protos, context.genfiles_dir.path)
200
201 context.actions.run(
202 inputs = protos + includes,
203 tools = tools,
204 outputs = out_files,
205 executable = context.executable._protoc,
206 arguments = arguments,
207 mnemonic = "ProtocInvocation",
208 )
209
210 p = PyInfo(transitive_sources = depset(direct = out_files))
211 py_info = _merge_pyinfos(
212 [
213 p,
214 context.attr._grpc_library[PyInfo],
215 ] + [dep[PyInfo] for dep in context.attr.py_deps],
216 )
217
218 runfiles = context.runfiles(files = out_files, transitive_files = py_info.transitive_sources).merge(context.attr._grpc_library[DefaultInfo].data_runfiles)
219
220 return [
221 DefaultInfo(
222 files = depset(direct = out_files),
223 runfiles = runfiles,
224 ),
225 py_info,
226 ]
227
228 _generate_pb2_grpc_src = rule(
229 attrs = {
230 "deps": attr.label_list(
231 mandatory = True,
232 allow_empty = False,
233 providers = [ProtoInfo],
234 ),
235 "py_deps": attr.label_list(
236 mandatory = True,
237 allow_empty = False,
238 providers = [PyInfo],
239 ),
240 "strip_prefixes": attr.string_list(),
241 "_grpc_plugin": attr.label(
242 executable = True,
243 providers = ["files_to_run"],
244 cfg = "host",
245 default = Label("//src/compiler:grpc_python_plugin"),
246 ),
247 "_protoc": attr.label(
248 executable = True,
249 providers = ["files_to_run"],
250 cfg = "host",
251 default = Label("//external:protocol_compiler"),
252 ),
253 "_grpc_library": attr.label(
254 default = Label("//src/python/grpcio/grpc:grpcio"),
255 providers = [PyInfo],
256 ),
257 },
258 implementation = _generate_pb2_grpc_src_impl,
259 )
260
261 def py_grpc_library(
262 name,
263 srcs,
264 deps,
265 strip_prefixes = [],
266 **kwargs):
267 """Generate python code for gRPC services defined in a protobuf.
268
269 Args:
270 name: The name of the target.
271 srcs: (List of `labels`) a single proto_library target containing the
272 schema of the service.
273 deps: (List of `labels`) a single py_proto_library target for the
274 proto_library in `srcs`.
275 strip_prefixes: (List of `strings`) If provided, this prefix will be
276 stripped from the beginning of foo_pb2 modules imported by the
277 generated stubs. This is useful in combination with the `imports`
278 attribute of the `py_library` rule.
279 **kwargs: Additional arguments to be supplied to the invocation of
280 py_library.
281 """
282 if len(srcs) != 1:
283 fail("Can only compile a single proto at a time.")
284
285 if len(deps) != 1:
286 fail("Deps must have length 1.")
287
288 _generate_pb2_grpc_src(
289 name = name,
290 deps = srcs,
291 py_deps = deps,
292 strip_prefixes = strip_prefixes,
293 **kwargs
294 )