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={}", base.display());
8 println!("cargo:warning=Rebuilding precompiled 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_default_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
51/// Creates a default engine for compiling Wasm.
52/// N.B.: this must create the same `Engine` as
53/// the `create_default_engine` function
54/// in `plugin_runtime/src/plugin.rs`.
55fn create_default_engine() -> Engine {
56 let mut config = Config::default();
57 config.async_support(true);
58 // config.epoch_interruption(true);
59 Engine::new(&config).expect("Could not create engine")
60}
61
62fn precompile(path: &Path, engine: &Engine) {
63 let bytes = std::fs::read(path).expect("Could not read wasm module");
64 let compiled = engine
65 .precompile_module(&bytes)
66 .expect("Could not precompile module");
67 let out_path = path.parent().unwrap().join(&format!(
68 "{}.pre",
69 path.file_name().unwrap().to_string_lossy()
70 ));
71 let mut out_file = std::fs::File::create(out_path)
72 .expect("Could not create output file for precompiled module");
73 out_file.write_all(&compiled).unwrap();
74}