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
use crate::cmd::{Binary, Command, Runnable};
use crate::toolchain::MAIN_TOOLCHAIN_NAME;
use crate::tools::{Tool, RUSTUP};
use crate::workspace::Workspace;
use failure::{Error, ResultExt};
use std::env::consts::EXE_SUFFIX;
use std::fs::{self, File};
use std::io;
use tempfile::tempdir;

static RUSTUP_BASE_URL: &str = "https://static.rust-lang.org/rustup/dist";

pub(crate) struct Rustup;

impl Runnable for Rustup {
    fn name(&self) -> Binary {
        Binary::ManagedByRustwide("rustup".into())
    }
}

impl Tool for Rustup {
    fn name(&self) -> &'static str {
        "rustup"
    }

    fn is_installed(&self, workspace: &Workspace) -> Result<bool, Error> {
        let path = self.binary_path(workspace);
        if !path.is_file() {
            return Ok(false);
        }

        Ok(crate::native::is_executable(path)?)
    }

    fn install(&self, workspace: &Workspace, _fast_install: bool) -> Result<(), Error> {
        fs::create_dir_all(workspace.cargo_home())?;
        fs::create_dir_all(workspace.rustup_home())?;

        let url = format!(
            "{}/{}/rustup-init{}",
            RUSTUP_BASE_URL,
            crate::HOST_TARGET,
            EXE_SUFFIX
        );
        let mut resp = workspace
            .http_client()
            .get(&url)
            .send()?
            .error_for_status()?;

        let tempdir = tempdir()?;
        let installer = &tempdir.path().join(format!("rustup-init{}", EXE_SUFFIX));
        {
            let mut file = File::create(installer)?;
            io::copy(&mut resp, &mut file)?;
            crate::native::make_executable(installer)?;
        }

        Command::new(workspace, installer.to_string_lossy().as_ref())
            .args(&[
                "-y",
                "--no-modify-path",
                "--default-toolchain",
                MAIN_TOOLCHAIN_NAME,
                "--profile",
                workspace.rustup_profile(),
            ])
            .env("RUSTUP_HOME", workspace.rustup_home())
            .env("CARGO_HOME", workspace.cargo_home())
            .run()
            .with_context(|_| "unable to install rustup")?;

        Ok(())
    }

    fn update(&self, workspace: &Workspace, _fast_install: bool) -> Result<(), Error> {
        Command::new(workspace, &RUSTUP)
            .args(&["self", "update"])
            .run()
            .with_context(|_| "failed to update rustup")?;
        Command::new(workspace, &RUSTUP)
            .args(&["update", MAIN_TOOLCHAIN_NAME])
            .run()
            .with_context(|_| format!("failed to update main toolchain {}", MAIN_TOOLCHAIN_NAME))?;
        Ok(())
    }
}