build.rs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. use std::{
  2. collections::hash_map::DefaultHasher, fs::read_to_string, hash::Hasher, process::Command,
  3. };
  4. fn main() {
  5. // If any TS changes, re-run the build script
  6. println!("cargo:rerun-if-changed=src/ts/*.ts");
  7. // Compute the hash of the ts files
  8. let hash = hash_dir("./src/ts");
  9. // If the hash matches the one on disk, we're good and don't need to update bindings
  10. if let Ok(contents) = read_to_string("./src/js/hash.txt") {
  11. if contents.trim() == hash.to_string() {
  12. return;
  13. }
  14. }
  15. // Otherwise, generate the bindings and write the new hash to disk
  16. // Generate the bindings for both native and web
  17. gen_bindings("common", "common");
  18. gen_bindings("native", "native");
  19. gen_bindings("core", "core");
  20. std::fs::write("src/js/hash.txt", hash.to_string()).unwrap();
  21. }
  22. /// Hashes the contents of a directory
  23. fn hash_dir(dir: &str) -> u128 {
  24. let mut out = 0;
  25. for entry in std::fs::read_dir(dir).unwrap() {
  26. let entry = entry.unwrap();
  27. let path = entry.path();
  28. let Some(ext) = path.extension() else {
  29. continue;
  30. };
  31. if ext != "ts" {
  32. continue;
  33. }
  34. // Hash the contents of the file and then add it to the overall hash
  35. // This makes us order invariant
  36. let mut hasher = DefaultHasher::new();
  37. hasher.write(&std::fs::read(&path).unwrap());
  38. out += hasher.finish() as u128;
  39. }
  40. out
  41. }
  42. // okay...... so tsc might fail if the user doesn't have it installed
  43. // we don't really want to fail if that's the case
  44. // but if you started *editing* the .ts files, you're gonna have a bad time
  45. // so.....
  46. // we need to hash each of the .ts files and add that hash to the JS files
  47. // if the hashes don't match, we need to fail the build
  48. // that way we also don't need
  49. fn gen_bindings(input_name: &str, output_name: &str) {
  50. // If the file is generated, and the hash is different, we need to generate it
  51. let status = Command::new("bun")
  52. .arg("build")
  53. .arg(format!("src/ts/{input_name}.ts"))
  54. .arg("--outfile")
  55. .arg(format!("src/js/{output_name}.js"))
  56. .arg("--minify-whitespace")
  57. .arg("--minify-syntax")
  58. .status()
  59. .unwrap();
  60. if !status.success() {
  61. panic!(
  62. "Failed to generate bindings for {}. Make sure you have tsc installed",
  63. input_name
  64. );
  65. }
  66. }