use super::unit_graph::UnitGraph;
use crate::resolver::Resolve;
use crate::resolver::errors::describe_path;
use crate::util::data_structures::{HashMap, HashSet};
use crate::util::errors::CargoResult;
use crate::workspace::PackageId;
pub fn validate_links(resolve: &Resolve, unit_graph: &UnitGraph) -> CargoResult<()> {
let mut validated: HashSet<PackageId> = HashSet::default();
let mut links: HashMap<String, PackageId> = HashMap::default();
let mut units: Vec<_> = unit_graph.keys().collect();
units.sort_unstable();
for unit in units {
if !validated.insert(unit.pkg.package_id()) {
continue;
}
let Some(lib) = unit.pkg.manifest().links() else {
continue;
};
if let Some(&prev) = links.get(lib) {
let prev_path = resolve
.path_to_top(&prev)
.into_iter()
.map(|(p, d)| (p, d.and_then(|d| d.iter().next())));
let pkg = unit.pkg.package_id();
let path = resolve
.path_to_top(&pkg)
.into_iter()
.map(|(p, d)| (p, d.and_then(|d| d.iter().next())));
anyhow::bail!(
"multiple packages link to native library `{}`, \
but a native library can be linked only once\n\
\n\
{}\nlinks to native library `{}`\n\
\n\
{}\nalso links to native library `{}`",
lib,
describe_path(prev_path),
lib,
describe_path(path),
lib
)
}
links.insert(lib.to_string(), unit.pkg.package_id());
}
Ok(())
}