aboutsummaryrefslogtreecommitdiff
path: root/xtask/src/install.rs
blob: 91426377fec133e630892d58c5af878cb0093155 (plain)
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
//! Installs rust-analyzer language server and/or editor plugin.

use std::{env, path::PathBuf, str};

use anyhow::{bail, format_err, Context, Result};

use crate::not_bash::{pushd, run};

// Latest stable, feel free to send a PR if this lags behind.
const REQUIRED_RUST_VERSION: u32 = 41;

pub struct InstallCmd {
    pub client: Option<ClientOpt>,
    pub server: Option<ServerOpt>,
}

pub enum ClientOpt {
    VsCode,
}

pub struct ServerOpt {
    pub jemalloc: bool,
}

impl InstallCmd {
    pub fn run(self) -> Result<()> {
        let both = self.server.is_some() && self.client.is_some();
        if cfg!(target_os = "macos") {
            fix_path_for_mac().context("Fix path for mac")?
        }
        if let Some(server) = self.server {
            install_server(server).context("install server")?;
        }
        if let Some(client) = self.client {
            install_client(client).context("install client")?;
        }
        if both {
            eprintln!(
                "
    Installation complete.

    Add `\"rust-analyzer.raLspServerPath\": \"ra_lsp_server\",` to VS Code settings,
    otherwise it will use the latest release from GitHub.
"
            )
        }
        Ok(())
    }
}

fn fix_path_for_mac() -> Result<()> {
    let mut vscode_path: Vec<PathBuf> = {
        const COMMON_APP_PATH: &str =
            r"/Applications/Visual Studio Code.app/Contents/Resources/app/bin";
        const ROOT_DIR: &str = "";
        let home_dir = match env::var("HOME") {
            Ok(home) => home,
            Err(e) => bail!("Failed getting HOME from environment with error: {}.", e),
        };

        [ROOT_DIR, &home_dir]
            .iter()
            .map(|dir| String::from(*dir) + COMMON_APP_PATH)
            .map(PathBuf::from)
            .filter(|path| path.exists())
            .collect()
    };

    if !vscode_path.is_empty() {
        let vars = match env::var_os("PATH") {
            Some(path) => path,
            None => bail!("Could not get PATH variable from env."),
        };

        let mut paths = env::split_paths(&vars).collect::<Vec<_>>();
        paths.append(&mut vscode_path);
        let new_paths = env::join_paths(paths).context("build env PATH")?;
        env::set_var("PATH", &new_paths);
    }

    Ok(())
}

fn install_client(ClientOpt::VsCode: ClientOpt) -> Result<()> {
    let _dir = pushd("./editors/code");

    let find_code = |f: fn(&str) -> bool| -> Result<&'static str> {
        ["code", "code-insiders", "codium", "code-oss"]
            .iter()
            .copied()
            .find(|bin| f(bin))
            .ok_or_else(|| {
                format_err!("Can't execute `code --version`. Perhaps it is not in $PATH?")
            })
    };

    let installed_extensions;
    if cfg!(unix) {
        run!("npm --version").context("`npm` is required to build the VS Code plugin")?;
        run!("npm install")?;

        run!("npm run package --scripts-prepend-node-path")?;

        let code = find_code(|bin| run!("{} --version", bin).is_ok())?;
        run!("{} --install-extension rust-analyzer.vsix --force", code)?;
        installed_extensions = run!("{} --list-extensions", code; echo = false)?;
    } else {
        run!("cmd.exe /c npm --version")
            .context("`npm` is required to build the VS Code plugin")?;
        run!("cmd.exe /c npm install")?;

        run!("cmd.exe /c npm run package")?;

        let code = find_code(|bin| run!("cmd.exe /c {}.cmd --version", bin).is_ok())?;
        run!(r"cmd.exe /c {}.cmd --install-extension rust-analyzer.vsix --force", code)?;
        installed_extensions = run!("cmd.exe /c {}.cmd --list-extensions", code; echo = false)?;
    }

    if !installed_extensions.contains("rust-analyzer") {
        bail!(
            "Could not install the Visual Studio Code extension. \
             Please make sure you have at least NodeJS 12.x together with the latest version of VS Code installed and try again."
        );
    }

    Ok(())
}

fn install_server(opts: ServerOpt) -> Result<()> {
    let mut old_rust = false;
    if let Ok(stdout) = run!("cargo --version") {
        if !check_version(&stdout, REQUIRED_RUST_VERSION) {
            old_rust = true;
        }
    }

    if old_rust {
        eprintln!(
            "\nWARNING: at least rust 1.{}.0 is required to compile rust-analyzer\n",
            REQUIRED_RUST_VERSION,
        )
    }

    let jemalloc = if opts.jemalloc { "--features jemalloc" } else { "" };
    let res = run!("cargo install --path crates/ra_lsp_server --locked --force {}", jemalloc);

    if res.is_err() && old_rust {
        eprintln!(
            "\nWARNING: at least rust 1.{}.0 is required to compile rust-analyzer\n",
            REQUIRED_RUST_VERSION,
        );
    }

    res.map(drop)
}

fn check_version(version_output: &str, min_minor_version: u32) -> bool {
    // Parse second the number out of
    //      cargo 1.39.0-beta (1c6ec66d5 2019-09-30)
    let minor: Option<u32> = version_output.split('.').nth(1).and_then(|it| it.parse().ok());
    match minor {
        None => true,
        Some(minor) => minor >= min_minor_version,
    }
}