build.rs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. use std::process::Command;
  2. fn main() {
  3. // If any TS changes, re-run the build script
  4. println!("cargo:rerun-if-changed=src/ts/*.ts");
  5. // Compute the hash of the ts files
  6. let hash = hash_ts_files();
  7. // If the hash matches the one on disk, we're good and don't need to update bindings
  8. if include_str!("src/js/hash.txt").trim() == hash.to_string() {
  9. return;
  10. }
  11. // Otherwise, generate the bindings and write the new hash to disk
  12. // Generate the bindings for both native and web
  13. gen_bindings("common", "common");
  14. gen_bindings("native", "native");
  15. gen_bindings("core", "core");
  16. std::fs::write("src/js/hash.txt", hash.to_string()).unwrap();
  17. }
  18. /// Hashes the contents of a directory
  19. fn hash_ts_files() -> u128 {
  20. let mut out = 0;
  21. let files = [
  22. include_str!("src/ts/common.ts"),
  23. include_str!("src/ts/native.ts"),
  24. include_str!("src/ts/core.ts"),
  25. ];
  26. // Let's make the dumbest hasher by summing the bytes of the files
  27. // The location is multiplied by the byte value to make sure that the order of the bytes matters
  28. let mut idx = 0;
  29. for file in files {
  30. for byte in file.bytes() {
  31. idx += 1;
  32. out += (byte as u128) * (idx as u128);
  33. }
  34. }
  35. out
  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-whitespace")
  52. .arg("--minify-syntax")
  53. .status()
  54. .unwrap();
  55. if !status.success() {
  56. panic!(
  57. "Failed to generate bindings for {}. Make sure you have tsc installed",
  58. input_name
  59. );
  60. }
  61. }