build.rs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. fn generate_tests() {
  2. use std::env;
  3. use std::ffi::OsStr;
  4. use std::fs::{self, File};
  5. use std::io::Write;
  6. use std::path::{Path, PathBuf};
  7. let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
  8. let mut dst = File::create(Path::new(&out_dir).join("tests.rs")).unwrap();
  9. let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
  10. let tests_dir = manifest_dir.join("tests").join("rust");
  11. let tests = fs::read_dir(&tests_dir).unwrap();
  12. let entries = tests.map(|t| t.expect("Couldn't read test file"));
  13. println!("cargo:rerun-if-changed={}", tests_dir.display());
  14. // Try to make a decent guess at where our binary will end up in.
  15. //
  16. // TODO(emilio): Ideally running tests will just use the library-version of
  17. // cbindgen instead of the built binary.
  18. let cbindgen_path = out_dir
  19. .parent()
  20. .unwrap()
  21. .parent()
  22. .unwrap()
  23. .parent()
  24. .unwrap()
  25. .join("cbindgen");
  26. for entry in entries {
  27. let path_segment = if entry.file_type().unwrap().is_file() {
  28. match entry.path().extension().and_then(OsStr::to_str) {
  29. Some("rs") => {}
  30. _ => continue,
  31. };
  32. entry
  33. .path()
  34. .file_stem()
  35. .unwrap()
  36. .to_str()
  37. .unwrap()
  38. .to_owned()
  39. } else {
  40. entry.file_name().to_str().unwrap().to_owned()
  41. };
  42. let identifier = path_segment
  43. .replace(|c| !char::is_alphanumeric(c), "_")
  44. .replace("__", "_");
  45. writeln!(
  46. dst,
  47. "test_file!({:?}, test_{}, {:?}, {:?});",
  48. cbindgen_path,
  49. identifier,
  50. path_segment,
  51. entry.path(),
  52. )
  53. .unwrap();
  54. }
  55. dst.flush().unwrap();
  56. }
  57. fn main() {
  58. generate_tests();
  59. }