//! Compiles the `.proto` files into one descriptor set the crate reads at run time, and into Rust //! structs (prost) that read the handlers' JSON straight into protobuf (#470). protox is a //! compiler in Rust, so building needs no `protoc` on the host or in the image. use prost::Message as _; use std::fmt::Write as _; fn main() { let files = ["proto/ipx.proto", "proto/directory.proto", "proto/play.proto"]; for f in files { println!("cargo:rerun-if-changed={f}"); } let set = protox::compile(files, ["proto"]).unwrap_or_else(|e| panic!("{e:?}")); let out = std::path::PathBuf::from(std::env::var("OUT_DIR").expect("cargo sets OUT_DIR")); std::fs::write(out.join("wire.bin"), set.encode_to_vec()).expect("writing the descriptor set"); // Every message that reads from JSON with serde: all but the bodies holding Google's Value or // ListValue, whose JSON serde cannot read; those go the slow way, through prost-reflect. let mut config = prost_build::Config::new(); let mut fast = String::from( "/// An answer's JSON as message `name` in protobuf, when `name` has a struct here.\n\ pub fn json_to_proto(name: &str, json: &[u8]) -> Option, String>> {\n match name {\n", ); for file in set.file.iter().filter(|f| f.package() != "google.protobuf") { for m in &file.message_type { if m.field.iter().any(|f| f.type_name().starts_with(".google.")) { continue; } let path = format!(".{}.{}", file.package(), m.name()); // A list message is the JSON array itself. let list = matches!(&m.field[..], [only] if only.name() == "items" && only.label() == prost_types::field_descriptor_proto::Label::Repeated); let attrs = if list { "#[derive(serde::Deserialize)] #[serde(transparent)]" } else { // Debug builds refuse a field the message lacks, as the slow way does. "#[derive(serde::Deserialize)] #[serde(default)] #[cfg_attr(debug_assertions, serde(deny_unknown_fields))]" }; config.type_attribute(&path, attrs); writeln!(fast, " {:?} => Some(encode::(json)),", &path[1..], file.package(), m.name()) .expect("writing to a String"); } } fast.push_str(" _ => None,\n }\n}\n"); std::fs::write(out.join("fast.rs"), fast).expect("writing fast.rs"); config.out_dir(&out).compile_fds(set).unwrap_or_else(|e| panic!("{e:?}")); }