github.com/bazelbuild/rules_go@v0.47.2-0.20240515105122-e7ddb9ea474e/proto/compiler.bzl (about)

     1  # Copyright 2017 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  load(
    16      "@bazel_skylib//lib:paths.bzl",
    17      "paths",
    18  )
    19  load(
    20      "@rules_proto//proto:proto_common.bzl",
    21      proto_toolchains = "toolchains",
    22  )
    23  load(
    24      "//go:def.bzl",
    25      "GoLibrary",
    26      "go_context",
    27  )
    28  load(
    29      "//go/private:common.bzl",
    30      "GO_TOOLCHAIN",
    31      "GO_TOOLCHAIN_LABEL",
    32  )
    33  load(
    34      "//go/private/rules:transition.bzl",
    35      "go_reset_target",
    36  )
    37  
    38  # This is actually a misuse of Proto toolchains: The proper way to use `protoc` would be to go
    39  # through a Go-specific `proto_lang_toolchain` and use the methods on `proto_common` to interact
    40  # with `protoc`. Since rules_go has a very bespoke setup with customizable compilers and the need
    41  # to apply reset transitions in case `protoc` *is* built from source, this would require major
    42  # changes.
    43  # TODO: Revisit this after --incompatible_enable_proto_toolchain_resolution has been enabled by
    44  #  default.
    45  _PROTO_TOOLCHAIN_TYPE = "@rules_proto//proto:toolchain_type"
    46  
    47  GoProtoCompiler = provider(
    48      doc = "Information and dependencies needed to generate Go code from protos",
    49      fields = {
    50          "compile": """A function with the signature:
    51  
    52      def compile(go, compiler, protos, imports, importpath)
    53  
    54  where go is the go_context object, compiler is this GoProtoCompiler, protos
    55  is a list of ProtoInfo providers for protos to compile, imports is a depset
    56  of strings mapping proto import paths to Go import paths, and importpath is
    57  the import path of the Go library being generated.
    58  
    59  The function should declare output .go files and actions to generate them.
    60  It should return a list of .go Files to be compiled by the Go compiler.
    61  """,
    62          "deps": """List of targets providing GoLibrary, GoSource, and GoArchive.
    63  These are added as implicit dependencies for any go_proto_library using this
    64  compiler. Typically, these are Well Known Types and proto runtime libraries.""",
    65          "valid_archive": """A Boolean indicating whether the .go files produced
    66  by this compiler are buildable on their own. Compilers that just add methods
    67  to structs produced by other compilers will set this to False.""",
    68          "internal": "Opaque value containing data used by compile.",
    69      },
    70  )
    71  
    72  def go_proto_compile(go, compiler, protos, imports, importpath):
    73      """Invokes protoc to generate Go sources for a given set of protos
    74  
    75      Args:
    76          go: the go object, returned by go_context.
    77          compiler: a GoProtoCompiler provider.
    78          protos: list of ProtoInfo providers for protos to compile.
    79          imports: depset of strings mapping proto import paths to Go import paths.
    80          importpath: the import path of the Go library being generated.
    81  
    82      Returns:
    83          A list of .go Files generated by the compiler.
    84      """
    85  
    86      go_srcs = []
    87      outpath = None
    88      proto_paths = {}
    89      desc_sets = []
    90      for proto in protos:
    91          desc_sets.append(proto.transitive_descriptor_sets)
    92          for src in proto.check_deps_sources.to_list():
    93              path = proto_path(src, proto)
    94              if path in proto_paths:
    95                  if proto_paths[path] != src:
    96                      fail("proto files {} and {} have the same import path, {}".format(
    97                          src.path,
    98                          proto_paths[path].path,
    99                          path,
   100                      ))
   101                  continue
   102              proto_paths[path] = src
   103  
   104              suffixes = compiler.internal.suffixes
   105              if not suffixes:
   106                  suffixes = [compiler.internal.suffix]
   107              for suffix in suffixes:
   108                  out = go.declare_file(
   109                      go,
   110                      path = importpath + "/" + src.basename[:-len(".proto")],
   111                      ext = suffix,
   112                  )
   113                  go_srcs.append(out)
   114              if outpath == None:
   115                  outpath = go_srcs[0].dirname[:-len(importpath)]
   116  
   117      transitive_descriptor_sets = depset(direct = [], transitive = desc_sets)
   118  
   119      args = go.actions.args()
   120      args.add("-protoc", compiler.internal.protoc.executable)
   121      args.add("-importpath", importpath)
   122      args.add("-out_path", outpath)
   123      args.add("-plugin", compiler.internal.plugin)
   124  
   125      # TODO(jayconrod): can we just use go.env instead?
   126      args.add_all(compiler.internal.options, before_each = "-option")
   127      if compiler.internal.import_path_option:
   128          args.add_all([importpath], before_each = "-option", format_each = "import_path=%s")
   129      args.add_all(transitive_descriptor_sets, before_each = "-descriptor_set")
   130      args.add_all(go_srcs, before_each = "-expected")
   131      args.add_all(imports, before_each = "-import")
   132      args.add_all(proto_paths.keys())
   133      args.use_param_file("-param=%s")
   134      go.actions.run(
   135          inputs = depset(
   136              direct = [
   137                  compiler.internal.go_protoc,
   138                  compiler.internal.plugin,
   139              ],
   140              transitive = [transitive_descriptor_sets],
   141          ),
   142          outputs = go_srcs,
   143          progress_message = "Generating into %s" % go_srcs[0].dirname,
   144          mnemonic = "GoProtocGen",
   145          executable = compiler.internal.go_protoc,
   146          toolchain = GO_TOOLCHAIN_LABEL,
   147          tools = [compiler.internal.protoc],
   148          arguments = [args],
   149          env = go.env,
   150          # We may need the shell environment (potentially augmented with --action_env)
   151          # to invoke protoc on Windows. If protoc was built with mingw, it probably needs
   152          # .dll files in non-default locations that must be in PATH. The target configuration
   153          # may not have a C compiler, so we have no idea what PATH should be.
   154          use_default_shell_env = "PATH" not in go.env,
   155      )
   156      return go_srcs
   157  
   158  def proto_path(src, proto):
   159      """proto_path returns the string used to import the proto. This is the proto
   160      source path within its repository, adjusted by import_prefix and
   161      strip_import_prefix.
   162  
   163      Args:
   164          src: the proto source File.
   165          proto: the ProtoInfo provider.
   166  
   167      Returns:
   168          An import path string.
   169      """
   170      if proto.proto_source_root == ".":
   171          # true if proto sources were generated
   172          prefix = src.root.path + "/"
   173      elif proto.proto_source_root.startswith(src.root.path):
   174          # sometimes true when import paths are adjusted with import_prefix
   175          prefix = proto.proto_source_root + "/"
   176      else:
   177          # usually true when paths are not adjusted
   178          prefix = paths.join(src.root.path, proto.proto_source_root) + "/"
   179      if not src.path.startswith(prefix):
   180          # sometimes true when importing multiple adjusted protos
   181          return src.path
   182      return src.path[len(prefix):]
   183  
   184  def _go_proto_compiler_impl(ctx):
   185      go = go_context(ctx)
   186      library = go.new_library(go)
   187      source = go.library_to_source(go, ctx.attr, library, ctx.coverage_instrumented())
   188      proto_toolchain = proto_toolchains.find_toolchain(
   189          ctx,
   190          legacy_attr = "_legacy_proto_toolchain",
   191          toolchain_type = _PROTO_TOOLCHAIN_TYPE,
   192      )
   193      return [
   194          GoProtoCompiler(
   195              deps = ctx.attr.deps,
   196              compile = go_proto_compile,
   197              valid_archive = ctx.attr.valid_archive,
   198              internal = struct(
   199                  options = ctx.attr.options,
   200                  suffix = ctx.attr.suffix,
   201                  suffixes = ctx.attr.suffixes,
   202                  protoc = proto_toolchain.proto_compiler,
   203                  go_protoc = ctx.executable._go_protoc,
   204                  plugin = ctx.executable.plugin,
   205                  import_path_option = ctx.attr.import_path_option,
   206              ),
   207          ),
   208          library,
   209          source,
   210      ]
   211  
   212  _go_proto_compiler = rule(
   213      implementation = _go_proto_compiler_impl,
   214      attrs = dict({
   215          "deps": attr.label_list(providers = [GoLibrary]),
   216          "options": attr.string_list(),
   217          "suffix": attr.string(default = ".pb.go"),
   218          "suffixes": attr.string_list(),
   219          "valid_archive": attr.bool(default = True),
   220          "import_path_option": attr.bool(default = False),
   221          "plugin": attr.label(
   222              executable = True,
   223              cfg = "exec",
   224              mandatory = True,
   225          ),
   226          "_go_protoc": attr.label(
   227              executable = True,
   228              cfg = "exec",
   229              default = "//go/tools/builders:go-protoc",
   230          ),
   231          "_go_context_data": attr.label(
   232              default = "//:go_context_data",
   233          ),
   234      }, **proto_toolchains.if_legacy_toolchain({
   235          "_legacy_proto_toolchain": attr.label(
   236              # Setting cfg = "exec" here as the legacy_proto_toolchain target
   237              # already needs to apply the non_go_tool_transition. Flipping the
   238              # two would be more idiomatic, but proto_toolchains.find_toolchain
   239              # doesn't support split transitions.
   240              cfg = "exec",
   241              default = "//proto/private:legacy_proto_toolchain",
   242          ),
   243      })),
   244      toolchains = [GO_TOOLCHAIN] + proto_toolchains.use_toolchain(_PROTO_TOOLCHAIN_TYPE),
   245  )
   246  
   247  def go_proto_compiler(name, **kwargs):
   248      plugin = kwargs.pop("plugin", "@com_github_golang_protobuf//protoc-gen-go")
   249      reset_plugin_name = name + "_reset_plugin_"
   250      go_reset_target(
   251          name = reset_plugin_name,
   252          dep = plugin,
   253          visibility = ["//visibility:private"],
   254      )
   255      _go_proto_compiler(
   256          name = name,
   257          plugin = reset_plugin_name,
   258          **kwargs
   259      )