diff --git a/pw_protobuf_compiler/nanopb_proto_library.bzl b/pw_protobuf_compiler/nanopb_proto_library.bzl index d808f8c27..7e99ad000 100644 --- a/pw_protobuf_compiler/nanopb_proto_library.bzl +++ b/pw_protobuf_compiler/nanopb_proto_library.bzl @@ -57,16 +57,25 @@ def nanopb_proto_library(*, name, deps, tags = [], options = None, **kwargs): **kwargs ) +def _custom_opt_for_library_include_format(): + """Return correctly set --library-include-format. + + When using nanopb_proto_library from a monorepo in which nanopb is not an + external repository but just a build target within the main tree, the + #include statements need to be relative to the root of that tree. Handle + this case using --library-include-format. + """ + pb_h = Label("@com_github_nanopb_nanopb//:pb.h") + if pb_h.workspace_root == "": + # Monorepo case + return "--library-include-format=#include \"{}/%s\"".format(pb_h.package) + else: + return "--library-include-format=#include \"%s\"" + _nanopb_proto_compiler_aspect = proto_compiler_aspect( ["pb.h", "pb.c"], Label("@com_github_nanopb_nanopb//:protoc-gen-nanopb"), - [], - { - "_pb_h": attr.label( - default = Label("@com_github_nanopb_nanopb//:pb.h"), - allow_single_file = True, - ), - }, + [_custom_opt_for_library_include_format()], ) _nanopb_proto_library = rule( diff --git a/pw_protobuf_compiler/private/proto.bzl b/pw_protobuf_compiler/private/proto.bzl index 6f3fb319e..989611fe3 100644 --- a/pw_protobuf_compiler/private/proto.bzl +++ b/pw_protobuf_compiler/private/proto.bzl @@ -194,14 +194,6 @@ def _proto_compiler_aspect_impl(target, ctx): continue args.add("--custom_opt={}".format(plugin_option)) - # In certain environments the path to pb.h must be defined, rather - # than relying on the default location. - # Use a format string rather than `quote`, to maintain support - # for nanopb 3. - if hasattr(ctx.attr, "_pb_h"): - plugin_options_arg = "--library-include-format=#include \"{}/%s\"".format(ctx.file._pb_h.dirname) - args.add("--custom_opt={}".format(plugin_options_arg)) - args.add("--custom_out={}".format(out_path)) args.add_all(proto_info.direct_sources) @@ -247,7 +239,7 @@ def _proto_compiler_aspect_impl(target, ctx): includes = transitive_includes, )] -def proto_compiler_aspect(extensions, protoc_plugin, plugin_options = [], additional_attrs = {}): +def proto_compiler_aspect(extensions, protoc_plugin, plugin_options = []): """Returns an aspect that runs the proto compiler. The aspect propagates through the deps of proto_library targets, running @@ -278,7 +270,7 @@ def proto_compiler_aspect(extensions, protoc_plugin, plugin_options = [], additi executable = True, cfg = "exec", ), - } | additional_attrs, + }, implementation = _proto_compiler_aspect_impl, provides = [PwProtoInfo], toolchains = ["@rules_python//python:exec_tools_toolchain_type"],