rules_proto

Bazel Gazelle Protobuf gRPC

stackb/rules_proto contains code and examples for using protobuf in your Bazel repository.

@build_stack_rules_proto//language/protobuf implements a gazelle “Language” that parses your *.proto files and generates BUILD rules. You can integrate this language into your own repository via the gazelle_binary rule.

The protobuf gazelle language is configured using gazelle “directives”. Here’s an example configuration that enables a “proto_language” that combines the “python” plugin (the one that’s built-in to protoc), grpc, and dropbox/mypy-protobuf:

# -- The "proto_rule" directive instantiates a rule configuration --
# gazelle:proto_rule proto_compile implementation stackb:rules_proto:proto_compile

# -- The "proto_plugin" directive instantiates a plugin configuration --
# gazelle:proto_plugin python implementation builtin:python
# gazelle:proto_plugin grpc-python implementation grpc:grpc:grpc_python_plugin
# gazelle:proto_plugin mypy implementation dropbox:mypy-protobuf:protoc-gen-mypy

# -- The "proto_language" directive binds the rule(s) and plugin(s) together --
# gazelle:proto_language python rule proto_compile
# gazelle:proto_language python plugin python
# gazelle:proto_language python plugin grpc-python
# gazelle:proto_language python plugin mypy
# gazelle:proto_language python enabled true

With this configuration, any subdirectory that contains *.proto files will be scanned by gazelle and corresponding proto build rules produced.

Here’s what you might expect to be generated with the above configuration (NOTE: This extension delegates to @bazel_gazelle//language/proto to produce the proto_library rule). :

proto_library(
    name = "example_proto",
    srcs = ["example.proto"],
    visibility = ["//visibility:public"],
)

proto_compile(
    name = "example_python_compile",
    outputs = [
        "example_pb2_grpc.py",
        "example_pb2.py",
        "example_pb2.pyi",
    ],
    plugins = [
        "@build_stack_rules_proto//plugin/builtin:python",
        "@build_stack_rules_proto//plugin/grpc/grpc:grpc_python_plugin",
        "@build_stack_rules_proto//plugin/dropbox/mypy-protobuf:protoc-gen-grpc-mypy",
    ],
    proto = "example_proto",
)

The generated outputs could then be consumed as follows:

py_library(
    srcs = [
        "example_pb2_grpc.py",
        "example_pb2.py",
    ],
    deps = [
        requirement("protobuf"),
        requirement("grpcio"),
    ],
)

Please refer to the following guides to get started:

For reference, the [examples/golden/testdata] directory contains a number of tested example configurations.


Copyright © 2021 Stack.Build.