Skip to content

Commit

Permalink
fix: use generated binary path from cargo instead
Browse files Browse the repository at this point in the history
Previously when we'd invoke wasm-bindgen we'd assume that the binary we wanted
to process was `target/wasm32-unknown-unknown{debug|release}/crate.wasm`, which
isn't the case for all flags that Cargo accepts.
  • Loading branch information
zebp committed Aug 18, 2024
1 parent 62ab39c commit bc4a4c6
Show file tree
Hide file tree
Showing 4 changed files with 80 additions and 38 deletions.
22 changes: 1 addition & 21 deletions src/bindgen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,30 +21,10 @@ pub fn wasm_bindgen_build(
reference_types: bool,
target: Target,
profile: BuildProfile,
extra_options: &Vec<String>,
wasm_path: &Path,
) -> Result<()> {
let release_or_debug = match profile {
BuildProfile::Release | BuildProfile::Profiling => "release",
BuildProfile::Dev => "debug",
};

let out_dir = out_dir.to_str().unwrap();

let target_directory = {
let mut has_target_dir_iter = extra_options.iter();
has_target_dir_iter
.find(|&it| it == "--target-dir")
.and_then(|_| has_target_dir_iter.next())
.map(Path::new)
.unwrap_or(data.target_directory())
};

let wasm_path = target_directory
.join("wasm32-unknown-unknown")
.join(release_or_debug)
.join(data.crate_name())
.with_extension("wasm");

let dts_arg = if disable_dts {
"--no-typescript"
} else {
Expand Down
46 changes: 40 additions & 6 deletions src/build/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ use crate::emoji;
use crate::manifest::Crate;
use crate::PBAR;
use anyhow::{anyhow, bail, Context, Result};
use std::path::Path;
use std::process::Command;
use cargo_metadata::Message;
use std::io::BufReader;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::str;

pub mod wasm_target;
Expand Down Expand Up @@ -77,12 +79,16 @@ pub fn cargo_build_wasm(
path: &Path,
profile: BuildProfile,
extra_options: &[String],
) -> Result<()> {
) -> Result<PathBuf> {
let msg = format!("{}Compiling to Wasm...", emoji::CYCLONE);
PBAR.info(&msg);

let mut cmd = Command::new("cargo");
cmd.current_dir(path).arg("build").arg("--lib");
cmd.current_dir(path)
.stdout(Stdio::piped())
.arg("build")
.arg("--lib")
.arg("--message-format=json-render-diagnostics");

if PBAR.quiet() {
cmd.arg("--quiet");
Expand Down Expand Up @@ -129,8 +135,36 @@ pub fn cargo_build_wasm(
.collect::<Result<Vec<_>>>()?;
cmd.args(extra_options_with_absolute_paths);

child::run(cmd, "cargo build").context("Compiling your crate to WebAssembly failed")?;
Ok(())
let mut last_artifact = None;

child::run_with_handler(cmd, "cargo build", |child| {
let stdout = child.stdout.take().unwrap();
let reader = BufReader::new(stdout);

for message in cargo_metadata::Message::parse_stream(reader) {
match message? {
Message::CompilerArtifact(artifact) => last_artifact = Some(artifact),
Message::CompilerMessage(msg) => {
if let Some(rendered) = msg.message.rendered {
println!("{}", rendered);
}
}
_ => (),
}
}

Ok(())
})
.context("Compiling your crate to WebAssembly failed")?;

let last_artifact = last_artifact
.ok_or_else(|| anyhow!("No artifacts were generated by cargo build"))?
.filenames
.into_iter()
.next()
.ok_or_else(|| anyhow!("No artifact filenames were generated by cargo build"))?;

Ok(PathBuf::from(last_artifact))
}

/// Runs `cargo build --tests` targeting `wasm32-unknown-unknown`.
Expand Down
28 changes: 27 additions & 1 deletion src/child.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
use crate::install::Tool;
use anyhow::{bail, Result};
use log::info;
use std::process::{Command, Stdio};
use std::process::{Child, Command, Stdio};

/// Return a new Command object
pub fn new_command(program: &str) -> Command {
Expand Down Expand Up @@ -62,3 +62,29 @@ pub fn run_capture_stdout(mut command: Command, command_name: &Tool) -> Result<S
)
}
}

/// Run the command and handle child, return on success.
pub fn run_with_handler<T>(
mut command: Command,
command_name: &str,
handle: impl FnOnce(&mut Child) -> Result<T>,
) -> Result<T> {
info!("Running {:?}", command);

let mut child = command.spawn()?;

let ret = handle(&mut child)?;

let status = child.wait()?;

if status.success() {
Ok(ret)
} else {
bail!(
"failed to execute `{}`: exited with {}\n full command: {:?}",
command_name,
status,
command,
)
}
}
22 changes: 12 additions & 10 deletions src/command/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ pub struct Build {
pub bindgen: Option<install::Status>,
pub cache: Cache,
pub extra_options: Vec<String>,
// step state
cargo_artifact: Option<PathBuf>,
}

/// What sort of output we're going to be generating and flags we're invoking
Expand Down Expand Up @@ -247,6 +249,7 @@ impl Build {
bindgen: None,
cache: cache::get_wasm_pack_cache()?,
extra_options: build_opts.extra_options,
cargo_artifact: None,
})
}

Expand Down Expand Up @@ -355,16 +358,13 @@ impl Build {

fn step_build_wasm(&mut self) -> Result<()> {
info!("Building wasm...");
build::cargo_build_wasm(&self.crate_path, self.profile, &self.extra_options)?;
let cargo_artifact =
build::cargo_build_wasm(&self.crate_path, self.profile, &self.extra_options)?;

info!("wasm built at {:#?}.", cargo_artifact);

self.cargo_artifact = Some(cargo_artifact);

info!(
"wasm built at {:#?}.",
&self
.crate_path
.join("target")
.join("wasm32-unknown-unknown")
.join("release")
);
Ok(())
}

Expand Down Expand Up @@ -431,7 +431,9 @@ impl Build {
self.reference_types,
self.target,
self.profile,
&self.extra_options,
self.cargo_artifact
.as_ref()
.expect("bindgen ran before cargo build"),
)?;
info!("wasm bindings were built at {:#?}.", &self.out_dir);
Ok(())
Expand Down

0 comments on commit bc4a4c6

Please sign in to comment.