build.rs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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");
  9. // for entry in ["common", "form", "interpreter"].iter() {
  10. // gen_bindings(entry);
  11. // }
  12. }
  13. // okay...... so tsc might fail if the user doesn't have it installed
  14. // we don't really want to fail if that's the case
  15. // but if you started *editing* the .ts files, you're gonna have a bad time
  16. // so.....
  17. // we need to hash each of the .ts files and add that hash to the JS files
  18. // if the hashes don't match, we need to fail the build
  19. // that way we also don't need
  20. fn gen_bindings(name: &str) {
  21. let contents = read_to_string(&format!("src/{name}.ts")).unwrap();
  22. let generated = read_to_string(&format!("src/gen/{name}.js")).unwrap_or_default();
  23. let hashed = hash_file(&contents);
  24. // If the file is generated, and the hash is the same, we're good, don't do anything
  25. if generated
  26. .lines()
  27. .next()
  28. .unwrap_or_default()
  29. .starts_with(&format!("// DO NOT EDIT THIS FILE. HASH: {}", hashed))
  30. {
  31. return;
  32. }
  33. // If the file is generated, and the hash is different, we need to generate it
  34. let status = Command::new("tsc")
  35. .arg(format!("src/{name}.ts"))
  36. .arg("--outDir")
  37. .arg("gen")
  38. .arg("--target")
  39. .arg("es6")
  40. .status()
  41. .unwrap();
  42. if !status.success() {
  43. panic!(
  44. "Failed to generate bindings for {}. Make sure you have tsc installed",
  45. name
  46. );
  47. }
  48. // The file should exist, and now we need write the TS hash to the file
  49. let generated = read_to_string(&format!("gen/{name}.js")).unwrap();
  50. let generated = format!("// DO NOT EDIT THIS FILE. HASH: {}\n{}", hashed, generated);
  51. std::fs::write(&format!("src/gen/{name}.js"), generated).unwrap();
  52. }
  53. fn hash_file(obj: &str) -> u64 {
  54. let mut hasher = DefaultHasher::new();
  55. obj.hash(&mut hasher);
  56. hasher.finish()
  57. }