build.rs 2.2 KB

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