Skip to content

Don't use $CARGO_BUILD_TARGET in cargo metadata #15271

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 6, 2025
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
37 changes: 34 additions & 3 deletions src/cargo/core/compiler/compile_kind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,20 @@ pub enum CompileKind {
Target(CompileTarget),
}

/// Fallback behavior in the
/// [`CompileKind::from_requested_targets_with_fallback`] function when
/// no targets are specified.
pub enum CompileKindFallback {
/// The build configuration is consulted to find the default target, such as
/// `$CARGO_BUILD_TARGET` or reading `build.target`.
BuildConfig,

/// Only the host should be returned when targets aren't explicitly
/// specified. This is used by `cargo metadata` for example where "only
/// host" has a special meaning in terms of the returned metadata.
JustHost,
}

impl CompileKind {
pub fn is_host(&self) -> bool {
matches!(self, CompileKind::Host)
Expand All @@ -53,6 +67,21 @@ impl CompileKind {
pub fn from_requested_targets(
gctx: &GlobalContext,
targets: &[String],
) -> CargoResult<Vec<CompileKind>> {
CompileKind::from_requested_targets_with_fallback(
gctx,
targets,
CompileKindFallback::BuildConfig,
)
}

/// Same as [`CompileKind::from_requested_targets`] except that if `targets`
/// doesn't explicitly mention anything the behavior of what to return is
/// controlled by the `fallback` argument.
pub fn from_requested_targets_with_fallback(
gctx: &GlobalContext,
targets: &[String],
fallback: CompileKindFallback,
) -> CargoResult<Vec<CompileKind>> {
let dedup = |targets: &[String]| {
Ok(targets
Expand All @@ -70,9 +99,11 @@ impl CompileKind {
return dedup(targets);
}

let kinds = match &gctx.build_config()?.target {
None => Ok(vec![CompileKind::Host]),
Some(build_target_config) => dedup(&build_target_config.values(gctx)?),
let kinds = match (fallback, &gctx.build_config()?.target) {
(_, None) | (CompileKindFallback::JustHost, _) => Ok(vec![CompileKind::Host]),
(CompileKindFallback::BuildConfig, Some(build_target_config)) => {
dedup(&build_target_config.values(gctx)?)
}
};

kinds
Expand Down
2 changes: 1 addition & 1 deletion src/cargo/core/compiler/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ pub use self::build_context::{
use self::build_plan::BuildPlan;
pub use self::build_runner::{BuildRunner, Metadata, UnitHash};
pub use self::compilation::{Compilation, Doctest, UnitOutput};
pub use self::compile_kind::{CompileKind, CompileTarget};
pub use self::compile_kind::{CompileKind, CompileKindFallback, CompileTarget};
pub use self::crate_type::CrateType;
pub use self::custom_build::LinkArgTarget;
pub use self::custom_build::{BuildOutput, BuildScriptOutputs, BuildScripts};
Expand Down
14 changes: 11 additions & 3 deletions src/cargo/ops/cargo_output_metadata.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::core::compiler::artifact::match_artifacts_kind_with_targets;
use crate::core::compiler::{CompileKind, RustcTargetData};
use crate::core::compiler::{CompileKind, CompileKindFallback, RustcTargetData};
use crate::core::dependency::DepKind;
use crate::core::package::SerializedPackage;
use crate::core::resolver::{features::CliFeatures, HasDevUnits, Resolve};
Expand Down Expand Up @@ -132,8 +132,16 @@ fn build_resolve_graph(
) -> CargoResult<(Vec<SerializedPackage>, MetadataResolve)> {
// TODO: Without --filter-platform, features are being resolved for `host` only.
// How should this work?
let requested_kinds =
CompileKind::from_requested_targets(ws.gctx(), &metadata_opts.filter_platforms)?;
//
// Otherwise note that "just host" is used as the fallback here if
// `filter_platforms` is empty to intentionally avoid reading
// `$CARGO_BUILD_TARGET` (or `build.target`) which makes sense for other
// subcommands like `cargo build` but does not fit with this command.
let requested_kinds = CompileKind::from_requested_targets_with_fallback(
ws.gctx(),
&metadata_opts.filter_platforms,
CompileKindFallback::JustHost,
)?;
let mut target_data = RustcTargetData::new(ws, &requested_kinds)?;
// Resolve entire workspace.
let specs = Packages::All(Vec::new()).to_package_id_specs(ws)?;
Expand Down
45 changes: 38 additions & 7 deletions tests/testsuite/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1224,7 +1224,7 @@ fn workspace_metadata_with_dependencies_no_deps() {
name = "bar"
version = "0.5.0"
authors = ["wycats@example.com"]

[dependencies]
baz = { path = "../baz/" }
artifact = { path = "../artifact/", artifact = "bin" }
Expand Down Expand Up @@ -1474,13 +1474,13 @@ fn workspace_metadata_with_dependencies_and_resolve() {
name = "artifact"
version = "0.5.0"
authors = []

[lib]
crate-type = ["staticlib", "cdylib", "rlib"]

[[bin]]
name = "bar-name"

[[bin]]
name = "baz-name"
"#,
Expand All @@ -1494,10 +1494,10 @@ fn workspace_metadata_with_dependencies_and_resolve() {
name = "bin-only-artifact"
version = "0.5.0"
authors = []

[[bin]]
name = "a-name"

[[bin]]
name = "b-name"
"#,
Expand Down Expand Up @@ -4343,7 +4343,7 @@ fn workspace_metadata_with_dependencies_no_deps_artifact() {
name = "bar"
version = "0.5.0"
authors = ["wycats@example.com"]

[dependencies]
baz = { path = "../baz/" }
baz-renamed = { path = "../baz/" }
Expand Down Expand Up @@ -4954,3 +4954,34 @@ local-time = 1979-05-27
)
.run();
}

#[cargo_test]
fn metadata_ignores_build_target_configuration() -> anyhow::Result<()> {
let p = project()
.file(
"Cargo.toml",
r#"
[package]
name = "foo"

[target.'cfg(something)'.dependencies]
foobar = "0.0.1"
"#,
)
.file("src/lib.rs", "")
.build();
Package::new("foobar", "0.0.1").publish();

let output1 = p
.cargo("metadata -q --format-version 1")
.exec_with_output()?;
let output2 = p
.cargo("metadata -q --format-version 1")
.env("CARGO_BUILD_TARGET", rustc_host())
.exec_with_output()?;
assert!(
output1.stdout == output2.stdout,
"metadata should not change when `CARGO_BUILD_TARGET` is set",
);
Ok(())
}