| """Create a repository to reference the pre-built protoc toolchains. |
| |
| Ensures that Bazel only downloads required binaries for selected toolchains. |
| |
| This follows guidance here: |
| https://docs.bazel.build/versions/main/skylark/deploying.html#registering-toolchains |
| " |
| Note that in order to resolve toolchains in the analysis phase |
| Bazel needs to analyze all toolchain targets that are registered. |
| Bazel will not need to analyze all targets referenced by toolchain.toolchain attribute. |
| If in order to register toolchains you need to perform complex computation in the repository, |
| consider splitting the repository with toolchain targets |
| from the repository with <LANG>_toolchain targets. |
| Former will be always fetched, |
| and the latter will only be fetched when user actually needs to build <LANG> code. |
| " |
| |
| The "complex computation" in our case is simply downloading our pre-built protoc binaries. |
| This guidance tells us how to avoid that: we put the toolchain targets in the alias repository |
| with only the toolchain attribute pointing into the platform-specific repositories. |
| """ |
| |
| load(":versions.bzl", "PROTOC_PLATFORMS") |
| |
| def _toolchains_repo_impl(repository_ctx): |
| build_content = """# Generated by protoc/private/protoc_toolchains.bzl |
| # |
| # These can be registered in the workspace file or passed to --extra_toolchains flag. |
| # By default all these toolchains are registered by the rules_proto_toolchains macro |
| # so you don't normally need to interact with these targets. |
| |
| """ |
| |
| for [platform, meta] in PROTOC_PLATFORMS.items(): |
| build_content += """ |
| toolchain( |
| name = "{platform}_toolchain", |
| exec_compatible_with = {compatible_with}, |
| # Bazel does not follow this attribute during analysis, so the referenced repo |
| # will only be fetched if this toolchain is selected. |
| toolchain = "@{user_repository_name}.{platform}//:prebuilt_protoc_toolchain", |
| toolchain_type = "@rules_proto//proto:toolchain_type", |
| ) |
| """.format( |
| platform = platform.replace("-", "_"), |
| user_repository_name = repository_ctx.attr.user_repository_name, |
| compatible_with = meta["compatible_with"], |
| ) |
| repository_ctx.file("BUILD.bazel", build_content) |
| |
| protoc_toolchains_repo = repository_rule( |
| _toolchains_repo_impl, |
| doc = """\ |
| Creates a single repository with toolchain definitions for all known platforms |
| that can be registered or selected. |
| """, |
| attrs = { |
| "user_repository_name": attr.string( |
| doc = """What the user chose for the base name. |
| Needed since bzlmod apparent name has extra tilde segments. |
| """, |
| mandatory = True, |
| ), |
| }, |
| ) |