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