]> git.lizzy.rs Git - rust.git/blob - xtask/src/install.rs
Revert "Rewrite `#[derive]` removal to be based on AST"
[rust.git] / xtask / src / install.rs
1 //! Installs rust-analyzer language server and/or editor plugin.
2
3 use std::{env, path::PathBuf, str};
4
5 use anyhow::{bail, format_err, Context, Result};
6 use xshell::{cmd, pushd};
7
8 use crate::flags;
9
10 // Latest stable, feel free to send a PR if this lags behind.
11 const REQUIRED_RUST_VERSION: u32 = 51;
12
13 impl flags::Install {
14     pub(crate) fn run(self) -> Result<()> {
15         if cfg!(target_os = "macos") {
16             fix_path_for_mac().context("Fix path for mac")?
17         }
18         if let Some(server) = self.server() {
19             install_server(server).context("install server")?;
20         }
21         if let Some(client) = self.client() {
22             install_client(client).context("install client")?;
23         }
24         Ok(())
25     }
26 }
27
28 #[derive(Clone)]
29 pub(crate) struct ClientOpt {
30     pub(crate) code_bin: Option<String>,
31 }
32
33 const VS_CODES: &[&str] = &["code", "code-exploration", "code-insiders", "codium", "code-oss"];
34
35 pub(crate) struct ServerOpt {
36     pub(crate) malloc: Malloc,
37 }
38
39 pub(crate) enum Malloc {
40     System,
41     Mimalloc,
42     Jemalloc,
43 }
44
45 fn fix_path_for_mac() -> Result<()> {
46     let mut vscode_path: Vec<PathBuf> = {
47         const COMMON_APP_PATH: &str =
48             r"/Applications/Visual Studio Code.app/Contents/Resources/app/bin";
49         const ROOT_DIR: &str = "";
50         let home_dir = match env::var("HOME") {
51             Ok(home) => home,
52             Err(e) => bail!("Failed getting HOME from environment with error: {}.", e),
53         };
54
55         [ROOT_DIR, &home_dir]
56             .iter()
57             .map(|dir| String::from(*dir) + COMMON_APP_PATH)
58             .map(PathBuf::from)
59             .filter(|path| path.exists())
60             .collect()
61     };
62
63     if !vscode_path.is_empty() {
64         let vars = match env::var_os("PATH") {
65             Some(path) => path,
66             None => bail!("Could not get PATH variable from env."),
67         };
68
69         let mut paths = env::split_paths(&vars).collect::<Vec<_>>();
70         paths.append(&mut vscode_path);
71         let new_paths = env::join_paths(paths).context("build env PATH")?;
72         env::set_var("PATH", &new_paths);
73     }
74
75     Ok(())
76 }
77
78 fn install_client(client_opt: ClientOpt) -> Result<()> {
79     let _dir = pushd("./editors/code");
80
81     // Package extension.
82     if cfg!(unix) {
83         cmd!("npm --version").run().context("`npm` is required to build the VS Code plugin")?;
84         cmd!("npm ci").run()?;
85
86         cmd!("npm run package --scripts-prepend-node-path").run()?;
87     } else {
88         cmd!("cmd.exe /c npm --version")
89             .run()
90             .context("`npm` is required to build the VS Code plugin")?;
91         cmd!("cmd.exe /c npm ci").run()?;
92
93         cmd!("cmd.exe /c npm run package").run()?;
94     };
95
96     // Find the appropriate VS Code binary.
97     let lifetime_extender;
98     let candidates: &[&str] = match client_opt.code_bin.as_deref() {
99         Some(it) => {
100             lifetime_extender = [it];
101             &lifetime_extender[..]
102         }
103         None => VS_CODES,
104     };
105     let code = candidates
106         .iter()
107         .copied()
108         .find(|&bin| {
109             if cfg!(unix) {
110                 cmd!("{bin} --version").read().is_ok()
111             } else {
112                 cmd!("cmd.exe /c {bin}.cmd --version").read().is_ok()
113             }
114         })
115         .ok_or_else(|| {
116             format_err!("Can't execute `{} --version`. Perhaps it is not in $PATH?", candidates[0])
117         })?;
118
119     // Install & verify.
120     let installed_extensions = if cfg!(unix) {
121         cmd!("{code} --install-extension rust-analyzer.vsix --force").run()?;
122         cmd!("{code} --list-extensions").read()?
123     } else {
124         cmd!("cmd.exe /c {code}.cmd --install-extension rust-analyzer.vsix --force").run()?;
125         cmd!("cmd.exe /c {code}.cmd --list-extensions").read()?
126     };
127
128     if !installed_extensions.contains("rust-analyzer") {
129         bail!(
130             "Could not install the Visual Studio Code extension. \
131             Please make sure you have at least NodeJS 12.x together with the latest version of VS Code installed and try again. \
132             Note that installing via xtask install does not work for VS Code Remote, instead you’ll need to install the .vsix manually."
133         );
134     }
135
136     Ok(())
137 }
138
139 fn install_server(opts: ServerOpt) -> Result<()> {
140     let mut old_rust = false;
141     if let Ok(stdout) = cmd!("cargo --version").read() {
142         if !check_version(&stdout, REQUIRED_RUST_VERSION) {
143             old_rust = true;
144         }
145     }
146
147     if old_rust {
148         eprintln!(
149             "\nWARNING: at least rust 1.{}.0 is required to compile rust-analyzer\n",
150             REQUIRED_RUST_VERSION,
151         )
152     }
153     let features = match opts.malloc {
154         Malloc::System => &[][..],
155         Malloc::Mimalloc => &["--features", "mimalloc"],
156         Malloc::Jemalloc => &["--features", "jemalloc"],
157     };
158
159     let cmd = cmd!("cargo install --path crates/rust-analyzer --locked --force --features force-always-assert {features...}");
160     let res = cmd.run();
161
162     if res.is_err() && old_rust {
163         eprintln!(
164             "\nWARNING: at least rust 1.{}.0 is required to compile rust-analyzer\n",
165             REQUIRED_RUST_VERSION,
166         );
167     }
168
169     res?;
170     Ok(())
171 }
172
173 fn check_version(version_output: &str, min_minor_version: u32) -> bool {
174     // Parse second the number out of
175     //      cargo 1.39.0-beta (1c6ec66d5 2019-09-30)
176     let minor: Option<u32> = version_output.split('.').nth(1).and_then(|it| it.parse().ok());
177     match minor {
178         None => true,
179         Some(minor) => minor >= min_minor_version,
180     }
181 }