build.rs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. }
  22. else {
  23. name = &line[4..len-1]; // Remove keywords and semi-colon
  24. }
  25. // Build the paths to relevant files.
  26. let src = &format!("proto/{}.proto", name);
  27. let dest = &format!("src/{}.rs", name);
  28. // Get the contents of the existing generated file.
  29. let mut existing = "".to_string();
  30. if Path::new(dest).exists() {
  31. // Removing CRLF line endings if present.
  32. existing = read_to_string(dest).unwrap().replace("\r\n", "\n");
  33. }
  34. println!("Regenerating {} from {}", dest, src);
  35. // Parse the proto files as the protobuf-codegen-pure crate does.
  36. let p = parse_and_typecheck(&["proto"], &[src]).expect("protoc");
  37. // But generate them with the protobuf-codegen crate directly.
  38. // Then we can keep the result in-memory.
  39. let result = protobuf_codegen::gen(&p.file_descriptors, &p.relative_paths, &customizations);
  40. // Protoc result as a byte array.
  41. let new = &result.first().unwrap().content;
  42. // Convert to utf8 to compare with existing.
  43. let new = std::str::from_utf8(&new).unwrap();
  44. // Save newly generated file if changed.
  45. if new != existing {
  46. write(dest, &new).unwrap();
  47. }
  48. }
  49. }