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