use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use anyhow::{Context, Result, bail};
use serde::Deserialize;
use crate::instrument::{self};
use crate::reverts;
use super::*;
#[derive(Deserialize)]
pub(super) struct Metadata {
pub(super) packages: Vec<Package>,
pub(super) workspace_root: PathBuf,
pub(super) target_directory: PathBuf,
}
#[derive(Deserialize)]
pub(super) struct Package {
pub(super) name: String,
#[serde(default)]
pub(super) dependencies: Vec<Dependency>,
pub(super) features: BTreeMap<String, Vec<String>>,
pub(super) manifest_path: PathBuf,
pub(super) targets: Vec<Target>,
}
impl Package {
pub(super) fn enabled_local_features(
&self,
workspace: &Path,
cargo: &CargoConfig,
) -> BTreeSet<&str> {
if cargo.all_features {
return self.features.keys().map(String::as_str).collect();
}
let mut pending = Vec::new();
if !cargo.no_default_features {
pending.push("default");
}
let at_workspace_root = self.manifest_path.parent() == Some(workspace);
for feature in cargo
.features
.iter()
.flat_map(|features| features.split(|c: char| c == ',' || c.is_whitespace()))
{
match feature.split_once('/') {
Some((package, name)) if package == self.name => pending.push(name),
None if at_workspace_root => pending.push(feature),
_ => {}
}
}
let mut enabled = BTreeSet::new();
while let Some(feature) = pending.pop() {
if let Some((name, activates)) = self.features.get_key_value(feature)
&& enabled.insert(name.as_str())
{
pending.extend(activates.iter().map(String::as_str));
}
}
enabled
}
}
#[derive(Deserialize)]
pub(super) struct Dependency {
pub(super) name: String,
}
#[derive(Deserialize)]
pub(super) struct Target {
pub(super) name: String,
pub(super) kind: Vec<String>,
pub(super) src_path: PathBuf,
pub(super) test: bool,
#[serde(default)]
pub(super) doctest: bool,
#[serde(default, rename = "required-features")]
pub(super) required_features: Vec<String>,
}
impl Target {
pub(super) fn is_production(&self) -> bool {
matches!(self.test_build_arg(), Some(("--lib" | "--bin", _)))
}
pub(super) fn test_build_arg(&self) -> Option<(&'static str, Option<&str>)> {
match self.kind.first()?.as_str() {
"lib" | "rlib" | "cdylib" | "dylib" | "staticlib" | "proc-macro" => {
Some(("--lib", None))
}
"bin" => Some(("--bin", Some(&self.name))),
"example" => Some(("--example", Some(&self.name))),
"test" => Some(("--test", Some(&self.name))),
"bench" => Some(("--bench", Some(&self.name))),
_ => None,
}
}
}
pub(super) fn test_build_flags(
packages: &[&Package],
names: &[String],
workspace: &Path,
cargo: &CargoConfig,
) -> Option<Vec<String>> {
if names.is_empty() {
return None;
}
let selected = |target: &Target| target.test && names.contains(&target.name);
let mut selectors = BTreeSet::new();
for package in packages {
let enabled_features = package.enabled_local_features(workspace, cargo);
for target in package.targets.iter().filter(|t| selected(t)) {
let selector = target.test_build_arg()?;
if target
.required_features
.iter()
.any(|feature| !enabled_features.contains(feature.as_str()))
|| selector
.1
.is_some_and(|name| name.contains(['*', '?', '[']))
{
return None;
}
selectors.insert(selector);
}
}
if selectors.is_empty()
|| packages.iter().flat_map(|p| &p.targets).any(|target| {
!selected(target)
&& target
.test_build_arg()
.is_some_and(|selector| selectors.contains(&selector))
})
{
return None;
}
Some(
selectors
.into_iter()
.map(|(flag, name)| match name {
Some(name) => format!("{flag}={name}"),
None => flag.to_owned(),
})
.collect(),
)
}
#[derive(Deserialize)]
pub(super) struct CargoMessage {
pub(super) reason: String,
pub(super) package_id: Option<String>,
pub(super) target: Option<ArtifactTarget>,
pub(super) profile: Option<Profile>,
pub(super) executable: Option<PathBuf>,
#[serde(default)]
pub(super) filenames: Vec<PathBuf>,
pub(super) features: Option<Vec<String>>,
pub(super) message: Option<Diagnostic>,
}
#[derive(Deserialize)]
pub(super) struct ArtifactTarget {
pub(super) name: String,
pub(super) kind: Vec<String>,
pub(super) src_path: Option<PathBuf>,
}
#[derive(Deserialize)]
pub(super) struct Profile {
pub(super) test: bool,
}
#[derive(Deserialize)]
pub(super) struct Diagnostic {
pub(super) level: String,
pub(super) rendered: Option<String>,
pub(super) message: Option<String>,
#[serde(default)]
pub(super) spans: Vec<DiagnosticSpan>,
}
#[derive(Deserialize)]
pub(super) struct DiagnosticSpan {
pub(super) file_name: String,
pub(super) byte_start: usize,
pub(super) line_start: usize,
pub(super) is_primary: bool,
}
#[derive(Debug, PartialEq, Clone)]
pub(super) struct ErrorSpan {
pub(super) file: String,
pub(super) byte_start: usize,
pub(super) line: usize,
}
#[derive(Debug, PartialEq)]
pub(super) struct CompileError {
pub(super) primary: Vec<ErrorSpan>,
pub(super) secondary: Vec<ErrorSpan>,
pub(super) rendered: String,
}
#[derive(Debug, Default, PartialEq)]
pub(super) struct BuildOutput {
pub(super) test_binaries: Vec<(String, PathBuf, String, Vec<String>)>,
pub(super) errors: Vec<CompileError>,
pub(super) diagnostics: Vec<String>,
pub(super) build_scripts: Vec<serde_json::Value>,
pub(super) artifacts: Vec<(PathBuf, Vec<PathBuf>)>,
pub(super) features: Vec<(PathBuf, Vec<String>)>,
}
#[derive(Debug, PartialEq)]
pub(super) enum SourceBuild {
Built,
Refused,
Failed(String),
}
pub(super) fn source_build(output: &std::process::Output) -> SourceBuild {
if output.status.success() {
return SourceBuild::Built;
}
let refused = !parse_build_output(&String::from_utf8_lossy(&output.stdout), &[])
.diagnostics
.is_empty();
if refused {
return SourceBuild::Refused;
}
let said = String::from_utf8_lossy(&output.stderr);
let last: Vec<&str> = said.lines().rev().take(3).collect();
let last: Vec<&str> = last.into_iter().rev().collect();
SourceBuild::Failed(format!("{} ({})", last.join(" / "), output.status))
}
pub(super) fn dependents_of(package: &str, packages: &[Package]) -> Vec<String> {
let mut reverse = BTreeMap::<&str, Vec<&str>>::new();
for other in packages {
for dependency in &other.dependencies {
reverse
.entry(&dependency.name)
.or_default()
.push(&other.name);
}
}
let mut found = BTreeSet::new();
let mut frontier = vec![package];
while let Some(current) = frontier.pop() {
if let Some(next) = reverse.get(current) {
for &other in next {
if other != package && found.insert(other) {
frontier.push(other);
}
}
}
}
found.into_iter().map(str::to_owned).collect()
}
pub(super) fn is_package(id: &str, name: &str) -> bool {
let (path, fragment) = id.split_once('#').unwrap_or((id, ""));
fragment.split('@').next() == Some(name)
|| path.rsplit('/').next() == Some(name)
|| id.split(' ').next() == Some(name)
}
pub(super) fn parse_build_output(stdout: &str, packages: &[&str]) -> BuildOutput {
let mut out = BuildOutput::default();
for line in stdout.lines() {
let Ok(msg) = serde_json::from_str::<CargoMessage>(line) else {
continue;
};
match msg.reason.as_str() {
"compiler-artifact" => {
let Some(target) = msg.target else { continue };
if let Some(path) = target.src_path {
let root = normalize(&path);
if let Some(features) = msg.features {
out.features.push((root.clone(), features));
}
out.artifacts.push((root, msg.filenames));
}
if let (Some(exe), Some(profile), Some(id)) =
(msg.executable, msg.profile, msg.package_id.as_deref())
&& profile.test
&& let Some(package) = packages.iter().find(|name| is_package(id, name))
{
out.test_binaries
.push((target.name, exe, package.to_string(), target.kind));
}
}
"build-script-executed" => {
if let Ok(script) = serde_json::from_str(line) {
out.build_scripts.push(script);
}
}
"compiler-message" => {
let Some(diag) = msg.message else { continue };
if diag.level != "error" {
continue;
}
let rendered = diag.rendered.or(diag.message).unwrap_or_default();
if !rendered.is_empty() && !out.diagnostics.contains(&rendered) {
out.diagnostics.push(rendered.clone());
}
let span = |s: &DiagnosticSpan| ErrorSpan {
file: s.file_name.clone(),
byte_start: s.byte_start,
line: s.line_start,
};
let error = CompileError {
primary: diag
.spans
.iter()
.filter(|s| s.is_primary)
.map(span)
.collect(),
secondary: diag
.spans
.iter()
.filter(|s| !s.is_primary)
.map(span)
.collect(),
rendered,
};
if !error.primary.is_empty() && !out.errors.contains(&error) {
out.errors.push(error);
}
}
_ => {}
}
}
out.test_binaries.sort_by(|left, right| {
(&left.2, &left.3, &left.0, &left.1).cmp(&(&right.2, &right.3, &right.0, &right.1))
});
out
}
pub(super) fn dependency_file(artifact: &Path) -> Option<String> {
let stem = artifact.file_stem()?.to_str()?;
let unprefixed = match artifact.extension().and_then(|ext| ext.to_str()) {
Some("a" | "so" | "dylib" | "rlib" | "rmeta") => stem.strip_prefix("lib"),
_ => None,
};
unprefixed
.and_then(|stem| fs::read_to_string(artifact.with_file_name(format!("{stem}.d"))).ok())
.or_else(|| fs::read_to_string(artifact.with_extension("d")).ok())
}
pub(super) fn dep_inputs(text: &str, copy: &Path) -> BTreeSet<PathBuf> {
text.lines()
.filter_map(|line| line.strip_suffix(':'))
.map(|name| name.replace("\\ ", " ").replace("\\#", "#"))
.map(|name| normalize(©.join(name)))
.collect()
}
pub(super) fn directory_entries(path: &Path) -> impl Iterator<Item = PathBuf> + use<> {
fs::read_dir(path)
.into_iter()
.flatten()
.filter_map(|entry| entry.ok().map(|entry| entry.path()))
}
pub(super) fn same_binary(a: &Path, b: &Path) -> Option<bool> {
let (a, b) = (fs::File::open(a).ok()?, fs::File::open(b).ok()?);
let (left, right) = (a.metadata().ok()?, b.metadata().ok()?);
if !left.is_file() || !right.is_file() || left.len() != right.len() {
return Some(false);
}
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
if left.ino() == right.ino() && left.dev() == right.dev() {
return Some(true);
}
}
compare_streams(a, b).ok()
}
pub(super) fn compare_streams(
a: impl std::io::Read,
b: impl std::io::Read,
) -> std::io::Result<bool> {
use std::io::{BufRead, BufReader, ErrorKind};
const BUFFER_BYTES: usize = 64 * 1024;
let mut a = BufReader::with_capacity(BUFFER_BYTES, a);
let mut b = BufReader::with_capacity(BUFFER_BYTES, b);
loop {
let left = match a.fill_buf() {
Ok(bytes) => bytes,
Err(error) if error.kind() == ErrorKind::Interrupted => continue,
Err(error) => return Err(error),
};
let right = match b.fill_buf() {
Ok(bytes) => bytes,
Err(error) if error.kind() == ErrorKind::Interrupted => continue,
Err(error) => return Err(error),
};
let count = left.len().min(right.len());
if count == 0 {
return Ok(left.is_empty() && right.is_empty());
}
if left[..count] != right[..count] {
return Ok(false);
}
a.consume(count);
b.consume(count);
}
}
pub(super) fn artifact_inputs(artifact: &Path, root: &Path, copy: &Path) -> BTreeSet<PathBuf> {
let read = |binary: &Path| {
dependency_file(binary)
.map(|text| dep_inputs(&text, copy))
.filter(|inputs| inputs.contains(root))
};
if let Some(inputs) = read(artifact) {
return inputs;
}
let Some((profile, stem)) = artifact
.parent()
.zip(artifact.file_stem().and_then(|s| s.to_str()))
else {
return BTreeSet::new();
};
let crate_stem = stem.replace('-', "_");
let hashed = format!("{crate_stem}-");
let old = directory_entries(&profile.join("deps")).filter(|path| {
path.extension() == artifact.extension()
&& path
.file_stem()
.and_then(|s| s.to_str())
.is_some_and(|name| name.starts_with(&hashed))
});
let mut private_name = std::ffi::OsString::from(crate_stem);
if let Some(extension) = artifact.extension() {
private_name.push(".");
private_name.push(extension);
}
let new = directory_entries(&profile.join("build"))
.flat_map(|package| directory_entries(&package))
.map(|unit| unit.join("out").join(&private_name));
old.chain(new)
.filter_map(|path| {
let inputs = read(&path)?;
(same_binary(artifact, &path) == Some(true)).then_some(inputs)
})
.reduce(|left, right| left.intersection(&right).cloned().collect())
.unwrap_or_default()
}
#[derive(Default)]
pub(super) struct BuiltSources {
pub(super) files: BTreeMap<PathBuf, BTreeSet<PathBuf>>,
pub(super) features: BTreeMap<PathBuf, Vec<BTreeSet<String>>>,
}
pub(super) fn left_out_of_all(per_build: &[Vec<(usize, usize)>]) -> Vec<(usize, usize)> {
let mut all: Vec<(usize, usize)> = per_build
.iter()
.flatten()
.filter(|(from, to)| {
per_build
.iter()
.all(|ranges| ranges.iter().any(|(start, end)| start <= from && to <= end))
})
.copied()
.collect();
all.sort_unstable();
all.dedup();
all
}
pub(super) fn configuration_names_a_feature(dir: &Path, cargo_home: Option<PathBuf>) -> bool {
let home = cargo_home
.or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".cargo")));
dir.ancestors()
.map(|dir| dir.join(".cargo"))
.chain(home)
.flat_map(|dir| [dir.join("config.toml"), dir.join("config")])
.filter_map(|file| fs::read_to_string(file).ok())
.any(|text| text.contains("--cfg") && text.contains("feature"))
}
pub(super) fn features_from_flags(
flags: impl IntoIterator<Item = Option<std::ffi::OsString>>,
) -> bool {
flags.into_iter().flatten().any(|value| {
let value = value.to_string_lossy();
value.contains("cfg") && value.replace("target-feature", "").contains("feature")
})
}
impl BuiltSources {
pub(super) fn from_artifacts(
artifacts: &[(PathBuf, Vec<PathBuf>)],
features: &[(PathBuf, Vec<String>)],
features_known: bool,
copy: &Path,
) -> Self {
let mut built = Self::default();
for (root, features) in features.iter().filter(|_| features_known) {
let set: BTreeSet<String> = features.iter().cloned().collect();
let sets = built.features.entry(root.clone()).or_default();
if !sets.contains(&set) {
sets.push(set);
}
}
for (root, artifacts) in artifacts {
if !root.starts_with(copy) {
continue;
}
let files = built.files.entry(root.clone()).or_default();
files.insert(root.clone());
if let Some(inputs) = artifacts
.iter()
.map(|file| artifact_inputs(file, root, copy))
.find(|inputs| !inputs.is_empty())
{
files.extend(inputs);
}
}
built
}
pub(super) fn contains(&self, source: &SourceFile) -> bool {
source.owners.iter().any(|root| {
self.files
.get(root)
.is_some_and(|files| files.contains(&source.path))
})
}
pub(super) fn left_out(&self, source: &SourceFile) -> Vec<(usize, usize)> {
self.left_out_of(source, &source.original)
.unwrap_or_default()
}
pub(super) fn builds_of(&self, source: &SourceFile) -> Option<Vec<&BTreeSet<String>>> {
let mut builds: Vec<&BTreeSet<String>> = vec![];
for root in &source.owners {
if !self
.files
.get(root)
.is_some_and(|files| files.contains(&source.path))
{
continue;
}
builds.extend(self.features.get(root)?);
}
Some(builds)
}
pub(super) fn left_out_of(
&self,
source: &SourceFile,
text: &str,
) -> Option<Vec<(usize, usize)>> {
let builds = self.builds_of(source)?;
let parsed = instrument::parse_source(text).ok()?;
let per_build: Vec<Vec<(usize, usize)>> = builds
.iter()
.map(|features| instrument::inactive_ranges(text, &parsed, features))
.collect();
Some(left_out_of_all(&per_build))
}
pub(super) fn same_program(&self, source: &SourceFile, a: &str, b: &str) -> bool {
let (Some(builds), Ok(parsed_a), Ok(parsed_b)) = (
self.builds_of(source),
instrument::parse_source(a),
instrument::parse_source(b),
) else {
return false;
};
let apart = |text: &str, parsed: &syn::File, features: &BTreeSet<String>| {
let mut ranges = instrument::inactive_ranges(text, parsed, features);
ranges.extend(instrument::settled_cfg_attributes(text, parsed, features));
ranges
};
!builds.is_empty()
&& builds.iter().all(|features| {
reverts::same_build(
a,
&apart(a, &parsed_a, features),
b,
&apart(b, &parsed_b, features),
)
})
}
}
pub(super) fn cargo_metadata(dir: &Path, cargo: &CargoConfig) -> Result<Metadata> {
let output = Command::new("cargo")
.args(["metadata", "--no-deps", "--format-version", "1"])
.args(cargo.flags())
.current_dir(dir)
.output()
.context("running cargo metadata")?;
if !output.status.success() {
bail!(
"cargo metadata failed:\n{}",
String::from_utf8_lossy(&output.stderr)
);
}
serde_json::from_slice(&output.stdout).context("parsing cargo metadata")
}