build.rs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. let expected = include_str!("src/js/hash.txt").trim();
  9. if expected == hash.to_string() {
  10. return;
  11. }
  12. panic!("Hashes match, no need to update bindings. {expected} != {hash}",);
  13. // Otherwise, generate the bindings and write the new hash to disk
  14. // Generate the bindings for both native and web
  15. gen_bindings("common", "common");
  16. gen_bindings("native", "native");
  17. gen_bindings("core", "core");
  18. std::fs::write("src/js/hash.txt", hash.to_string()).unwrap();
  19. }
  20. /// Hashes the contents of a directory
  21. fn hash_ts_files() -> u128 {
  22. let mut out = 0;
  23. let files = [
  24. include_str!("src/ts/common.ts"),
  25. include_str!("src/ts/native.ts"),
  26. include_str!("src/ts/core.ts"),
  27. ];
  28. // Let's make the dumbest hasher by summing the bytes of the files
  29. // The location is multiplied by the byte value to make sure that the order of the bytes matters
  30. let mut idx = 0;
  31. for file in files {
  32. // windows + git does a weird thing with line endings, so we need to normalize them
  33. for line in file.lines() {
  34. idx += 1;
  35. for byte in line.bytes() {
  36. idx += 1;
  37. out += (byte as u128) * (idx as u128);
  38. }
  39. }
  40. }
  41. out
  42. }
  43. // okay...... so tsc might fail if the user doesn't have it installed
  44. // we don't really want to fail if that's the case
  45. // but if you started *editing* the .ts files, you're gonna have a bad time
  46. // so.....
  47. // we need to hash each of the .ts files and add that hash to the JS files
  48. // if the hashes don't match, we need to fail the build
  49. // that way we also don't need
  50. fn gen_bindings(input_name: &str, output_name: &str) {
  51. // If the file is generated, and the hash is different, we need to generate it
  52. let status = Command::new("bun")
  53. .arg("build")
  54. .arg(format!("src/ts/{input_name}.ts"))
  55. .arg("--outfile")
  56. .arg(format!("src/js/{output_name}.js"))
  57. .arg("--minify-whitespace")
  58. .arg("--minify-syntax")
  59. .status()
  60. .unwrap();
  61. if !status.success() {
  62. panic!(
  63. "Failed to generate bindings for {}. Make sure you have tsc installed",
  64. input_name
  65. );
  66. }
  67. }