use std::env;
use std::fs;
use std::io;
use std::io::IsTerminal;
use std::path::Path;
use std::process;
use anyhow::{anyhow, bail, Context, Result};
use which;
pub fn install() -> ! {
if let Err(e) = do_install() {
eprintln!("{}", e);
for cause in e.chain() {
eprintln!("Caused by: {}", cause);
}
}
if cfg!(windows) {
println!("Press enter to close this window...");
let mut line = String::new();
drop(io::stdin().read_line(&mut line));
}
process::exit(0);
}
fn do_install() -> Result<()> {
let rustup = match which::which("rustup") {
Ok(path) => path,
Err(_) => {
bail!(
"failed to find an installation of `rustup` in `PATH`, \
is rustup already installed?"
);
}
};
let installation_dir = match rustup.parent() {
Some(parent) => parent,
None => bail!("can't install when `rustup` is at the root of the filesystem"),
};
let destination = installation_dir
.join("wasm-pack")
.with_extension(env::consts::EXE_EXTENSION);
if destination.exists() {
confirm_can_overwrite(&destination)?;
}
let me = env::current_exe()?;
fs::copy(&me, &destination)
.with_context(|| anyhow!("failed to copy executable to `{}`", destination.display()))?;
println!(
"info: successfully installed wasm-pack to `{}`",
destination.display()
);
Ok(())
}
fn confirm_can_overwrite(dst: &Path) -> Result<()> {
if env::args().any(|arg| arg == "-f") {
return Ok(());
}
let stdin = io::stdin();
if !stdin.is_terminal() {
bail!(
"existing wasm-pack installation found at `{}`, pass `-f` to \
force installation over this file, otherwise aborting \
installation now",
dst.display()
);
}
eprintln!(
"info: existing wasm-pack installation found at `{}`",
dst.display()
);
eprint!("info: would you like to overwrite this file? [y/N]: ");
let mut line = String::new();
stdin.read_line(&mut line).context("failed to read stdin")?;
if line.starts_with('y') || line.starts_with('Y') {
return Ok(());
}
bail!("aborting installation");
}