在 Bazel 中将 protobuf 文件作为依赖项添加到 py_proto_library

Add protobuf file as dependency to py_proto_library in Bazel

我想将 a.proto 导入 b.proto 并使用 Bazel 进行编译。

构建:

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";

当我使用 Bazel 运行 时,我得到 does not have mandatory providers: 'py'. 错误,即使根据示例 here 它应该如何工作。

我尝试使用文件组将 a.proto 添加为依赖项,但同样的错误,因为显然 deps 需要 python 个文件。 py_proto_library 的运作方式是否与 java_proto_library 不同?如果是这样,我如何添加 a.proto 作为依赖项以便正确导入它?

编辑: 我正在从 https://github.com/pubref/rules_protobuf/archive/v0.8.1.tar.gz

加载 protobuf

此规则接受 .proto 个文件,如果您将它们作为 proto_deps 传递,但我收到错误 Import "a.proto" was not found or had errors.

也许我应该以某种方式指定 imports

上游 protobuf 提供的 py_proto_library 宏与 Bazel 博客 post 中描述的规则不同。 py_proto_library 规则的 deps 只能包含其他 py_proto_library 规则。 .proto 自己的文件必须放在 srcs.

终于明白了。我的困惑来自于不同的 protobuf 库具有不同的定义:

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

我用的是第一个,那个把 .proto 依赖作为 proto_deps。我错过的另一件事是导入语句路径必须相对于 WORKSPACE 文件。

b.proto:

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

构建:

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

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

工作空间:

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()