1use crate::child;
4use crate::install;
5use crate::PBAR;
6use anyhow::Result;
7use binary_install::Cache;
8use std::path::Path;
9use std::path::PathBuf;
10use std::process::Command;
11
12pub fn run(cache: &Cache, out_dir: &Path, args: &[String], install_permitted: bool) -> Result<()> {
15 let wasm_opt_path = match find_wasm_opt(cache, install_permitted)? {
16 Some(path) => path,
17 None => return Ok(()),
19 };
20
21 PBAR.info("Optimizing wasm binaries with `wasm-opt`...");
22
23 for file in out_dir.read_dir()? {
24 let file = file?;
25 let path = file.path();
26 if path.extension().and_then(|s| s.to_str()) != Some("wasm") {
27 continue;
28 }
29
30 let tmp = path.with_extension("wasm-opt.wasm");
31 let mut cmd = Command::new(&wasm_opt_path);
32 cmd.arg(&path).arg("-o").arg(&tmp).args(args);
33 child::run(cmd, "wasm-opt")?;
34 std::fs::rename(&tmp, &path)?;
35 }
36
37 Ok(())
38}
39
40pub fn find_wasm_opt(cache: &Cache, install_permitted: bool) -> Result<Option<PathBuf>> {
48 if let Ok(path) = which::which("wasm-opt") {
50 PBAR.info(&format!("found wasm-opt at {:?}", path));
51 return Ok(Some(path));
52 }
53
54 match install::download_prebuilt(&install::Tool::WasmOpt, cache, "latest", install_permitted)? {
55 install::Status::Found(download) => Ok(Some(download.binary("bin/wasm-opt")?)),
56 install::Status::CannotInstall => {
57 PBAR.info("Skipping wasm-opt as no downloading was requested");
58 Ok(None)
59 }
60 install::Status::PlatformNotSupported => {
61 PBAR.info("Skipping wasm-opt because it is not supported on this platform");
62 Ok(None)
63 }
64 }
65}