From 2980ba1fde50a6fc8863750b9dd7f09e3c1227ce Mon Sep 17 00:00:00 2001 From: robojumper Date: Mon, 4 May 2020 13:29:09 +0200 Subject: Support build.rs cargo:rustc-cfg --- crates/ra_project_model/src/cargo_workspace.rs | 10 ++++++++-- crates/ra_project_model/src/lib.rs | 7 +++++++ 2 files changed, 15 insertions(+), 2 deletions(-) (limited to 'crates/ra_project_model') diff --git a/crates/ra_project_model/src/cargo_workspace.rs b/crates/ra_project_model/src/cargo_workspace.rs index 362ee30fe..afbd30164 100644 --- a/crates/ra_project_model/src/cargo_workspace.rs +++ b/crates/ra_project_model/src/cargo_workspace.rs @@ -83,6 +83,7 @@ pub struct PackageData { pub dependencies: Vec, pub edition: Edition, pub features: Vec, + pub cfgs: Vec, pub out_dir: Option, pub proc_macro_dylib_path: Option, } @@ -165,10 +166,12 @@ impl CargoWorkspace { })?; let mut out_dir_by_id = FxHashMap::default(); + let mut cfgs = FxHashMap::default(); let mut proc_macro_dylib_paths = FxHashMap::default(); if cargo_features.load_out_dirs_from_check { let resources = load_extern_resources(cargo_toml, cargo_features)?; out_dir_by_id = resources.out_dirs; + cfgs = resources.cfgs; proc_macro_dylib_paths = resources.proc_dylib_paths; } @@ -194,6 +197,7 @@ impl CargoWorkspace { edition, dependencies: Vec::new(), features: Vec::new(), + cfgs: cfgs.get(&id).cloned().unwrap_or_default(), out_dir: out_dir_by_id.get(&id).cloned(), proc_macro_dylib_path: proc_macro_dylib_paths.get(&id).cloned(), }); @@ -275,6 +279,7 @@ impl CargoWorkspace { pub struct ExternResources { out_dirs: FxHashMap, proc_dylib_paths: FxHashMap, + cfgs: FxHashMap>, } pub fn load_extern_resources( @@ -300,8 +305,9 @@ pub fn load_extern_resources( for message in cargo_metadata::parse_messages(output.stdout.as_slice()) { if let Ok(message) = message { match message { - Message::BuildScriptExecuted(BuildScript { package_id, out_dir, .. }) => { - res.out_dirs.insert(package_id, out_dir); + Message::BuildScriptExecuted(BuildScript { package_id, out_dir, cfgs, .. }) => { + res.out_dirs.insert(package_id.clone(), out_dir); + res.cfgs.insert(package_id, cfgs); } Message::CompilerArtifact(message) => { diff --git a/crates/ra_project_model/src/lib.rs b/crates/ra_project_model/src/lib.rs index 731cbd291..2d5d61b61 100644 --- a/crates/ra_project_model/src/lib.rs +++ b/crates/ra_project_model/src/lib.rs @@ -399,6 +399,13 @@ impl ProjectWorkspace { let cfg_options = { let mut opts = default_cfg_options.clone(); opts.insert_features(cargo[pkg].features.iter().map(Into::into)); + opts.insert_cfgs( + cargo[pkg] + .cfgs + .iter() + .filter_map(|c| c.to_str()) + .map(Into::into), + ); opts }; let mut env = Env::default(); -- cgit v1.2.3 From f2dd233ddc60b647fe9c32ea2d712224005ae99e Mon Sep 17 00:00:00 2001 From: robojumper Date: Tue, 5 May 2020 14:53:52 +0200 Subject: Assume cargo_metadata uses String for cfgs soon --- crates/ra_project_model/src/cargo_workspace.rs | 11 ++++++++--- crates/ra_project_model/src/lib.rs | 8 +------- 2 files changed, 9 insertions(+), 10 deletions(-) (limited to 'crates/ra_project_model') diff --git a/crates/ra_project_model/src/cargo_workspace.rs b/crates/ra_project_model/src/cargo_workspace.rs index afbd30164..bf83adc42 100644 --- a/crates/ra_project_model/src/cargo_workspace.rs +++ b/crates/ra_project_model/src/cargo_workspace.rs @@ -83,7 +83,7 @@ pub struct PackageData { pub dependencies: Vec, pub edition: Edition, pub features: Vec, - pub cfgs: Vec, + pub cfgs: Vec, pub out_dir: Option, pub proc_macro_dylib_path: Option, } @@ -279,7 +279,7 @@ impl CargoWorkspace { pub struct ExternResources { out_dirs: FxHashMap, proc_dylib_paths: FxHashMap, - cfgs: FxHashMap>, + cfgs: FxHashMap>, } pub fn load_extern_resources( @@ -307,7 +307,12 @@ pub fn load_extern_resources( match message { Message::BuildScriptExecuted(BuildScript { package_id, out_dir, cfgs, .. }) => { res.out_dirs.insert(package_id.clone(), out_dir); - res.cfgs.insert(package_id, cfgs); + res.cfgs.insert( + package_id, + // FIXME: Current `cargo_metadata` uses `PathBuf` instead of `String`, + // change when https://github.com/oli-obk/cargo_metadata/pulls/112 reaches crates.io + cfgs.iter().filter_map(|c| c.to_str().map(|s| s.to_owned())).collect(), + ); } Message::CompilerArtifact(message) => { diff --git a/crates/ra_project_model/src/lib.rs b/crates/ra_project_model/src/lib.rs index 2d5d61b61..7231da221 100644 --- a/crates/ra_project_model/src/lib.rs +++ b/crates/ra_project_model/src/lib.rs @@ -399,13 +399,7 @@ impl ProjectWorkspace { let cfg_options = { let mut opts = default_cfg_options.clone(); opts.insert_features(cargo[pkg].features.iter().map(Into::into)); - opts.insert_cfgs( - cargo[pkg] - .cfgs - .iter() - .filter_map(|c| c.to_str()) - .map(Into::into), - ); + opts.insert_cfgs(cargo[pkg].cfgs.iter().map(Into::into)); opts }; let mut env = Env::default(); -- cgit v1.2.3 From ffaef1b7aeb61984992e231d9af20f39486403ea Mon Sep 17 00:00:00 2001 From: Craig Disselkoen Date: Tue, 5 May 2020 11:59:41 -0700 Subject: ra_project_model: look for Cargo in more places See #3118 --- crates/ra_project_model/Cargo.toml | 2 + crates/ra_project_model/src/cargo_workspace.rs | 59 ++++++++++++++++++++++---- 2 files changed, 52 insertions(+), 9 deletions(-) (limited to 'crates/ra_project_model') diff --git a/crates/ra_project_model/Cargo.toml b/crates/ra_project_model/Cargo.toml index 5e651fe70..91958ed94 100644 --- a/crates/ra_project_model/Cargo.toml +++ b/crates/ra_project_model/Cargo.toml @@ -22,3 +22,5 @@ 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 59f46a2a0..a15a8c68e 100644 --- a/crates/ra_project_model/src/cargo_workspace.rs +++ b/crates/ra_project_model/src/cargo_workspace.rs @@ -8,7 +8,7 @@ use std::{ process::Command, }; -use anyhow::{Context, Result}; +use anyhow::{Context, Error, Result}; use cargo_metadata::{BuildScript, CargoOpt, Message, MetadataCommand, PackageId}; use ra_arena::{Arena, Idx}; use ra_db::Edition; @@ -145,12 +145,8 @@ impl CargoWorkspace { cargo_toml: &Path, cargo_features: &CargoConfig, ) -> Result { - let _ = Command::new(cargo_binary()) - .arg("--version") - .output() - .context("failed to run `cargo --version`, is `cargo` in PATH?")?; - let mut meta = MetadataCommand::new(); + meta.cargo_path(cargo_binary()?); meta.manifest_path(cargo_toml); if cargo_features.all_features { meta.features(CargoOpt::AllFeatures); @@ -288,7 +284,7 @@ pub fn load_extern_resources( cargo_toml: &Path, cargo_features: &CargoConfig, ) -> Result { - let mut cmd = Command::new(cargo_binary()); + let mut cmd = Command::new(cargo_binary()?); cmd.args(&["check", "--message-format=json", "--manifest-path"]).arg(cargo_toml); if cargo_features.all_features { cmd.arg("--all-features"); @@ -337,6 +333,51 @@ fn is_dylib(path: &Path) -> bool { } } -fn cargo_binary() -> String { - env::var("CARGO").unwrap_or_else(|_| "cargo".to_string()) +/// Return a `String` to use for executable `cargo`. +/// +/// E.g., this may just be `cargo` if that gives a valid Cargo executable; or it +/// may be a full path to a valid Cargo. +fn cargo_binary() -> Result { + // The current implementation checks three places for a `cargo` to use: + // 1) $CARGO environment variable (erroring if this is set but not a usable Cargo) + // 2) `cargo` + // 3) `~/.cargo/bin/cargo` + if let Ok(path) = env::var("CARGO") { + if is_valid_cargo(&path) { + Ok(path) + } else { + Err(Error::msg("`CARGO` environment variable points to something that's not a valid Cargo executable")) + } + } else { + let final_path: Option = if is_valid_cargo("cargo") { + Some("cargo".to_owned()) + } else { + if let Some(mut path) = dirs::home_dir() { + path.push(".cargo"); + path.push("bin"); + path.push("cargo"); + if is_valid_cargo(&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 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 and $CARGO from that terminal; but + // launching VSCode from Dock does not inherit environment variables from a terminal. + // For more discussion, see #3118. + Error::msg("Failed to find `cargo` executable. Make sure `cargo` is in `$PATH`, or set `$CARGO` to point to a valid Cargo executable.") + ) + } +} + +/// Does the given `Path` point to a usable `Cargo`? +fn is_valid_cargo(p: impl AsRef) -> bool { + Command::new(p.as_ref()).arg("--version").output().is_ok() } -- cgit v1.2.3 From 5aa1bba107ef434e61c3136120b9478a307d67a9 Mon Sep 17 00:00:00 2001 From: Craig Disselkoen Date: Tue, 5 May 2020 13:44:43 -0700 Subject: more generic, find rustc as well --- crates/ra_project_model/src/cargo_workspace.rs | 57 ++-------------------- crates/ra_project_model/src/find_executables.rs | 63 +++++++++++++++++++++++++ crates/ra_project_model/src/lib.rs | 1 + crates/ra_project_model/src/sysroot.rs | 4 +- 4 files changed, 71 insertions(+), 54 deletions(-) create mode 100644 crates/ra_project_model/src/find_executables.rs (limited to 'crates/ra_project_model') diff --git a/crates/ra_project_model/src/cargo_workspace.rs b/crates/ra_project_model/src/cargo_workspace.rs index a15a8c68e..c7350d1e0 100644 --- a/crates/ra_project_model/src/cargo_workspace.rs +++ b/crates/ra_project_model/src/cargo_workspace.rs @@ -1,14 +1,14 @@ //! FIXME: write short doc here use std::{ - env, ffi::OsStr, ops, path::{Path, PathBuf}, process::Command, }; -use anyhow::{Context, Error, Result}; +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; @@ -146,7 +146,7 @@ impl CargoWorkspace { cargo_features: &CargoConfig, ) -> Result { let mut meta = MetadataCommand::new(); - meta.cargo_path(cargo_binary()?); + meta.cargo_path(get_path_for_executable("cargo")?); meta.manifest_path(cargo_toml); if cargo_features.all_features { meta.features(CargoOpt::AllFeatures); @@ -284,7 +284,7 @@ pub fn load_extern_resources( cargo_toml: &Path, cargo_features: &CargoConfig, ) -> Result { - let mut cmd = Command::new(cargo_binary()?); + let mut cmd = Command::new(get_path_for_executable("cargo")?); cmd.args(&["check", "--message-format=json", "--manifest-path"]).arg(cargo_toml); if cargo_features.all_features { cmd.arg("--all-features"); @@ -332,52 +332,3 @@ fn is_dylib(path: &Path) -> bool { Some(ext) => matches!(ext.as_str(), "dll" | "dylib" | "so"), } } - -/// Return a `String` to use for executable `cargo`. -/// -/// E.g., this may just be `cargo` if that gives a valid Cargo executable; or it -/// may be a full path to a valid Cargo. -fn cargo_binary() -> Result { - // The current implementation checks three places for a `cargo` to use: - // 1) $CARGO environment variable (erroring if this is set but not a usable Cargo) - // 2) `cargo` - // 3) `~/.cargo/bin/cargo` - if let Ok(path) = env::var("CARGO") { - if is_valid_cargo(&path) { - Ok(path) - } else { - Err(Error::msg("`CARGO` environment variable points to something that's not a valid Cargo executable")) - } - } else { - let final_path: Option = if is_valid_cargo("cargo") { - Some("cargo".to_owned()) - } else { - if let Some(mut path) = dirs::home_dir() { - path.push(".cargo"); - path.push("bin"); - path.push("cargo"); - if is_valid_cargo(&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 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 and $CARGO from that terminal; but - // launching VSCode from Dock does not inherit environment variables from a terminal. - // For more discussion, see #3118. - Error::msg("Failed to find `cargo` executable. Make sure `cargo` is in `$PATH`, or set `$CARGO` to point to a valid Cargo executable.") - ) - } -} - -/// Does the given `Path` point to a usable `Cargo`? -fn is_valid_cargo(p: impl AsRef) -> bool { - Command::new(p.as_ref()).arg("--version").output().is_ok() -} diff --git a/crates/ra_project_model/src/find_executables.rs b/crates/ra_project_model/src/find_executables.rs new file mode 100644 index 000000000..9b020d3da --- /dev/null +++ b/crates/ra_project_model/src/find_executables.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` 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 c2b33c1dc..5028b6b6d 100644 --- a/crates/ra_project_model/src/lib.rs +++ b/crates/ra_project_model/src/lib.rs @@ -1,6 +1,7 @@ //! FIXME: write short doc here mod cargo_workspace; +mod find_executables; mod json_project; mod sysroot; diff --git a/crates/ra_project_model/src/sysroot.rs b/crates/ra_project_model/src/sysroot.rs index 55ff5ad80..8d68032b2 100644 --- a/crates/ra_project_model/src/sysroot.rs +++ b/crates/ra_project_model/src/sysroot.rs @@ -1,5 +1,6 @@ //! FIXME: write short doc here +use super::find_executables::get_path_for_executable; use anyhow::{bail, Context, Result}; use std::{ env, ops, @@ -114,7 +115,8 @@ fn get_or_install_rust_src(cargo_toml: &Path) -> Result { if let Ok(path) = env::var("RUST_SRC_PATH") { return Ok(path.into()); } - let rustc_output = run_command_in_cargo_dir(cargo_toml, "rustc", &["--print", "sysroot"])?; + let rustc = get_path_for_executable("rustc")?; + let rustc_output = run_command_in_cargo_dir(cargo_toml, &rustc, &["--print", "sysroot"])?; let stdout = String::from_utf8(rustc_output.stdout)?; let sysroot_path = Path::new(stdout.trim()); let src_path = sysroot_path.join("lib/rustlib/src/rust/src"); -- cgit v1.2.3 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 --- 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 +- 5 files changed, 8 insertions(+), 71 deletions(-) delete mode 100644 crates/ra_project_model/src/find_executables.rs (limited to 'crates/ra_project_model') 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 From 44b01ccff3d993daae237c75d466050711d06268 Mon Sep 17 00:00:00 2001 From: Craig Disselkoen Date: Wed, 6 May 2020 12:39:11 -0700 Subject: return a PathBuf instead of String --- crates/ra_project_model/src/sysroot.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'crates/ra_project_model') diff --git a/crates/ra_project_model/src/sysroot.rs b/crates/ra_project_model/src/sysroot.rs index 516e0472d..ed374f241 100644 --- a/crates/ra_project_model/src/sysroot.rs +++ b/crates/ra_project_model/src/sysroot.rs @@ -89,9 +89,10 @@ fn create_command_text(program: &str, args: &[&str]) -> String { format!("{} {}", program, args.join(" ")) } -fn run_command_in_cargo_dir(cargo_toml: &Path, program: &str, args: &[&str]) -> Result { +fn run_command_in_cargo_dir(cargo_toml: impl AsRef, program: impl AsRef, args: &[&str]) -> Result { + let program = program.as_ref().as_os_str().to_str().expect("Invalid Unicode in path"); let output = Command::new(program) - .current_dir(cargo_toml.parent().unwrap()) + .current_dir(cargo_toml.as_ref().parent().unwrap()) .args(args) .output() .context(format!("{} failed", create_command_text(program, args)))?; -- cgit v1.2.3 From 5d4648884baf591fe8f53e8ceae6d559564e9797 Mon Sep 17 00:00:00 2001 From: Craig Disselkoen Date: Wed, 6 May 2020 12:47:13 -0700 Subject: cargo fmt --- crates/ra_project_model/src/sysroot.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'crates/ra_project_model') diff --git a/crates/ra_project_model/src/sysroot.rs b/crates/ra_project_model/src/sysroot.rs index ed374f241..11c26ad89 100644 --- a/crates/ra_project_model/src/sysroot.rs +++ b/crates/ra_project_model/src/sysroot.rs @@ -89,7 +89,11 @@ fn create_command_text(program: &str, args: &[&str]) -> String { format!("{} {}", program, args.join(" ")) } -fn run_command_in_cargo_dir(cargo_toml: impl AsRef, program: impl AsRef, args: &[&str]) -> Result { +fn run_command_in_cargo_dir( + cargo_toml: impl AsRef, + program: impl AsRef, + args: &[&str], +) -> Result { let program = program.as_ref().as_os_str().to_str().expect("Invalid Unicode in path"); let output = Command::new(program) .current_dir(cargo_toml.as_ref().parent().unwrap()) -- cgit v1.2.3 From d3110859ba4e97cf17d2c997befa92fb63bfb138 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Fri, 8 May 2020 02:56:53 +0200 Subject: Move feature desugaring to the right abstraction layer --- crates/ra_project_model/src/lib.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) (limited to 'crates/ra_project_model') diff --git a/crates/ra_project_model/src/lib.rs b/crates/ra_project_model/src/lib.rs index 8703429d4..c226ffa57 100644 --- a/crates/ra_project_model/src/lib.rs +++ b/crates/ra_project_model/src/lib.rs @@ -398,8 +398,18 @@ impl ProjectWorkspace { let edition = cargo[pkg].edition; let cfg_options = { let mut opts = default_cfg_options.clone(); - opts.insert_features(cargo[pkg].features.iter().map(Into::into)); - opts.insert_cfgs(cargo[pkg].cfgs.iter().map(Into::into)); + for feature in cargo[pkg].features.iter() { + opts.insert_key_value("feature".into(), feature.into()); + } + for cfg in cargo[pkg].cfgs.iter() { + match cfg.find('=') { + Some(split) => opts.insert_key_value( + cfg[..split].into(), + cfg[split + 1..].trim_matches('"').into(), + ), + None => opts.insert_atom(cfg.into()), + }; + } opts }; let mut env = Env::default(); -- cgit v1.2.3 From 6713be0b130670324c61d9deb38b7b6aee6a8bac Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Fri, 8 May 2020 12:25:36 +0200 Subject: Rename ra_env -> ra_toolchain --- crates/ra_project_model/Cargo.toml | 2 +- crates/ra_project_model/src/cargo_workspace.rs | 2 +- crates/ra_project_model/src/lib.rs | 2 +- crates/ra_project_model/src/sysroot.rs | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) (limited to 'crates/ra_project_model') diff --git a/crates/ra_project_model/Cargo.toml b/crates/ra_project_model/Cargo.toml index 626478468..a32a5daab 100644 --- a/crates/ra_project_model/Cargo.toml +++ b/crates/ra_project_model/Cargo.toml @@ -16,7 +16,7 @@ cargo_metadata = "0.9.1" ra_arena = { path = "../ra_arena" } ra_cfg = { path = "../ra_cfg" } ra_db = { path = "../ra_db" } -ra_env = { path = "../ra_env" } +ra_toolchain = { path = "../ra_toolchain" } ra_proc_macro = { path = "../ra_proc_macro" } 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 eb9f33ee8..9683bfcc0 100644 --- a/crates/ra_project_model/src/cargo_workspace.rs +++ b/crates/ra_project_model/src/cargo_workspace.rs @@ -11,7 +11,7 @@ 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 ra_toolchain::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/lib.rs b/crates/ra_project_model/src/lib.rs index 88a6ffb2a..4f0b9c77e 100644 --- a/crates/ra_project_model/src/lib.rs +++ b/crates/ra_project_model/src/lib.rs @@ -14,7 +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 ra_toolchain::get_path_for_executable; use rustc_hash::FxHashMap; use serde_json::from_reader; diff --git a/crates/ra_project_model/src/sysroot.rs b/crates/ra_project_model/src/sysroot.rs index 11c26ad89..2b628c2a3 100644 --- a/crates/ra_project_model/src/sysroot.rs +++ b/crates/ra_project_model/src/sysroot.rs @@ -1,14 +1,14 @@ //! FIXME: write short doc here -use anyhow::{bail, Context, Result}; use std::{ env, ops, path::{Path, PathBuf}, process::{Command, Output}, }; +use anyhow::{bail, Context, Result}; use ra_arena::{Arena, Idx}; -use ra_env::get_path_for_executable; +use ra_toolchain::get_path_for_executable; #[derive(Default, Debug, Clone)] pub struct Sysroot { -- cgit v1.2.3 From ecff5dc141046c5b9e40639657247a05fb9b0344 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Fri, 8 May 2020 14:54:29 +0200 Subject: Cleanup --- crates/ra_project_model/src/cargo_workspace.rs | 5 ++- crates/ra_project_model/src/lib.rs | 32 ++++++++--------- crates/ra_project_model/src/sysroot.rs | 49 ++++++-------------------- 3 files changed, 29 insertions(+), 57 deletions(-) (limited to 'crates/ra_project_model') 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}; use cargo_metadata::{BuildScript, CargoOpt, Message, MetadataCommand, PackageId}; use ra_arena::{Arena, Idx}; use ra_db::Edition; -use ra_toolchain::get_path_for_executable; use rustc_hash::FxHashMap; /// `CargoWorkspace` represents the logical structure of, well, a Cargo @@ -147,7 +146,7 @@ impl CargoWorkspace { cargo_features: &CargoConfig, ) -> Result { let mut meta = MetadataCommand::new(); - meta.cargo_path(get_path_for_executable("cargo")?); + meta.cargo_path(ra_toolchain::cargo()); meta.manifest_path(cargo_toml); if cargo_features.all_features { meta.features(CargoOpt::AllFeatures); @@ -289,7 +288,7 @@ pub fn load_extern_resources( cargo_toml: &Path, cargo_features: &CargoConfig, ) -> Result { - let mut cmd = Command::new(get_path_for_executable("cargo")?); + let mut cmd = Command::new(ra_toolchain::cargo()); cmd.args(&["check", "--message-format=json", "--manifest-path"]).arg(cargo_toml); if cargo_features.all_features { 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::{ fs::{read_dir, File, ReadDir}, io::{self, BufReader}, path::{Path, PathBuf}, - process::Command, + process::{Command, Output}, }; use anyhow::{bail, Context, Result}; use ra_cfg::CfgOptions; use ra_db::{CrateGraph, CrateName, Edition, Env, ExternSource, ExternSourceId, FileId}; -use ra_toolchain::get_path_for_executable; use rustc_hash::FxHashMap; use serde_json::from_reader; @@ -568,25 +567,18 @@ pub fn get_rustc_cfg_options(target: Option<&String>) -> CfgOptions { } } - match (|| -> Result { + let rustc_cfgs = || -> Result { // `cfg(test)` and `cfg(debug_assertion)` are handled outside, so we suppress them here. - let mut cmd = Command::new(get_path_for_executable("rustc")?); + let mut cmd = Command::new(ra_toolchain::rustc()); cmd.args(&["--print", "cfg", "-O"]); if let Some(target) = target { cmd.args(&["--target", target.as_str()]); } - let output = cmd.output().context("Failed to get output from rustc --print cfg -O")?; - if !output.status.success() { - bail!( - "rustc --print cfg -O exited with exit code ({})", - output - .status - .code() - .map_or(String::from("no exit code"), |code| format!("{}", code)) - ); - } + let output = output(cmd)?; Ok(String::from_utf8(output.stdout)?) - })() { + }(); + + match rustc_cfgs { Ok(rustc_cfgs) => { for line in rustc_cfgs.lines() { match line.find('=') { @@ -599,8 +591,16 @@ pub fn get_rustc_cfg_options(target: Option<&String>) -> CfgOptions { } } } - Err(e) => log::error!("failed to get rustc cfgs: {}", e), + Err(e) => log::error!("failed to get rustc cfgs: {:#}", e), } cfg_options } + +fn output(mut cmd: Command) -> Result { + let output = cmd.output().with_context(|| format!("{:?} failed", cmd))?; + if !output.status.success() { + bail!("{:?} failed, {}", cmd, output.status) + } + Ok(output) +} 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 @@ use std::{ env, ops, path::{Path, PathBuf}, - process::{Command, Output}, + process::Command, }; -use anyhow::{bail, Context, Result}; +use anyhow::{bail, Result}; use ra_arena::{Arena, Idx}; -use ra_toolchain::get_path_for_executable; + +use crate::output; #[derive(Default, Debug, Clone)] pub struct Sysroot { @@ -85,50 +86,22 @@ impl Sysroot { } } -fn create_command_text(program: &str, args: &[&str]) -> String { - format!("{} {}", program, args.join(" ")) -} - -fn run_command_in_cargo_dir( - cargo_toml: impl AsRef, - program: impl AsRef, - args: &[&str], -) -> Result { - let program = program.as_ref().as_os_str().to_str().expect("Invalid Unicode in path"); - let output = Command::new(program) - .current_dir(cargo_toml.as_ref().parent().unwrap()) - .args(args) - .output() - .context(format!("{} failed", create_command_text(program, args)))?; - if !output.status.success() { - match output.status.code() { - Some(code) => bail!( - "failed to run the command: '{}' exited with code {}", - create_command_text(program, args), - code - ), - None => bail!( - "failed to run the command: '{}' terminated by signal", - create_command_text(program, args) - ), - }; - } - Ok(output) -} - fn get_or_install_rust_src(cargo_toml: &Path) -> Result { if let Ok(path) = env::var("RUST_SRC_PATH") { return Ok(path.into()); } - let rustc = get_path_for_executable("rustc")?; - let rustc_output = run_command_in_cargo_dir(cargo_toml, &rustc, &["--print", "sysroot"])?; + let current_dir = cargo_toml.parent().unwrap(); + let mut rustc = Command::new(ra_toolchain::rustc()); + rustc.current_dir(current_dir).args(&["--print", "sysroot"]); + let rustc_output = output(rustc)?; let stdout = String::from_utf8(rustc_output.stdout)?; let sysroot_path = Path::new(stdout.trim()); let src_path = sysroot_path.join("lib/rustlib/src/rust/src"); if !src_path.exists() { - let rustup = get_path_for_executable("rustup")?; - run_command_in_cargo_dir(cargo_toml, &rustup, &["component", "add", "rust-src"])?; + let mut rustup = Command::new(ra_toolchain::rustup()); + rustup.current_dir(current_dir).args(&["component", "add", "rust-src"]); + let _output = output(rustup)?; } if !src_path.exists() { bail!( -- cgit v1.2.3 From f739e0119c0d74c155f91ad27616a638fe494e2d Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Fri, 8 May 2020 18:53:53 +0200 Subject: Add stderr to error message --- crates/ra_project_model/src/lib.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'crates/ra_project_model') diff --git a/crates/ra_project_model/src/lib.rs b/crates/ra_project_model/src/lib.rs index 5a0a87ed7..3adb8baf6 100644 --- a/crates/ra_project_model/src/lib.rs +++ b/crates/ra_project_model/src/lib.rs @@ -600,7 +600,12 @@ pub fn get_rustc_cfg_options(target: Option<&String>) -> CfgOptions { fn output(mut cmd: Command) -> Result { let output = cmd.output().with_context(|| format!("{:?} failed", cmd))?; if !output.status.success() { - bail!("{:?} failed, {}", cmd, output.status) + match String::from_utf8(output.stderr) { + Ok(stderr) if !stderr.is_empty() => { + bail!("{:?} failed, {}\nstderr:\n{}", cmd, output.status, stderr) + } + _ => bail!("{:?} failed, {}", cmd, output.status), + } } Ok(output) } -- cgit v1.2.3 From e83a2912b8deaab560d1ea39232c06a29530d6e5 Mon Sep 17 00:00:00 2001 From: veetaha Date: Sat, 9 May 2020 02:51:59 +0300 Subject: Simpify project discovery --- crates/ra_project_model/src/lib.rs | 51 +++++++++++--------------------------- 1 file changed, 15 insertions(+), 36 deletions(-) (limited to 'crates/ra_project_model') diff --git a/crates/ra_project_model/src/lib.rs b/crates/ra_project_model/src/lib.rs index 3adb8baf6..4f098b706 100644 --- a/crates/ra_project_model/src/lib.rs +++ b/crates/ra_project_model/src/lib.rs @@ -88,46 +88,28 @@ impl ProjectRoot { } pub fn discover(path: &Path) -> io::Result> { - if let Some(project_json) = find_rust_project_json(path) { + if let Some(project_json) = find_in_parent_dirs(path, "rust-project.json") { return Ok(vec![ProjectRoot::ProjectJson(project_json)]); } return find_cargo_toml(path) .map(|paths| paths.into_iter().map(ProjectRoot::CargoToml).collect()); - fn find_rust_project_json(path: &Path) -> Option { - if path.ends_with("rust-project.json") { - return Some(path.to_path_buf()); - } - - let mut curr = Some(path); - while let Some(path) = curr { - let candidate = path.join("rust-project.json"); - if candidate.exists() { - return Some(candidate); - } - curr = path.parent(); - } - - None - } - fn find_cargo_toml(path: &Path) -> io::Result> { - if path.ends_with("Cargo.toml") { - return Ok(vec![path.to_path_buf()]); + match find_in_parent_dirs(path, "Cargo.toml") { + Some(it) => Ok(vec![it]), + None => Ok(find_cargo_toml_in_child_dir(read_dir(path)?)), } + } - if let Some(p) = find_cargo_toml_in_parent_dir(path) { - return Ok(vec![p]); + fn find_in_parent_dirs(path: &Path, target_file_name: &str) -> Option { + if path.ends_with(target_file_name) { + return Some(path.to_owned()); } - let entities = read_dir(path)?; - Ok(find_cargo_toml_in_child_dir(entities)) - } - - fn find_cargo_toml_in_parent_dir(path: &Path) -> Option { let mut curr = Some(path); + while let Some(path) = curr { - let candidate = path.join("Cargo.toml"); + let candidate = path.join(target_file_name); if candidate.exists() { return Some(candidate); } @@ -139,14 +121,11 @@ impl ProjectRoot { fn find_cargo_toml_in_child_dir(entities: ReadDir) -> Vec { // Only one level down to avoid cycles the easy way and stop a runaway scan with large projects - let mut valid_canditates = vec![]; - for entity in entities.filter_map(Result::ok) { - let candidate = entity.path().join("Cargo.toml"); - if candidate.exists() { - valid_canditates.push(candidate) - } - } - valid_canditates + entities + .filter_map(Result::ok) + .map(|it| it.path().join("Cargo.toml")) + .filter(|it| it.exists()) + .collect() } } } -- cgit v1.2.3