Add new functions to generate rust bindings in `build.rs`
Add RustWasm::generate_to_out_dir that parses the wit folder, selects a world, generates bindings and places them in a file in the OUT_DIR. generate_to_out_dir_modify allows modifying the generated file.
Sample build.rs
use anyhow::Result;
use std::borrow::Cow;
use wit_bindgen_rust::Opts;
fn main() -> Result<()> {
Opts {
generate_all: true,
additional_derive_attributes: vec![
"serde::Serialize".to_string(),
"serde::Deserialize".to_string(),
],
..Default::default()
}
.build()
.generate_to_out_dir_modify(Some("any"), |contents| {
let contents = String::from_utf8(contents.to_vec()).unwrap();
let re = regex::Regex::new(r"(pub\s+enum\s+\w+)").unwrap();
Cow::Owned(
re.replace_all(&contents, "#[serde(rename_all = \"kebab-case\")]\n$1")
.into_owned()
.into_bytes(),
)
})
}
Then the following snipped would include it:
mod generated {
include!(concat!(env!("OUT_DIR"), "/wit_bindgen_generated.rs"));
}
Although this should be simplified as well.
Closes #1423
Thanks for the quick review! Additionally I would like to add a macro to include the generated file:
#[cfg(feature = "macros")]
#[macro_export]
macro_rules! include_wit {
($name:literal) => {
include!(concat!(env!("OUT_DIR"), "/", $name, ".rs"));
};
}
so that the bindings can be included simply with wit_bindgen::include_wit!("myworld");.
Is it a good idea to add it to wit-bindgen ?
Personally I'd say that should be left out of the crate and documented in the usage of this method. I (subjectively) don't feel that clears the threshold for inclusion just yet, but if it becomes a common/frequent way of using wit-bindgen it seems ok to add.
Understood, in that case the PR is done.
Looks like an intermittent failure, so let's try again
Sigh, I think Github infra might be having a bad day. I'll try again tomorrow