build.rs 2.6 KB

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