build.rs

 1use std::{io::Write, path::Path};
 2use wasmtime::{Config, Engine};
 3
 4fn main() {
 5    let base = Path::new("../../plugins");
 6
 7    // Find all files and folders that don't change when rebuilt
 8    let crates = std::fs::read_dir(base).expect("Could not find plugin directory");
 9    for dir in crates {
10        let path = dir.unwrap().path();
11        let name = path.file_name().and_then(|x| x.to_str());
12        let is_dir = path.is_dir();
13        if is_dir && name != Some("target") && name != Some("bin") {
14            println!("cargo:rerun-if-changed={}", path.display());
15        }
16    }
17
18    // Clear out and recreate the plugin bin directory
19    let _ = std::fs::remove_dir_all(base.join("bin"));
20    let _ =
21        std::fs::create_dir_all(base.join("bin")).expect("Could not make plugins bin directory");
22
23    // Compile the plugins using the same profile as the current Zed build
24    let (profile_flags, profile_target) = match std::env::var("PROFILE").unwrap().as_str() {
25        "debug" => (&[][..], "debug"),
26        "release" => (&["--release"][..], "release"),
27        unknown => panic!("unknown profile `{}`", unknown),
28    };
29    // Invoke cargo to build the plugins
30    let build_successful = std::process::Command::new("cargo")
31        .args([
32            "build",
33            "--target",
34            "wasm32-wasi",
35            "--manifest-path",
36            base.join("Cargo.toml").to_str().unwrap(),
37        ])
38        .args(profile_flags)
39        .status()
40        .expect("Could not build plugins")
41        .success();
42    assert!(build_successful);
43
44    // Get the target architecture for pre-cross-compilation of plugins
45    // and create and engine with the appropriate config
46    let target_triple = std::env::var("TARGET").unwrap().to_string();
47    println!("cargo:rerun-if-env-changed=TARGET");
48    let engine = create_default_engine(&target_triple);
49
50    // Find all compiled binaries
51    let binaries = std::fs::read_dir(base.join("target/wasm32-wasi").join(profile_target))
52        .expect("Could not find compiled plugins in target");
53
54    // Copy and precompile all compiled plugins we can find
55    for file in binaries {
56        let is_wasm = || {
57            let path = file.ok()?.path();
58            if path.extension()? == "wasm" {
59                Some(path)
60            } else {
61                None
62            }
63        };
64
65        if let Some(path) = is_wasm() {
66            let out_path = base.join("bin").join(path.file_name().unwrap());
67            std::fs::copy(&path, &out_path).expect("Could not copy compiled plugin to bin");
68            precompile(&out_path, &engine);
69        }
70    }
71}
72
73/// Creates an engine with the default configuration.
74/// N.B. This must create an engine with the same config as the one
75/// in `plugin_runtime/src/plugin.rs`.
76fn create_default_engine(target_triple: &str) -> Engine {
77    let mut config = Config::default();
78    config
79        .target(target_triple)
80        .expect(&format!("Could not set target to `{}`", target_triple));
81    config.async_support(true);
82    config.consume_fuel(true);
83    Engine::new(&config).expect("Could not create precompilation engine")
84}
85
86fn precompile(path: &Path, engine: &Engine) {
87    let bytes = std::fs::read(path).expect("Could not read wasm module");
88    let compiled = engine
89        .precompile_module(&bytes)
90        .expect("Could not precompile module");
91    let out_path = path.parent().unwrap().join(&format!(
92        "{}.pre",
93        path.file_name().unwrap().to_string_lossy(),
94    ));
95    let mut out_file = std::fs::File::create(out_path)
96        .expect("Could not create output file for precompiled module");
97    out_file.write_all(&compiled).unwrap();
98}