build.rs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. extern crate protobuf_codegen; // Does the business
  2. extern crate protobuf_codegen_pure; // Helper function
  3. use std::fs::{read_to_string, write};
  4. use std::path::Path;
  5. use protobuf_codegen_pure::parse_and_typecheck;
  6. use protobuf_codegen_pure::Customize;
  7. fn main() {
  8. let customizations = Customize {
  9. ..Default::default()
  10. };
  11. let lib_str = read_to_string("src/lib.rs").unwrap();
  12. // Iterate over the desired module names.
  13. for line in lib_str.lines() {
  14. if !line.starts_with("pub mod ") && !line.starts_with("mod ") {
  15. continue;
  16. }
  17. let len = line.len();
  18. let name;
  19. if line.starts_with("pub mod ") {
  20. name = &line[8..len - 1]; // Remove keywords and semi-colon
  21. } else {
  22. name = &line[4..len - 1]; // Remove keywords and semi-colon
  23. }
  24. // Build the paths to relevant files.
  25. let src = &format!("proto/{}.proto", name);
  26. let dest = &format!("src/{}.rs", name);
  27. // Get the contents of the existing generated file.
  28. let mut existing = "".to_string();
  29. if Path::new(dest).exists() {
  30. // Removing CRLF line endings if present.
  31. existing = read_to_string(dest).unwrap().replace("\r\n", "\n");
  32. }
  33. println!("Regenerating {} from {}", dest, src);
  34. // Parse the proto files as the protobuf-codegen-pure crate does.
  35. let p = parse_and_typecheck(&["proto"], &[src]).expect("protoc");
  36. // But generate them with the protobuf-codegen crate directly.
  37. // Then we can keep the result in-memory.
  38. let result = protobuf_codegen::gen(&p.file_descriptors, &p.relative_paths, &customizations);
  39. // Protoc result as a byte array.
  40. let new = &result.first().unwrap().content;
  41. // Convert to utf8 to compare with existing.
  42. let new = std::str::from_utf8(&new).unwrap();
  43. // Save newly generated file if changed.
  44. if new != existing {
  45. write(dest, &new).unwrap();
  46. }
  47. }
  48. }