Skip to content

Commit 9802c0c

Browse files
author
Jon Gjengset
committed
Default to host platform for cargo metadata
This modifies the logic for calling cargo metadata so that it will use the host platform if no explicit target platform is given. This is needed since cargo metadata defaults to outputting information for _all_ targets. Fixes #6908.
1 parent 554dd21 commit 9802c0c

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

crates/project_model/src/cargo_workspace.rs

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ use paths::{AbsPath, AbsPathBuf};
1616
use rustc_hash::FxHashMap;
1717

1818
use crate::cfg_flag::CfgFlag;
19+
use crate::utf8_stdout;
1920

2021
/// `CargoWorkspace` represents the logical structure of, well, a Cargo
2122
/// workspace. It pretty closely mirrors `cargo metadata` output.
@@ -166,8 +167,35 @@ impl CargoWorkspace {
166167
if let Some(parent) = cargo_toml.parent() {
167168
meta.current_dir(parent.to_path_buf());
168169
}
169-
if let Some(target) = config.target.as_ref() {
170-
meta.other_options(vec![String::from("--filter-platform"), target.clone()]);
170+
let target = if let Some(target) = config.target.as_ref() {
171+
Some(target.clone())
172+
} else {
173+
// cargo metadata defaults to giving information for _all_ targets.
174+
// In the absence of a preference from the user, we use the host platform.
175+
let mut rustc = Command::new(toolchain::rustc());
176+
rustc.current_dir(cargo_toml.parent().unwrap()).arg("-vV");
177+
log::debug!("Discovering host platform by {:?}", rustc);
178+
match utf8_stdout(rustc) {
179+
Ok(stdout) => {
180+
let field = "host: ";
181+
let target =
182+
stdout.lines().find(|l| l.starts_with(field)).map(|l| &l[field.len()..]);
183+
if let Some(target) = target {
184+
Some(target.to_string())
185+
} else {
186+
// If we fail to resolve the host platform, it's not the end of the world.
187+
log::info!("rustc -vV did not report host platform, got:\n{}", stdout);
188+
None
189+
}
190+
}
191+
Err(e) => {
192+
log::warn!("Failed to discover host platform: {}", e);
193+
None
194+
}
195+
}
196+
};
197+
if let Some(target) = target {
198+
meta.other_options(vec![String::from("--filter-platform"), target]);
171199
}
172200
let mut meta = meta.exec().with_context(|| {
173201
format!("Failed to run `cargo metadata --manifest-path {}`", cargo_toml.display())

0 commit comments

Comments
 (0)