aboutsummaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
authorAleksey Kladov <[email protected]>2020-05-08 13:54:29 +0100
committerAleksey Kladov <[email protected]>2020-05-08 13:55:28 +0100
commitecff5dc141046c5b9e40639657247a05fb9b0344 (patch)
tree871ebe102579fd2c8a35d2d5df4ed18b27219fd6 /crates
parent7c0409e0c7249fe793b5d05829fcd984d06ec770 (diff)
Cleanup
Diffstat (limited to 'crates')
-rw-r--r--crates/ra_flycheck/src/lib.rs7
-rw-r--r--crates/ra_project_model/src/cargo_workspace.rs5
-rw-r--r--crates/ra_project_model/src/lib.rs32
-rw-r--r--crates/ra_project_model/src/sysroot.rs49
-rw-r--r--crates/ra_toolchain/Cargo.toml1
-rw-r--r--crates/ra_toolchain/src/lib.rs69
6 files changed, 64 insertions, 99 deletions
diff --git a/crates/ra_flycheck/src/lib.rs b/crates/ra_flycheck/src/lib.rs
index 561657edb..68dcee285 100644
--- a/crates/ra_flycheck/src/lib.rs
+++ b/crates/ra_flycheck/src/lib.rs
@@ -16,7 +16,6 @@ use lsp_types::{
16 CodeAction, CodeActionOrCommand, Diagnostic, Url, WorkDoneProgress, WorkDoneProgressBegin, 16 CodeAction, CodeActionOrCommand, Diagnostic, Url, WorkDoneProgress, WorkDoneProgressBegin,
17 WorkDoneProgressEnd, WorkDoneProgressReport, 17 WorkDoneProgressEnd, WorkDoneProgressReport,
18}; 18};
19use ra_toolchain::get_path_for_executable;
20 19
21use crate::conv::{map_rust_diagnostic_to_lsp, MappedRustDiagnostic}; 20use crate::conv::{map_rust_diagnostic_to_lsp, MappedRustDiagnostic};
22 21
@@ -216,10 +215,10 @@ impl FlycheckThread {
216 215
217 let mut cmd = match &self.config { 216 let mut cmd = match &self.config {
218 FlycheckConfig::CargoCommand { command, all_targets, all_features, extra_args } => { 217 FlycheckConfig::CargoCommand { command, all_targets, all_features, extra_args } => {
219 let mut cmd = Command::new(get_path_for_executable("cargo").unwrap()); 218 let mut cmd = Command::new(ra_toolchain::cargo());
220 cmd.arg(command); 219 cmd.arg(command);
221 cmd.args(&["--workspace", "--message-format=json", "--manifest-path"]); 220 cmd.args(&["--workspace", "--message-format=json", "--manifest-path"])
222 cmd.arg(self.workspace_root.join("Cargo.toml")); 221 .arg(self.workspace_root.join("Cargo.toml"));
223 if *all_targets { 222 if *all_targets {
224 cmd.arg("--all-targets"); 223 cmd.arg("--all-targets");
225 } 224 }
diff --git a/crates/ra_project_model/src/cargo_workspace.rs b/crates/ra_project_model/src/cargo_workspace.rs
index 9683bfcc0..082af4f96 100644
--- a/crates/ra_project_model/src/cargo_workspace.rs
+++ b/crates/ra_project_model/src/cargo_workspace.rs
@@ -11,7 +11,6 @@ use anyhow::{Context, Result};
11use cargo_metadata::{BuildScript, CargoOpt, Message, MetadataCommand, PackageId}; 11use cargo_metadata::{BuildScript, CargoOpt, Message, MetadataCommand, PackageId};
12use ra_arena::{Arena, Idx}; 12use ra_arena::{Arena, Idx};
13use ra_db::Edition; 13use ra_db::Edition;
14use ra_toolchain::get_path_for_executable;
15use rustc_hash::FxHashMap; 14use rustc_hash::FxHashMap;
16 15
17/// `CargoWorkspace` represents the logical structure of, well, a Cargo 16/// `CargoWorkspace` represents the logical structure of, well, a Cargo
@@ -147,7 +146,7 @@ impl CargoWorkspace {
147 cargo_features: &CargoConfig, 146 cargo_features: &CargoConfig,
148 ) -> Result<CargoWorkspace> { 147 ) -> Result<CargoWorkspace> {
149 let mut meta = MetadataCommand::new(); 148 let mut meta = MetadataCommand::new();
150 meta.cargo_path(get_path_for_executable("cargo")?); 149 meta.cargo_path(ra_toolchain::cargo());
151 meta.manifest_path(cargo_toml); 150 meta.manifest_path(cargo_toml);
152 if cargo_features.all_features { 151 if cargo_features.all_features {
153 meta.features(CargoOpt::AllFeatures); 152 meta.features(CargoOpt::AllFeatures);
@@ -289,7 +288,7 @@ pub fn load_extern_resources(
289 cargo_toml: &Path, 288 cargo_toml: &Path,
290 cargo_features: &CargoConfig, 289 cargo_features: &CargoConfig,
291) -> Result<ExternResources> { 290) -> Result<ExternResources> {
292 let mut cmd = Command::new(get_path_for_executable("cargo")?); 291 let mut cmd = Command::new(ra_toolchain::cargo());
293 cmd.args(&["check", "--message-format=json", "--manifest-path"]).arg(cargo_toml); 292 cmd.args(&["check", "--message-format=json", "--manifest-path"]).arg(cargo_toml);
294 if cargo_features.all_features { 293 if cargo_features.all_features {
295 cmd.arg("--all-features"); 294 cmd.arg("--all-features");
diff --git a/crates/ra_project_model/src/lib.rs b/crates/ra_project_model/src/lib.rs
index 4f0b9c77e..5a0a87ed7 100644
--- a/crates/ra_project_model/src/lib.rs
+++ b/crates/ra_project_model/src/lib.rs
@@ -8,13 +8,12 @@ use std::{
8 fs::{read_dir, File, ReadDir}, 8 fs::{read_dir, File, ReadDir},
9 io::{self, BufReader}, 9 io::{self, BufReader},
10 path::{Path, PathBuf}, 10 path::{Path, PathBuf},
11 process::Command, 11 process::{Command, Output},
12}; 12};
13 13
14use anyhow::{bail, Context, Result}; 14use anyhow::{bail, Context, Result};
15use ra_cfg::CfgOptions; 15use ra_cfg::CfgOptions;
16use ra_db::{CrateGraph, CrateName, Edition, Env, ExternSource, ExternSourceId, FileId}; 16use ra_db::{CrateGraph, CrateName, Edition, Env, ExternSource, ExternSourceId, FileId};
17use ra_toolchain::get_path_for_executable;
18use rustc_hash::FxHashMap; 17use rustc_hash::FxHashMap;
19use serde_json::from_reader; 18use serde_json::from_reader;
20 19
@@ -568,25 +567,18 @@ pub fn get_rustc_cfg_options(target: Option<&String>) -> CfgOptions {
568 } 567 }
569 } 568 }
570 569
571 match (|| -> Result<String> { 570 let rustc_cfgs = || -> Result<String> {
572 // `cfg(test)` and `cfg(debug_assertion)` are handled outside, so we suppress them here. 571 // `cfg(test)` and `cfg(debug_assertion)` are handled outside, so we suppress them here.
573 let mut cmd = Command::new(get_path_for_executable("rustc")?); 572 let mut cmd = Command::new(ra_toolchain::rustc());
574 cmd.args(&["--print", "cfg", "-O"]); 573 cmd.args(&["--print", "cfg", "-O"]);
575 if let Some(target) = target { 574 if let Some(target) = target {
576 cmd.args(&["--target", target.as_str()]); 575 cmd.args(&["--target", target.as_str()]);
577 } 576 }
578 let output = cmd.output().context("Failed to get output from rustc --print cfg -O")?; 577 let output = output(cmd)?;
579 if !output.status.success() {
580 bail!(
581 "rustc --print cfg -O exited with exit code ({})",
582 output
583 .status
584 .code()
585 .map_or(String::from("no exit code"), |code| format!("{}", code))
586 );
587 }
588 Ok(String::from_utf8(output.stdout)?) 578 Ok(String::from_utf8(output.stdout)?)
589 })() { 579 }();
580
581 match rustc_cfgs {
590 Ok(rustc_cfgs) => { 582 Ok(rustc_cfgs) => {
591 for line in rustc_cfgs.lines() { 583 for line in rustc_cfgs.lines() {
592 match line.find('=') { 584 match line.find('=') {
@@ -599,8 +591,16 @@ pub fn get_rustc_cfg_options(target: Option<&String>) -> CfgOptions {
599 } 591 }
600 } 592 }
601 } 593 }
602 Err(e) => log::error!("failed to get rustc cfgs: {}", e), 594 Err(e) => log::error!("failed to get rustc cfgs: {:#}", e),
603 } 595 }
604 596
605 cfg_options 597 cfg_options
606} 598}
599
600fn output(mut cmd: Command) -> Result<Output> {
601 let output = cmd.output().with_context(|| format!("{:?} failed", cmd))?;
602 if !output.status.success() {
603 bail!("{:?} failed, {}", cmd, output.status)
604 }
605 Ok(output)
606}
diff --git a/crates/ra_project_model/src/sysroot.rs b/crates/ra_project_model/src/sysroot.rs
index 2b628c2a3..a8a196e64 100644
--- a/crates/ra_project_model/src/sysroot.rs
+++ b/crates/ra_project_model/src/sysroot.rs
@@ -3,12 +3,13 @@
3use std::{ 3use std::{
4 env, ops, 4 env, ops,
5 path::{Path, PathBuf}, 5 path::{Path, PathBuf},
6 process::{Command, Output}, 6 process::Command,
7}; 7};
8 8
9use anyhow::{bail, Context, Result}; 9use anyhow::{bail, Result};
10use ra_arena::{Arena, Idx}; 10use ra_arena::{Arena, Idx};
11use ra_toolchain::get_path_for_executable; 11
12use crate::output;
12 13
13#[derive(Default, Debug, Clone)] 14#[derive(Default, Debug, Clone)]
14pub struct Sysroot { 15pub struct Sysroot {
@@ -85,50 +86,22 @@ impl Sysroot {
85 } 86 }
86} 87}
87 88
88fn create_command_text(program: &str, args: &[&str]) -> String {
89 format!("{} {}", program, args.join(" "))
90}
91
92fn run_command_in_cargo_dir(
93 cargo_toml: impl AsRef<Path>,
94 program: impl AsRef<Path>,
95 args: &[&str],
96) -> Result<Output> {
97 let program = program.as_ref().as_os_str().to_str().expect("Invalid Unicode in path");
98 let output = Command::new(program)
99 .current_dir(cargo_toml.as_ref().parent().unwrap())
100 .args(args)
101 .output()
102 .context(format!("{} failed", create_command_text(program, args)))?;
103 if !output.status.success() {
104 match output.status.code() {
105 Some(code) => bail!(
106 "failed to run the command: '{}' exited with code {}",
107 create_command_text(program, args),
108 code
109 ),
110 None => bail!(
111 "failed to run the command: '{}' terminated by signal",
112 create_command_text(program, args)
113 ),
114 };
115 }
116 Ok(output)
117}
118
119fn get_or_install_rust_src(cargo_toml: &Path) -> Result<PathBuf> { 89fn get_or_install_rust_src(cargo_toml: &Path) -> Result<PathBuf> {
120 if let Ok(path) = env::var("RUST_SRC_PATH") { 90 if let Ok(path) = env::var("RUST_SRC_PATH") {
121 return Ok(path.into()); 91 return Ok(path.into());
122 } 92 }
123 let rustc = get_path_for_executable("rustc")?; 93 let current_dir = cargo_toml.parent().unwrap();
124 let rustc_output = run_command_in_cargo_dir(cargo_toml, &rustc, &["--print", "sysroot"])?; 94 let mut rustc = Command::new(ra_toolchain::rustc());
95 rustc.current_dir(current_dir).args(&["--print", "sysroot"]);
96 let rustc_output = output(rustc)?;
125 let stdout = String::from_utf8(rustc_output.stdout)?; 97 let stdout = String::from_utf8(rustc_output.stdout)?;
126 let sysroot_path = Path::new(stdout.trim()); 98 let sysroot_path = Path::new(stdout.trim());
127 let src_path = sysroot_path.join("lib/rustlib/src/rust/src"); 99 let src_path = sysroot_path.join("lib/rustlib/src/rust/src");
128 100
129 if !src_path.exists() { 101 if !src_path.exists() {
130 let rustup = get_path_for_executable("rustup")?; 102 let mut rustup = Command::new(ra_toolchain::rustup());
131 run_command_in_cargo_dir(cargo_toml, &rustup, &["component", "add", "rust-src"])?; 103 rustup.current_dir(current_dir).args(&["component", "add", "rust-src"]);
104 let _output = output(rustup)?;
132 } 105 }
133 if !src_path.exists() { 106 if !src_path.exists() {
134 bail!( 107 bail!(
diff --git a/crates/ra_toolchain/Cargo.toml b/crates/ra_toolchain/Cargo.toml
index fbad1073e..1873fbe16 100644
--- a/crates/ra_toolchain/Cargo.toml
+++ b/crates/ra_toolchain/Cargo.toml
@@ -5,5 +5,4 @@ version = "0.1.0"
5authors = ["rust-analyzer developers"] 5authors = ["rust-analyzer developers"]
6 6
7[dependencies] 7[dependencies]
8anyhow = "1.0.26"
9home = "0.5.3" 8home = "0.5.3"
diff --git a/crates/ra_toolchain/src/lib.rs b/crates/ra_toolchain/src/lib.rs
index afa76619d..3c307a0ea 100644
--- a/crates/ra_toolchain/src/lib.rs
+++ b/crates/ra_toolchain/src/lib.rs
@@ -1,21 +1,26 @@
1//! This crate contains a single public function 1//! This crate contains a single public function
2//! [`get_path_for_executable`](fn.get_path_for_executable.html). 2//! [`get_path_for_executable`](fn.get_path_for_executable.html).
3//! See docs there for more information. 3//! See docs there for more information.
4use std::{ 4use std::{env, iter, path::PathBuf};
5 env,
6 path::{Path, PathBuf},
7 process::Command,
8};
9 5
10use anyhow::{bail, Result}; 6pub fn cargo() -> PathBuf {
7 get_path_for_executable("cargo")
8}
9
10pub fn rustc() -> PathBuf {
11 get_path_for_executable("rustc")
12}
13
14pub fn rustup() -> PathBuf {
15 get_path_for_executable("rustup")
16}
11 17
12/// Return a `PathBuf` to use for the given executable. 18/// Return a `PathBuf` to use for the given executable.
13/// 19///
14/// E.g., `get_path_for_executable("cargo")` may return just `cargo` if that 20/// E.g., `get_path_for_executable("cargo")` may return just `cargo` if that
15/// gives a valid Cargo executable; or it may return a full path to a valid 21/// gives a valid Cargo executable; or it may return a full path to a valid
16/// Cargo. 22/// Cargo.
17pub fn get_path_for_executable(executable_name: &'static str) -> Result<PathBuf> { 23fn get_path_for_executable(executable_name: &'static str) -> PathBuf {
18 assert!(executable_name == "rustc" || executable_name == "cargo");
19 // The current implementation checks three places for an executable to use: 24 // The current implementation checks three places for an executable to use:
20 // 1) Appropriate environment variable (erroring if this is set but not a usable executable) 25 // 1) Appropriate environment variable (erroring if this is set but not a usable executable)
21 // example: for cargo, this checks $CARGO environment variable; for rustc, $RUSTC; etc 26 // example: for cargo, this checks $CARGO environment variable; for rustc, $RUSTC; etc
@@ -25,45 +30,35 @@ pub fn get_path_for_executable(executable_name: &'static str) -> Result<PathBuf>
25 // example: for cargo, this tries ~/.cargo/bin/cargo 30 // example: for cargo, this tries ~/.cargo/bin/cargo
26 // It seems that this is a reasonable place to try for cargo, rustc, and rustup 31 // It seems that this is a reasonable place to try for cargo, rustc, and rustup
27 let env_var = executable_name.to_ascii_uppercase(); 32 let env_var = executable_name.to_ascii_uppercase();
28 if let Ok(path) = env::var(&env_var) { 33 if let Some(path) = env::var_os(&env_var) {
29 return if is_valid_executable(&path) { 34 return path.into();
30 Ok(path.into())
31 } else {
32 bail!(
33 "`{}` environment variable points to something that's not a valid executable",
34 env_var
35 )
36 };
37 } 35 }
38 36
39 if is_valid_executable(executable_name) { 37 if lookup_in_path(executable_name) {
40 return Ok(executable_name.into()); 38 return executable_name.into();
41 } 39 }
42 40
43 if let Some(mut path) = home::home_dir() { 41 if let Some(mut path) = home::home_dir() {
44 path.push(".cargo"); 42 path.push(".cargo");
45 path.push("bin"); 43 path.push("bin");
46 path.push(executable_name); 44 path.push(executable_name);
47 if is_valid_executable(&path) { 45 if path.is_file() {
48 return Ok(path); 46 return path;
49 } 47 }
50 } 48 }
51 // This error message may also be caused by $PATH or $CARGO/$RUSTC/etc not being set correctly 49 executable_name.into()
52 // for VSCode, even if they are set correctly in a terminal.
53 // On macOS in particular, launching VSCode from terminal with `code <dirname>` causes VSCode
54 // to inherit environment variables including $PATH, $CARGO, $RUSTC, etc from that terminal;
55 // but launching VSCode from Dock does not inherit environment variables from a terminal.
56 // For more discussion, see #3118.
57 bail!(
58 "Failed to find `{}` executable. Make sure `{}` is in `$PATH`, or set `${}` to point to a valid executable.",
59 executable_name, executable_name, env_var
60 )
61} 50}
62 51
63/// Does the given `Path` point to a usable executable? 52fn lookup_in_path(exec: &str) -> bool {
64/// 53 let paths = env::var_os("PATH").unwrap_or_default();
65/// (assumes the executable takes a `--version` switch and writes to stdout, 54 let mut candidates = env::split_paths(&paths).flat_map(|path| {
66/// which is true for `cargo`, `rustc`, and `rustup`) 55 let candidate = path.join(&exec);
67fn is_valid_executable(p: &'static str) -> bool { 56 let with_exe = if env::consts::EXE_EXTENSION == "" {
68 Command::new(p).arg("--version").output().is_ok() 57 None
58 } else {
59 Some(candidate.with_extension(env::consts::EXE_EXTENSION))
60 };
61 iter::once(candidate).chain(with_exe)
62 });
63 candidates.any(|it| it.is_file())
69} 64}