This repository demonstrates how to generate Rust code from Protocol Buffer definitions using Bazel with the rules_rust and protobuf integration.
This project showcases:
- Setting up Bazel with Protocol Buffers and Rust
- Generating Rust code from
.protofiles - Handling dependencies between proto files
- Using Google's well-known types (like
google.protobuf.Timestamp) - Applying patches to resolve compatibility issues
.
├── MODULE.bazel # Bazel module configuration
├── BUILD # Root build file
├── proto/
│ ├── BUILD.bazel # Proto build rules for foo.proto
│ ├── foo.proto # Main proto definition
│ └── bar/
│ ├── BUILD.bazel # Proto build rules for bar.proto
│ └── bar.proto # Dependency proto definition
└── third_party/patches/
├── BUILD # Build file for patches
└── protobuf_rules_rust.patch # Compatibility patch for protobuf + rules_rust
- Uses Protocol Buffers edition 2023
- Defines a
Foomessage with various field types including:- Basic types (
int32,string) - Repeated fields (
repeated int32) - Message references (references
Barfrombar.proto) - Google well-known types (
google.protobuf.Timestamp)
- Basic types (
- Includes an enum
ProductAttribute
- Simple message definition that
foo.protodepends on - Demonstrates cross-package proto dependencies
- protobuf: Version 32.1 with custom patches
- rules_rust: Version 0.65.0
- Patched Protobuf Integration: Uses a patch file to resolve compatibility issues between
protobufandrules_rust - Rust Proto Libraries: Generates
rust_proto_librarytargets fromproto_librarydefinitions - Cross-package Dependencies: Shows how proto files in different directories can reference each other
The protobuf_rules_rust.patch addresses several compatibility issues:
- Updates
rules_rustversion from 0.56.0 to 0.65.0 - Configures Rust toolchain with edition 2021 and Rust version 1.79.0
- Fixes package visibility and label resolution issues
- Corrects kernel selection logic for UPB vs CPP backends
//proto:foo_proto- Protocol buffer library for foo.proto//proto/bar:bar_proto- Protocol buffer library for bar.proto
//proto:foo_rust_proto- Generated Rust code for foo.proto//proto/bar:bar_rust_proto- Generated Rust code for bar.proto
To build all targets:
bazel build //...To build specific Rust proto libraries:
bazel build //proto:foo_rust_proto
bazel build //proto/bar:bar_rust_protoThe project demonstrates proper dependency management:
foo.protoimports and usesbar.proto- Both proto files use Google's well-known types
- Bazel build files properly declare dependencies using
depsattribute
This setup has been tested with:
- Bazel (latest)
- Protocol Buffers 32.1
- rules_rust 0.65.0
- Rust 1.79.0
The patch file ensures compatibility between these specific versions and may need updates for different version combinations.
When built, Bazel will generate Rust code in the bazel-bin directory structure, providing Rust structs and implementations for all defined Protocol Buffer messages and enums.