15 unstable releases (5 breaking)
| 0.8.0 | Feb 3, 2025 |
|---|---|
| 0.6.1 | Jan 2, 2025 |
| 0.6.0 | Dec 26, 2024 |
| 0.5.0 | Aug 1, 2024 |
| 0.1.4 | Apr 3, 2024 |
#2592 in Encoding
1,001 downloads per month
61KB
1K
SLoC
femtopb-build
A code generator/protobuf compiler for the femtopb library. Uses protox and prost-build
under the hood, but for now only a limited subset of their full APIs are exposed.
Usage
This library is meant to be used in your build.rs script to generate Rust code at build time.
First, add both femtopb and femtopb-build to your dependencies like this:
[dependencies]
[build-dependencies]
An example of a valid build.rs file is:
fn main() -> anyhow::Result<()> {
femtopb_build::compile_protos(
&["src/myapi/v1/myapi.proto", "src/myapi/v1/foo.proto"],
&["src"],
)
}
The first argument to compile_protos lists which proto schema files to compile,
and the second argument lists include dirs, where imports from one proto file to another
will get resolved.
You may then include the parts of the schema that you want to use in your application. The file
name of the generated file will be based on the protobuf package declaration (and for sanity
should probably match your directory structure, too).
pub mod myapi {
pub mod v1 {
include!(concat!(env!("OUT_DIR"), "/myapi.v1.rs"));
}
}
use myapi::v1::Foo;
// ...
To view the generated code, the easiest way is probably to just run cargo doc.
Checking in generated code
If you don't want to generate the code during the build, another common approach is to generate
the code once and check in the generated code in source control. A common, but hacky, way is to
add an example to your crate that generates the code.
For example, create a file called examples/mycrate-generate-schema.rs containing:
fn main() -> anyhow::Result<()> {
femtopb_build::compile_protos_into(
&["src/myapi/v1/myapi.proto", "src/myapi/v1/foo.proto"],
&["src"],
"src",
)
}
Here, we use the compile_protos_into function that lets you specify a custom output directory,
and we use the src dir of the crate to have the schemas live next to the rest of the
application code (you may of course decide to structure things differently).
Dependencies
~13–19MB
~337K SLoC