1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
pub mod dependencies;
mod krate;
pub mod target;

use crate::terminal::emoji;

use binary_install::{Cache, Download};
use krate::Krate;
use log::info;
use semver::Version;

use std::env;
use std::fs;
use std::path::{Path, PathBuf};

use lazy_static::lazy_static;

lazy_static! {
    static ref CACHE: Cache = get_wrangler_cache().expect("Could not get Wrangler cache location");
}

enum ToolDownload {
    NeedsInstall(Version),
    InstalledAt(Download),
}

pub fn install_cargo_generate() -> Result<PathBuf, failure::Error> {
    let tool_name = "cargo-generate";
    let tool_author = "ashleygwilliams";
    let is_binary = true;
    let version = Version::parse(dependencies::GENERATE_VERSION)?;
    install(tool_name, tool_author, is_binary, version)?.binary(tool_name)
}

pub fn install_wasm_pack() -> Result<PathBuf, failure::Error> {
    let tool_name = "wasm-pack";
    let tool_author = "rustwasm";
    let is_binary = true;
    let version = Version::parse(dependencies::WASM_PACK_VERSION)?;
    install(tool_name, tool_author, is_binary, version)?.binary(tool_name)
}

pub fn install(
    tool_name: &str,
    owner: &str,
    is_binary: bool,
    version: Version,
) -> Result<Download, failure::Error> {
    let download = match tool_needs_update(tool_name, version)? {
        ToolDownload::NeedsInstall(version) => {
            println!("{}  Installing {} v{}...", emoji::DOWN, tool_name, version);
            let binaries: Vec<&str> = if is_binary { vec![tool_name] } else { vec![] };
            let download =
                download_prebuilt(tool_name, owner, &version.to_string(), binaries.as_ref());
            match download {
                Ok(download) => Ok(download),
                Err(e) => Err(failure::format_err!(
                    "could not download `{}`\n{}",
                    tool_name,
                    e
                )),
            }
        }
        ToolDownload::InstalledAt(download) => Ok(download),
    }?;
    log::debug!("tool {} located at {:?}", tool_name, download);
    Ok(download)
}

fn tool_needs_update(
    tool_name: &str,
    target_version: Version,
) -> Result<ToolDownload, failure::Error> {
    let current_installation = get_installation(tool_name, &target_version);
    // if something goes wrong checking the current installation
    // we shouldn't fail, we should just re-install for them
    if let Ok(current_installation) = current_installation {
        if let Some((installed_version, installed_location)) = current_installation {
            if installed_version.major == target_version.major
                && installed_version >= target_version
            {
                return Ok(ToolDownload::InstalledAt(Download::at(&installed_location)));
            }
        }
    }
    Ok(ToolDownload::NeedsInstall(target_version))
}

fn get_installation(
    tool_name: &str,
    target_version: &Version,
) -> Result<Option<(Version, PathBuf)>, failure::Error> {
    for entry in fs::read_dir(&CACHE.destination)? {
        let entry = entry?;
        let filename = entry.file_name().into_string();
        if let Ok(filename) = filename {
            if filename.starts_with(tool_name) {
                let installed_version = filename
                    .split(&format!("{}-", tool_name))
                    .collect::<Vec<&str>>()[1];
                let installed_version = Version::parse(installed_version);
                // if the installed version can't be parsed, ignore it
                if let Ok(installed_version) = installed_version {
                    if &installed_version == target_version {
                        return Ok(Some((installed_version, entry.path())));
                    }
                }
            }
        }
    }
    Ok(None)
}

fn download_prebuilt(
    tool_name: &str,
    owner: &str,
    version: &str,
    binaries: &[&str],
) -> Result<Download, failure::Error> {
    let url = match prebuilt_url(tool_name, owner, version) {
        Some(url) => url,
        None => failure::bail!(format!(
            "no prebuilt {} binaries are available for this platform",
            tool_name
        )),
    };

    info!("prebuilt artifact {}", url);

    // no binaries are expected; downloading it as an artifact
    let res = if !binaries.is_empty() {
        CACHE.download_version(true, tool_name, binaries, &url, version)?
    } else {
        CACHE.download_artifact_version(tool_name, &url, version)?
    };

    match res {
        Some(download) => Ok(download),
        None => failure::bail!("{} is not installed!", tool_name),
    }
}

fn prebuilt_url(tool_name: &str, owner: &str, version: &str) -> Option<String> {
    if tool_name == "wranglerjs" {
        Some(format!(
            "https://workers.cloudflare.com/get-wranglerjs-binary/{0}/v{1}.tar.gz",
            tool_name, version
        ))
    } else {
        let target = if target::LINUX && target::x86_64 {
            "x86_64-unknown-linux-musl"
        } else if target::MACOS && target::x86_64 {
            "x86_64-apple-darwin"
        } else if target::WINDOWS && target::x86_64 {
            "x86_64-pc-windows-msvc"
        } else {
            return None;
        };

        let url = format!(
            "https://workers.cloudflare.com/get-binary/{0}/{1}/v{2}/{3}.tar.gz",
            owner, tool_name, version, target
        );
        Some(url)
    }
}

pub fn get_latest_version(tool_name: &str) -> Result<Version, failure::Error> {
    // TODO: return the latest version pulled from github api, not via Krate.
    let latest_version = Krate::new(tool_name)?.max_version;
    Version::parse(&latest_version)
        .map_err(|e| failure::format_err!("could not parse latest version\n{}", e))
}

fn get_wrangler_cache() -> Result<Cache, failure::Error> {
    if let Ok(path) = env::var("WRANGLER_CACHE") {
        Ok(Cache::at(Path::new(&path)))
    } else {
        Cache::new("wrangler")
    }
}