Search code examples
pythonprotocol-buffersbazel

Add protobuf file as dependency to py_proto_library in Bazel


I would like to import a.proto into b.proto and compile with Bazel.

BUILD:

py_proto_library(
    name = "b_py_proto",
    protos = ["b.proto"],
    deps = [
        ":a_proto"
    ]
)

py_proto_library(
  name = "a_proto",
  protos = ["a.proto"]
)

b.proto

import public "a.proto";

When I run it with Bazel I get does not have mandatory providers: 'py'. error, even though according to the example here that's how it should work.

I tried using filegroup to add a.proto as a dependency, and same error, because apparently deps expects python files. Is py_proto_library operating differently than java_proto_library? If so, how can I add a.proto as dependency so that it gets imported correctly?

EDIT: I am loading protobuf from https://github.com/pubref/rules_protobuf/archive/v0.8.1.tar.gz

This rule accepts .proto files if you pass them as proto_deps, but then I get an error Import "a.proto" was not found or had errors.

Maybe I should specify imports somehow?


Solution

  • Finally figured this out. My confusion came from the fact that there are different protobuf libraries with different definitions:

    1. https://github.com/pubref/rules_protobuf/blob/master/python/rules.bzl
    2. https://github.com/google/protobuf/blob/master/protobuf.bzl

    I was using the first one, and that one takes the .proto dependencies as proto_deps. Another thing I missed is that the import statemnt path has to be relative to the WORKSPACE file.

    b.proto:

    import public "path/relative/to/WORKSPACE/a.proto";
    

    BUILD:

    py_proto_library(
        name = "b_py_proto",
        protos = ["b.proto"],
        proto_deps = [
            ":a_proto"
        ]
    )
    
    py_proto_library(
      name = "a_proto",
      protos = ["a.proto"]
    )
    

    WORKSPACE:

    http_archive(
        name = "org_pubref_rules_protobuf",
        strip_prefix = "rules_protobuf-0.8.1",
        urls = ["https://github.com/pubref/rules_protobuf/archive/v0.8.1.tar.gz"],
        sha256 = "fb9852446b5ba688cd7178a60ff451623e4112d015c6adfe0e9a06c5d2dedc08"
    )
    
    load("@org_pubref_rules_protobuf//python:rules.bzl", "py_proto_repositories")
    py_proto_repositories()