use crate::modtree::{PathSite, Reach};
use crate::path::RelPath;
use crate::target::PackageId;
use super::Workspace;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct ForeignModulePath<'a> {
pub file: &'a RelPath,
pub reach: &'a Reach,
pub site: &'a PathSite,
pub package: PackageId,
pub owner: Option<PackageId>,
}
impl Workspace {
#[must_use]
pub fn foreign_module_paths(&self) -> Vec<ForeignModulePath<'_>> {
let mut found = Vec::new();
for file in self.files.values() {
for reach in &file.reached {
let Some(site) = &reach.path_attribute else {
continue;
};
let target = &self.targets[reach.target.index()];
let owner = self.owning_package(&site.resolved);
if owner != Some(target.package_id) {
found.push(ForeignModulePath {
file: &file.path,
reach,
site,
package: target.package_id,
owner,
});
}
}
}
found
}
fn owning_package(&self, path: &RelPath) -> Option<PackageId> {
self.package_ids()
.filter(|id| holds(&self.packages[id.index()].dir, path))
.max_by_key(|id| self.packages[id.index()].dir.segments().count())
}
}
fn holds(dir: &RelPath, path: &RelPath) -> bool {
if dir.authority() != path.authority() {
return false;
}
let mut rest = path.segments();
dir.segments().all(|segment| rest.next() == Some(segment))
&& rest.all(|segment| segment != "..")
}