Skip to main content

xtask/
install.rs

1//! Installs rust-analyzer language server and/or editor plugin.
2
3use std::{env, path::PathBuf, str};
4
5use anyhow::{Context, bail, format_err};
6use xshell::{Shell, cmd};
7
8use crate::{
9    flags::{self, Malloc, PgoTrainingCrate},
10    util::detect_target,
11};
12
13impl flags::Install {
14    pub(crate) fn run(self, sh: &Shell) -> anyhow::Result<()> {
15        if cfg!(target_os = "macos") {
16            fix_path_for_mac(sh).context("Fix path for mac")?;
17        }
18        if let Some(server) = self.server() {
19            install_server(sh, server).context("install server")?;
20        }
21        if let Some(server) = self.proc_macro_server() {
22            install_proc_macro_server(sh, server).context("install proc-macro server")?;
23        }
24        if let Some(client) = self.client() {
25            install_client(sh, client).context("install client")?;
26        }
27        Ok(())
28    }
29}
30
31#[derive(Clone)]
32pub(crate) struct ClientOpt {
33    pub(crate) code_bin: Option<String>,
34}
35
36const VS_CODES: &[&str] = &["code", "code-exploration", "code-insiders", "codium", "code-oss"];
37
38pub(crate) struct ServerOpt {
39    pub(crate) malloc: Malloc,
40    pub(crate) dev_rel: bool,
41    pub(crate) pgo: Option<PgoTrainingCrate>,
42    pub(crate) force_always_assert: bool,
43}
44
45impl ServerOpt {
46    fn to_features(&self) -> Vec<&'static str> {
47        let malloc_features = self.malloc.to_features();
48        let mut features = Vec::with_capacity(
49            malloc_features.len() + if self.force_always_assert { 2 } else { 0 },
50        );
51        features.extend(malloc_features);
52        if self.force_always_assert {
53            features.extend(["--features", "force-always-assert"]);
54        }
55        features
56    }
57}
58
59pub(crate) struct ProcMacroServerOpt {
60    pub(crate) dev_rel: bool,
61}
62
63fn fix_path_for_mac(sh: &Shell) -> anyhow::Result<()> {
64    let mut vscode_path: Vec<PathBuf> = {
65        const COMMON_APP_PATH: &str =
66            r"/Applications/Visual Studio Code.app/Contents/Resources/app/bin";
67        const ROOT_DIR: &str = "";
68        let home_dir = sh.var("HOME").map_err(|err| {
69            format_err!("Failed getting HOME from environment with error: {}.", err)
70        })?;
71
72        [ROOT_DIR, &home_dir]
73            .into_iter()
74            .map(|dir| dir.to_owned() + COMMON_APP_PATH)
75            .map(PathBuf::from)
76            .filter(|path| path.exists())
77            .collect()
78    };
79
80    if !vscode_path.is_empty() {
81        let vars = sh.var_os("PATH").context("Could not get PATH variable from env.")?;
82
83        let mut paths = env::split_paths(&vars).collect::<Vec<_>>();
84        paths.append(&mut vscode_path);
85        let new_paths = env::join_paths(paths).context("build env PATH")?;
86        sh.set_var("PATH", new_paths);
87    }
88
89    Ok(())
90}
91
92fn install_client(sh: &Shell, client_opt: ClientOpt) -> anyhow::Result<()> {
93    let _dir = sh.push_dir("./editors/code");
94
95    // Package extension.
96    if cfg!(unix) {
97        cmd!(sh, "npm --version").run().context("`npm` is required to build the VS Code plugin")?;
98        cmd!(sh, "npm ci").run()?;
99
100        cmd!(sh, "npm run package --scripts-prepend-node-path").run()?;
101    } else {
102        cmd!(sh, "cmd.exe /c npm --version")
103            .run()
104            .context("`npm` is required to build the VS Code plugin")?;
105        cmd!(sh, "cmd.exe /c npm ci").run()?;
106
107        cmd!(sh, "cmd.exe /c npm run package").run()?;
108    };
109
110    // Find the appropriate VS Code binary.
111    let candidates: &[&str] = match client_opt.code_bin.as_deref() {
112        Some(it) => &[it],
113        None => VS_CODES,
114    };
115    let code = candidates
116        .iter()
117        .copied()
118        .find(|&bin| {
119            if cfg!(unix) {
120                cmd!(sh, "{bin} --version").read().is_ok()
121            } else {
122                cmd!(sh, "cmd.exe /c {bin}.cmd --version").read().is_ok()
123            }
124        })
125        .ok_or_else(|| {
126            format_err!("Can't execute `{} --version`. Perhaps it is not in $PATH?", candidates[0])
127        })?;
128
129    // Install & verify.
130    let installed_extensions = if cfg!(unix) {
131        cmd!(sh, "{code} --install-extension rust-analyzer.vsix --force").run()?;
132        cmd!(sh, "{code} --list-extensions").read()?
133    } else {
134        cmd!(sh, "cmd.exe /c {code}.cmd --install-extension rust-analyzer.vsix --force").run()?;
135        cmd!(sh, "cmd.exe /c {code}.cmd --list-extensions").read()?
136    };
137
138    if !installed_extensions.contains("rust-analyzer") {
139        bail!(
140            "Could not install the Visual Studio Code extension. \
141            Please make sure you have at least NodeJS 16.x together with the latest version of VS Code installed and try again. \
142            Note that installing via xtask install does not work for VS Code Remote, instead you’ll need to install the .vsix manually."
143        );
144    }
145
146    Ok(())
147}
148
149fn install_server(sh: &Shell, opts: ServerOpt) -> anyhow::Result<()> {
150    let features = &opts.to_features();
151    let profile = if opts.dev_rel { "dev-rel" } else { "release" };
152
153    let mut install_cmd = cmd!(
154        sh,
155        "cargo install --path crates/rust-analyzer --profile={profile} --locked --force {features...}"
156    );
157
158    if let Some(train_crate) = opts.pgo {
159        let target = detect_target(sh);
160        let build_cmd = cmd!(
161            sh,
162            "cargo build --manifest-path ./crates/rust-analyzer/Cargo.toml --bin rust-analyzer --target {target} --profile={profile} --locked {features...}"
163        );
164
165        let profile = crate::pgo::gather_pgo_profile(sh, build_cmd, &target, train_crate)?;
166        install_cmd = crate::pgo::apply_pgo_to_cmd(install_cmd, &profile);
167    }
168
169    install_cmd.run()?;
170    Ok(())
171}
172
173fn install_proc_macro_server(sh: &Shell, opts: ProcMacroServerOpt) -> anyhow::Result<()> {
174    let profile = if opts.dev_rel { "dev-rel" } else { "release" };
175
176    let mut cmd = cmd!(
177        sh,
178        "cargo install --path crates/proc-macro-srv-cli --profile={profile} --locked --force --features in-rust-tree"
179    );
180    if std::env::var_os("RUSTUP_TOOLCHAIN").is_none() {
181        cmd = cmd.env("RUSTUP_TOOLCHAIN", "nightly");
182    } else {
183        cmd = cmd.env("RUSTC_BOOTSTRAP", "1");
184    }
185
186    cmd.run()?;
187
188    Ok(())
189}