Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update example crate to import a .proto file from the well-known types #20456

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions rust/release_crates/protobuf_codegen/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,28 @@
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};

#[derive(Debug, Clone)]
pub struct Dependency {
pub crate_name: String,
pub import_paths: Vec<PathBuf>,
pub include_paths: Vec<PathBuf>,
pub proto_files: Vec<String>,
}

#[derive(Debug)]
pub struct CodeGen {
inputs: Vec<PathBuf>,
output_dir: PathBuf,
includes: Vec<PathBuf>,
dependencies: Vec<Dependency>,
}

#[macro_export]
macro_rules! proto_dep {
($c:ident) => {
$c::get_dependency(stringify!($c))
}
}

const VERSION: &str = env!("CARGO_PKG_VERSION");
Expand Down Expand Up @@ -62,6 +80,7 @@ impl CodeGen {
inputs: Vec::new(),
output_dir: PathBuf::from(std::env::var("OUT_DIR").unwrap()).join("protobuf_generated"),
includes: Vec::new(),
dependencies: Vec::new(),
}
}

Expand Down Expand Up @@ -90,6 +109,11 @@ impl CodeGen {
self
}

pub fn dependency(&mut self, dep: Dependency) -> &mut Self {
self.dependencies.push(dep.clone());
self
}

fn expected_generated_rs_files(&self) -> Vec<PathBuf> {
self.inputs
.iter()
Expand Down Expand Up @@ -147,13 +171,36 @@ impl CodeGen {
for include in &self.includes {
println!("cargo:rerun-if-changed={}", include.display());
}
for dep in &self.dependencies {
for path in &dep.import_paths {
println!("cargo:rerun-if-changed={}", path.display());
}
}

let crate_mapping_path = self.output_dir.join("crate_mapping.txt");
{
let mut file = File::create(crate_mapping_path.clone()).unwrap();
for dep in &self.dependencies {
file.write_all(format!("{}\n", dep.crate_name).as_bytes()).expect("");
file.write_all(format!("{}\n", dep.proto_files.len()).as_bytes()).expect("");
for f in &dep.proto_files {
file.write_all(format!("{}\n", f).as_bytes()).expect("");
}
}
}

cmd.arg(format!("--rust_out={}", self.output_dir.display()))
.arg("--rust_opt=experimental-codegen=enabled,kernel=upb")
.arg(format!("--upb_minitable_out={}", self.output_dir.display()));
for include in &self.includes {
cmd.arg(format!("--proto_path={}", include.display()));
}
for dep in &self.dependencies {
for path in &dep.import_paths {
cmd.arg(format!("--proto_path={}", path.display()));
}
}
cmd.arg(format!("--rust_opt=crate_mapping={}", crate_mapping_path.display()));
let output = cmd.output().map_err(|e| format!("failed to run protoc: {}", e))?;
println!("{}", std::str::from_utf8(&output.stdout).unwrap());
eprintln!("{}", std::str::from_utf8(&output.stderr).unwrap());
Expand All @@ -172,6 +219,12 @@ impl CodeGen {
.include(self.output_dir.clone())
.flag("-std=c99");

for dep in &self.dependencies {
for path in &dep.include_paths {
cc_build.include(path);
}
}

for path in &self.expected_generated_rs_files() {
if !path.exists() {
return Err(format!("expected generated file {} does not exist", path.display()));
Expand Down
2 changes: 2 additions & 0 deletions rust/release_crates/protobuf_example/Cargo-template.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ license = "BSD-3-Clause"

[dependencies]
protobuf = { version = "{VERSION}", path = "../protobuf", package = "protobuf" }
protobuf_well_known_types = { version = "{VERSION}", path = "../protobuf_well_known_types", package = "protobuf-well-known-types" }

[build-dependencies]
protobuf-codegen = { version = "{VERSION}", path = "../protobuf_codegen", package = "protobuf-codegen" }
protobuf_well_known_types = { version = "{VERSION}", path = "../protobuf_well_known_types", package = "protobuf-well-known-types" }
2 changes: 2 additions & 0 deletions rust/release_crates/protobuf_example/build.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use protobuf_codegen::CodeGen;
use protobuf_codegen::proto_dep;

fn main() {
CodeGen::new()
.inputs(["proto_example/foo.proto", "proto_example/bar/bar.proto"])
.include("proto")
.dependency(proto_dep!(protobuf_well_known_types))
.generate_and_compile()
.unwrap();
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ edition = "2023";

package proto_example;

import "google/protobuf/timestamp.proto";
import "proto_example/bar/bar.proto";

message Foo {
int32 int = 1;
repeated int32 numbers = 2;
string name = 3;
Bar bar = 4;
google.protobuf.Timestamp timestamp = 5;
}
8 changes: 8 additions & 0 deletions rust/release_crates/protobuf_example/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,12 @@ mod tests {
let nums: Vec<_> = foo.bar().numbers().iter().collect();
assert_eq!(nums, vec![1, 2, 3]);
}

#[test]
fn set_well_known_type() {
let foo = proto!(Foo { timestamp: __ { seconds: 99, nanos: 13 } });

assert_eq!(foo.timestamp().seconds(), 99);
assert_eq!(foo.timestamp().nanos(), 13);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ license = "BSD-3-Clause"

[dependencies]
protobuf = { version = "{VERSION}", path = "../protobuf", package = "protobuf" }
protobuf-codegen = { version = "{VERSION}", path = "../protobuf_codegen", package = "protobuf-codegen" }

[build-dependencies]
protobuf-codegen = { version = "{VERSION}", path = "../protobuf_codegen", package = "protobuf-codegen" }
22 changes: 22 additions & 0 deletions rust/release_crates/protobuf_well_known_types/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1 +1,23 @@
use std::path::Path;

include!(concat!(env!("OUT_DIR"), "/protobuf_generated/google/protobuf/generated.rs"));

pub fn get_dependency(crate_name: &str) -> protobuf_codegen::Dependency {
protobuf_codegen::Dependency {
crate_name: crate_name.to_string(),
import_paths: vec!(Path::new(env!("CARGO_MANIFEST_DIR")).join("proto")),
include_paths: vec!(Path::new(env!("OUT_DIR")).join("protobuf_generated")),
proto_files: vec!(
"google/protobuf/any.proto".to_string(),
"google/protobuf/api.proto".to_string(),
"google/protobuf/duration.proto".to_string(),
"google/protobuf/empty.proto".to_string(),
"google/protobuf/field_mask.proto".to_string(),
"google/protobuf/source_context.proto".to_string(),
"google/protobuf/struct.proto".to_string(),
"google/protobuf/timestamp.proto".to_string(),
"google/protobuf/type.proto".to_string(),
"google/protobuf/wrappers.proto".to_string(),
),
}
}
Loading