Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Automatically install wasm32-unknown-unknown #11

Merged
merged 1 commit into from
Apr 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ pub use self::build::*;
pub use self::check::*;
pub use self::metadata::*;
pub use self::new::*;
use crate::target;

fn root_manifest(manifest_path: Option<&Path>, config: &Config) -> Result<PathBuf> {
match manifest_path {
Expand Down Expand Up @@ -136,6 +137,7 @@ impl CompileOptions {
let spec = Packages::from_flags(self.workspace, self.exclude, self.packages)?;

if self.targets.is_empty() {
target::install_wasm32_unknown_unknown()?;
self.targets.push("wasm32-unknown-unknown".to_string());
}

Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ use wit_bindgen_gen_rust_wasm::Opts;
use wit_component::ComponentEncoder;
use wit_parser::Interface;

mod target;

pub mod commands;

const COMPONENT_PATH: &str = "package.metadata.component";
Expand Down
51 changes: 51 additions & 0 deletions src/target.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use anyhow::{bail, Result};
use std::{env, path::PathBuf, process::{Command, Stdio}};

pub fn install_wasm32_unknown_unknown() -> Result<()> {
let sysroot = get_sysroot()?;
if sysroot.join("lib/rustlib/wasm32-unknown-unknown").exists() {
return Ok(());
}

if env::var_os("RUSTUP_TOOLCHAIN").is_none() {
bail!(
"failed to find the `wasm32-unknown-unknown` target \
and `rustup` is not available. If you're using rustup \
make sure that it's correctly installed; if not, make sure to \
install the `wasm32-unknown-unknown` target before using this command"
);
}

let output = Command::new("rustup")
.arg("target")
.arg("add")
.arg("wasm32-unknown-unknown")
.stderr(Stdio::inherit())
.stdout(Stdio::inherit())
.output()?;

if !output.status.success() {
bail!("failed to install the `wasm32-unknown-unknown` target");
}

Ok(())
}

fn get_sysroot() -> Result<PathBuf> {
let output = Command::new("rustc")
.arg("--print")
.arg("sysroot")
.output()?;

if !output.status.success() {
bail!(
"failed to execute `rustc --print sysroot`, \
command exited with error: {}",
String::from_utf8_lossy(&output.stderr)
);
}

let sysroot = PathBuf::from(String::from_utf8(output.stdout)?.trim());

Ok(sysroot)
}