build.rs

 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=Rebuilding 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    println!("cargo:warning={:?}", binaries);
31
32    let engine = create_engine();
33
34    for file in binaries {
35        let is_wasm = || {
36            let path = file.ok()?.path();
37            if path.extension()? == "wasm" {
38                Some(path)
39            } else {
40                None
41            }
42        };
43
44        if let Some(path) = is_wasm() {
45            let out_path = base.join("bin").join(path.file_name().unwrap());
46            std::fs::copy(&path, &out_path).expect("Could not copy compiled plugin to bin");
47            precompile(&out_path, &engine);
48        }
49    }
50}
51
52fn create_engine() -> Engine {
53    let mut config = Config::default();
54    config.async_support(true);
55    // config.epoch_interruption(true);
56    Engine::new(&config).expect("Could not create engine")
57}
58
59fn precompile(path: &Path, engine: &Engine) {
60    let bytes = std::fs::read(path).expect("Could not read wasm module");
61    let compiled = engine
62        .precompile_module(&bytes)
63        .expect("Could not precompile module");
64    let out_path = path.parent().unwrap().join(&format!(
65        "{}.pre",
66        path.file_name().unwrap().to_string_lossy()
67    ));
68    let mut out_file = std::fs::File::create(out_path)
69        .expect("Could not create output file for precompiled module");
70    out_file.write_all(&compiled).unwrap();
71}