use std::path::Path;
use fallow_config::{PackageJson, ResolvedConfig};
use rustc_hash::FxHashSet;
use crate::plugins::AggregatedPluginResult;
use crate::results::{ImportSite, UnlistedDependency};
use super::{UnlistedDependencyContext, should_skip_unlisted_package, types_package_name};
pub(super) fn extend(
mut unlisted: Vec<UnlistedDependency>,
plugin_result: Option<&AggregatedPluginResult>,
ctx: &UnlistedDependencyContext<'_>,
) -> Vec<UnlistedDependency> {
let required = plugin_result.map_or(&[][..], |pr| pr.required_dependencies.as_slice());
for requirement in required {
let package_name = requirement.package_name.as_str();
if (requirement.dev_only && ctx.config.production)
|| config_path_is_ignored(&requirement.config_path, ctx.config)
|| should_skip_unlisted_package(package_name, ctx)
|| ctx.ignore_deps.suppresses(package_name)
|| std::iter::once(package_name)
.chain(requirement.provided_by.iter().copied())
.any(|name| config_dependency_is_declared(name, &requirement.config_path, ctx))
{
continue;
}
let site = ImportSite {
path: requirement.config_path.clone(),
line: requirement.line,
col: requirement.col,
};
match unlisted
.iter_mut()
.find(|finding| finding.package_name == package_name)
{
Some(finding) => {
if !finding
.imported_from
.iter()
.any(|known| known.path == site.path)
{
finding.imported_from.push(site);
finding
.imported_from
.sort_by(|a, b| a.path.cmp(&b.path).then(a.line.cmp(&b.line)));
}
}
None => unlisted.push(UnlistedDependency {
package_name: package_name.to_owned(),
imported_from: vec![site],
}),
}
}
unlisted
}
pub(super) fn plugin_referenced_set(
plugin_result: Option<&AggregatedPluginResult>,
) -> FxHashSet<&str> {
plugin_result
.map(|pr| {
pr.referenced_dependencies
.iter()
.map(String::as_str)
.chain(pr.required_dependencies.iter().flat_map(|requirement| {
std::iter::once(requirement.package_name.as_str())
.chain(requirement.provided_by.iter().copied())
}))
.collect()
})
.unwrap_or_default()
}
fn config_path_is_ignored(config_path: &Path, config: &ResolvedConfig) -> bool {
config_path
.strip_prefix(&config.root)
.is_ok_and(|relative| config.ignore_patterns.is_match(relative))
}
fn config_dependency_is_declared(
package_name: &str,
config_path: &Path,
ctx: &UnlistedDependencyContext<'_>,
) -> bool {
let types_name = types_package_name(package_name);
let declares =
|deps: &FxHashSet<String>| deps.contains(package_name) || deps.contains(&types_name);
if declares(ctx.all_deps)
|| ctx
.ws_dep_map
.iter()
.filter(|workspace| config_path.starts_with(&workspace.root))
.any(|workspace| declares(&workspace.deps))
{
return true;
}
config_path
.ancestors()
.skip(1)
.take_while(|dir| dir.starts_with(&ctx.config.root))
.filter_map(|dir| PackageJson::load(&dir.join("package.json")).ok())
.any(|pkg| {
pkg.all_dependency_names()
.iter()
.any(|name| name == package_name || *name == types_name)
})
}