build.rs 2.3 KB

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