Skip to content
This repository was archived by the owner on Dec 29, 2022. It is now read-only.

Update cargo #635

Merged
merged 3 commits into from
Dec 22, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 36 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ build = "build.rs"
[dependencies]
cargo = { git = "https://github.com/rust-lang/cargo" }
env_logger = "0.4"
failure = "0.1.1"
jsonrpc-core = "7.0.1"
languageserver-types = "0.16"
lazy_static = "0.2"
Expand Down
18 changes: 7 additions & 11 deletions src/actions/post_build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,19 +56,19 @@ impl PostBuildHandler {
self.notifier.notify_begin();

match result {
BuildResult::Success(messages, new_analysis) => {
BuildResult::Success(cwd, messages, new_analysis) => {
thread::spawn(move || {
trace!("build - Success");

// Emit appropriate diagnostics using the ones from build.
self.handle_messages(messages);
self.handle_messages(&cwd, messages);

// Reload the analysis data.
debug!("reload analysis: {:?}", self.project_path);
if new_analysis.is_empty() {
self.reload_analysis_from_disk();
self.reload_analysis_from_disk(&cwd);
} else {
self.reload_analysis_from_memory(new_analysis);
self.reload_analysis_from_memory(&cwd, new_analysis);
}

// Wake up any threads blocked on this analysis.
Expand All @@ -90,7 +90,7 @@ impl PostBuildHandler {
}
}

fn handle_messages(&self, messages: Vec<String>) {
fn handle_messages(&self, cwd: &Path, messages: Vec<String>) {
// These notifications will include empty sets of errors for files
// which had errors, but now don't. This instructs the IDE to clear
// errors for those files.
Expand All @@ -101,8 +101,6 @@ impl PostBuildHandler {
v.clear();
}

let cwd = ::std::env::current_dir().unwrap();

for msg in &messages {
if let Some(FileDiagnostic {
file_path,
Expand All @@ -119,8 +117,7 @@ impl PostBuildHandler {
self.emit_notifications(&results);
}

fn reload_analysis_from_disk(&self) {
let cwd = ::std::env::current_dir().unwrap();
fn reload_analysis_from_disk(&self, cwd: &Path) {
if self.use_black_list {
self.analysis
.reload_with_blacklist(&self.project_path, &cwd, &CRATE_BLACKLIST)
Expand All @@ -130,8 +127,7 @@ impl PostBuildHandler {
}
}

fn reload_analysis_from_memory(&self, analysis: Vec<Analysis>) {
let cwd = ::std::env::current_dir().unwrap();
fn reload_analysis_from_memory(&self, cwd: &Path, analysis: Vec<Analysis>) {
if self.use_black_list {
self.analysis
.reload_from_analysis(analysis, &self.project_path, &cwd, &CRATE_BLACKLIST)
Expand Down
44 changes: 24 additions & 20 deletions src/build/cargo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use std::collections::{BTreeMap, HashMap, HashSet};
use std::env;
use std::ffi::OsString;
use std::fs::{read_dir, remove_file};
use std::path::Path;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::{Arc, Mutex};
use std::thread;
Expand Down Expand Up @@ -64,10 +64,10 @@ pub(super) fn cargo(internals: &Internals) -> BuildResult {

match handle
.join()
.map_err(|_| "thread panicked".into())
.map_err(|_| format_err!("thread panicked"))
.and_then(|res| res)
{
Ok(_) if workspace_mode => {
Ok(ref cwd) if workspace_mode => {
let diagnostics = Arc::try_unwrap(diagnostics_clone)
.unwrap()
.into_inner()
Expand All @@ -76,9 +76,9 @@ pub(super) fn cargo(internals: &Internals) -> BuildResult {
.unwrap()
.into_inner()
.unwrap();
BuildResult::Success(diagnostics, analysis)
BuildResult::Success(cwd.clone(), diagnostics, analysis)
}
Ok(_) => BuildResult::Success(vec![], vec![]),
Ok(cwd) => BuildResult::Success(cwd, vec![], vec![]),
Err(err) => {
let stdout = String::from_utf8(out_clone.lock().unwrap().to_owned()).unwrap();
info!("cargo failed\ncause: {}\nstdout: {}", err, stdout);
Expand All @@ -95,13 +95,15 @@ fn run_cargo(
compiler_messages: Arc<Mutex<Vec<String>>>,
analysis: Arc<Mutex<Vec<Analysis>>>,
out: Arc<Mutex<Vec<u8>>>,
) -> CargoResult<()> {
) -> CargoResult<PathBuf> {
// Lock early to guarantee synchronized access to env var for the scope of Cargo routine.
// Additionally we need to pass inner lock to RlsExecutor, since it needs to hand it down
// during exec() callback when calling linked compiler in parallel, for which we need to
// guarantee consistent environment variables.
let (lock_guard, inner_lock) = env_lock.lock();

let mut restore_env = Environment::push_with_lock(&HashMap::new(), None, lock_guard);

let build_dir = {
let mut compilation_cx = compilation_cx.lock().unwrap();
// Since Cargo build routine will try to regenerate the unit dep graph,
Expand All @@ -123,7 +125,7 @@ fn run_cargo(
let rls_config = rls_config.lock().unwrap();

let target_dir = rls_config.target_dir.as_ref().map(|p| p as &Path);
make_cargo_config(manifest_dir, target_dir, shell)
make_cargo_config(manifest_dir, target_dir, restore_env.get_old_cwd(), shell)
};

let ws = Workspace::new(&manifest_path, &config)?;
Expand Down Expand Up @@ -186,16 +188,14 @@ fn run_cargo(
..CompileOptions::default(&config, CompileMode::Check { test: false })
};

// Create a custom environment for running cargo, the environment is reset afterwards automatically
let mut env: HashMap<String, Option<OsString>> = HashMap::new();
env.insert("RUSTFLAGS".to_owned(), Some(rustflags.into()));
// Create a custom environment for running cargo, the environment is reset
// afterwards automatically
restore_env.push_var("RUSTFLAGS", &Some(rustflags.into()));

if clear_env_rust_log {
env.insert("RUST_LOG".to_owned(), None);
restore_env.push_var("RUST_LOG", &None);
}

let _restore_env = Environment::push_with_lock(&env, lock_guard);

let exec = RlsExecutor::new(
&ws,
compilation_cx.clone(),
Expand All @@ -213,7 +213,9 @@ fn run_cargo(
compilation_cx.lock().unwrap().build_plan
);

Ok(())
Ok(compilation_cx.lock().unwrap().cwd.clone().unwrap_or_else(|| {
restore_env.get_old_cwd().to_path_buf()
}))
}

struct RlsExecutor {
Expand Down Expand Up @@ -475,11 +477,12 @@ impl Executor for RlsExecutor {
&self.vfs,
&args,
&envs,
cargo_cmd.get_cwd(),
&build_dir,
self.config.clone(),
env_lock,
) {
BuildResult::Success(mut messages, mut analysis) => {
BuildResult::Success(_, mut messages, mut analysis) => {
self.compiler_messages.lock().unwrap().append(&mut messages);
self.analysis.lock().unwrap().append(&mut analysis);
}
Expand All @@ -493,6 +496,7 @@ impl Executor for RlsExecutor {
let mut compilation_cx = self.compilation_cx.lock().unwrap();
compilation_cx.args = args;
compilation_cx.envs = envs;
compilation_cx.cwd = cargo_cmd.get_cwd().map(|p| p.to_path_buf());

Ok(())
}
Expand Down Expand Up @@ -596,13 +600,13 @@ fn prepare_cargo_rustflags(config: &Config) -> String {

/// Construct a cargo configuration for the given build and target directories
/// and shell.
pub fn make_cargo_config(build_dir: &Path, target_dir: Option<&Path>, shell: Shell) -> CargoConfig {
pub fn make_cargo_config(build_dir: &Path,
target_dir: Option<&Path>,
cwd: &Path,
shell: Shell) -> CargoConfig {
let config = CargoConfig::new(
shell,
// This is Cargo's cwd. We're using the actual cwd,
// because Cargo will generate relative paths based
// on this to source files it wants to compile
env::current_dir().unwrap(),
cwd.to_path_buf(),
homedir(&build_dir).unwrap(),
);

Expand Down
15 changes: 14 additions & 1 deletion src/build/environment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::collections::HashMap;
use std::env;
use std::ffi::OsString;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, MutexGuard};

// Ensures we don't race on the env vars. This is only also important in tests,
Expand All @@ -23,19 +24,26 @@ lazy_static! {
/// Requires supplying an external lock guard to guarantee env var consistency across multiple threads.
pub struct Environment<'a> {
old_vars: HashMap<String, Option<OsString>>,
old_cwd: PathBuf,
_guard: MutexGuard<'a, ()>,
}

impl<'a> Environment<'a> {
pub fn push_with_lock(
envs: &HashMap<String, Option<OsString>>,
cwd: Option<&Path>,
lock: MutexGuard<'a, ()>,
) -> Environment<'a> {
let mut result = Environment {
old_vars: HashMap::new(),
old_cwd: env::current_dir().expect("failed to read cwd"),
_guard: lock,
};

if let Some(cwd) = cwd {
env::set_current_dir(cwd).expect("failed to change cwd");
}

for (k, v) in envs {
result.push_var(k, v);
}
Expand All @@ -49,10 +57,15 @@ impl<'a> Environment<'a> {
None => env::remove_var(key),
}
}

pub fn get_old_cwd(&self) -> &Path {
&self.old_cwd
}
}

impl<'a> Drop for Environment<'a> {
fn drop(&mut self) {
drop(env::set_current_dir(&self.old_cwd));
for (k, v) in &self.old_vars {
match *v {
Some(ref v) => env::set_var(k, v),
Expand Down
Loading