Debian Codegraph @

src/main/starlark/builtins_bzl/common/proto/proto_common.bzl

raw
1 # Copyright 2021 The Bazel Authors. All rights reserved.
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
15 """Definition of proto_common module, together with bazel providers for proto rules."""
16
17 ProtoLangToolchainInfo = provider(
18 doc = """Specifies how to generate language-specific code from .proto files.
19 Used by LANG_proto_library rules.""",
20 fields = dict(
21 out_replacement_format_flag = """(str) Format string used when passing output to the plugin
22 used by proto compiler.""",
23 output_files = """("single","multiple","legacy") Format out_replacement_format_flag with
24 a path to single file or a directory in case of multiple files.""",
25 plugin_format_flag = "(str) Format string used when passing plugin to proto compiler.",
26 plugin = "(FilesToRunProvider) Proto compiler plugin.",
27 runtime = "(Target) Runtime.",
28 provided_proto_sources = "(list[ProtoSource]) Proto sources provided by the toolchain.",
29 proto_compiler = "(FilesToRunProvider) Proto compiler.",
30 protoc_opts = "(list[str]) Options to pass to proto compiler.",
31 progress_message = "(str) Progress message to set on the proto compiler action.",
32 mnemonic = "(str) Mnemonic to set on the proto compiler action.",
33 allowlist_different_package = """(Target) Allowlist to create lang_proto_library in a
34 different package than proto_library""",
35 toolchain_type = """(Label) Toolchain type that was used to obtain this info""",
36 ),
37 )
38
39 def _import_virtual_proto_path(path):
40 """Imports all paths for virtual imports.
41
42 They're of the form:
43 'bazel-out/k8-fastbuild/bin/external/foo/e/_virtual_imports/e' or
44 'bazel-out/foo/k8-fastbuild/bin/e/_virtual_imports/e'"""
45 if path.count("/") > 4:
46 return "-I%s" % path
47 return None
48
49 def _import_repo_proto_path(path):
50 """Imports all paths for generated files in external repositories.
51
52 They are of the form:
53 'bazel-out/k8-fastbuild/bin/external/foo' or
54 'bazel-out/foo/k8-fastbuild/bin'"""
55 path_count = path.count("/")
56 if path_count > 2 and path_count <= 4:
57 return "-I%s" % path
58 return None
59
60 def _import_main_output_proto_path(path):
61 """Imports all paths for generated files or source files in external repositories.
62
63 They're of the form:
64 'bazel-out/k8-fastbuild/bin'
65 'external/foo'
66 '../foo'
67 """
68 if path.count("/") <= 2 and path != ".":
69 return "-I%s" % path
70 return None
71
72 def _remove_repo(file):
73 """Removes `../repo/` prefix from path, e.g. `../repo/package/path -> package/path`"""
74 short_path = file.short_path
75 workspace_root = file.owner.workspace_root
76 if workspace_root:
77 if workspace_root.startswith("external/"):
78 workspace_root = "../" + workspace_root.removeprefix("external/")
79 return short_path.removeprefix(workspace_root + "/")
80 return short_path
81
82 def _get_import_path(proto_file):
83 """Returns the import path of a .proto file
84
85 This is the path as used for the the file that can be used in an `import` statement in another
86 .proto file.
87
88 Args:
89 proto_file: (File) The .proto file
90 Returns:
91 (str) import path
92 """
93 repo_path = _remove_repo(proto_file)
94 index = repo_path.find("_virtual_imports/")
95 if index >= 0:
96 index = repo_path.find("/", index + len("_virtual_imports/"))
97 repo_path = repo_path[index + 1:]
98 return repo_path
99
100 def _output_directory(proto_info, root):
101 proto_source_root = proto_info.proto_source_root
102 if proto_source_root.startswith(root.path):
103 #TODO(b/281812523): remove this branch when bin_dir is removed from proto_source_root
104 proto_source_root = proto_source_root.removeprefix(root.path).removeprefix("/")
105
106 if proto_source_root == "" or proto_source_root == ".":
107 return root.path
108
109 return root.path + "/" + proto_source_root
110
111 def _check_collocated(label, proto_info, proto_lang_toolchain_info):
112 """Checks if lang_proto_library is collocated with proto_library.
113
114 Exceptions are allowed by an allowlist defined on `proto_lang_toolchain` and
115 on an allowlist defined on `proto_library`'s `allow_exports` attribute.
116
117 If checks are not successful the function fails.
118
119 Args:
120 label: (Label) The label of lang_proto_library
121 proto_info: (ProtoInfo) The ProtoInfo from the proto_library dependency.
122 proto_lang_toolchain_info: (ProtoLangToolchainInfo) The proto lang toolchain info.
123 Obtained from a `proto_lang_toolchain` target.
124 """
125 PackageSpecificationInfo = _builtins.toplevel.PackageSpecificationInfo
126 if (proto_info.direct_descriptor_set.owner.package != label.package and
127 proto_lang_toolchain_info.allowlist_different_package):
128 if not proto_lang_toolchain_info.allowlist_different_package[PackageSpecificationInfo].contains(label):
129 fail(("lang_proto_library '%s' may only be created in the same package " +
130 "as proto_library '%s'") % (label, proto_info.direct_descriptor_set.owner))
131 if (proto_info.direct_descriptor_set.owner.package != label.package and
132 hasattr(proto_info, "allow_exports")):
133 if not proto_info.allow_exports[PackageSpecificationInfo].contains(label):
134 fail(("lang_proto_library '%s' may only be created in the same package " +
135 "as proto_library '%s'") % (label, proto_info.direct_descriptor_set.owner))
136
137 def _compile(
138 actions,
139 proto_info,
140 proto_lang_toolchain_info,
141 generated_files,
142 plugin_output = None,
143 additional_args = None,
144 additional_tools = [],
145 additional_inputs = depset(),
146 resource_set = None,
147 experimental_exec_group = None,
148 experimental_progress_message = None,
149 experimental_output_files = "legacy"):
150 """Creates proto compile action for compiling *.proto files to language specific sources.
151
152 Args:
153 actions: (ActionFactory) Obtained by ctx.actions, used to register the actions.
154 proto_info: (ProtoInfo) The ProtoInfo from proto_library to generate the sources for.
155 proto_lang_toolchain_info: (ProtoLangToolchainInfo) The proto lang toolchain info.
156 Obtained from a `proto_lang_toolchain` target or constructed ad-hoc..
157 generated_files: (list[File]) The output files generated by the proto compiler.
158 Callee needs to declare files using `ctx.actions.declare_file`.
159 See also: `proto_common.declare_generated_files`.
160 plugin_output: (File|str) Deprecated: Set `proto_lang_toolchain.output_files`
161 and remove the parameter.
162 For backwards compatibility, when the proto_lang_toolchain isn't updated
163 the value is used.
164 additional_args: (Args) Additional arguments to add to the action.
165 Accepts an ctx.actions.args() object that is added at the beginning
166 of the command line.
167 additional_tools: (list[File]) Additional tools to add to the action.
168 additional_inputs: (Depset[File]) Additional input files to add to the action.
169 resource_set: (func) A callback function that is passed to the created action.
170 See `ctx.actions.run`, `resource_set` parameter for full definition of
171 the callback.
172 experimental_exec_group: (str) Sets `exec_group` on proto compile action.
173 Avoid using this parameter.
174 experimental_progress_message: Overrides progress_message from the toolchain.
175 Don't use this parameter. It's only intended for the transition.
176 experimental_output_files: (str) Overwrites output_files from the toolchain.
177 Don't use this parameter. It's only intended for the transition.
178 """
179 if type(generated_files) != type([]):
180 fail("generated_files is expected to be a list of Files")
181 if not generated_files:
182 return # nothing to do
183 if experimental_output_files not in ["single", "multiple", "legacy"]:
184 fail('experimental_output_files expected to be one of ["single", "multiple", "legacy"]')
185
186 args = actions.args()
187 args.use_param_file(param_file_arg = "@%s")
188 args.set_param_file_format("multiline")
189 tools = list(additional_tools)
190
191 if experimental_output_files != "legacy":
192 output_files = experimental_output_files
193 else:
194 output_files = getattr(proto_lang_toolchain_info, "output_files", "legacy")
195 if output_files != "legacy":
196 if proto_lang_toolchain_info.out_replacement_format_flag:
197 if output_files == "single":
198 if len(generated_files) > 1:
199 fail("generated_files only expected a single file")
200 plugin_output = generated_files[0]
201 else:
202 plugin_output = _output_directory(proto_info, generated_files[0].root)
203
204 if plugin_output:
205 args.add(plugin_output, format = proto_lang_toolchain_info.out_replacement_format_flag)
206 if proto_lang_toolchain_info.plugin:
207 tools.append(proto_lang_toolchain_info.plugin)
208 args.add(proto_lang_toolchain_info.plugin.executable, format = proto_lang_toolchain_info.plugin_format_flag)
209
210 # Protoc searches for .protos -I paths in order they are given and then
211 # uses the path within the directory as the package.
212 # This requires ordering the paths from most specific (longest) to least
213 # specific ones, so that no path in the list is a prefix of any of the
214 # following paths in the list.
215 # For example: 'bazel-out/k8-fastbuild/bin/external/foo' needs to be listed
216 # before 'bazel-out/k8-fastbuild/bin'. If not, protoc will discover file under
217 # the shorter path and use 'external/foo/...' as its package path.
218 args.add_all(proto_info.transitive_proto_path, map_each = _import_virtual_proto_path)
219 args.add_all(proto_info.transitive_proto_path, map_each = _import_repo_proto_path)
220 args.add_all(proto_info.transitive_proto_path, map_each = _import_main_output_proto_path)
221 args.add("-I.") # Needs to come last
222
223 args.add_all(proto_lang_toolchain_info.protoc_opts)
224
225 args.add_all(proto_info.direct_sources)
226
227 if additional_args:
228 additional_args.use_param_file(param_file_arg = "@%s")
229 additional_args.set_param_file_format("multiline")
230
231 actions.run(
232 mnemonic = proto_lang_toolchain_info.mnemonic,
233 progress_message = experimental_progress_message if experimental_progress_message else proto_lang_toolchain_info.progress_message,
234 executable = proto_lang_toolchain_info.proto_compiler,
235 arguments = [additional_args, args] if additional_args else [args],
236 inputs = depset(transitive = [proto_info.transitive_sources, additional_inputs]),
237 outputs = generated_files,
238 tools = tools,
239 use_default_shell_env = True,
240 resource_set = resource_set,
241 exec_group = experimental_exec_group,
242 toolchain = _toolchain_type(proto_lang_toolchain_info),
243 )
244
245 _BAZEL_TOOLS_PREFIX = "external/bazel_tools/"
246
247 def _experimental_filter_sources(proto_info, proto_lang_toolchain_info):
248 if not proto_info.direct_sources:
249 return [], []
250
251 # Collect a set of provided protos
252 provided_proto_sources = proto_lang_toolchain_info.provided_proto_sources
253 provided_paths = {}
254 for src in provided_proto_sources:
255 path = src.path
256
257 # For listed protos bundled with the Bazel tools repository, their exec paths start
258 # with external/bazel_tools/. This prefix needs to be removed first, because the protos in
259 # user repositories will not have that prefix.
260 if path.startswith(_BAZEL_TOOLS_PREFIX):
261 provided_paths[path[len(_BAZEL_TOOLS_PREFIX):]] = None
262 else:
263 provided_paths[path] = None
264
265 # Filter proto files
266 proto_files = proto_info._direct_proto_sources
267 excluded = []
268 included = []
269 for proto_file in proto_files:
270 if proto_file.path in provided_paths:
271 excluded.append(proto_file)
272 else:
273 included.append(proto_file)
274 return included, excluded
275
276 def _experimental_should_generate_code(
277 proto_info,
278 proto_lang_toolchain_info,
279 rule_name,
280 target_label):
281 """Checks if the code should be generated for the given proto_library.
282
283 The code shouldn't be generated only when the toolchain already provides it
284 to the language through its runtime dependency.
285
286 It fails when the proto_library contains mixed proto files, that should and
287 shouldn't generate code.
288
289 Args:
290 proto_info: (ProtoInfo) The ProtoInfo from proto_library to check the generation for.
291 proto_lang_toolchain_info: (ProtoLangToolchainInfo) The proto lang toolchain info.
292 Obtained from a `proto_lang_toolchain` target or constructed ad-hoc.
293 rule_name: (str) Name of the rule used in the failure message.
294 target_label: (Label) The label of the target used in the failure message.
295
296 Returns:
297 (bool) True when the code should be generated.
298 """
299 included, excluded = _experimental_filter_sources(proto_info, proto_lang_toolchain_info)
300
301 if included and excluded:
302 fail(("The 'srcs' attribute of '%s' contains protos for which '%s' " +
303 "shouldn't generate code (%s), in addition to protos for which it should (%s).\n" +
304 "Separate '%s' into 2 proto_library rules.") % (
305 target_label,
306 rule_name,
307 ", ".join([f.short_path for f in excluded]),
308 ", ".join([f.short_path for f in included]),
309 target_label,
310 ))
311
312 return bool(included)
313
314 def _declare_generated_files(
315 actions,
316 proto_info,
317 extension,
318 name_mapper = None):
319 """Declares generated files with a specific extension.
320
321 Use this in lang_proto_library-es when protocol compiler generates files
322 that correspond to .proto file names.
323
324 The function removes ".proto" extension with given one (e.g. ".pb.cc") and
325 declares new output files.
326
327 Args:
328 actions: (ActionFactory) Obtained by ctx.actions, used to declare the files.
329 proto_info: (ProtoInfo) The ProtoInfo to declare the files for.
330 extension: (str) The extension to use for generated files.
331 name_mapper: (str->str) A function mapped over the base filename without
332 the extension. Used it to replace characters in the name that
333 cause problems in a specific programming language.
334
335 Returns:
336 (list[File]) The list of declared files.
337 """
338 proto_sources = proto_info.direct_sources
339 outputs = []
340
341 for src in proto_sources:
342 basename_no_ext = src.basename[:-(len(src.extension) + 1)]
343
344 if name_mapper:
345 basename_no_ext = name_mapper(basename_no_ext)
346
347 # Note that two proto_library rules can have the same source file, so this is actually a
348 # shared action. NB: This can probably result in action conflicts if the proto_library rules
349 # are not the same.
350 outputs.append(actions.declare_file(basename_no_ext + extension, sibling = src))
351
352 return outputs
353
354 def _toolchain_type(proto_lang_toolchain_info):
355 if _builtins.toplevel.proto_common.incompatible_enable_proto_toolchain_resolution():
356 return getattr(proto_lang_toolchain_info, "toolchain_type", None)
357 else:
358 return None
359
360 def _find_toolchain(ctx, legacy_attr, toolchain_type):
361 if _builtins.toplevel.proto_common.incompatible_enable_proto_toolchain_resolution():
362 toolchain = ctx.toolchains[toolchain_type]
363 if not toolchain:
364 fail("No toolchains registered for '%s'." % toolchain_type)
365 return toolchain.proto
366 else:
367 return getattr(ctx.attr, legacy_attr)[ProtoLangToolchainInfo]
368
369 def _use_toolchain(toolchain_type):
370 if _builtins.toplevel.proto_common.incompatible_enable_proto_toolchain_resolution():
371 return [_builtins.toplevel.config_common.toolchain_type(toolchain_type, mandatory = False)]
372 else:
373 return []
374
375 def _if_legacy_toolchain(legacy_attr_dict):
376 if _builtins.toplevel.proto_common.incompatible_enable_proto_toolchain_resolution():
377 return {}
378 else:
379 return legacy_attr_dict
380
381 toolchains = struct(
382 use_toolchain = _use_toolchain,
383 find_toolchain = _find_toolchain,
384 if_legacy_toolchain = _if_legacy_toolchain,
385 )
386
387 proto_common_do_not_use = struct(
388 compile = _compile,
389 declare_generated_files = _declare_generated_files,
390 check_collocated = _check_collocated,
391 experimental_should_generate_code = _experimental_should_generate_code,
392 experimental_filter_sources = _experimental_filter_sources,
393 get_import_path = _get_import_path,
394 ProtoLangToolchainInfo = ProtoLangToolchainInfo,
395 INCOMPATIBLE_ENABLE_PROTO_TOOLCHAIN_RESOLUTION = _builtins.toplevel.proto_common.incompatible_enable_proto_toolchain_resolution(),
396 INCOMPATIBLE_PASS_TOOLCHAIN_TYPE = True,
397 )