| 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 |
"""Utility functions for generating protobuf code.""" |
| 15 |
|
| 16 |
load("@rules_proto//proto:defs.bzl", "ProtoInfo") |
| 17 |
|
| 18 |
_PROTO_EXTENSION = ".proto" |
| 19 |
_VIRTUAL_IMPORTS = "/_virtual_imports/" |
| 20 |
|
| 21 |
def well_known_proto_libs(): |
| 22 |
return [ |
| 23 |
"@com_google_protobuf//:any_proto", |
| 24 |
"@com_google_protobuf//:api_proto", |
| 25 |
"@com_google_protobuf//:compiler_plugin_proto", |
| 26 |
"@com_google_protobuf//:descriptor_proto", |
| 27 |
"@com_google_protobuf//:duration_proto", |
| 28 |
"@com_google_protobuf//:empty_proto", |
| 29 |
"@com_google_protobuf//:field_mask_proto", |
| 30 |
"@com_google_protobuf//:source_context_proto", |
| 31 |
"@com_google_protobuf//:struct_proto", |
| 32 |
"@com_google_protobuf//:timestamp_proto", |
| 33 |
"@com_google_protobuf//:type_proto", |
| 34 |
"@com_google_protobuf//:wrappers_proto", |
| 35 |
] |
| 36 |
|
| 37 |
def is_well_known(label): |
| 38 |
return label in well_known_proto_libs() |
| 39 |
|
| 40 |
def get_proto_root(workspace_root): |
| 41 |
"""Gets the root protobuf directory. |
| 42 |
|
| 43 |
Args: |
| 44 |
workspace_root: context.label.workspace_root |
| 45 |
|
| 46 |
Returns: |
| 47 |
The directory relative to which generated include paths should be. |
| 48 |
""" |
| 49 |
if workspace_root: |
| 50 |
return "/{}".format(workspace_root) |
| 51 |
else: |
| 52 |
return "" |
| 53 |
|
| 54 |
def _strip_proto_extension(proto_filename): |
| 55 |
if not proto_filename.endswith(_PROTO_EXTENSION): |
| 56 |
fail('"{}" does not end with "{}"'.format( |
| 57 |
proto_filename, |
| 58 |
_PROTO_EXTENSION, |
| 59 |
)) |
| 60 |
return proto_filename[:-len(_PROTO_EXTENSION)] |
| 61 |
|
| 62 |
def proto_path_to_generated_filename(proto_path, fmt_str): |
| 63 |
"""Calculates the name of a generated file for a protobuf path. |
| 64 |
|
| 65 |
For example, "examples/protos/helloworld.proto" might map to |
| 66 |
"helloworld.pb.h". |
| 67 |
|
| 68 |
Args: |
| 69 |
proto_path: The path to the .proto file. |
| 70 |
fmt_str: A format string used to calculate the generated filename. For |
| 71 |
example, "{}.pb.h" might be used to calculate a C++ header filename. |
| 72 |
|
| 73 |
Returns: |
| 74 |
The generated filename. |
| 75 |
""" |
| 76 |
return fmt_str.format(_strip_proto_extension(proto_path)) |
| 77 |
|
| 78 |
def get_include_directory(source_file): |
| 79 |
"""Returns the include directory path for the source_file. |
| 80 |
|
| 81 |
All of the include statements within the given source_file are calculated |
| 82 |
relative to the directory returned by this method. |
| 83 |
|
| 84 |
The returned directory path can be used as the "--proto_path=" argument |
| 85 |
value. |
| 86 |
|
| 87 |
Args: |
| 88 |
source_file: A proto file. |
| 89 |
|
| 90 |
Returns: |
| 91 |
The include directory path for the source_file. |
| 92 |
""" |
| 93 |
directory = source_file.path |
| 94 |
prefix_len = 0 |
| 95 |
|
| 96 |
if is_in_virtual_imports(source_file): |
| 97 |
root, relative = source_file.path.split(_VIRTUAL_IMPORTS, 2) |
| 98 |
result = root + _VIRTUAL_IMPORTS + relative.split("/", 1)[0] |
| 99 |
return result |
| 100 |
|
| 101 |
if not source_file.is_source and directory.startswith(source_file.root.path): |
| 102 |
prefix_len = len(source_file.root.path) + 1 |
| 103 |
|
| 104 |
if directory.startswith("external", prefix_len): |
| 105 |
external_separator = directory.find("/", prefix_len) |
| 106 |
repository_separator = directory.find("/", external_separator + 1) |
| 107 |
return directory[:repository_separator] |
| 108 |
else: |
| 109 |
return source_file.root.path if source_file.root.path else "." |
| 110 |
|
| 111 |
def get_plugin_args( |
| 112 |
plugin, |
| 113 |
flags, |
| 114 |
dir_out, |
| 115 |
generate_mocks, |
| 116 |
plugin_name = "PLUGIN"): |
| 117 |
"""Returns arguments configuring protoc to use a plugin for a language. |
| 118 |
|
| 119 |
Args: |
| 120 |
plugin: An executable file to run as the protoc plugin. |
| 121 |
flags: The plugin flags to be passed to protoc. |
| 122 |
dir_out: The output directory for the plugin. |
| 123 |
generate_mocks: A bool indicating whether to generate mocks. |
| 124 |
plugin_name: A name of the plugin, it is required to be unique when there |
| 125 |
are more than one plugin used in a single protoc command. |
| 126 |
Returns: |
| 127 |
A list of protoc arguments configuring the plugin. |
| 128 |
""" |
| 129 |
augmented_flags = list(flags) |
| 130 |
if generate_mocks: |
| 131 |
augmented_flags.append("generate_mock_code=true") |
| 132 |
|
| 133 |
augmented_dir_out = dir_out |
| 134 |
if augmented_flags: |
| 135 |
augmented_dir_out = ",".join(augmented_flags) + ":" + dir_out |
| 136 |
|
| 137 |
return [ |
| 138 |
"--plugin=protoc-gen-{plugin_name}={plugin_path}".format( |
| 139 |
plugin_name = plugin_name, |
| 140 |
plugin_path = plugin.path, |
| 141 |
), |
| 142 |
"--{plugin_name}_out={dir_out}".format( |
| 143 |
plugin_name = plugin_name, |
| 144 |
dir_out = augmented_dir_out, |
| 145 |
), |
| 146 |
] |
| 147 |
|
| 148 |
def _make_prefix(label): |
| 149 |
"""Returns the directory prefix for a label. |
| 150 |
|
| 151 |
@repo//foo/bar:sub/dir/file.proto => 'external/repo/foo/bar/' |
| 152 |
//foo/bar:sub/dir/file.proto => 'foo/bar/' |
| 153 |
//:sub/dir/file.proto => '' |
| 154 |
|
| 155 |
That is, the prefix can be removed from a file's full path to |
| 156 |
obtain the file's relative location within the package's effective |
| 157 |
directory.""" |
| 158 |
|
| 159 |
wsr = label.workspace_root |
| 160 |
pkg = label.package |
| 161 |
|
| 162 |
if not wsr and not pkg: |
| 163 |
return "" |
| 164 |
elif not wsr: |
| 165 |
return pkg + "/" |
| 166 |
elif not pkg: |
| 167 |
return wsr + "/" |
| 168 |
else: |
| 169 |
return wsr + "/" + pkg + "/" |
| 170 |
|
| 171 |
def get_staged_proto_file(label, context, source_file): |
| 172 |
"""Copies a proto file to the appropriate location if necessary. |
| 173 |
|
| 174 |
Args: |
| 175 |
label: The label of the rule using the .proto file. |
| 176 |
context: The ctx object for the rule or aspect. |
| 177 |
source_file: The original .proto file. |
| 178 |
|
| 179 |
Returns: |
| 180 |
The original proto file OR a new file in the staged location. |
| 181 |
""" |
| 182 |
if source_file.dirname == label.package or \ |
| 183 |
is_in_virtual_imports(source_file): |
| 184 |
# Current target and source_file are in same package |
| 185 |
return source_file |
| 186 |
else: |
| 187 |
# Current target and source_file are in different packages (most |
| 188 |
# probably even in different repositories) |
| 189 |
prefix = _make_prefix(source_file.owner) |
| 190 |
copied_proto = context.actions.declare_file(source_file.path[len(prefix):]) |
| 191 |
context.actions.run_shell( |
| 192 |
inputs = [source_file], |
| 193 |
outputs = [copied_proto], |
| 194 |
command = "cp {} {}".format(source_file.path, copied_proto.path), |
| 195 |
mnemonic = "CopySourceProto", |
| 196 |
) |
| 197 |
return copied_proto |
| 198 |
|
| 199 |
def protos_from_context(context): |
| 200 |
"""Copies proto files to the appropriate location. |
| 201 |
|
| 202 |
Args: |
| 203 |
context: The ctx object for the rule. |
| 204 |
|
| 205 |
Returns: |
| 206 |
A list of the protos. |
| 207 |
""" |
| 208 |
protos = [] |
| 209 |
for src in context.attr.deps: |
| 210 |
for file in src[ProtoInfo].direct_sources: |
| 211 |
protos.append(get_staged_proto_file(context.label, context, file)) |
| 212 |
return protos |
| 213 |
|
| 214 |
def includes_from_deps(deps): |
| 215 |
"""Get includes from rule dependencies.""" |
| 216 |
return [ |
| 217 |
file |
| 218 |
for src in deps |
| 219 |
for file in src[ProtoInfo].transitive_imports.to_list() |
| 220 |
] |
| 221 |
|
| 222 |
def get_proto_arguments(protos, genfiles_dir_path): |
| 223 |
"""Get the protoc arguments specifying which protos to compile. |
| 224 |
|
| 225 |
Args: |
| 226 |
protos: The protob files to supply. |
| 227 |
genfiles_dir_path: The path to the genfiles directory. |
| 228 |
|
| 229 |
Returns: |
| 230 |
The arguments to supply to protoc. |
| 231 |
""" |
| 232 |
arguments = [] |
| 233 |
for proto in protos: |
| 234 |
strip_prefix_len = 0 |
| 235 |
if is_in_virtual_imports(proto): |
| 236 |
incl_directory = get_include_directory(proto) |
| 237 |
if proto.path.startswith(incl_directory): |
| 238 |
strip_prefix_len = len(incl_directory) + 1 |
| 239 |
elif proto.path.startswith(genfiles_dir_path): |
| 240 |
strip_prefix_len = len(genfiles_dir_path) + 1 |
| 241 |
|
| 242 |
arguments.append(proto.path[strip_prefix_len:]) |
| 243 |
|
| 244 |
return arguments |
| 245 |
|
| 246 |
def declare_out_files(protos, context, generated_file_format): |
| 247 |
"""Declares and returns the files to be generated. |
| 248 |
|
| 249 |
Args: |
| 250 |
protos: A list of files. The protos to declare. |
| 251 |
context: The context object. |
| 252 |
generated_file_format: A format string. Will be passed to |
| 253 |
proto_path_to_generated_filename to generate the filename of each |
| 254 |
generated file. |
| 255 |
|
| 256 |
Returns: |
| 257 |
A list of file providers. |
| 258 |
""" |
| 259 |
|
| 260 |
out_file_paths = [] |
| 261 |
for proto in protos: |
| 262 |
if not is_in_virtual_imports(proto): |
| 263 |
prefix = _make_prefix(proto.owner) |
| 264 |
full_prefix = context.genfiles_dir.path + "/" + prefix |
| 265 |
if proto.path.startswith(full_prefix): |
| 266 |
out_file_paths.append(proto.path[len(full_prefix):]) |
| 267 |
elif proto.path.startswith(prefix): |
| 268 |
out_file_paths.append(proto.path[len(prefix):]) |
| 269 |
else: |
| 270 |
out_file_paths.append(proto.path[proto.path.index(_VIRTUAL_IMPORTS) + 1:]) |
| 271 |
|
| 272 |
return [ |
| 273 |
context.actions.declare_file( |
| 274 |
proto_path_to_generated_filename( |
| 275 |
out_file_path, |
| 276 |
generated_file_format, |
| 277 |
), |
| 278 |
) |
| 279 |
for out_file_path in out_file_paths |
| 280 |
] |
| 281 |
|
| 282 |
def get_out_dir(protos, context): |
| 283 |
"""Returns the value to supply to the --<lang>_out= protoc flag. |
| 284 |
|
| 285 |
The result is based on the input source proto files and current context. |
| 286 |
|
| 287 |
Args: |
| 288 |
protos: A list of protos to be used as source files in protoc command |
| 289 |
context: A ctx object for the rule. |
| 290 |
Returns: |
| 291 |
The value of --<lang>_out= argument. |
| 292 |
""" |
| 293 |
at_least_one_virtual = 0 |
| 294 |
for proto in protos: |
| 295 |
if is_in_virtual_imports(proto): |
| 296 |
at_least_one_virtual = True |
| 297 |
elif at_least_one_virtual: |
| 298 |
fail("Proto sources must be either all virtual imports or all real") |
| 299 |
if at_least_one_virtual: |
| 300 |
out_dir = get_include_directory(protos[0]) |
| 301 |
ws_root = protos[0].owner.workspace_root |
| 302 |
prefix = "/" + _make_prefix(protos[0].owner) + _VIRTUAL_IMPORTS[1:] |
| 303 |
|
| 304 |
return struct( |
| 305 |
path = out_dir, |
| 306 |
import_path = out_dir[out_dir.find(prefix) + 1:], |
| 307 |
) |
| 308 |
|
| 309 |
out_dir = context.genfiles_dir.path |
| 310 |
ws_root = context.label.workspace_root |
| 311 |
if ws_root: |
| 312 |
out_dir = out_dir + "/" + ws_root |
| 313 |
return struct(path = out_dir, import_path = None) |
| 314 |
|
| 315 |
def is_in_virtual_imports(source_file, virtual_folder = _VIRTUAL_IMPORTS): |
| 316 |
"""Determines if source_file is virtual. |
| 317 |
|
| 318 |
A file is virtual if placed in the _virtual_imports subdirectory. The |
| 319 |
output of all proto_library targets which use import_prefix and/or |
| 320 |
strip_import_prefix arguments is placed under _virtual_imports directory. |
| 321 |
|
| 322 |
Args: |
| 323 |
source_file: A proto file. |
| 324 |
virtual_folder: The virtual folder name (is set to "_virtual_imports" |
| 325 |
by default) |
| 326 |
Returns: |
| 327 |
True if source_file is located under _virtual_imports, False otherwise. |
| 328 |
""" |
| 329 |
return not source_file.is_source and virtual_folder in source_file.path |