1# Copyright 2024 The Pigweed Authors 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); you may not 4# use this file except in compliance with the License. You may obtain a copy of 5# the License at 6# 7# https://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, WITHOUT 11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12# License for the specific language governing permissions and limitations under 13# the License. 14"""Rule for generating C++ proto libraries using nanopb.""" 15 16load("@bazel_tools//tools/cpp:toolchain_utils.bzl", "use_cpp_toolchain") 17load("@com_google_protobuf//bazel/common:proto_info.bzl", "ProtoInfo") 18load("@rules_cc//cc/common:cc_info.bzl", "CcInfo") 19load("//pw_protobuf_compiler/private:proto.bzl", "compile_proto", "proto_compiler_aspect") 20 21def nanopb_proto_library(*, name, deps, **kwargs): 22 """A C++ proto library generated using nanopb. 23 24 Attributes: 25 deps: proto_library targets for which to generate this library. 26 """ 27 28 _nanopb_proto_library( 29 name = name, 30 protos = deps, 31 deps = [ 32 Label("@com_github_nanopb_nanopb//:nanopb"), 33 ], 34 **kwargs 35 ) 36 37def _custom_opt_for_library_include_format(): 38 """Return correctly set --library-include-format. 39 40 When using nanopb_proto_library from a monorepo in which nanopb is not an 41 external repository but just a build target within the main tree, the 42 #include statements need to be relative to the root of that tree. Handle 43 this case using --library-include-format. 44 """ 45 pb_h = Label("@com_github_nanopb_nanopb//:pb.h") 46 if pb_h.workspace_root == "": 47 # Monorepo case 48 return "--library-include-format=#include \"{}/%s\"".format(pb_h.package) 49 else: 50 return "--library-include-format=#include \"%s\"" 51 52_nanopb_proto_compiler_aspect = proto_compiler_aspect( 53 ["pb.h", "pb.c"], 54 Label("@com_github_nanopb_nanopb//:protoc-gen-nanopb"), 55 [_custom_opt_for_library_include_format()], 56) 57 58_nanopb_proto_library = rule( 59 implementation = compile_proto, 60 attrs = { 61 "deps": attr.label_list( 62 providers = [CcInfo], 63 ), 64 "protos": attr.label_list( 65 providers = [ProtoInfo], 66 aspects = [_nanopb_proto_compiler_aspect], 67 ), 68 }, 69 fragments = ["cpp"], 70 toolchains = use_cpp_toolchain(), 71) 72