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