diff options
-rw-r--r-- | Cargo.lock | 19 | ||||
-rw-r--r-- | crates/ra_env/Cargo.toml | 9 | ||||
-rw-r--r-- | crates/ra_env/src/lib.rs | 66 | ||||
-rw-r--r-- | crates/ra_flycheck/Cargo.toml | 1 | ||||
-rw-r--r-- | crates/ra_flycheck/src/lib.rs | 8 | ||||
-rw-r--r-- | crates/ra_project_model/Cargo.toml | 3 | ||||
-rw-r--r-- | crates/ra_project_model/src/cargo_workspace.rs | 14 | ||||
-rw-r--r-- | crates/ra_project_model/src/lib.rs | 3 | ||||
-rw-r--r-- | crates/ra_project_model/src/sysroot.rs | 16 | ||||
-rw-r--r-- | editors/code/src/cargo.ts | 81 | ||||
-rw-r--r-- | editors/code/src/commands/runnables.ts | 7 | ||||
-rw-r--r-- | editors/code/src/main.ts | 8 | ||||
-rw-r--r-- | editors/code/src/util.ts | 11 |
13 files changed, 183 insertions, 63 deletions
diff --git a/Cargo.lock b/Cargo.lock index 264b9b7fb..36cff6402 100644 --- a/Cargo.lock +++ b/Cargo.lock | |||
@@ -465,6 +465,15 @@ dependencies = [ | |||
465 | ] | 465 | ] |
466 | 466 | ||
467 | [[package]] | 467 | [[package]] |
468 | name = "home" | ||
469 | version = "0.5.3" | ||
470 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
471 | checksum = "2456aef2e6b6a9784192ae780c0f15bc57df0e918585282325e8c8ac27737654" | ||
472 | dependencies = [ | ||
473 | "winapi 0.3.8", | ||
474 | ] | ||
475 | |||
476 | [[package]] | ||
468 | name = "idna" | 477 | name = "idna" |
469 | version = "0.2.0" | 478 | version = "0.2.0" |
470 | source = "registry+https://github.com/rust-lang/crates.io-index" | 479 | source = "registry+https://github.com/rust-lang/crates.io-index" |
@@ -949,6 +958,14 @@ dependencies = [ | |||
949 | ] | 958 | ] |
950 | 959 | ||
951 | [[package]] | 960 | [[package]] |
961 | name = "ra_env" | ||
962 | version = "0.1.0" | ||
963 | dependencies = [ | ||
964 | "anyhow", | ||
965 | "home", | ||
966 | ] | ||
967 | |||
968 | [[package]] | ||
952 | name = "ra_flycheck" | 969 | name = "ra_flycheck" |
953 | version = "0.1.0" | 970 | version = "0.1.0" |
954 | dependencies = [ | 971 | dependencies = [ |
@@ -958,6 +975,7 @@ dependencies = [ | |||
958 | "jod-thread", | 975 | "jod-thread", |
959 | "log", | 976 | "log", |
960 | "lsp-types", | 977 | "lsp-types", |
978 | "ra_env", | ||
961 | "serde_json", | 979 | "serde_json", |
962 | ] | 980 | ] |
963 | 981 | ||
@@ -1162,6 +1180,7 @@ dependencies = [ | |||
1162 | "ra_arena", | 1180 | "ra_arena", |
1163 | "ra_cfg", | 1181 | "ra_cfg", |
1164 | "ra_db", | 1182 | "ra_db", |
1183 | "ra_env", | ||
1165 | "ra_proc_macro", | 1184 | "ra_proc_macro", |
1166 | "rustc-hash", | 1185 | "rustc-hash", |
1167 | "serde", | 1186 | "serde", |
diff --git a/crates/ra_env/Cargo.toml b/crates/ra_env/Cargo.toml new file mode 100644 index 000000000..f0a401be5 --- /dev/null +++ b/crates/ra_env/Cargo.toml | |||
@@ -0,0 +1,9 @@ | |||
1 | [package] | ||
2 | edition = "2018" | ||
3 | name = "ra_env" | ||
4 | version = "0.1.0" | ||
5 | authors = ["rust-analyzer developers"] | ||
6 | |||
7 | [dependencies] | ||
8 | anyhow = "1.0.26" | ||
9 | home = "0.5.3" | ||
diff --git a/crates/ra_env/src/lib.rs b/crates/ra_env/src/lib.rs new file mode 100644 index 000000000..413da1982 --- /dev/null +++ b/crates/ra_env/src/lib.rs | |||
@@ -0,0 +1,66 @@ | |||
1 | //! This crate contains a single public function | ||
2 | //! [`get_path_for_executable`](fn.get_path_for_executable.html). | ||
3 | //! See docs there for more information. | ||
4 | |||
5 | use anyhow::{bail, Result}; | ||
6 | use std::env; | ||
7 | use std::path::{Path, PathBuf}; | ||
8 | use std::process::Command; | ||
9 | |||
10 | /// Return a `PathBuf` to use for the given executable. | ||
11 | /// | ||
12 | /// E.g., `get_path_for_executable("cargo")` may return just `cargo` if that | ||
13 | /// gives a valid Cargo executable; or it may return a full path to a valid | ||
14 | /// Cargo. | ||
15 | pub fn get_path_for_executable(executable_name: impl AsRef<str>) -> Result<PathBuf> { | ||
16 | // The current implementation checks three places for an executable to use: | ||
17 | // 1) Appropriate environment variable (erroring if this is set but not a usable executable) | ||
18 | // example: for cargo, this checks $CARGO environment variable; for rustc, $RUSTC; etc | ||
19 | // 2) `<executable_name>` | ||
20 | // example: for cargo, this tries just `cargo`, which will succeed if `cargo` is on the $PATH | ||
21 | // 3) `~/.cargo/bin/<executable_name>` | ||
22 | // example: for cargo, this tries ~/.cargo/bin/cargo | ||
23 | // It seems that this is a reasonable place to try for cargo, rustc, and rustup | ||
24 | let executable_name = executable_name.as_ref(); | ||
25 | let env_var = executable_name.to_ascii_uppercase(); | ||
26 | if let Ok(path) = env::var(&env_var) { | ||
27 | if is_valid_executable(&path) { | ||
28 | Ok(path.into()) | ||
29 | } else { | ||
30 | bail!( | ||
31 | "`{}` environment variable points to something that's not a valid executable", | ||
32 | env_var | ||
33 | ) | ||
34 | } | ||
35 | } else { | ||
36 | if is_valid_executable(executable_name) { | ||
37 | return Ok(executable_name.into()); | ||
38 | } | ||
39 | if let Some(mut path) = ::home::home_dir() { | ||
40 | path.push(".cargo"); | ||
41 | path.push("bin"); | ||
42 | path.push(executable_name); | ||
43 | if is_valid_executable(&path) { | ||
44 | return Ok(path); | ||
45 | } | ||
46 | } | ||
47 | // This error message may also be caused by $PATH or $CARGO/$RUSTC/etc not being set correctly | ||
48 | // for VSCode, even if they are set correctly in a terminal. | ||
49 | // On macOS in particular, launching VSCode from terminal with `code <dirname>` causes VSCode | ||
50 | // to inherit environment variables including $PATH, $CARGO, $RUSTC, etc from that terminal; | ||
51 | // but launching VSCode from Dock does not inherit environment variables from a terminal. | ||
52 | // For more discussion, see #3118. | ||
53 | bail!( | ||
54 | "Failed to find `{}` executable. Make sure `{}` is in `$PATH`, or set `${}` to point to a valid executable.", | ||
55 | executable_name, executable_name, env_var | ||
56 | ) | ||
57 | } | ||
58 | } | ||
59 | |||
60 | /// Does the given `Path` point to a usable executable? | ||
61 | /// | ||
62 | /// (assumes the executable takes a `--version` switch and writes to stdout, | ||
63 | /// which is true for `cargo`, `rustc`, and `rustup`) | ||
64 | fn is_valid_executable(p: impl AsRef<Path>) -> bool { | ||
65 | Command::new(p.as_ref()).arg("--version").output().is_ok() | ||
66 | } | ||
diff --git a/crates/ra_flycheck/Cargo.toml b/crates/ra_flycheck/Cargo.toml index 3d5093264..d0f7fb2dc 100644 --- a/crates/ra_flycheck/Cargo.toml +++ b/crates/ra_flycheck/Cargo.toml | |||
@@ -14,6 +14,7 @@ log = "0.4.8" | |||
14 | cargo_metadata = "0.9.1" | 14 | cargo_metadata = "0.9.1" |
15 | serde_json = "1.0.48" | 15 | serde_json = "1.0.48" |
16 | jod-thread = "0.1.1" | 16 | jod-thread = "0.1.1" |
17 | ra_env = { path = "../ra_env" } | ||
17 | 18 | ||
18 | [dev-dependencies] | 19 | [dev-dependencies] |
19 | insta = "0.16.0" | 20 | insta = "0.16.0" |
diff --git a/crates/ra_flycheck/src/lib.rs b/crates/ra_flycheck/src/lib.rs index f27252949..d8b727b0e 100644 --- a/crates/ra_flycheck/src/lib.rs +++ b/crates/ra_flycheck/src/lib.rs | |||
@@ -4,7 +4,6 @@ | |||
4 | mod conv; | 4 | mod conv; |
5 | 5 | ||
6 | use std::{ | 6 | use std::{ |
7 | env, | ||
8 | io::{self, BufRead, BufReader}, | 7 | io::{self, BufRead, BufReader}, |
9 | path::PathBuf, | 8 | path::PathBuf, |
10 | process::{Command, Stdio}, | 9 | process::{Command, Stdio}, |
@@ -17,6 +16,7 @@ use lsp_types::{ | |||
17 | CodeAction, CodeActionOrCommand, Diagnostic, Url, WorkDoneProgress, WorkDoneProgressBegin, | 16 | CodeAction, CodeActionOrCommand, Diagnostic, Url, WorkDoneProgress, WorkDoneProgressBegin, |
18 | WorkDoneProgressEnd, WorkDoneProgressReport, | 17 | WorkDoneProgressEnd, WorkDoneProgressReport, |
19 | }; | 18 | }; |
19 | use ra_env::get_path_for_executable; | ||
20 | 20 | ||
21 | use crate::conv::{map_rust_diagnostic_to_lsp, MappedRustDiagnostic}; | 21 | use crate::conv::{map_rust_diagnostic_to_lsp, MappedRustDiagnostic}; |
22 | 22 | ||
@@ -216,7 +216,7 @@ impl FlycheckThread { | |||
216 | 216 | ||
217 | let mut cmd = match &self.config { | 217 | let mut cmd = match &self.config { |
218 | FlycheckConfig::CargoCommand { command, all_targets, all_features, extra_args } => { | 218 | FlycheckConfig::CargoCommand { command, all_targets, all_features, extra_args } => { |
219 | let mut cmd = Command::new(cargo_binary()); | 219 | let mut cmd = Command::new(get_path_for_executable("cargo").unwrap()); |
220 | cmd.arg(command); | 220 | cmd.arg(command); |
221 | cmd.args(&["--workspace", "--message-format=json", "--manifest-path"]); | 221 | cmd.args(&["--workspace", "--message-format=json", "--manifest-path"]); |
222 | cmd.arg(self.workspace_root.join("Cargo.toml")); | 222 | cmd.arg(self.workspace_root.join("Cargo.toml")); |
@@ -337,7 +337,3 @@ fn run_cargo( | |||
337 | 337 | ||
338 | Ok(()) | 338 | Ok(()) |
339 | } | 339 | } |
340 | |||
341 | fn cargo_binary() -> String { | ||
342 | env::var("CARGO").unwrap_or_else(|_| "cargo".to_string()) | ||
343 | } | ||
diff --git a/crates/ra_project_model/Cargo.toml b/crates/ra_project_model/Cargo.toml index 5e651fe70..626478468 100644 --- a/crates/ra_project_model/Cargo.toml +++ b/crates/ra_project_model/Cargo.toml | |||
@@ -14,8 +14,9 @@ rustc-hash = "1.1.0" | |||
14 | cargo_metadata = "0.9.1" | 14 | cargo_metadata = "0.9.1" |
15 | 15 | ||
16 | ra_arena = { path = "../ra_arena" } | 16 | ra_arena = { path = "../ra_arena" } |
17 | ra_db = { path = "../ra_db" } | ||
18 | ra_cfg = { path = "../ra_cfg" } | 17 | ra_cfg = { path = "../ra_cfg" } |
18 | ra_db = { path = "../ra_db" } | ||
19 | ra_env = { path = "../ra_env" } | ||
19 | ra_proc_macro = { path = "../ra_proc_macro" } | 20 | ra_proc_macro = { path = "../ra_proc_macro" } |
20 | 21 | ||
21 | serde = { version = "1.0.106", features = ["derive"] } | 22 | serde = { version = "1.0.106", features = ["derive"] } |
diff --git a/crates/ra_project_model/src/cargo_workspace.rs b/crates/ra_project_model/src/cargo_workspace.rs index 16fff9f1c..eb9f33ee8 100644 --- a/crates/ra_project_model/src/cargo_workspace.rs +++ b/crates/ra_project_model/src/cargo_workspace.rs | |||
@@ -1,7 +1,6 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! FIXME: write short doc here |
2 | 2 | ||
3 | use std::{ | 3 | use std::{ |
4 | env, | ||
5 | ffi::OsStr, | 4 | ffi::OsStr, |
6 | ops, | 5 | ops, |
7 | path::{Path, PathBuf}, | 6 | path::{Path, PathBuf}, |
@@ -12,6 +11,7 @@ use anyhow::{Context, Result}; | |||
12 | use cargo_metadata::{BuildScript, CargoOpt, Message, MetadataCommand, PackageId}; | 11 | use cargo_metadata::{BuildScript, CargoOpt, Message, MetadataCommand, PackageId}; |
13 | use ra_arena::{Arena, Idx}; | 12 | use ra_arena::{Arena, Idx}; |
14 | use ra_db::Edition; | 13 | use ra_db::Edition; |
14 | use ra_env::get_path_for_executable; | ||
15 | use rustc_hash::FxHashMap; | 15 | use rustc_hash::FxHashMap; |
16 | 16 | ||
17 | /// `CargoWorkspace` represents the logical structure of, well, a Cargo | 17 | /// `CargoWorkspace` represents the logical structure of, well, a Cargo |
@@ -146,12 +146,8 @@ impl CargoWorkspace { | |||
146 | cargo_toml: &Path, | 146 | cargo_toml: &Path, |
147 | cargo_features: &CargoConfig, | 147 | cargo_features: &CargoConfig, |
148 | ) -> Result<CargoWorkspace> { | 148 | ) -> Result<CargoWorkspace> { |
149 | let _ = Command::new(cargo_binary()) | ||
150 | .arg("--version") | ||
151 | .output() | ||
152 | .context("failed to run `cargo --version`, is `cargo` in PATH?")?; | ||
153 | |||
154 | let mut meta = MetadataCommand::new(); | 149 | let mut meta = MetadataCommand::new(); |
150 | meta.cargo_path(get_path_for_executable("cargo")?); | ||
155 | meta.manifest_path(cargo_toml); | 151 | meta.manifest_path(cargo_toml); |
156 | if cargo_features.all_features { | 152 | if cargo_features.all_features { |
157 | meta.features(CargoOpt::AllFeatures); | 153 | meta.features(CargoOpt::AllFeatures); |
@@ -293,7 +289,7 @@ pub fn load_extern_resources( | |||
293 | cargo_toml: &Path, | 289 | cargo_toml: &Path, |
294 | cargo_features: &CargoConfig, | 290 | cargo_features: &CargoConfig, |
295 | ) -> Result<ExternResources> { | 291 | ) -> Result<ExternResources> { |
296 | let mut cmd = Command::new(cargo_binary()); | 292 | let mut cmd = Command::new(get_path_for_executable("cargo")?); |
297 | cmd.args(&["check", "--message-format=json", "--manifest-path"]).arg(cargo_toml); | 293 | cmd.args(&["check", "--message-format=json", "--manifest-path"]).arg(cargo_toml); |
298 | if cargo_features.all_features { | 294 | if cargo_features.all_features { |
299 | cmd.arg("--all-features"); | 295 | cmd.arg("--all-features"); |
@@ -347,7 +343,3 @@ fn is_dylib(path: &Path) -> bool { | |||
347 | Some(ext) => matches!(ext.as_str(), "dll" | "dylib" | "so"), | 343 | Some(ext) => matches!(ext.as_str(), "dll" | "dylib" | "so"), |
348 | } | 344 | } |
349 | } | 345 | } |
350 | |||
351 | fn cargo_binary() -> String { | ||
352 | env::var("CARGO").unwrap_or_else(|_| "cargo".to_string()) | ||
353 | } | ||
diff --git a/crates/ra_project_model/src/lib.rs b/crates/ra_project_model/src/lib.rs index c226ffa57..88a6ffb2a 100644 --- a/crates/ra_project_model/src/lib.rs +++ b/crates/ra_project_model/src/lib.rs | |||
@@ -14,6 +14,7 @@ use std::{ | |||
14 | use anyhow::{bail, Context, Result}; | 14 | use anyhow::{bail, Context, Result}; |
15 | use ra_cfg::CfgOptions; | 15 | use ra_cfg::CfgOptions; |
16 | use ra_db::{CrateGraph, CrateName, Edition, Env, ExternSource, ExternSourceId, FileId}; | 16 | use ra_db::{CrateGraph, CrateName, Edition, Env, ExternSource, ExternSourceId, FileId}; |
17 | use ra_env::get_path_for_executable; | ||
17 | use rustc_hash::FxHashMap; | 18 | use rustc_hash::FxHashMap; |
18 | use serde_json::from_reader; | 19 | use serde_json::from_reader; |
19 | 20 | ||
@@ -569,7 +570,7 @@ pub fn get_rustc_cfg_options(target: Option<&String>) -> CfgOptions { | |||
569 | 570 | ||
570 | match (|| -> Result<String> { | 571 | match (|| -> Result<String> { |
571 | // `cfg(test)` and `cfg(debug_assertion)` are handled outside, so we suppress them here. | 572 | // `cfg(test)` and `cfg(debug_assertion)` are handled outside, so we suppress them here. |
572 | let mut cmd = Command::new("rustc"); | 573 | let mut cmd = Command::new(get_path_for_executable("rustc")?); |
573 | cmd.args(&["--print", "cfg", "-O"]); | 574 | cmd.args(&["--print", "cfg", "-O"]); |
574 | if let Some(target) = target { | 575 | if let Some(target) = target { |
575 | cmd.args(&["--target", target.as_str()]); | 576 | cmd.args(&["--target", target.as_str()]); |
diff --git a/crates/ra_project_model/src/sysroot.rs b/crates/ra_project_model/src/sysroot.rs index 55ff5ad80..11c26ad89 100644 --- a/crates/ra_project_model/src/sysroot.rs +++ b/crates/ra_project_model/src/sysroot.rs | |||
@@ -8,6 +8,7 @@ use std::{ | |||
8 | }; | 8 | }; |
9 | 9 | ||
10 | use ra_arena::{Arena, Idx}; | 10 | use ra_arena::{Arena, Idx}; |
11 | use ra_env::get_path_for_executable; | ||
11 | 12 | ||
12 | #[derive(Default, Debug, Clone)] | 13 | #[derive(Default, Debug, Clone)] |
13 | pub struct Sysroot { | 14 | pub struct Sysroot { |
@@ -88,9 +89,14 @@ fn create_command_text(program: &str, args: &[&str]) -> String { | |||
88 | format!("{} {}", program, args.join(" ")) | 89 | format!("{} {}", program, args.join(" ")) |
89 | } | 90 | } |
90 | 91 | ||
91 | fn run_command_in_cargo_dir(cargo_toml: &Path, program: &str, args: &[&str]) -> Result<Output> { | 92 | fn 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"); | ||
92 | let output = Command::new(program) | 98 | let output = Command::new(program) |
93 | .current_dir(cargo_toml.parent().unwrap()) | 99 | .current_dir(cargo_toml.as_ref().parent().unwrap()) |
94 | .args(args) | 100 | .args(args) |
95 | .output() | 101 | .output() |
96 | .context(format!("{} failed", create_command_text(program, args)))?; | 102 | .context(format!("{} failed", create_command_text(program, args)))?; |
@@ -114,13 +120,15 @@ fn get_or_install_rust_src(cargo_toml: &Path) -> Result<PathBuf> { | |||
114 | if let Ok(path) = env::var("RUST_SRC_PATH") { | 120 | if let Ok(path) = env::var("RUST_SRC_PATH") { |
115 | return Ok(path.into()); | 121 | return Ok(path.into()); |
116 | } | 122 | } |
117 | let rustc_output = run_command_in_cargo_dir(cargo_toml, "rustc", &["--print", "sysroot"])?; | 123 | let rustc = get_path_for_executable("rustc")?; |
124 | let rustc_output = run_command_in_cargo_dir(cargo_toml, &rustc, &["--print", "sysroot"])?; | ||
118 | let stdout = String::from_utf8(rustc_output.stdout)?; | 125 | let stdout = String::from_utf8(rustc_output.stdout)?; |
119 | let sysroot_path = Path::new(stdout.trim()); | 126 | let sysroot_path = Path::new(stdout.trim()); |
120 | let src_path = sysroot_path.join("lib/rustlib/src/rust/src"); | 127 | let src_path = sysroot_path.join("lib/rustlib/src/rust/src"); |
121 | 128 | ||
122 | if !src_path.exists() { | 129 | if !src_path.exists() { |
123 | run_command_in_cargo_dir(cargo_toml, "rustup", &["component", "add", "rust-src"])?; | 130 | let rustup = get_path_for_executable("rustup")?; |
131 | run_command_in_cargo_dir(cargo_toml, &rustup, &["component", "add", "rust-src"])?; | ||
124 | } | 132 | } |
125 | if !src_path.exists() { | 133 | if !src_path.exists() { |
126 | bail!( | 134 | bail!( |
diff --git a/editors/code/src/cargo.ts b/editors/code/src/cargo.ts index a328ba9bd..2a2c2e0e1 100644 --- a/editors/code/src/cargo.ts +++ b/editors/code/src/cargo.ts | |||
@@ -1,6 +1,9 @@ | |||
1 | import * as cp from 'child_process'; | 1 | import * as cp from 'child_process'; |
2 | import * as os from 'os'; | ||
3 | import * as path from 'path'; | ||
2 | import * as readline from 'readline'; | 4 | import * as readline from 'readline'; |
3 | import { OutputChannel } from 'vscode'; | 5 | import { OutputChannel } from 'vscode'; |
6 | import { isValidExecutable } from './util'; | ||
4 | 7 | ||
5 | interface CompilationArtifact { | 8 | interface CompilationArtifact { |
6 | fileName: string; | 9 | fileName: string; |
@@ -10,17 +13,9 @@ interface CompilationArtifact { | |||
10 | } | 13 | } |
11 | 14 | ||
12 | export class Cargo { | 15 | export class Cargo { |
13 | rootFolder: string; | 16 | constructor(readonly rootFolder: string, readonly output: OutputChannel) { } |
14 | env?: Record<string, string>; | ||
15 | output: OutputChannel; | ||
16 | |||
17 | public constructor(cargoTomlFolder: string, output: OutputChannel, env: Record<string, string> | undefined = undefined) { | ||
18 | this.rootFolder = cargoTomlFolder; | ||
19 | this.output = output; | ||
20 | this.env = env; | ||
21 | } | ||
22 | 17 | ||
23 | public async artifactsFromArgs(cargoArgs: string[]): Promise<CompilationArtifact[]> { | 18 | private async artifactsFromArgs(cargoArgs: string[]): Promise<CompilationArtifact[]> { |
24 | const artifacts: CompilationArtifact[] = []; | 19 | const artifacts: CompilationArtifact[] = []; |
25 | 20 | ||
26 | try { | 21 | try { |
@@ -37,17 +32,13 @@ export class Cargo { | |||
37 | isTest: message.profile.test | 32 | isTest: message.profile.test |
38 | }); | 33 | }); |
39 | } | 34 | } |
40 | } | 35 | } else if (message.reason === 'compiler-message') { |
41 | else if (message.reason === 'compiler-message') { | ||
42 | this.output.append(message.message.rendered); | 36 | this.output.append(message.message.rendered); |
43 | } | 37 | } |
44 | }, | 38 | }, |
45 | stderr => { | 39 | stderr => this.output.append(stderr), |
46 | this.output.append(stderr); | ||
47 | } | ||
48 | ); | 40 | ); |
49 | } | 41 | } catch (err) { |
50 | catch (err) { | ||
51 | this.output.show(true); | 42 | this.output.show(true); |
52 | throw new Error(`Cargo invocation has failed: ${err}`); | 43 | throw new Error(`Cargo invocation has failed: ${err}`); |
53 | } | 44 | } |
@@ -55,9 +46,8 @@ export class Cargo { | |||
55 | return artifacts; | 46 | return artifacts; |
56 | } | 47 | } |
57 | 48 | ||
58 | public async executableFromArgs(args: string[]): Promise<string> { | 49 | async executableFromArgs(args: readonly string[]): Promise<string> { |
59 | const cargoArgs = [...args]; // to remain args unchanged | 50 | const cargoArgs = [...args, "--message-format=json"]; |
60 | cargoArgs.push("--message-format=json"); | ||
61 | 51 | ||
62 | const artifacts = await this.artifactsFromArgs(cargoArgs); | 52 | const artifacts = await this.artifactsFromArgs(cargoArgs); |
63 | 53 | ||
@@ -70,24 +60,27 @@ export class Cargo { | |||
70 | return artifacts[0].fileName; | 60 | return artifacts[0].fileName; |
71 | } | 61 | } |
72 | 62 | ||
73 | runCargo( | 63 | private runCargo( |
74 | cargoArgs: string[], | 64 | cargoArgs: string[], |
75 | onStdoutJson: (obj: any) => void, | 65 | onStdoutJson: (obj: any) => void, |
76 | onStderrString: (data: string) => void | 66 | onStderrString: (data: string) => void |
77 | ): Promise<number> { | 67 | ): Promise<number> { |
78 | return new Promise<number>((resolve, reject) => { | 68 | return new Promise((resolve, reject) => { |
79 | const cargo = cp.spawn('cargo', cargoArgs, { | 69 | let cargoPath; |
70 | try { | ||
71 | cargoPath = getCargoPathOrFail(); | ||
72 | } catch (err) { | ||
73 | return reject(err); | ||
74 | } | ||
75 | |||
76 | const cargo = cp.spawn(cargoPath, cargoArgs, { | ||
80 | stdio: ['ignore', 'pipe', 'pipe'], | 77 | stdio: ['ignore', 'pipe', 'pipe'], |
81 | cwd: this.rootFolder, | 78 | cwd: this.rootFolder |
82 | env: this.env, | ||
83 | }); | 79 | }); |
84 | 80 | ||
85 | cargo.on('error', err => { | 81 | cargo.on('error', err => reject(new Error(`could not launch cargo: ${err}`))); |
86 | reject(new Error(`could not launch cargo: ${err}`)); | 82 | |
87 | }); | 83 | cargo.stderr.on('data', chunk => onStderrString(chunk.toString())); |
88 | cargo.stderr.on('data', chunk => { | ||
89 | onStderrString(chunk.toString()); | ||
90 | }); | ||
91 | 84 | ||
92 | const rl = readline.createInterface({ input: cargo.stdout }); | 85 | const rl = readline.createInterface({ input: cargo.stdout }); |
93 | rl.on('line', line => { | 86 | rl.on('line', line => { |
@@ -103,4 +96,28 @@ export class Cargo { | |||
103 | }); | 96 | }); |
104 | }); | 97 | }); |
105 | } | 98 | } |
106 | } \ No newline at end of file | 99 | } |
100 | |||
101 | // Mirrors `ra_env::get_path_for_executable` implementation | ||
102 | function getCargoPathOrFail(): string { | ||
103 | const envVar = process.env.CARGO; | ||
104 | const executableName = "cargo"; | ||
105 | |||
106 | if (envVar) { | ||
107 | if (isValidExecutable(envVar)) return envVar; | ||
108 | |||
109 | throw new Error(`\`${envVar}\` environment variable points to something that's not a valid executable`); | ||
110 | } | ||
111 | |||
112 | if (isValidExecutable(executableName)) return executableName; | ||
113 | |||
114 | const standardLocation = path.join(os.homedir(), '.cargo', 'bin', executableName); | ||
115 | |||
116 | if (isValidExecutable(standardLocation)) return standardLocation; | ||
117 | |||
118 | throw new Error( | ||
119 | `Failed to find \`${executableName}\` executable. ` + | ||
120 | `Make sure \`${executableName}\` is in \`$PATH\`, ` + | ||
121 | `or set \`${envVar}\` to point to a valid executable.` | ||
122 | ); | ||
123 | } | ||
diff --git a/editors/code/src/commands/runnables.ts b/editors/code/src/commands/runnables.ts index d77e8188c..2ed150e25 100644 --- a/editors/code/src/commands/runnables.ts +++ b/editors/code/src/commands/runnables.ts | |||
@@ -119,8 +119,11 @@ export function debugSingle(ctx: Ctx): Cmd { | |||
119 | } | 119 | } |
120 | 120 | ||
121 | if (!debugEngine) { | 121 | if (!debugEngine) { |
122 | vscode.window.showErrorMessage(`Install [CodeLLDB](https://marketplace.visualstudio.com/items?itemName=${lldbId})` | 122 | vscode.window.showErrorMessage( |
123 | + ` or [MS C++ tools](https://marketplace.visualstudio.com/items?itemName=${cpptoolsId}) extension for debugging.`); | 123 | `Install [CodeLLDB](https://marketplace.visualstudio.com/items?itemName=${lldbId}) ` + |
124 | `or [MS C++ tools](https://marketplace.visualstudio.com/items?itemName=${cpptoolsId}) ` + | ||
125 | `extension for debugging.` | ||
126 | ); | ||
124 | return; | 127 | return; |
125 | } | 128 | } |
126 | 129 | ||
diff --git a/editors/code/src/main.ts b/editors/code/src/main.ts index efd56a84b..9b020d001 100644 --- a/editors/code/src/main.ts +++ b/editors/code/src/main.ts | |||
@@ -8,10 +8,9 @@ import { activateInlayHints } from './inlay_hints'; | |||
8 | import { activateStatusDisplay } from './status_display'; | 8 | import { activateStatusDisplay } from './status_display'; |
9 | import { Ctx } from './ctx'; | 9 | import { Ctx } from './ctx'; |
10 | import { Config, NIGHTLY_TAG } from './config'; | 10 | import { Config, NIGHTLY_TAG } from './config'; |
11 | import { log, assert } from './util'; | 11 | import { log, assert, isValidExecutable } from './util'; |
12 | import { PersistentState } from './persistent_state'; | 12 | import { PersistentState } from './persistent_state'; |
13 | import { fetchRelease, download } from './net'; | 13 | import { fetchRelease, download } from './net'; |
14 | import { spawnSync } from 'child_process'; | ||
15 | import { activateTaskProvider } from './tasks'; | 14 | import { activateTaskProvider } from './tasks'; |
16 | 15 | ||
17 | let ctx: Ctx | undefined; | 16 | let ctx: Ctx | undefined; |
@@ -179,10 +178,7 @@ async function bootstrapServer(config: Config, state: PersistentState): Promise< | |||
179 | 178 | ||
180 | log.debug("Using server binary at", path); | 179 | log.debug("Using server binary at", path); |
181 | 180 | ||
182 | const res = spawnSync(path, ["--version"], { encoding: 'utf8' }); | 181 | if (!isValidExecutable(path)) { |
183 | log.debug("Checked binary availability via --version", res); | ||
184 | log.debug(res, "--version output:", res.output); | ||
185 | if (res.status !== 0) { | ||
186 | throw new Error(`Failed to execute ${path} --version`); | 182 | throw new Error(`Failed to execute ${path} --version`); |
187 | } | 183 | } |
188 | 184 | ||
diff --git a/editors/code/src/util.ts b/editors/code/src/util.ts index 6f91f81d6..127a9e911 100644 --- a/editors/code/src/util.ts +++ b/editors/code/src/util.ts | |||
@@ -1,6 +1,7 @@ | |||
1 | import * as lc from "vscode-languageclient"; | 1 | import * as lc from "vscode-languageclient"; |
2 | import * as vscode from "vscode"; | 2 | import * as vscode from "vscode"; |
3 | import { strict as nativeAssert } from "assert"; | 3 | import { strict as nativeAssert } from "assert"; |
4 | import { spawnSync } from "child_process"; | ||
4 | 5 | ||
5 | export function assert(condition: boolean, explanation: string): asserts condition { | 6 | export function assert(condition: boolean, explanation: string): asserts condition { |
6 | try { | 7 | try { |
@@ -82,3 +83,13 @@ export function isRustDocument(document: vscode.TextDocument): document is RustD | |||
82 | export function isRustEditor(editor: vscode.TextEditor): editor is RustEditor { | 83 | export function isRustEditor(editor: vscode.TextEditor): editor is RustEditor { |
83 | return isRustDocument(editor.document); | 84 | return isRustDocument(editor.document); |
84 | } | 85 | } |
86 | |||
87 | export function isValidExecutable(path: string): boolean { | ||
88 | log.debug("Checking availability of a binary at", path); | ||
89 | |||
90 | const res = spawnSync(path, ["--version"], { encoding: 'utf8' }); | ||
91 | |||
92 | log.debug(res, "--version output:", res.output); | ||
93 | |||
94 | return res.status === 0; | ||
95 | } | ||