use std::{
env, process::{Command, self}, fs, path::{PathBuf, Path}, hash::{Hash, Hasher},
collections::hash_map::DefaultHasher,
};
const SKIP_BUILD_ENV: &str = "SKIP_WASM_BUILD";
const DUMMY_WASM_BINARY_ENV: &str = "BUILD_DUMMY_WASM_BINARY";
const TRIGGER_WASM_BUILD_ENV: &str = "TRIGGER_WASM_BUILD";
fn replace_back_slashes<T: ToString>(path: T) -> String {
path.to_string().replace("\\", "/")
}
fn get_manifest_dir() -> PathBuf {
env::var("CARGO_MANIFEST_DIR")
.expect("`CARGO_MANIFEST_DIR` is always set for `build.rs` files; qed")
.into()
}
pub struct WasmBuilderSelectProject {
_ignore: (),
}
impl WasmBuilderSelectProject {
pub fn with_current_project(self) -> WasmBuilderSelectSource {
WasmBuilderSelectSource(get_manifest_dir().join("Cargo.toml"))
}
pub fn with_project(
self,
path: impl Into<PathBuf>,
) -> Result<WasmBuilderSelectSource, &'static str> {
let path = path.into();
if path.ends_with("Cargo.toml") {
Ok(WasmBuilderSelectSource(path))
} else {
Err("Project path must point to the `Cargo.toml` of the project")
}
}
}
pub struct WasmBuilderSelectSource(PathBuf);
impl WasmBuilderSelectSource {
pub fn with_wasm_builder_from_path(self, path: &'static str) -> WasmBuilder {
WasmBuilder {
source: WasmBuilderSource::Path(path),
rust_flags: Vec::new(),
file_name: None,
project_cargo_toml: self.0,
}
}
pub fn with_wasm_builder_from_git(self, repo: &'static str, rev: &'static str) -> WasmBuilder {
WasmBuilder {
source: WasmBuilderSource::Git { repo, rev },
rust_flags: Vec::new(),
file_name: None,
project_cargo_toml: self.0,
}
}
pub fn with_wasm_builder_from_crates(self, version: &'static str) -> WasmBuilder {
WasmBuilder {
source: WasmBuilderSource::Crates(version),
rust_flags: Vec::new(),
file_name: None,
project_cargo_toml: self.0,
}
}
pub fn with_wasm_builder_from_crates_or_path(
self,
version: &'static str,
path: &'static str,
) -> WasmBuilder {
WasmBuilder {
source: WasmBuilderSource::CratesOrPath { version, path },
rust_flags: Vec::new(),
file_name: None,
project_cargo_toml: self.0,
}
}
pub fn with_wasm_builder_source(self, source: WasmBuilderSource) -> WasmBuilder {
WasmBuilder {
source,
rust_flags: Vec::new(),
file_name: None,
project_cargo_toml: self.0,
}
}
}
pub struct WasmBuilder {
source: WasmBuilderSource,
rust_flags: Vec<String>,
file_name: Option<String>,
project_cargo_toml: PathBuf,
}
impl WasmBuilder {
pub fn new() -> WasmBuilderSelectProject {
WasmBuilderSelectProject {
_ignore: (),
}
}
pub fn export_heap_base(mut self) -> Self {
self.rust_flags.push("-Clink-arg=--export=__heap_base".into());
self
}
pub fn set_file_name(mut self, file_name: impl Into<String>) -> Self {
self.file_name = Some(file_name.into());
self
}
pub fn import_memory(mut self) -> Self {
self.rust_flags.push("-C link-arg=--import-memory".into());
self
}
pub fn append_to_rust_flags(mut self, flag: impl Into<String>) -> Self {
self.rust_flags.push(flag.into());
self
}
pub fn build(self) {
if check_skip_build() {
generate_rerun_if_changed_instructions();
return;
}
let out_dir = PathBuf::from(env::var("OUT_DIR").expect("`OUT_DIR` is set by cargo!"));
let file_path = out_dir.join(self.file_name.unwrap_or_else(|| "wasm_binary.rs".into()));
let mut hasher = DefaultHasher::new();
self.project_cargo_toml.hash(&mut hasher);
let project_name = env::var("CARGO_PKG_NAME").expect("`CARGO_PKG_NAME` is set by cargo!");
let project_folder = get_workspace_root()
.join(format!("{}{}", project_name, hasher.finish()));
if check_provide_dummy_wasm_binary() {
provide_dummy_wasm_binary(&file_path);
} else {
create_project(
&project_folder,
&file_path,
self.source,
&self.project_cargo_toml,
&self.rust_flags.into_iter().map(|f| format!("{} ", f)).collect::<String>(),
);
run_project(&project_folder);
}
generate_rerun_if_changed_instructions();
}
}
pub enum WasmBuilderSource {
Path(&'static str),
Git {
repo: &'static str,
rev: &'static str,
},
Crates(&'static str),
CratesOrPath {
version: &'static str,
path: &'static str,
}
}
impl WasmBuilderSource {
fn to_cargo_source(&self, manifest_dir: &Path) -> String {
match self {
WasmBuilderSource::Path(path) => {
replace_back_slashes(format!("path = \"{}\"", manifest_dir.join(path).display()))
}
WasmBuilderSource::Git { repo, rev } => {
format!("git = \"{}\", rev=\"{}\"", repo, rev)
}
WasmBuilderSource::Crates(version) => {
format!("version = \"{}\"", version)
}
WasmBuilderSource::CratesOrPath { version, path } => {
replace_back_slashes(
format!(
"path = \"{}\", version = \"{}\"",
manifest_dir.join(path).display(),
version
)
)
}
}
}
}
#[deprecated(
since = "1.0.5",
note = "Please switch to [`WasmBuilder`]",
)]
pub fn build_current_project_with_rustflags(
file_name: &str,
wasm_builder_source: WasmBuilderSource,
default_rust_flags: &str,
) {
WasmBuilder::new()
.with_current_project()
.with_wasm_builder_source(wasm_builder_source)
.append_to_rust_flags(default_rust_flags)
.set_file_name(file_name)
.build()
}
#[deprecated(
since = "1.0.5",
note = "Please switch to [`WasmBuilder`]",
)]
pub fn build_current_project(file_name: &str, wasm_builder_source: WasmBuilderSource) {
#[allow(deprecated)]
build_current_project_with_rustflags(file_name, wasm_builder_source, "");
}
fn get_workspace_root() -> PathBuf {
let out_dir_env = env::var("OUT_DIR").expect("`OUT_DIR` is set by cargo!");
let mut out_dir = PathBuf::from(&out_dir_env);
loop {
match out_dir.parent() {
Some(parent) if out_dir.ends_with("build") => return parent.join("wbuild-runner"),
_ => if !out_dir.pop() {
break;
}
}
}
panic!("Could not find target dir in: {}", out_dir_env)
}
fn create_project(
project_folder: &Path,
file_path: &Path,
wasm_builder_source: WasmBuilderSource,
cargo_toml_path: &Path,
default_rustflags: &str,
) {
fs::create_dir_all(project_folder.join("src"))
.expect("WASM build runner dir create can not fail; qed");
fs::write(
project_folder.join("Cargo.toml"),
format!(
r#"
[package]
name = "wasm-build-runner-impl"
version = "1.0.0"
edition = "2018"
[dependencies]
substrate-wasm-builder = {{ {wasm_builder_source} }}
[workspace]
"#,
wasm_builder_source = wasm_builder_source.to_cargo_source(&get_manifest_dir()),
)
).expect("WASM build runner `Cargo.toml` writing can not fail; qed");
fs::write(
project_folder.join("src/main.rs"),
format!(
r#"
use substrate_wasm_builder::build_project_with_default_rustflags;
fn main() {{
build_project_with_default_rustflags(
"{file_path}",
"{cargo_toml_path}",
"{default_rustflags}",
)
}}
"#,
file_path = replace_back_slashes(file_path.display()),
cargo_toml_path = replace_back_slashes(cargo_toml_path.display()),
default_rustflags = default_rustflags,
)
).expect("WASM build runner `main.rs` writing can not fail; qed");
}
fn run_project(project_folder: &Path) {
let cargo = env::var("CARGO").expect("`CARGO` env variable is always set when executing `build.rs`.");
let mut cmd = Command::new(cargo);
cmd.arg("run").arg(format!("--manifest-path={}", project_folder.join("Cargo.toml").display()));
if env::var("DEBUG") != Ok(String::from("true")) {
cmd.arg("--release");
}
cmd.env_remove("CARGO_TARGET_DIR");
if !cmd.status().map(|s| s.success()).unwrap_or(false) {
process::exit(1);
}
}
fn generate_crate_skip_build_env_name() -> String {
format!(
"SKIP_{}_WASM_BUILD",
env::var("CARGO_PKG_NAME").expect("Package name is set").to_uppercase().replace('-', "_"),
)
}
fn check_skip_build() -> bool {
env::var(SKIP_BUILD_ENV).is_ok() || env::var(generate_crate_skip_build_env_name()).is_ok()
}
fn check_provide_dummy_wasm_binary() -> bool {
env::var(DUMMY_WASM_BINARY_ENV).is_ok()
}
fn provide_dummy_wasm_binary(file_path: &Path) {
fs::write(
file_path,
"pub const WASM_BINARY: &[u8] = &[]; pub const WASM_BINARY_BLOATY: &[u8] = &[];",
).expect("Writing dummy WASM binary should not fail");
}
fn generate_rerun_if_changed_instructions() {
println!("cargo:rerun-if-env-changed={}", SKIP_BUILD_ENV);
println!("cargo:rerun-if-env-changed={}", DUMMY_WASM_BINARY_ENV);
println!("cargo:rerun-if-env-changed={}", TRIGGER_WASM_BUILD_ENV);
println!("cargo:rerun-if-env-changed={}", generate_crate_skip_build_env_name());
}