use std::collections::HashMap;
use std::sync::{Arc, OnceLock};
use super::exemption::OperatorExemptions;
#[cfg(all(doc, feature = "lsp-responses"))]
use super::generate_hover;
use super::in_use_version::CachedList;
#[cfg(doc)]
use super::{
DependencyOutcome, REGISTRY_FETCH_BUDGET, await_interactive_fetch, candidate_verdict,
generate_diagnostics_from_cache, latest_verdict, local_cooldown_precedence,
};
use super::{
DependencyOutcomes, EcosystemFormatter, GossipFindings, InteractiveFetchGate, LookupMiss,
PackageSuppression, SuppressedKinds, SuppressionSet,
};
use crate::ecosystem::Dependency;
use crate::error::FetchFailure;
use crate::licenses::LicensePolicy;
use crate::lockfile::LockScopes;
use crate::osv::{CandidateStatusMap, LatestStatusMap, VulnerabilityMap};
use crate::parser::DependencySource;
use crate::{
ConcreteVersion, DepsDevClient, EcosystemId, LicenseSource, LockScope, NormalizedName,
PackageKey, PackageVersions, TyposquatSignal,
};
pub type CachedVersionsMap = HashMap<NormalizedName, PackageVersions>;
pub type ResolvedVersionsMap = HashMap<NormalizedName, ConcreteVersion>;
#[derive(Clone)]
pub struct LockCandidates {
versions: Vec<ConcreteVersion>,
preference: OwnerPreference,
scopes: Option<Box<[LockScopes]>>,
cache: OnceLock<CachedList>,
}
impl PartialEq for LockCandidates {
fn eq(&self, other: &Self) -> bool {
self.versions == other.versions
&& self.preference == other.preference
&& self.scopes == other.scopes
}
}
impl Eq for LockCandidates {}
impl std::fmt::Debug for LockCandidates {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LockCandidates")
.field("versions", &self.versions)
.field("preference", &self.preference)
.field("scopes", &self.scopes)
.finish_non_exhaustive()
}
}
#[derive(Clone, PartialEq, Eq)]
pub(crate) enum OwnerPreference {
Unscoped,
Owned(Box<[bool]>),
Descriptors(Box<[Box<[crate::VersionReq]>]>),
}
impl std::fmt::Debug for OwnerPreference {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Unscoped => f.write_str("Unscoped"),
Self::Owned(flags) => f.debug_tuple("Owned").field(flags).finish(),
Self::Descriptors(per_version) => {
let redacted: Vec<Vec<String>> = per_version
.iter()
.map(|descriptors| {
descriptors
.iter()
.map(|d| crate::redact::redact_declaration_key(d.as_str()).into_owned())
.collect()
})
.collect();
f.debug_tuple("Descriptors").field(&redacted).finish()
}
}
}
}
impl LockCandidates {
pub(crate) const fn with_preference(
versions: Vec<ConcreteVersion>,
preference: OwnerPreference,
) -> Self {
Self {
versions,
preference,
scopes: None,
cache: OnceLock::new(),
}
}
pub(crate) fn with_scopes(mut self, scopes: Box<[LockScopes]>) -> Self {
self.scopes = Some(scopes);
self
}
pub(crate) fn has_non_project(&self) -> bool {
self.scopes
.as_deref()
.is_some_and(|scopes| scopes.iter().any(|s| s.has_non_project()))
}
pub(crate) fn needs_selection(&self) -> bool {
self.versions.len() > 1 || self.has_non_project()
}
pub(crate) fn scope_mask(&self, scope: LockScope) -> Vec<bool> {
match self.scopes.as_deref() {
Some(scopes) => scopes.iter().map(|s| s.contains(scope)).collect(),
None => vec![scope == LockScope::Project; self.versions.len()],
}
}
#[must_use]
pub fn has_scope(&self, scope: LockScope) -> bool {
self.scope_mask(scope).contains(&true)
}
pub(crate) fn cached_list(&self, formatter: &dyn EcosystemFormatter) -> &CachedList {
self.cache
.get_or_init(|| CachedList::new(&self.versions, formatter))
}
pub(crate) const fn preference(&self) -> &OwnerPreference {
&self.preference
}
#[must_use]
pub fn versions(&self) -> &[ConcreteVersion] {
&self.versions
}
#[must_use]
pub fn len(&self) -> usize {
self.versions.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.versions.is_empty()
}
}
impl From<Vec<ConcreteVersion>> for LockCandidates {
fn from(versions: Vec<ConcreteVersion>) -> Self {
Self::with_preference(versions, OwnerPreference::Unscoped)
}
}
pub type ResolvedCandidatesMap = HashMap<NormalizedName, LockCandidates>;
#[non_exhaustive]
#[derive(Debug, Clone, Copy)]
pub struct VersionData<'a> {
cached: &'a CachedVersionsMap,
resolved: &'a ResolvedVersionsMap,
resolved_version_candidates: Option<&'a ResolvedCandidatesMap>,
pub vulnerabilities: Option<&'a VulnerabilityMap>,
pub outcomes: Option<&'a DependencyOutcomes>,
pub ecosystem: Option<EcosystemId>,
pub network: crate::NetworkMode,
pub trust: Option<&'a Arc<DepsDevClient>>,
pub license_prefetch: Option<&'a HashMap<NormalizedName, Vec<String>>>,
pub license_source: Option<LicenseSource>,
pub license_policy: Option<&'a LicensePolicy>,
pub typosquat_prefetch: Option<&'a HashMap<NormalizedName, TyposquatSignal>>,
pub gossip_prefetch: Option<&'a HashMap<NormalizedName, GossipFindings>>,
pub gossip_client: Option<&'a Arc<DepsDevClient>>,
pub latest_status: Option<&'a LatestStatusMap>,
pub candidate_status: Option<&'a CandidateStatusMap>,
pub interactive_fetch: Option<&'a InteractiveFetchGate>,
pub suppression: Option<&'a SuppressionSet>,
pub advisory_exemptions: Option<&'a OperatorExemptions>,
pub now: crate::freshness::PublishTime,
}
impl<'a> VersionData<'a> {
pub fn new(cached: &'a CachedVersionsMap, resolved: &'a ResolvedVersionsMap) -> Self {
Self {
cached,
resolved,
resolved_version_candidates: None,
vulnerabilities: None,
outcomes: None,
ecosystem: None,
network: crate::NetworkMode::Online,
trust: None,
license_prefetch: None,
license_source: None,
license_policy: None,
typosquat_prefetch: None,
gossip_prefetch: None,
gossip_client: None,
latest_status: None,
candidate_status: None,
interactive_fetch: None,
suppression: None,
advisory_exemptions: None,
now: crate::freshness::PublishTime::now(),
}
}
#[must_use]
pub fn cached_for(&self, key: &PackageKey) -> Option<&'a PackageVersions> {
self.cached.get(key.normalized())
}
#[must_use]
pub fn resolved_for(&self, key: &PackageKey) -> Option<&'a ConcreteVersion> {
self.resolved.get(key.normalized())
}
#[must_use]
pub fn fetch_failure_for(&self, key: &PackageKey) -> Option<&'a FetchFailure> {
self.outcomes
.and_then(|outcomes| outcomes.fetch_failure(key.normalized()))
}
#[must_use]
pub fn lookup_miss_for(&self, key: &PackageKey) -> Option<LookupMiss> {
self.outcomes
.and_then(|outcomes| outcomes.lookup_miss(key.normalized()))
}
#[must_use]
pub fn reportable_lookup_miss(
&self,
dep: &dyn Dependency,
key: &PackageKey,
formatter: &dyn EcosystemFormatter,
) -> Option<LookupMiss> {
let miss = self.lookup_miss_for(key)?;
if miss == LookupMiss::NotLookedUp || self.network.is_offline() {
return None;
}
let source = dep.source();
if !formatter.can_resolve_source(&source)
|| matches!(source, DependencySource::AlternateRegistry { .. })
{
return None;
}
Some(miss)
}
#[must_use]
pub fn is_resolved(&self, key: &PackageKey) -> bool {
self.resolved_for(key).is_some()
}
#[must_use]
pub fn is_resolved_for(&self, dep: &dyn Dependency, key: &PackageKey) -> bool {
match dep.lock_scope() {
crate::LockScope::Project => self.is_resolved(key),
scope @ crate::LockScope::BuildScript => self
.resolved_version_candidates
.and_then(|candidates| candidates.get(key.normalized()))
.is_some_and(|candidates| candidates.has_scope(scope)),
}
}
#[must_use]
pub fn resolved_candidates_for(&self, key: &PackageKey) -> Option<&'a [ConcreteVersion]> {
self.resolved_version_candidates
.and_then(|candidates| candidates.get(key.normalized()))
.map(LockCandidates::versions)
}
pub(crate) const fn resolved_map(&self) -> &'a ResolvedVersionsMap {
self.resolved
}
pub(crate) const fn candidates_map(&self) -> Option<&'a ResolvedCandidatesMap> {
self.resolved_version_candidates
}
#[must_use]
pub const fn with_interactive_fetch_gate(mut self, gate: &'a InteractiveFetchGate) -> Self {
self.interactive_fetch = Some(gate);
self
}
#[must_use]
pub const fn with_resolved_version_candidates(
mut self,
candidates: &'a ResolvedCandidatesMap,
) -> Self {
self.resolved_version_candidates = Some(candidates);
self
}
#[must_use]
pub fn with_vulnerabilities(mut self, vulnerabilities: &'a VulnerabilityMap) -> Self {
self.vulnerabilities = Some(vulnerabilities);
self
}
#[must_use]
pub fn with_latest_status(mut self, latest_status: &'a LatestStatusMap) -> Self {
self.latest_status = Some(latest_status);
self
}
#[must_use]
pub fn with_candidate_status(mut self, candidate_status: &'a CandidateStatusMap) -> Self {
self.candidate_status = Some(candidate_status);
self
}
#[must_use]
pub fn with_outcomes(mut self, outcomes: &'a DependencyOutcomes) -> Self {
self.outcomes = Some(outcomes);
self
}
#[must_use]
pub const fn with_ecosystem(mut self, ecosystem: EcosystemId) -> Self {
self.ecosystem = Some(ecosystem);
self
}
#[must_use]
pub const fn with_network(mut self, network: crate::NetworkMode) -> Self {
self.network = network;
self
}
#[must_use]
pub const fn with_trust(mut self, client: &'a Arc<DepsDevClient>) -> Self {
self.trust = Some(client);
self
}
#[must_use]
pub const fn with_license_prefetch(
mut self,
licenses: &'a HashMap<NormalizedName, Vec<String>>,
) -> Self {
self.license_prefetch = Some(licenses);
self
}
#[must_use]
pub const fn with_license_source(mut self, source: LicenseSource) -> Self {
self.license_source = Some(source);
self
}
#[must_use]
pub const fn with_license_policy(mut self, policy: &'a LicensePolicy) -> Self {
self.license_policy = Some(policy);
self
}
#[must_use]
pub const fn with_suppression(mut self, suppression: &'a SuppressionSet) -> Self {
self.suppression = Some(suppression);
self
}
#[must_use]
pub const fn with_advisory_exemptions(mut self, exemptions: &'a OperatorExemptions) -> Self {
self.advisory_exemptions = Some(exemptions);
self
}
#[must_use]
pub const fn with_now(mut self, now: crate::freshness::PublishTime) -> Self {
self.now = now;
self
}
#[must_use]
pub fn package_suppression(
&self,
formatter: &dyn EcosystemFormatter,
key: &PackageKey,
) -> PackageSuppression {
self.suppression
.map(|set| set.resolve(formatter))
.unwrap_or_default()
.for_package(key.normalized())
}
#[must_use]
pub fn suppressed_kinds_for(
&self,
formatter: &dyn EcosystemFormatter,
key: &PackageKey,
) -> SuppressedKinds {
self.package_suppression(formatter, key).kinds()
}
#[must_use]
pub const fn with_typosquat_prefetch(
mut self,
typosquat_prefetch: &'a HashMap<NormalizedName, TyposquatSignal>,
) -> Self {
self.typosquat_prefetch = Some(typosquat_prefetch);
self
}
#[must_use]
pub const fn with_gossip_prefetch(
mut self,
gossip_prefetch: &'a HashMap<NormalizedName, GossipFindings>,
) -> Self {
self.gossip_prefetch = Some(gossip_prefetch);
self
}
#[must_use]
pub const fn with_gossip_client(mut self, client: &'a Arc<DepsDevClient>) -> Self {
self.gossip_client = Some(client);
self
}
}