1use std::{io::Write, path::Path};
2use wasmtime::{Config, Engine};
3
4fn main() {
5 let base = Path::new("../../plugins");
6
7 // println!("cargo:rerun-if-changed=../../plugins/*");
8 println!("cargo:warning=Precompiling plugins...");
9
10 let _ = std::fs::remove_dir_all(base.join("bin"));
11 let _ =
12 std::fs::create_dir_all(base.join("bin")).expect("Could not make plugins bin directory");
13
14 let build_successful = std::process::Command::new("cargo")
15 .args([
16 "build",
17 "--release",
18 "--target",
19 "wasm32-wasi",
20 "--manifest-path",
21 base.join("Cargo.toml").to_str().unwrap(),
22 ])
23 .status()
24 .expect("Could not build plugins")
25 .success();
26 assert!(build_successful);
27
28 let binaries = std::fs::read_dir(base.join("target/wasm32-wasi/release"))
29 .expect("Could not find compiled plugins in target");
30
31 let engine = create_engine();
32
33 for file in binaries {
34 let is_wasm = || {
35 let path = file.ok()?.path();
36 if path.extension()? == "wasm" {
37 Some(path)
38 } else {
39 None
40 }
41 };
42
43 if let Some(path) = is_wasm() {
44 let out_path = base.join("bin").join(path.file_name().unwrap());
45 std::fs::copy(&path, &out_path).expect("Could not copy compiled plugin to bin");
46 precompile(&out_path, &engine);
47 }
48 }
49}
50
51fn create_engine() -> Engine {
52 let mut config = Config::default();
53 config.async_support(true);
54 // config.epoch_interruption(true);
55 Engine::new(&config).expect("Could not create engine")
56}
57
58fn precompile(path: &Path, engine: &Engine) {
59 let bytes = std::fs::read(path).expect("Could not read wasm module");
60 let compiled = engine
61 .precompile_module(&bytes)
62 .expect("Could not precompile module");
63 let out_path = path.parent().unwrap().join(&format!(
64 "{}.pre",
65 path.file_name().unwrap().to_string_lossy()
66 ));
67 let mut out_file = std::fs::File::create(out_path)
68 .expect("Could not create output file for precompiled module");
69 out_file.write_all(&compiled).unwrap();
70}