Skip to content

Commit

Permalink
Detect when build.target is configured, and allow overriding it fro…
Browse files Browse the repository at this point in the history
…m the command line (#619)

* Detect when `build.target` is configured

This allows checking the correct directory for the json files. There are
two more correct approaches to this, but neither are usable currently:

 1. The most correct approach would be to read the `compiler-artifact`
    messages from `cargo --message-format=json`. Unfortunately as of the
    current nightly these don't work when using `--output-format=json`,
    they have an empty list of files.
 2. The next option would be to use `--out-dir` to tell cargo/rustdoc to
    place the json file in a known directory. As of the current nightly
    cargo doesn't support `--out-dir` with `cargo doc`, and attempting
    to pass it through to rustdoc directly results in an error because
    it is given more than once.

So instead, we query cargo to see if the user has configured
`build.target` through either a config file or environment variables.

* Add flag to specify which target to build for

* Add tests for both implicit and explicit targets

* Improve the unset config value detection

* Use `build_target` internally to refer to the target platform

* Add example target to CLI docs

* Add more documentation around setting the `--target`
  • Loading branch information
Nemo157 authored Jan 22, 2024
1 parent ae52c12 commit e21509e
Show file tree
Hide file tree
Showing 5 changed files with 106 additions and 2 deletions.
14 changes: 14 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ pub struct Check {
release_type: Option<ReleaseType>,
current_feature_config: rustdoc_gen::FeatureConfig,
baseline_feature_config: rustdoc_gen::FeatureConfig,
/// Which `--target` to use, if unset pass no flag
build_target: Option<String>,
}

/// The kind of release we're making.
Expand Down Expand Up @@ -236,6 +238,7 @@ impl Check {
release_type: None,
current_feature_config: rustdoc_gen::FeatureConfig::default_for_current(),
baseline_feature_config: rustdoc_gen::FeatureConfig::default_for_baseline(),
build_target: None,
}
}

Expand Down Expand Up @@ -300,6 +303,13 @@ impl Check {
self
}

/// Set what `--target` to build the documentation with, by default will not pass any flag
/// relying on the users cargo configuration.
pub fn with_build_target(&mut self, build_target: String) -> &mut Self {
self.build_target = Some(build_target);
self
}

/// Some `RustdocSource`s don't contain a path to the project root,
/// so they don't have a target directory. We try to deduce the target directory
/// on a "best effort" basis -- when the source contains a target dir,
Expand Down Expand Up @@ -419,13 +429,15 @@ impl Check {
crate_type: rustdoc_gen::CrateType::Current,
name: &name,
feature_config: &self.current_feature_config,
build_target: self.build_target.as_deref(),
},
CrateDataForRustdoc {
crate_type: rustdoc_gen::CrateType::Baseline {
highest_allowed_version: version,
},
name: &name,
feature_config: &self.baseline_feature_config,
build_target: self.build_target.as_deref(),
},
)?;

Expand Down Expand Up @@ -485,13 +497,15 @@ impl Check {
crate_type: rustdoc_gen::CrateType::Current,
name: crate_name,
feature_config: &self.current_feature_config,
build_target: self.build_target.as_deref(),
},
CrateDataForRustdoc {
crate_type: rustdoc_gen::CrateType::Baseline {
highest_allowed_version: Some(version),
},
name: crate_name,
feature_config: &self.baseline_feature_config,
build_target: self.build_target.as_deref(),
},
)?;

Expand Down
10 changes: 10 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,11 @@ struct CheckRelease {
)]
all_features: bool,

/// Which target to build the crate for, to check platform-specific APIs, e.g.
/// `x86_64-unknown-linux-gnu`.
#[arg(long = "target")]
build_target: Option<String>,

#[command(flatten)]
verbosity: clap_verbosity_flag::Verbosity<clap_verbosity_flag::InfoLevel>,
}
Expand Down Expand Up @@ -349,6 +354,11 @@ impl From<CheckRelease> for cargo_semver_checks::Check {
trim_features(&mut baseline_features);

check.with_extra_features(current_features, baseline_features);

if let Some(build_target) = value.build_target {
check.with_build_target(build_target);
}

check
}
}
Expand Down
49 changes: 47 additions & 2 deletions src/rustdoc_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,9 @@ impl RustdocCommand {
.arg(target_dir)
.arg("--package")
.arg(pkg_spec);
if let Some(build_target) = crate_data.build_target {
cmd.arg("--target").arg(build_target);
}
if !self.deps {
cmd.arg("--no-deps");
}
Expand All @@ -130,6 +133,48 @@ impl RustdocCommand {
}
}

let rustdoc_dir = if let Some(build_target) = crate_data.build_target {
target_dir.join(build_target).join("doc")
} else {
// If not passing an explicit `--target` flag, cargo may still pick a target to use
// instead of the "host" target, based on its config files and environment variables.

let build_target = {
let output = std::process::Command::new("cargo")
.env("RUSTC_BOOTSTRAP", "1")
.args([
"config",
"-Zunstable-options",
"--color=never",
"get",
"--format=json-value",
"build.target",
])
.output()?;
if output.status.success() {
serde_json::from_slice::<Option<String>>(&output.stdout)?
} else if std::str::from_utf8(&output.stderr)
.context("non-utf8 cargo output")?
// this is the only way to detect a not set config value currently:
// https://github.com/rust-lang/cargo/issues/13223
.contains("config value `build.target` is not set")
{
None
} else {
anyhow::bail!(
"running cargo-config failed:\n{}",
String::from_utf8_lossy(&output.stderr),
)
}
};

if let Some(build_target) = build_target {
target_dir.join(build_target).join("doc")
} else {
target_dir.join("doc")
}
};

// There's no great way to figure out whether that crate version has a lib target.
// We can't easily do it via the index, and we can't reliably do it via metadata.
// We're reduced to this heuristic:
Expand Down Expand Up @@ -175,7 +220,7 @@ in the metadata and stderr didn't mention it was lacking a lib target. This is p
let lib_name = lib_target.name.as_str();
let rustdoc_json_file_name = lib_name.replace('-', "_");

let json_path = target_dir.join(format!("doc/{rustdoc_json_file_name}.json"));
let json_path = rustdoc_dir.join(format!("{rustdoc_json_file_name}.json"));
if json_path.exists() {
return Ok(json_path);
} else {
Expand All @@ -195,7 +240,7 @@ in the metadata and stderr didn't mention it was lacking a lib target. This is p
let bin_name = bin_target.name.as_str();
let rustdoc_json_file_name = bin_name.replace('-', "_");

let json_path = target_dir.join(format!("doc/{rustdoc_json_file_name}.json"));
let json_path = rustdoc_dir.join(format!("{rustdoc_json_file_name}.json"));
if json_path.exists() {
return Ok(json_path);
} else {
Expand Down
1 change: 1 addition & 0 deletions src/rustdoc_gen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,7 @@ pub(crate) struct CrateDataForRustdoc<'a> {
pub(crate) crate_type: CrateType<'a>,
pub(crate) name: &'a str,
pub(crate) feature_config: &'a FeatureConfig,
pub(crate) build_target: Option<&'a str>,
}

impl<'a> CrateType<'a> {
Expand Down
34 changes: 34 additions & 0 deletions tests/specified_target.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use assert_cmd::Command;

fn base() -> Command {
let mut cmd = Command::cargo_bin("cargo-semver-checks").unwrap();
cmd.args([
"semver-checks",
"check-release",
"--manifest-path=test_crates/template/new",
"--baseline-root=test_crates/template/old",
]);
cmd
}

#[test]
fn with_default() {
base().env_remove("CARGO_BUILD_TARGET").assert().success();
}

#[test]
fn with_env_var() {
base()
.env("CARGO_BUILD_TARGET", "x86_64-unknown-linux-gnu")
.assert()
.success();
}

#[test]
fn with_flag() {
base()
.env_remove("CARGO_BUILD_TARGET")
.arg("--target=x86_64-unknown-linux-gnu")
.assert()
.success();
}

0 comments on commit e21509e

Please sign in to comment.