|
| 1 | +use anyhow::Result; |
| 2 | +use cargo_metadata::MetadataCommand; |
| 3 | +use heck::*; |
| 4 | +use std::path::{Path, PathBuf}; |
| 5 | +use std::process::Command; |
| 6 | +use std::{env, fs}; |
| 7 | +use wit_component::ComponentEncoder; |
| 8 | + |
| 9 | +fn main() -> Result<()> { |
| 10 | + let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap()); |
| 11 | + |
| 12 | + println!("cargo::rerun-if-changed=../src"); |
| 13 | + |
| 14 | + let status = Command::new("cargo") |
| 15 | + .arg("build") |
| 16 | + .arg("--package=test-programs") |
| 17 | + .arg("--target=wasm32-wasi") |
| 18 | + .env("CARGO_TARGET_DIR", &out_dir) |
| 19 | + .env("CARGO_PROFILE_DEV_DEBUG", "1") |
| 20 | + .status()?; |
| 21 | + assert!(status.success()); |
| 22 | + |
| 23 | + let meta = MetadataCommand::new().exec()?; |
| 24 | + let targets = meta |
| 25 | + .packages |
| 26 | + .iter() |
| 27 | + .find(|p| p.name == "test-programs") |
| 28 | + .unwrap() |
| 29 | + .targets |
| 30 | + .iter() |
| 31 | + .filter(|t| t.kind == ["bin"]) |
| 32 | + .map(|t| &t.name) |
| 33 | + .collect::<Vec<_>>(); |
| 34 | + |
| 35 | + let mut generated_code = String::new(); |
| 36 | + |
| 37 | + for target in targets { |
| 38 | + let camel = target.to_shouty_snake_case(); |
| 39 | + let wasm = out_dir |
| 40 | + .join("wasm32-wasi") |
| 41 | + .join("debug") |
| 42 | + .join(format!("{target}.wasm")); |
| 43 | + |
| 44 | + let path = compile_component(&wasm)?; |
| 45 | + generated_code += &format!("pub const {camel}_COMPONENT: &str = {path:?};\n"); |
| 46 | + } |
| 47 | + |
| 48 | + fs::write(out_dir.join("gen.rs"), generated_code)?; |
| 49 | + |
| 50 | + Ok(()) |
| 51 | +} |
| 52 | + |
| 53 | +// Compile a component, return the path of the binary |
| 54 | +fn compile_component(wasm: &Path) -> Result<PathBuf> { |
| 55 | + let module = fs::read(wasm)?; |
| 56 | + let component = ComponentEncoder::default() |
| 57 | + .module(module.as_slice())? |
| 58 | + .validate(true) |
| 59 | + .adapter( |
| 60 | + "wasi_snapshot_preview1", |
| 61 | + include_bytes!("wasi_snapshot_preview1.command.wasm"), |
| 62 | + )? |
| 63 | + .encode()?; |
| 64 | + let out_dir = wasm.parent().unwrap(); |
| 65 | + let stem = wasm.file_stem().unwrap().to_str().unwrap(); |
| 66 | + let component_path = out_dir.join(format!("{stem}.component.wasm")); |
| 67 | + fs::write(&component_path, component)?; |
| 68 | + Ok(component_path) |
| 69 | +} |
0 commit comments