From 303b444dbb66019fc916dd350e54f7675aa3007f Mon Sep 17 00:00:00 2001 From: Craig Disselkoen Date: Tue, 5 May 2020 14:07:10 -0700 Subject: pull function out into new crate ra_env; use in ra_flycheck as well --- Cargo.lock | 11 ++++- crates/ra_env/Cargo.toml | 9 ++++ crates/ra_env/src/lib.rs | 63 +++++++++++++++++++++++++ crates/ra_flycheck/Cargo.toml | 1 + crates/ra_flycheck/src/lib.rs | 8 +--- crates/ra_project_model/Cargo.toml | 5 +- crates/ra_project_model/src/cargo_workspace.rs | 2 +- crates/ra_project_model/src/find_executables.rs | 63 ------------------------- crates/ra_project_model/src/lib.rs | 4 +- crates/ra_project_model/src/sysroot.rs | 5 +- 10 files changed, 93 insertions(+), 78 deletions(-) create mode 100644 crates/ra_env/Cargo.toml create mode 100644 crates/ra_env/src/lib.rs delete mode 100644 crates/ra_project_model/src/find_executables.rs diff --git a/Cargo.lock b/Cargo.lock index b2d4569b3..28424b7d4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -999,6 +999,14 @@ dependencies = [ "test_utils", ] +[[package]] +name = "ra_env" +version = "0.1.0" +dependencies = [ + "anyhow", + "dirs", +] + [[package]] name = "ra_flycheck" version = "0.1.0" @@ -1009,6 +1017,7 @@ dependencies = [ "jod-thread", "log", "lsp-types", + "ra_env", "serde_json", ] @@ -1209,11 +1218,11 @@ version = "0.1.0" dependencies = [ "anyhow", "cargo_metadata", - "dirs", "log", "ra_arena", "ra_cfg", "ra_db", + "ra_env", "ra_proc_macro", "rustc-hash", "serde", diff --git a/crates/ra_env/Cargo.toml b/crates/ra_env/Cargo.toml new file mode 100644 index 000000000..7fed446a7 --- /dev/null +++ b/crates/ra_env/Cargo.toml @@ -0,0 +1,9 @@ +[package] +edition = "2018" +name = "ra_env" +version = "0.1.0" +authors = ["rust-analyzer developers"] + +[dependencies] +anyhow = "1.0.26" +dirs = "2.0" diff --git a/crates/ra_env/src/lib.rs b/crates/ra_env/src/lib.rs new file mode 100644 index 000000000..cb9fbf80c --- /dev/null +++ b/crates/ra_env/src/lib.rs @@ -0,0 +1,63 @@ +use anyhow::{Error, Result}; +use std::env; +use std::path::Path; +use std::process::Command; + +/// Return a `String` to use for the given executable. +/// +/// E.g., `get_path_for_executable("cargo")` may return just `cargo` if that +/// gives a valid Cargo executable; or it may return a full path to a valid +/// Cargo. +pub fn get_path_for_executable(executable_name: impl AsRef) -> Result { + // The current implementation checks three places for an executable to use: + // 1) Appropriate environment variable (erroring if this is set but not a usable executable) + // example: for cargo, this checks $CARGO environment variable; for rustc, $RUSTC; etc + // 2) `` + // example: for cargo, this tries just `cargo`, which will succeed if `cargo` is on the $PATH + // 3) `~/.cargo/bin/` + // example: for cargo, this tries ~/.cargo/bin/cargo + // It seems that this is a reasonable place to try for cargo, rustc, and rustup + let executable_name = executable_name.as_ref(); + let env_var = executable_name.to_ascii_uppercase(); + if let Ok(path) = env::var(&env_var) { + if is_valid_executable(&path) { + Ok(path) + } else { + Err(Error::msg(format!("`{}` environment variable points to something that's not a valid executable", env_var))) + } + } else { + let final_path: Option = if is_valid_executable(executable_name) { + Some(executable_name.to_owned()) + } else { + if let Some(mut path) = dirs::home_dir() { + path.push(".cargo"); + path.push("bin"); + path.push(executable_name); + if is_valid_executable(&path) { + Some(path.into_os_string().into_string().expect("Invalid Unicode in path")) + } else { + None + } + } else { + None + } + }; + final_path.ok_or( + // This error message may also be caused by $PATH or $CARGO/$RUSTC/etc not being set correctly + // for VSCode, even if they are set correctly in a terminal. + // On macOS in particular, launching VSCode from terminal with `code ` causes VSCode + // to inherit environment variables including $PATH, $CARGO, $RUSTC, etc from that terminal; + // but launching VSCode from Dock does not inherit environment variables from a terminal. + // For more discussion, see #3118. + Error::msg(format!("Failed to find `{}` executable. Make sure `{}` is in `$PATH`, or set `${}` to point to a valid executable.", executable_name, executable_name, env_var)) + ) + } +} + +/// Does the given `Path` point to a usable executable? +/// +/// (assumes the executable takes a `--version` switch and writes to stdout, +/// which is true for `cargo`, `rustc`, and `rustup`) +fn is_valid_executable(p: impl AsRef) -> bool { + Command::new(p.as_ref()).arg("--version").output().is_ok() +} 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" cargo_metadata = "0.9.1" serde_json = "1.0.48" jod-thread = "0.1.1" +ra_env = { path = "../ra_env" } [dev-dependencies] 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 @@ mod conv; use std::{ - env, io::{self, BufRead, BufReader}, path::PathBuf, process::{Command, Stdio}, @@ -17,6 +16,7 @@ use lsp_types::{ CodeAction, CodeActionOrCommand, Diagnostic, Url, WorkDoneProgress, WorkDoneProgressBegin, WorkDoneProgressEnd, WorkDoneProgressReport, }; +use ra_env::get_path_for_executable; use crate::conv::{map_rust_diagnostic_to_lsp, MappedRustDiagnostic}; @@ -216,7 +216,7 @@ impl FlycheckThread { let mut cmd = match &self.config { FlycheckConfig::CargoCommand { command, all_targets, all_features, extra_args } => { - let mut cmd = Command::new(cargo_binary()); + let mut cmd = Command::new(get_path_for_executable("cargo").unwrap()); cmd.arg(command); cmd.args(&["--workspace", "--message-format=json", "--manifest-path"]); cmd.arg(self.workspace_root.join("Cargo.toml")); @@ -337,7 +337,3 @@ fn run_cargo( Ok(()) } - -fn cargo_binary() -> String { - env::var("CARGO").unwrap_or_else(|_| "cargo".to_string()) -} diff --git a/crates/ra_project_model/Cargo.toml b/crates/ra_project_model/Cargo.toml index 91958ed94..626478468 100644 --- a/crates/ra_project_model/Cargo.toml +++ b/crates/ra_project_model/Cargo.toml @@ -14,13 +14,12 @@ rustc-hash = "1.1.0" cargo_metadata = "0.9.1" ra_arena = { path = "../ra_arena" } -ra_db = { path = "../ra_db" } ra_cfg = { path = "../ra_cfg" } +ra_db = { path = "../ra_db" } +ra_env = { path = "../ra_env" } ra_proc_macro = { path = "../ra_proc_macro" } serde = { version = "1.0.106", features = ["derive"] } serde_json = "1.0.48" anyhow = "1.0.26" - -dirs = "2.0" diff --git a/crates/ra_project_model/src/cargo_workspace.rs b/crates/ra_project_model/src/cargo_workspace.rs index c7350d1e0..4027f020f 100644 --- a/crates/ra_project_model/src/cargo_workspace.rs +++ b/crates/ra_project_model/src/cargo_workspace.rs @@ -7,11 +7,11 @@ use std::{ process::Command, }; -use super::find_executables::get_path_for_executable; use anyhow::{Context, Result}; use cargo_metadata::{BuildScript, CargoOpt, Message, MetadataCommand, PackageId}; use ra_arena::{Arena, Idx}; use ra_db::Edition; +use ra_env::get_path_for_executable; use rustc_hash::FxHashMap; /// `CargoWorkspace` represents the logical structure of, well, a Cargo diff --git a/crates/ra_project_model/src/find_executables.rs b/crates/ra_project_model/src/find_executables.rs deleted file mode 100644 index 9b020d3da..000000000 --- a/crates/ra_project_model/src/find_executables.rs +++ /dev/null @@ -1,63 +0,0 @@ -use anyhow::{Error, Result}; -use std::env; -use std::path::Path; -use std::process::Command; - -/// Return a `String` to use for the given executable. -/// -/// E.g., `get_path_for_executable("cargo")` may return just `cargo` if that -/// gives a valid Cargo executable; or it may return a full path to a valid -/// Cargo. -pub fn get_path_for_executable(executable_name: impl AsRef) -> Result { - // The current implementation checks three places for an executable to use: - // 1) Appropriate environment variable (erroring if this is set but not a usable executable) - // example: for cargo, this checks $CARGO environment variable; for rustc, $RUSTC; etc - // 2) `` - // example: for cargo, this tries just `cargo`, which will succeed if `cargo` in on the $PATH - // 3) `~/.cargo/bin/` - // example: for cargo, this tries ~/.cargo/bin/cargo - // It seems that this is a reasonable place to try for cargo, rustc, and rustup - let executable_name = executable_name.as_ref(); - let env_var = executable_name.to_ascii_uppercase(); - if let Ok(path) = env::var(&env_var) { - if is_valid_executable(&path) { - Ok(path) - } else { - Err(Error::msg(format!("`{}` environment variable points to something that's not a valid executable", env_var))) - } - } else { - let final_path: Option = if is_valid_executable(executable_name) { - Some(executable_name.to_owned()) - } else { - if let Some(mut path) = dirs::home_dir() { - path.push(".cargo"); - path.push("bin"); - path.push(executable_name); - if is_valid_executable(&path) { - Some(path.into_os_string().into_string().expect("Invalid Unicode in path")) - } else { - None - } - } else { - None - } - }; - final_path.ok_or( - // This error message may also be caused by $PATH or $CARGO/$RUSTC/etc not being set correctly - // for VSCode, even if they are set correctly in a terminal. - // On macOS in particular, launching VSCode from terminal with `code ` causes VSCode - // to inherit environment variables including $PATH, $CARGO, $RUSTC, etc from that terminal; - // but launching VSCode from Dock does not inherit environment variables from a terminal. - // For more discussion, see #3118. - Error::msg(format!("Failed to find `{}` executable. Make sure `{}` is in `$PATH`, or set `${}` to point to a valid executable.", executable_name, executable_name, env_var)) - ) - } -} - -/// Does the given `Path` point to a usable executable? -/// -/// (assumes the executable takes a `--version` switch and writes to stdout, -/// which is true for `cargo`, `rustc`, and `rustup`) -fn is_valid_executable(p: impl AsRef) -> bool { - Command::new(p.as_ref()).arg("--version").output().is_ok() -} diff --git a/crates/ra_project_model/src/lib.rs b/crates/ra_project_model/src/lib.rs index 5028b6b6d..e4b86f1e2 100644 --- a/crates/ra_project_model/src/lib.rs +++ b/crates/ra_project_model/src/lib.rs @@ -1,7 +1,6 @@ //! FIXME: write short doc here mod cargo_workspace; -mod find_executables; mod json_project; mod sysroot; @@ -15,6 +14,7 @@ use std::{ use anyhow::{bail, Context, Result}; use ra_cfg::CfgOptions; use ra_db::{CrateGraph, CrateName, Edition, Env, ExternSource, ExternSourceId, FileId}; +use ra_env::get_path_for_executable; use rustc_hash::FxHashMap; use serde_json::from_reader; @@ -559,7 +559,7 @@ pub fn get_rustc_cfg_options(target: Option<&String>) -> CfgOptions { match (|| -> Result { // `cfg(test)` and `cfg(debug_assertion)` are handled outside, so we suppress them here. - let mut cmd = Command::new("rustc"); + let mut cmd = Command::new(get_path_for_executable("rustc")?); cmd.args(&["--print", "cfg", "-O"]); if let Some(target) = target { 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 8d68032b2..516e0472d 100644 --- a/crates/ra_project_model/src/sysroot.rs +++ b/crates/ra_project_model/src/sysroot.rs @@ -1,6 +1,5 @@ //! FIXME: write short doc here -use super::find_executables::get_path_for_executable; use anyhow::{bail, Context, Result}; use std::{ env, ops, @@ -9,6 +8,7 @@ use std::{ }; use ra_arena::{Arena, Idx}; +use ra_env::get_path_for_executable; #[derive(Default, Debug, Clone)] pub struct Sysroot { @@ -122,7 +122,8 @@ fn get_or_install_rust_src(cargo_toml: &Path) -> Result { let src_path = sysroot_path.join("lib/rustlib/src/rust/src"); if !src_path.exists() { - run_command_in_cargo_dir(cargo_toml, "rustup", &["component", "add", "rust-src"])?; + let rustup = get_path_for_executable("rustup")?; + run_command_in_cargo_dir(cargo_toml, &rustup, &["component", "add", "rust-src"])?; } if !src_path.exists() { bail!( -- cgit v1.2.3