use super::diagnostic::{Diagnostic, DiagnosticCategory};
use super::environment::CfgSet;
use crate::Builder;
use std::collections::BTreeSet;
use std::ffi::OsString;
use std::fs;
use std::path::Path;
pub(super) fn add_features(
package: &Path,
builder: &Builder,
environment: &[(OsString, OsString)],
cfg: &mut CfgSet,
) -> Result<(), Diagnostic> {
let manifest_path = package.join("Cargo.toml");
let manifest = fs::read_to_string(&manifest_path).map_err(|error| {
Diagnostic::io(
DiagnosticCategory::Manifest,
"Cargo.toml",
"cannot read package manifest",
error,
)
})?;
let value = toml::from_str::<toml::Value>(&manifest).map_err(|error| {
let mut diagnostic = Diagnostic::new(
DiagnosticCategory::Manifest,
"Cargo.toml",
"cannot parse package manifest",
);
diagnostic.source = Some(Box::new(error));
diagnostic
})?;
let features = manifest_features(&value)?;
for (name, _) in environment {
let Some(name) = name.to_str() else { continue };
let Some(suffix) = name.strip_prefix("CARGO_FEATURE_") else {
continue;
};
let candidates = features
.iter()
.filter(|feature| cargo_feature_suffix(feature) == suffix)
.collect::<Vec<_>>();
match candidates.as_slice() {
[feature] => {
cfg.values
.entry("feature".to_owned())
.or_default()
.insert((*feature).clone());
}
[] => {
return Err(Diagnostic::new(
DiagnosticCategory::FeatureCfg,
"Cargo.toml",
format!("{name} does not match a manifest feature"),
));
}
many => {
let explicit = many
.iter()
.filter(|feature| {
builder
.custom_cfg_values("feature")
.any(|value| value == feature.as_str())
})
.count();
if explicit != 1 {
return Err(Diagnostic::new(
DiagnosticCategory::FeatureCfg,
"Cargo.toml",
format!("{name} ambiguously matches manifest features"),
));
}
}
}
}
Ok(())
}
fn manifest_features(manifest: &toml::Value) -> Result<BTreeSet<String>, Diagnostic> {
let mut features = BTreeSet::new();
let mut suppressed = BTreeSet::new();
if let Some(value) = manifest.get("features") {
let table = manifest_table(value, "features")?;
for (name, members) in table {
features.insert(name.clone());
let members = members
.as_array()
.ok_or_else(|| manifest_shape(format!("feature {name:?} must be an array")))?;
for member in members {
let member = member.as_str().ok_or_else(|| {
manifest_shape(format!("feature {name:?} contains a non-string member"))
})?;
if let Some(dependency) = member.strip_prefix("dep:") {
suppressed.insert(dependency.to_owned());
}
}
}
}
let mut optional_dependencies = BTreeSet::new();
let root = manifest
.as_table()
.ok_or_else(|| manifest_shape("manifest root must be a table"))?;
collect_dependency_tables(root, "", &mut optional_dependencies)?;
if let Some(targets) = manifest.get("target") {
let targets = manifest_table(targets, "target")?;
for (target, configuration) in targets {
let configuration = configuration
.as_table()
.ok_or_else(|| manifest_shape(format!("target {target:?} must be a table")))?;
collect_dependency_tables(
configuration,
&format!("target.{target}."),
&mut optional_dependencies,
)?;
}
}
features.extend(
optional_dependencies
.into_iter()
.filter(|dependency| !suppressed.contains(dependency)),
);
Ok(features)
}
fn collect_dependency_tables(
manifest: &toml::Table,
prefix: &str,
optional: &mut BTreeSet<String>,
) -> Result<(), Diagnostic> {
for table_name in ["dependencies", "build-dependencies"] {
let Some(dependencies) = manifest.get(table_name) else {
continue;
};
let dependencies = manifest_table(dependencies, &format!("{prefix}{table_name}"))?;
for (key, dependency) in dependencies {
match dependency {
toml::Value::String(_) => {}
toml::Value::Table(specification) => {
if let Some(value) = specification.get("optional") {
let is_optional = value.as_bool().ok_or_else(|| {
manifest_shape(format!(
"dependency {key:?} in [{prefix}{table_name}] has a non-boolean `optional` value"
))
})?;
if is_optional {
optional.insert(key.clone());
}
}
}
_ => {
return Err(manifest_shape(format!(
"dependency {key:?} in [{prefix}{table_name}] must be a string or table"
)));
}
}
}
}
Ok(())
}
fn manifest_table<'a>(value: &'a toml::Value, name: &str) -> Result<&'a toml::Table, Diagnostic> {
value
.as_table()
.ok_or_else(|| manifest_shape(format!("[{name}] must be a table")))
}
fn manifest_shape(message: impl Into<String>) -> Diagnostic {
Diagnostic::new(DiagnosticCategory::Manifest, "Cargo.toml", message)
}
fn cargo_feature_suffix(feature: &str) -> String {
feature
.chars()
.map(|character| {
if character == '-' {
'_'
} else {
character.to_ascii_uppercase()
}
})
.collect()
}